content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
namespace CodeGenerator.Application.DTOs.Employee
{
/// <summary>
/// 工作人员 - 录入
/// </summary>
public class EmployeeInputDto
{
/// <summary>
/// 所属部门主键
/// </summary>
public long DepartmentId { get; set; }
/// <summary>
/// 账号
/// </summary>
public string Account { get; set; }
/// <summary>
/// 密码
/// </summary>
public string Password { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string EmployeeName { get; set; }
/// <summary>
/// 性别
/// </summary>
public string Gender { get; set; }
/// <summary>
/// 民族
/// </summary>
public string Nation { get; set; }
/// <summary>
/// 出生日期
/// </summary>
public string BirthDate { get; set; }
/// <summary>
/// 证件类型
/// </summary>
public string CertificateType { get; set; }
/// <summary>
/// 证件号码
/// </summary>
public string CertificateNo { get; set; }
/// <summary>
/// 证件地址
/// </summary>
public string CertificateAddress { get; set; }
/// <summary>
/// 手机号
/// </summary>
public string MobileNo { get; set; }
/// <summary>
/// 联系电话
/// </summary>
public string ContactNumber { get; set; }
/// <summary>
/// 微信
/// </summary>
public string Weixin { get; set; }
/// <summary>
/// 电邮
/// </summary>
public string Email { get; set; }
/// <summary>
/// 通讯地址
/// </summary>
public string PostalAddress { get; set; }
/// <summary>
/// 紧急联系人
/// </summary>
public string EmergencyContact { get; set; }
/// <summary>
/// 紧急联系人电话
/// </summary>
public string EmergencyContactNumber { get; set; }
/// <summary>
/// 入职日期
/// </summary>
public DateTime? JoiningDate { get; set; }
/// <summary>
/// 工作岗位
/// </summary>
public string JobPosition { get; set; }
/// <summary>
/// 工作职务
/// </summary>
public string JobTitle { get; set; }
/// <summary>
/// 附加信息1
/// </summary>
public string AdditionalInformation1 { get; set; }
/// <summary>
/// 附加信息2
/// </summary>
public string AdditionalInformation2 { get; set; }
/// <summary>
/// 附加信息3
/// </summary>
public string AdditionalInformation3 { get; set; }
/// <summary>
/// 附加信息4
/// </summary>
public string AdditionalInformation4 { get; set; }
/// <summary>
/// 附加信息5
/// </summary>
public string AdditionalInformation5 { get; set; }
/// <summary>
/// 附加信息6
/// </summary>
public string AdditionalInformation6 { get; set; }
/// <summary>
/// 状态:正常、停用
/// </summary>
public string Status { get; set; }
}
}
| 21.181818 | 52 | 0.55833 | [
"MIT"
] | ileego/CodeGenerator | src/CodeGenerator.Application/DTOs/Employee/EmployeeInputDto.cs | 2,779 | C# |
using Org.BouncyCastle.Utilities.Encoders;
using Securo.GlobalPlatform.Commands;
using Securo.GlobalPlatform.Interfaces;
using Securo.GlobalPlatform.Model;
using Securo.GlobalPlatform.SecureMessaging;
using System;
namespace Securo.GlobalPlatform
{
public class CardManager : ICardManager
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private readonly IApduTransmit apduTransmit;
private readonly ISecureSessionDetailsCreator secureSessionDetailsCreator;
private readonly IScpInfoProvider scpInfoProvider;
private readonly ICardResponseParser cardResponseParser;
private readonly ISecureContextProviderFactory secureContextProviderFactory;
private ISecureContextProvider secureContextProvider;
private IAuthenticationCryptogramProvider<Scp03CardAuthenticationCryptogramData> cardAuthenticationCryptogramProvider;
private ScpInfo ScpInfo { get; set; }
public SecureSessionDetails SecureSessionDetails { get; private set; }
public string Aid { get; private set; }
const string GetDataApdu = "80CA006600";
public CardManager(
IApduTransmit apduTransmit,
IGpMasterKeysProvider gpMasterKeysProvider)
{
this.apduTransmit = apduTransmit;
this.secureSessionDetailsCreator = new SecureSessionDetailsCreator();
this.scpInfoProvider = new ScpInfoProvider();
this.cardResponseParser = new CardResponseParser();
this.secureContextProviderFactory = new SecureContextProviderFactory(gpMasterKeysProvider);
}
public void Select(string aid)
{
var selectCommand = new SelectApduCommand(0x04, 0x00, aid).Build();
var cardResponse = apduTransmit.Send(selectCommand);
if (cardResponse.StatusWord == 0x9000)
{
this.Aid = aid;
var cardRecogntionData = apduTransmit.Send(GetDataApdu);
if (cardRecogntionData.StatusWord == 0x9000)
{
this.ScpInfo = this.scpInfoProvider.Provide(Hex.Decode(cardRecogntionData.Data));
}
else
{
throw new InvalidOperationException("Can't perform Get Data command");
}
}
else
{
throw new InvalidOperationException($"Applet not found: {aid}");
}
}
public void InitializeUpdate(byte keySetVersion, byte keyIdentifier, string hostChallenge)
{
var command = new InitalizeUpdateCommand(keySetVersion, keyIdentifier, hostChallenge).Build();
var cardResponse = this.apduTransmit.Send(command);
if (cardResponse.StatusWord == 0x9000)
{
this.SecureSessionDetails = this.secureSessionDetailsCreator.Create(cardResponse.Data);
this.SecureSessionDetails.HostChallenge = hostChallenge;
this.SecureSessionDetails.ScpInfo = this.ScpInfo;
this.secureContextProvider = this.secureContextProviderFactory
.Provide((ScpMode)this.SecureSessionDetails.ScpInfo.ScpIdentifier);
this.secureContextProvider.InitializeSecureContext(this.SecureSessionDetails);
}
else
{
throw new InvalidOperationException($"Error in InitializeUpdate: SW={cardResponse.StatusWord.ToString("X2")}");
}
}
public void ExternalAuthenticate(SecurityLevel securityLevel)
{
var hostAuthCryptogram = this.secureContextProvider.CalculateHostCrypogram().Result;
var command = new ExternalAuthenticateCommand((byte)securityLevel, hostAuthCryptogram).Build();
var wrappedCommand = this.secureContextProvider.Wrap(SecurityLevel.Mac, command).Result;
var cardResponse = this.apduTransmit.Send(wrappedCommand);
if (cardResponse.StatusWord != 0x9000)
{
throw new InvalidOperationException($"Error in ExternalAuthenticate: SW={cardResponse.StatusWord.ToString("X2")}");
}
}
public void StoreData(string data)
{
var command = new StoreDataCommand(0x00, 0x00, data).Build();
var wrappedCommand = this.secureContextProvider.Wrap(SecurityLevel.Mac, command).Result;
var cardResponse = this.apduTransmit.Send(wrappedCommand);
if (cardResponse.StatusWord != 0x9000)
{
throw new InvalidOperationException($"Error in StoreData: SW={cardResponse.StatusWord.ToString("X2")}");
}
}
public string GetData(byte tagMsb, byte tagLsb)
{
throw new NotImplementedException();
}
public CardResponse TransmitApdu(SecurityLevel securityLevel, string command)
{
log.Info($"TX-Plain -> {command}");
var wrappedCommand = this.secureContextProvider.Wrap(securityLevel, command).Result;
var cardResponse = this.apduTransmit.Send(wrappedCommand);
if (cardResponse.StatusWord != 0x9000)
{
throw new InvalidOperationException($"Error in TransmitApdu: SW={cardResponse.StatusWord.ToString("X2")}");
}
else
{
var unwrappedResponse = this.secureContextProvider.Unwrap(securityLevel, cardResponse.FullResponse).Result.ToUpper();
log.Info($"RX-Plain -> {unwrappedResponse}");
return this.cardResponseParser.Parse(unwrappedResponse);
}
}
}
} | 45.888889 | 143 | 0.648737 | [
"MIT"
] | dimatteo31/securo-gp | src/Securo.GlobaPlatform/CardManager.cs | 5,784 | C# |
////////////////////////////////////////////////////////////////////////////////
//
// clipboard-top-down-dib
//
// This software is provided under the MIT License:
// Copyright (C) 2019 Nicholas Hayes
//
// See LICENSE.md in the project root for more information.
//
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ClipboardTopDownDib
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
pictureBox.Image = new Bitmap(typeof(Program), "A_Lion.jpg");
}
private void CopyImageToClipboardButton_Click(object sender, EventArgs e)
{
Bitmap image = pictureBox.Image as Bitmap;
if (image != null)
{
PlaceDibOnClipboard(image);
}
}
private static void PlaceDibOnClipboard(Bitmap image)
{
byte[] dibBytes = CreateDib(image);
if (dibBytes != null)
{
Clipboard.Clear();
Clipboard.SetData(DataFormats.Dib, new MemoryStream(dibBytes));
}
}
private static unsafe byte[] CreateDib(Bitmap image)
{
byte[] dibBytes = null;
byte[] imageData = GetImageDataBytes(image);
if (imageData != null)
{
const int ColorTableSize = 12;
dibBytes = new byte[NativeStructs.BITMAPINFOHEADER.SizeOf + ColorTableSize + imageData.Length];
fixed (byte* ptr = &dibBytes[0])
{
NativeStructs.BITMAPINFOHEADER* header = (NativeStructs.BITMAPINFOHEADER*)ptr;
// Write the header.
header->biSize = (uint)NativeStructs.BITMAPINFOHEADER.SizeOf;
header->biWidth = image.Width;
header->biHeight = -image.Height;
header->biPlanes = 1;
header->biBitCount = 32;
header->biCompression = NativeConstants.BI_BITFIELDS;
header->biSizeImage = (uint)imageData.Length;
// Write the color masks.
IntPtr colorMaskOffset = new IntPtr(ptr + NativeStructs.BITMAPINFOHEADER.SizeOf);
Marshal.WriteInt32(colorMaskOffset, 0, 0x00FF0000);
Marshal.WriteInt32(colorMaskOffset, 4, 0x0000FF00);
Marshal.WriteInt32(colorMaskOffset, 8, 0x000000FF);
}
Buffer.BlockCopy(imageData, 0, dibBytes, NativeStructs.BITMAPINFOHEADER.SizeOf + ColorTableSize, imageData.Length);
}
return dibBytes;
}
private static byte[] GetImageDataBytes(Bitmap image)
{
byte[] imageData = null;
BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
try
{
imageData = new byte[data.Stride * data.Height];
Marshal.Copy(data.Scan0, imageData, 0, imageData.Length);
}
finally
{
image.UnlockBits(data);
}
return imageData;
}
}
}
| 31.157895 | 145 | 0.526745 | [
"MIT"
] | 0xC0000054/clipboard-top-down-dib | Form1.cs | 3,554 | C# |
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using NSubstitute;
using Sfa.Tl.ResultsAndCertification.Common.Helpers;
using Sfa.Tl.ResultsAndCertification.Web.ViewModel.ProviderAddress;
using System.Collections.Generic;
using Xunit;
namespace Sfa.Tl.ResultsAndCertification.Web.UnitTests.Controllers.ProviderAddressTests.AddAddressSelectGet
{
public class When_NoCache_Found : TestSetup
{
private AddAddressViewModel _cacheResult;
private AddAddressPostcodeViewModel _postcodeViewModel;
private AddAddressSelectViewModel _addressesMockResult = null;
public override void Given()
{
_postcodeViewModel = new AddAddressPostcodeViewModel { Postcode = "xx1 1yy" };
_cacheResult = new AddAddressViewModel
{
AddAddressPostcode = _postcodeViewModel
};
_addressesMockResult = new AddAddressSelectViewModel
{
AddressSelectList = new List<SelectListItem> { new SelectListItem { Text = "Hello", Value = "236547891" } }
};
CacheService.GetAsync<AddAddressViewModel>(CacheKey).Returns(_cacheResult);
ProviderAddressLoader.GetAddressesByPostcodeAsync(_postcodeViewModel.Postcode).Returns(_addressesMockResult);
}
[Fact]
public void Then_Expected_Methods_Called()
{
CacheService.Received(1).GetAsync<AddAddressViewModel>(CacheKey);
ProviderAddressLoader.Received(1).GetAddressesByPostcodeAsync(_postcodeViewModel.Postcode);
}
[Fact]
public void Then_Returns_Expected_Results()
{
Result.Should().NotBeNull();
Result.Should().BeOfType(typeof(ViewResult));
var viewResult = Result as ViewResult;
viewResult.Model.Should().BeOfType(typeof(AddAddressSelectViewModel));
var model = viewResult.Model as AddAddressSelectViewModel;
model.Should().NotBeNull();
model.SelectedAddressUprn.Should().BeNull();
model.SelectedAddress.Should().BeNull();
model.DepartmentName.Should().BeNull();
model.Postcode.Should().Be(_postcodeViewModel.Postcode);
model.AddressSelectList.Should().NotBeNull();
model.AddressSelectList.Count.Should().Be(_addressesMockResult.AddressSelectList.Count);
model.AddressSelectList.Should().BeEquivalentTo(_addressesMockResult.AddressSelectList);
model.BackLink.Should().NotBeNull();
model.BackLink.RouteName.Should().Be(RouteConstants.AddAddressPostcode);
}
}
}
| 40.727273 | 123 | 0.687128 | [
"MIT"
] | SkillsFundingAgency/tl-result-and-certification | src/Tests/Sfa.Tl.ResultsAndCertification.Web.UnitTests/Controllers/ProviderAddressTests/AddAddressSelectGet/When_NoCache_Found.cs | 2,690 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;
using SqlMemoryDb.Exceptions;
using SqlMemoryDb.Helpers;
using SqlMemoryDb.SelectData;
using SqlParser;
namespace SqlMemoryDb
{
internal class RawData
{
public List<RawTableJoinRow> RawRowList = new List<RawTableJoinRow>();
public DbParameterCollection Parameters { get; set; }
public SqlBooleanExpression HavingClause { get; set; }
public SqlBooleanExpression WhereClause { get; set; }
public SqlOrderByItemCollection SortOrder { get; set; }
public MemoryDbDataReader.ResultBatch Batch { get; set; }
public Dictionary<string, Table> TableAliasList = new Dictionary<string, Table>();
public List<TableColumn> GroupByFields = new List<TableColumn>();
public readonly MemoryDbCommand Command;
public readonly MemoryDatabase Database;
private readonly List<Table> _CommonTableList = new List<Table>();
public RawData( MemoryDbCommand command, MemoryDbDataReader.ResultBatch batch = null )
{
Command = command;
Parameters = command.Parameters;
Database = ((MemoryDbConnection)Command.Connection).GetMemoryDatabase( );
Batch = batch;
}
public void AddTablesFromClause( SqlFromClause fromClause, Dictionary<string, Table> tables )
{
foreach (var expression in fromClause.TableExpressions)
{
AddTable( expression, tables );
}
}
public void AddTable( SqlTableExpression expression, Dictionary<string, Table> tables )
{
switch (expression)
{
case SqlTableRefExpression tableRef:
{
RawRowList = GetTableOrViewRows( tables, tableRef );
break;
}
case SqlQualifiedJoinTableExpression joinExpression:
{
AddTable( joinExpression.Left, tables );
var joinRowList = GetTableOrViewRows( tables, (SqlTableRefExpression)joinExpression.Right );
var nameJoin = Helper.GetAliasName((SqlTableRefExpression)joinExpression.Right);
AddAllTableJoinRows( joinRowList, nameJoin, joinExpression );
break;
}
}
}
private List<RawTableJoinRow> GetTableOrViewRows( Dictionary<string, Table> tables, SqlTableRefExpression tableRef )
{
List<RawTableJoinRow> rowList;
var name = Helper.GetAliasName( tableRef );
var qualifiedName = Helper.GetQualifiedName( tableRef.ObjectIdentifier );
if ( tables.ContainsKey( qualifiedName ) )
{
var table = tables[ qualifiedName ];
rowList = GetAllTableRows( table, name );
}
else if ( ((MemoryDbConnection)Command.Connection).TempTables.ContainsKey( qualifiedName ) )
{
var table = ((MemoryDbConnection)Command.Connection).TempTables[ qualifiedName ];
rowList = GetAllTableRows( table, name );
}
else if ( Database.Views.ContainsKey( qualifiedName ) )
{
var view = Database.Views[ qualifiedName ];
rowList = GetAllViewRows( view, name );
}
else if ( _CommonTableList.Any( t => t.FullName == qualifiedName ) )
{
var table = _CommonTableList.Single( t => t.FullName == qualifiedName );
rowList = GetAllTableRows( table, name );
}
else
{
throw new SqlInvalidObjectNameException( name );
}
return rowList;
}
public List<RawTableJoinRow> GetAllTableRows( Table table, string name )
{
var rawRowList = new List<RawTableJoinRow>( );
if ( TableAliasList.ContainsKey( name ) == false )
{
TableAliasList.Add( name, table );
}
foreach ( var row in table.Rows )
{
var tableRow = new RawTableRow
{
Name = name,
Table = table,
Row = row
};
var rows = new RawTableJoinRow( ) {tableRow};
rawRowList.Add( rows );
}
return rawRowList;
}
private List<RawTableJoinRow> GetAllViewRows( SqlCreateAlterViewStatementBase view, string name )
{
var command = new MemoryDbCommand( Command.Connection, Command.Parameters, Command.Variables );
var rawData = new RawData( command );
var batch = new ExecuteQueryStatement( Database, command ).Execute( Database.Tables, rawData, (SqlQuerySpecification)view.Definition.QueryExpression );
var identifier = view.Definition.Name;
if ( TableAliasList.ContainsKey( name ) == false )
{
var table = CreateTable( name, identifier, batch, null );
TableAliasList.Add( name, table );
}
return ResultBatch2RowList( TableAliasList[ name ], batch );
}
private List<RawTableJoinRow> ResultBatch2RowList( Table table,
MemoryDbDataReader.ResultBatch batch, SqlIdentifierCollection columnList = null )
{
var rowList = new List<RawTableJoinRow>( );
foreach ( var row in batch.ResultRows )
{
var tableRow = new RawTableRow
{
Name = table.FullName,
Table = table,
Row = row
};
var rows = new RawTableJoinRow( ) {tableRow};
rowList.Add( rows );
}
return rowList;
}
private Table CreateTable( string name, SqlObjectIdentifier identifier, MemoryDbDataReader.ResultBatch batch,
SqlIdentifierCollection columnList )
{
if ( columnList != null )
{
if ( columnList.Count > batch.Fields.Count )
{
throw new SqlInsertTooManyColumnsException( );
}
if ( columnList.Count < batch.Fields.Count )
{
throw new SqlInsertTooManyValuesException( );
}
}
var table = ( identifier != null ) ? new Table( identifier ) : new Table( name );
for ( int fieldIndex = 0; fieldIndex < batch.Fields.Count; fieldIndex++ )
{
var field = batch.Fields[ fieldIndex ];
var sqlType = Helper.DbType2SqlType(field.DbType);
var columnName = columnList != null ? columnList[ fieldIndex ].Value : field.Name;
var select = ( field as MemoryDbDataReader.ReaderFieldData )?.SelectFieldData;
var tc = ( select as SelectDataFromColumn )?.TableColumn;
var column = tc != null
? new Column( tc.Column, columnName, table.Columns.Count )
: new Column( table, columnName, sqlType, Database.UserDataTypes, table.Columns.Count );
table.Columns.Add( column );
}
return table;
}
public void AddAllTableJoinRows(List<RawTableJoinRow> joinRowList, string name, SqlQualifiedJoinTableExpression joinExpression )
{
var newTableRows = new List<RawTableJoinRow>( );
var filter = HelperConditional.GetRowFilter( joinExpression.OnClause.Expression, this );
foreach ( var currentRawRows in RawRowList )
{
var currentRowCount = newTableRows.Count;
foreach ( var row in joinRowList )
{
var newRows = new RawTableJoinRow( currentRawRows ) { row.First() };
if ( filter.IsValid( newRows ) )
{
newTableRows.Add( newRows );
}
}
if ( currentRowCount == newTableRows.Count && joinExpression.JoinOperator == SqlJoinOperatorType.LeftOuterJoin )
{
newTableRows.Add( currentRawRows );
}
}
RawRowList = newTableRows;
}
public void AddGroupByClause( SqlGroupByClause groupByClause )
{
foreach ( var item in groupByClause.Items )
{
switch ( item )
{
case SqlSimpleGroupByItem simpleItem:
var tableColumn = Helper.GetTableColumn( ( SqlColumnRefExpression ) simpleItem.Expression, this );
GroupByFields.Add( tableColumn );
break;
default:
throw new NotImplementedException();
}
}
}
public void ExecuteWhereClause( SqlWhereClause whereClause )
{
foreach ( var child in whereClause.Children )
{
var filter = HelperConditional.GetRowFilter( ( SqlBooleanExpression ) child, this );
RawRowList = RawRowList.Where( r => filter.IsValid( r ) ).ToList( );
}
}
public static bool RowsAreEqual( ArrayList row1, ArrayList row2 )
{
bool isEqual = true;
for ( int index = 0; (index < row2.Count) && isEqual; index++ )
{
isEqual &= row2[ index ].Equals( row1[ index ] );
}
return isEqual;
}
public void AddTablesFromCommonTableExpressions( SqlCommonTableExpressionCollection commonTableExpressions, Dictionary<string, Table> tables )
{
foreach ( var commonTableExpression in commonTableExpressions )
{
var command = new MemoryDbCommand( Command.Connection, Command.Parameters, Command.Variables );
var rawData = new RawData( command );
var batch = new ExecuteQueryStatement( Database, command ).Execute( Database.Tables, rawData, (SqlQuerySpecification)commonTableExpression.QueryExpression );
var name = commonTableExpression.Name.Value;
var table = CreateTable( name, null, batch, commonTableExpression.ColumnList );
table.Rows.AddRange( batch.ResultRows );
_CommonTableList.Add( table );
}
}
}
} | 40.718045 | 173 | 0.55812 | [
"MIT"
] | avheerwaarde/SqlMemoryDb | SqlParser/RawData.cs | 10,833 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20180601.Outputs
{
/// <summary>
/// Redirect configuration of an application gateway.
/// </summary>
[OutputType]
public sealed class ApplicationGatewayRedirectConfigurationResponse
{
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
public readonly string? Etag;
/// <summary>
/// Resource ID.
/// </summary>
public readonly string? Id;
/// <summary>
/// Include path in the redirected url.
/// </summary>
public readonly bool? IncludePath;
/// <summary>
/// Include query string in the redirected url.
/// </summary>
public readonly bool? IncludeQueryString;
/// <summary>
/// Name of the redirect configuration that is unique within an Application Gateway.
/// </summary>
public readonly string? Name;
/// <summary>
/// Path rules specifying redirect configuration.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceResponse> PathRules;
/// <summary>
/// Supported http redirection types - Permanent, Temporary, Found, SeeOther.
/// </summary>
public readonly string? RedirectType;
/// <summary>
/// Request routing specifying redirect configuration.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceResponse> RequestRoutingRules;
/// <summary>
/// Reference to a listener to redirect the request to.
/// </summary>
public readonly Outputs.SubResourceResponse? TargetListener;
/// <summary>
/// Url to redirect the request to.
/// </summary>
public readonly string? TargetUrl;
/// <summary>
/// Type of the resource.
/// </summary>
public readonly string? Type;
/// <summary>
/// Url path maps specifying default redirect configuration.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceResponse> UrlPathMaps;
[OutputConstructor]
private ApplicationGatewayRedirectConfigurationResponse(
string? etag,
string? id,
bool? includePath,
bool? includeQueryString,
string? name,
ImmutableArray<Outputs.SubResourceResponse> pathRules,
string? redirectType,
ImmutableArray<Outputs.SubResourceResponse> requestRoutingRules,
Outputs.SubResourceResponse? targetListener,
string? targetUrl,
string? type,
ImmutableArray<Outputs.SubResourceResponse> urlPathMaps)
{
Etag = etag;
Id = id;
IncludePath = includePath;
IncludeQueryString = includeQueryString;
Name = name;
PathRules = pathRules;
RedirectType = redirectType;
RequestRoutingRules = requestRoutingRules;
TargetListener = targetListener;
TargetUrl = targetUrl;
Type = type;
UrlPathMaps = urlPathMaps;
}
}
}
| 32.46789 | 92 | 0.604973 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20180601/Outputs/ApplicationGatewayRedirectConfigurationResponse.cs | 3,539 | C# |
using SpocR.DataContext.Attributes;
namespace SpocR.DataContext.Models
{
public class Column
{
[SqlFieldName("name")]
public string Name { get; set; }
[SqlFieldName("is_nullable")]
public bool IsNullable { get; set; }
[SqlFieldName("system_type_name")]
public string SqlTypeName { get; set; }
[SqlFieldName("max_length")]
public int MaxLength { get; set; }
}
} | 23.157895 | 47 | 0.611364 | [
"MIT"
] | nuetzliches/spocr | src/DataContext/Models/Column.cs | 440 | 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("ConsoleApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleApplication1")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("527a0369-8525-4546-a9b6-d50c085fd90c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.135135 | 84 | 0.747697 | [
"MIT"
] | indrapadmaja/VSGitSession | ConsoleApplication1/ConsoleApplication1/Properties/AssemblyInfo.cs | 1,414 | C# |
using Cosmos.Logging.Exceptions.Configurations;
using Cosmos.Logging.Extensions.Exceptions.Destructurers;
namespace Cosmos.Logging {
/// <summary>
/// Extensions for destructurer
/// </summary>
public static class DestructurerExtensions {
/// <summary>
/// Use MySql
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
public static ExceptionOptions UseMySql(this ExceptionOptions options) {
options.UseDestucturer<MySqlExceptionDestructurer>();
return options;
}
}
} | 31.052632 | 80 | 0.632203 | [
"Apache-2.0"
] | CosmosLoops/Cosmos | src/Cosmos.Logging.Extensions.MySql/Cosmos/Logging/DestructurerExtensions.cs | 590 | C# |
using System;
using Com.QueoFlow.Peanuts.Net.Core.Domain.Dto;
using Com.QueoFlow.Peanuts.Net.Core.Domain.Users;
using Com.QueoFlow.Peanuts.Net.Core.Infrastructure.Checks;
using Com.QueoFlow.Peanuts.Net.Core.Persistence.NHibernate;
namespace Com.QueoFlow.Peanuts.Net.Core.Domain.Peanuts {
/// <summary>
/// Beschreibt eine Teilnahme an einem <see cref="Peanut" />
/// </summary>
public class PeanutParticipation : Entity {
private readonly DateTime _createdAt;
private readonly User _createdBy;
private readonly Peanut _peanut;
private readonly UserGroupMembership _userGroupMembership;
private DateTime? _changedAt;
private User _changedBy;
private PeanutParticipationState _participationState;
private PeanutParticipationType _participationType;
public PeanutParticipation() {
}
public PeanutParticipation(Peanut peanut, UserGroupMembership userGroupMembership, PeanutParticipationDto participationDto, EntityCreatedDto entityCreatedDto) {
Require.NotNull(peanut, "peanut");
Require.NotNull(userGroupMembership, "userGroupMembership");
Require.NotNull(participationDto, "participationDto");
Require.NotNull(entityCreatedDto, "entityCreatedDto");
_peanut = peanut;
_userGroupMembership = userGroupMembership;
_createdBy = entityCreatedDto.CreatedBy;
_createdAt = entityCreatedDto.CreatedAt;
Update(participationDto);
}
/// <summary>
/// Ruft ab, wann die Teilnahme zuletzt geändert wurde.
/// </summary>
public virtual DateTime? ChangedAt {
get { return _changedAt; }
}
/// <summary>
/// Ruft ab, wer die Teilnahme zuletzt geändert hat.
/// </summary>
public virtual User ChangedBy {
get { return _changedBy; }
}
/// <summary>
/// Ruft ab, wann die Teilnahme erstellt wurde.
/// </summary>
public virtual DateTime CreatedAt {
get { return _createdAt; }
}
/// <summary>
/// Ruft ab, wer die Teilnahme erstellt hat.
/// </summary>
public virtual User CreatedBy {
get { return _createdBy; }
}
/// <summary>
/// Ruft die Art der Teilnahme ab.
/// </summary>
public virtual PeanutParticipationType ParticipationType {
get { return _participationType; }
}
/// <summary>
/// Ruft den Status der Teilnahme ab.
/// </summary>
public virtual PeanutParticipationState ParticipationState {
get { return _participationState; }
}
/// <summary>
/// Ruft den Peanuts ab, für den die Teilnahme ist.
/// </summary>
public virtual Peanut Peanut {
get { return _peanut; }
}
/// <summary>
/// Ruft das Mitglied ab, welches an dem Peanut teilnimmt.
/// </summary>
public virtual UserGroupMembership UserGroupMembership {
get { return _userGroupMembership; }
}
public virtual PeanutParticipationDto GetDto() {
return new PeanutParticipationDto(_participationType, _participationState);
}
/// <summary>
/// Ändert den Status der Teilnahme.
/// </summary>
/// <param name="participationState"></param>
public virtual void UpdateStatus(PeanutParticipationState participationState, EntityChangedDto entityChanged) {
Require.NotNull(entityChanged, "entityChanged");
_participationState = participationState;
Update(entityChanged);
}
private void Update(PeanutParticipationDto participationDto) {
_participationType = participationDto.ParticipationType;
_participationState = participationDto.ParticipationState;
}
private void Update(EntityChangedDto entityChanged) {
_changedAt = entityChanged.ChangedAt;
_changedBy = entityChanged.ChangedBy;
}
public virtual void Update(PeanutParticipationDto peanutParticipationDto, EntityChangedDto entityChangedDto) {
Update(peanutParticipationDto);
Update(entityChangedDto);
}
}
} | 34.65625 | 168 | 0.623084 | [
"MIT"
] | queoGmbH/peanuts | Peanuts.Net.Core/src/Domain/Peanuts/PeanutParticipation.cs | 4,442 | C# |
using Microsoft.OpenApi.Models;
namespace OrderService
{
/// <summary>
/// Parameter without body.
/// </summary>
public class NonBodyParameter : OpenApiParameter
{
/// <summary>
/// Default.
/// </summary>
public object Default { get; set; }
}
} | 20.266667 | 52 | 0.5625 | [
"MIT"
] | Burgyn/MMLib.SwaggerForOcelot | demo/OrderService/NonBodyParameter.cs | 306 | C# |
using System;
using System.IO;
using Newtonsoft.Json;
using OlibUI.Sample.Structures;
namespace OlibUI.Sample
{
public static class FileSettings
{
public static Settings LoadSettings() => JsonConvert.DeserializeObject<Settings>(File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "settings.json"));
public static void SaveSettings() => File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "settings.json", JsonConvert.SerializeObject(Program.Settings));
}
}
| 33.266667 | 167 | 0.765531 | [
"MIT"
] | Onebeld/OlibUI | src/OlibUI.Sample/FileSettings.cs | 501 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace demo {
public class TestApi {
public string Url { get; set; } = "";
}
}
| 15 | 46 | 0.594444 | [
"MIT"
] | dpzsoft/dotnet-core-dpz2-json | demo/TestApi.cs | 182 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// alipay.multimedia.xnnmini.model.create
/// </summary>
public class AlipayMultimediaXnnminiModelCreateRequest : IAlipayRequest<AlipayMultimediaXnnminiModelCreateResponse>
{
/// <summary>
/// xnn小程序创建模型
/// </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.multimedia.xnnmini.model.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.081301 | 119 | 0.551955 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayMultimediaXnnminiModelCreateRequest.cs | 2,855 | C# |
using droid.Editor.Windows;
using droid.Runtime.Prototyping.Actuators;
using droid.Runtime.ScriptableObjects;
using UnityEngine;
#if UNITY_EDITOR
using droid.Runtime.Prototyping.Actors;
using UnityEditor;
namespace droid.Editor.ScriptableObjects {
/// <summary>
///
/// </summary>
public static class CreatePlayerMotions {
/// <summary>
///
/// </summary>
[MenuItem(EditorScriptableObjectMenuPath._ScriptableObjectMenuPath + "PlayerMotions")]
public static void CreatePlayerMotionsAsset() {
var asset = ScriptableObject.CreateInstance<PlayerMotions>();
AssetDatabase.CreateAsset(asset, EditorWindowMenuPath._NewAssetPath + "NewPlayerMotions.asset");
AssetDatabase.SaveAssets();
EditorUtility.FocusProjectWindow();
Selection.activeObject = asset;
}
/// <summary>
///
/// </summary>
public class CreatePlayerMotionsWizard : ScriptableWizard {
const float WINDOW_WIDTH = 260, WINDOW_HEIGHT = 500;
[MenuItem(EditorScriptableObjectMenuPath._ScriptableObjectMenuPath + "PlayerMotions (Wizard)")]
private static void Init() {
var window = CreateWindow<CreatePlayerMotionsWizard>("Create Player Motions...");
window.Show();
}
private void Awake() {
var icon =
AssetDatabase.LoadAssetAtPath<Texture2D>(NeodroidSettings.Current.NeodroidImportLocationProp
+ "Gizmos/Icons/table.png");
this.minSize = this.maxSize = new Vector2(WINDOW_WIDTH, WINDOW_HEIGHT);
this.titleContent = new GUIContent(this.titleContent.text, icon);
}
/// <summary>
///
/// </summary>
[Header("Actuators to generate motions for")]
public Actor[] actors;
private void OnWizardCreate() {
var asset = CreateInstance<PlayerMotions>();
int motionCount = 0;
foreach (var actor in this.actors) {
foreach (var actuator in actor.Actuators) {
motionCount += ((Actuator)actuator.Value).InnerMotionNames.Length;
}
}
asset._Motions = new PlayerMotion[motionCount];
int i = 0;
foreach (var actor in this.actors) {
foreach (var actuator in actor.Actuators) {
for (int j = 0; j < ((Actuator)actuator.Value).InnerMotionNames.Length; j++, i++) {
asset._Motions[i] = new PlayerMotion {
_Actor = actor.Identifier,
_Actuator = ((Actuator)actuator.Value)
.InnerMotionNames[j]
};
}
}
}
AssetDatabase.CreateAsset(asset, EditorWindowMenuPath._NewAssetPath + "NewPlayerMotions.asset");
AssetDatabase.SaveAssets();
EditorUtility.FocusProjectWindow();
Selection.activeObject = asset;
}
}
}
}
#endif
| 33.666667 | 104 | 0.5967 | [
"Apache-2.0"
] | sintefneodroid/droid | Editor/ScriptableObjects/PlayerMotions.cs | 3,032 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Aspose Pty Ltd" file="ViewResult.cs">
// Copyright (c) 2003-2021 Aspose Pty Ltd
// </copyright>
// <summary>
// 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.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace GroupDocs.Viewer.Cloud.Sdk.Model
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
/// <summary>
/// View result information
/// </summary>
public class ViewResult
{
/// <summary>
/// View result pages
/// </summary>
public List<PageView> Pages { get; set; }
/// <summary>
/// Attachments
/// </summary>
public List<AttachmentView> Attachments { get; set; }
/// <summary>
/// ULR to retrieve file.
/// </summary>
public Resource File { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ViewResult {\n");
sb.Append(" Pages: ").Append(this.Pages).Append("\n");
sb.Append(" Attachments: ").Append(this.Attachments).Append("\n");
sb.Append(" File: ").Append(this.File).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
}
}
| 39.569444 | 119 | 0.581257 | [
"MIT"
] | groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet | src/GroupDocs.Viewer.Cloud.Sdk/Model/ViewResult.cs | 2,849 | C# |
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace Retro.Grid
{
[CustomEditor(typeof(Line))]
public class LineInspector : Editor
{
private static bool _bMoveStart;
private static bool _bMoveEnd;
public override void OnInspectorGUI()
{
Line myLine = (Line)target;
DrawDefaultInspector();
}
}
} | 20.761905 | 46 | 0.573394 | [
"MIT"
] | RetroZelda/retrolib-unity | RetroLib-Unity/Assets/Scripts/RetroLib/RetroGrid/Editor/LineInspector.cs | 438 | C# |
/*
Copyright (c) 2018, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using MatterHackers.Agg.UI;
using MatterHackers.DataConverters3D;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.PartPreviewWindow;
using MatterHackers.RenderOpenGl;
using MatterHackers.VectorMath;
using Newtonsoft.Json;
namespace MatterHackers.MatterControl.DesignTools.Operations
{
public class ScaleObject3D : TransformWrapperObject3D, IEditorDraw, IPropertyGridModifier
{
public enum ScaleType
{
Specify,
Inches_to_mm,
mm_to_Inches,
mm_to_cm,
cm_to_mm
}
public ScaleObject3D()
{
Name = "Scale".Localize();
}
public ScaleObject3D(IObject3D item, double x = 1, double y = 1, double z = 1)
: this(item, new Vector3(x, y, z))
{
}
public ScaleObject3D(IObject3D itemToScale, Vector3 scale)
: this()
{
WrapItems(new IObject3D[] { itemToScale });
ScaleRatio = scale;
Rebuild();
}
public override void WrapItems(IEnumerable<IObject3D> items, UndoBuffer undoBuffer = null)
{
base.WrapItems(items, undoBuffer);
// use source item as it may be a copy of item by the time we have wrapped it
var aabb = UntransformedChildren.GetAxisAlignedBoundingBox();
var newCenter = new Vector3(aabb.Center.X, aabb.Center.Y, aabb.MinXYZ.Z);
UntransformedChildren.Translate(-newCenter);
this.Translate(newCenter);
}
// this is the size we actually serialize
public Vector3 ScaleRatio = Vector3.One;
public ScaleType Operation { get; set; } = ScaleType.Specify;
[JsonIgnore]
[DisplayName("Width")]
public double SizeX
{
get
{
if (UsePercentage)
{
return ScaleRatio.X * 100;
}
return ScaleRatio.X * UntransformedChildren.GetAxisAlignedBoundingBox().XSize;
}
set
{
if (UsePercentage)
{
ScaleRatio.X = value / 100;
}
else
{
ScaleRatio.X = value / UntransformedChildren.GetAxisAlignedBoundingBox().XSize;
}
}
}
[JsonIgnore]
[DisplayName("Depth")]
public double SizeY
{
get
{
if (UsePercentage)
{
return ScaleRatio.Y * 100;
}
return ScaleRatio.Y * UntransformedChildren.GetAxisAlignedBoundingBox().YSize;
}
set
{
if (UsePercentage)
{
ScaleRatio.Y = value / 100;
}
else
{
ScaleRatio.Y = value / UntransformedChildren.GetAxisAlignedBoundingBox().YSize;
}
}
}
[JsonIgnore]
[DisplayName("Height")]
public double SizeZ
{
get
{
if (UsePercentage)
{
return ScaleRatio.Z * 100;
}
return ScaleRatio.Z * UntransformedChildren.GetAxisAlignedBoundingBox().ZSize;
}
set
{
if (UsePercentage)
{
ScaleRatio.Z = value / 100;
}
else
{
ScaleRatio.Z = value / UntransformedChildren.GetAxisAlignedBoundingBox().ZSize;
}
}
}
[Description("Ensure that the part maintains its proportions.")]
[DisplayName("Maintain Proportions")]
public bool MaitainProportions { get; set; } = true;
[Description("Toggle between specifying the size or the percentage to scale.")]
public bool UsePercentage { get; set; }
[Description("This is the position to perform the scale about.")]
public Vector3 ScaleAbout { get; set; }
public void DrawEditor(Object3DControlsLayer layer, List<Object3DView> transparentMeshes, DrawEventArgs e)
{
if (layer.Scene.SelectedItem != null
&& layer.Scene.SelectedItem.DescendantsAndSelf().Where((i) => i == this).Any())
{
layer.World.RenderAxis(ScaleAbout, this.WorldMatrix(), 30, 1);
}
}
public async override void OnInvalidate(InvalidateArgs invalidateArgs)
{
if ((invalidateArgs.InvalidateType.HasFlag(InvalidateType.Children)
|| invalidateArgs.InvalidateType.HasFlag(InvalidateType.Matrix)
|| invalidateArgs.InvalidateType.HasFlag(InvalidateType.Mesh))
&& invalidateArgs.Source != this
&& !RebuildLocked)
{
await Rebuild();
}
else if (invalidateArgs.InvalidateType.HasFlag(InvalidateType.Properties)
&& invalidateArgs.Source == this)
{
await Rebuild();
}
else
{
base.OnInvalidate(invalidateArgs);
}
}
public override Task Rebuild()
{
this.DebugDepth("Rebuild");
using (RebuildLock())
{
using (new CenterAndHeightMaintainer(this))
{
// set the matrix for the transform object
ItemWithTransform.Matrix = Matrix4X4.Identity;
ItemWithTransform.Matrix *= Matrix4X4.CreateTranslation(-ScaleAbout);
ItemWithTransform.Matrix *= Matrix4X4.CreateScale(ScaleRatio);
ItemWithTransform.Matrix *= Matrix4X4.CreateTranslation(ScaleAbout);
}
}
Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Matrix));
return Task.CompletedTask;
}
public void UpdateControls(PublicPropertyChange change)
{
change.SetRowVisible(nameof(SizeX), () => Operation == ScaleType.Specify);
change.SetRowVisible(nameof(SizeY), () => Operation == ScaleType.Specify);
change.SetRowVisible(nameof(SizeZ), () => Operation == ScaleType.Specify);
change.SetRowVisible(nameof(MaitainProportions), () => Operation == ScaleType.Specify);
change.SetRowVisible(nameof(UsePercentage), () => Operation == ScaleType.Specify);
change.SetRowVisible(nameof(ScaleAbout), () => Operation == ScaleType.Specify);
if (change.Changed == nameof(Operation))
{
// recalculate the scaling
double scale = 1;
switch (Operation)
{
case ScaleType.Inches_to_mm:
scale = 25.4;
break;
case ScaleType.mm_to_Inches:
scale = .0393;
break;
case ScaleType.mm_to_cm:
scale = .1;
break;
case ScaleType.cm_to_mm:
scale = 10;
break;
}
ScaleRatio = new Vector3(scale, scale, scale);
Rebuild();
}
else if (change.Changed == nameof(UsePercentage))
{
// make sure we update the controls on screen to reflect the different data type
Invalidate(new InvalidateArgs(null, InvalidateType.DisplayValues));
}
else if (change.Changed == nameof(MaitainProportions))
{
if (MaitainProportions)
{
var maxScale = Math.Max(ScaleRatio.X, Math.Max(ScaleRatio.Y, ScaleRatio.Z));
ScaleRatio = new Vector3(maxScale, maxScale, maxScale);
Rebuild();
// make sure we update the controls on screen to reflect the different data type
Invalidate(new InvalidateArgs(null, InvalidateType.DisplayValues));
}
}
else if (change.Changed == nameof(SizeX))
{
if (MaitainProportions)
{
// scale y and z to match
ScaleRatio[1] = ScaleRatio[0];
ScaleRatio[2] = ScaleRatio[0];
Rebuild();
// and invalidate the other properties
Invalidate(new InvalidateArgs(this, InvalidateType.Properties));
// then update the display values
Invalidate(new InvalidateArgs(null, InvalidateType.DisplayValues));
}
}
else if (change.Changed == nameof(SizeY))
{
if (MaitainProportions)
{
// scale y and z to match
ScaleRatio[0] = ScaleRatio[1];
ScaleRatio[2] = ScaleRatio[1];
Rebuild();
// and invalidate the other properties
Invalidate(new InvalidateArgs(this, InvalidateType.Properties));
// then update the display values
Invalidate(new InvalidateArgs(null, InvalidateType.DisplayValues));
}
}
else if (change.Changed == nameof(SizeZ))
{
if (MaitainProportions)
{
// scale y and z to match
ScaleRatio[0] = ScaleRatio[2];
ScaleRatio[1] = ScaleRatio[2];
Rebuild();
// and invalidate the other properties
Invalidate(new InvalidateArgs(this, InvalidateType.Properties));
// then update the display values
Invalidate(new InvalidateArgs(null, InvalidateType.DisplayValues));
}
}
}
}
} | 28.612308 | 108 | 0.702441 | [
"BSD-2-Clause"
] | MrnB/MatterControl | MatterControlLib/DesignTools/Operations/ScaleObject3D.cs | 9,301 | C# |
namespace commercetools.Sdk.Linq.Discount
{
public interface IDiscountPredicateExpressionVisitor : IPredicateExpressionVisitor
{
}
} | 24.166667 | 86 | 0.786207 | [
"Apache-2.0"
] | commercetools/commercetools-dotnet-core-sdk | commercetools.Sdk/commercetools.Sdk.Linq/Discount/IDiscountPredicateExpressionVisitor.cs | 147 | C# |
using Machine.Specifications;
namespace Dolittle.Queries.Validation.Specs.for_QueryArgumentValidationResult
{
public class when_asking_for_success_on_result_without_any_broken_rules : given.a_query_argument_validation_result_without_any_broken_rules
{
static bool success;
Because of = () => success = result.Success;
It should_be_considered_successful = () => success.ShouldBeTrue();
}
}
| 30.642857 | 143 | 0.7669 | [
"MIT"
] | dolittle-einar/Runtime | Specifications/Queries.Validation/for_QueryArgumentValidationResult/when_asking_for_success_on_result_without_any_broken_rules.cs | 431 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hoppy_GroundControl : MonoBehaviour
{
public float movementSpeed = 1;
public float resetPosition_x;
public bool moving = false;
Vector3 startPos;
// Start is called before the first frame update
void Start()
{
startPos = transform.position;
}
// Update is called once per frame
void Update()
{
if (moving)
transform.Translate(new Vector3(-Time.deltaTime * movementSpeed, 0, 0));
if (transform.position.x <= resetPosition_x)
transform.position = startPos;
}
}
| 24.074074 | 84 | 0.66 | [
"MIT"
] | JinguMastery/My-Unity-Project-OSMCity | Assets/Noedify/Demos/HoppyGame/Scripts/Hoppy_GroundControl.cs | 652 | C# |
using System;
using MixERP.Net.FrontEnd.Base;
namespace MixERP.Net.Core.Modules.BackOffice.Policy
{
public partial class DefaultEntityAccess : MixERPUserControl
{
public override void OnControlLoad(object sender, EventArgs e)
{
}
}
} | 22.583333 | 70 | 0.697417 | [
"MPL-2.0"
] | asine/mixerp | src/FrontEnd/Modules/BackOffice/Policy/DefaultEntityAccess.ascx.cs | 273 | C# |
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using PortingAssistant.Client.Model;
using PortingAssistant.Client.PortingProjectFile;
namespace PortingAssistant.Client.Porting
{
public class PortingHandler : IPortingHandler
{
private readonly ILogger _logger;
private readonly IPortingProjectFileHandler _portingProjectFileHandler;
/// <summary>
/// Create an Instance of a PortingHandler
/// </summary>
/// <param name="logger">An ILogger object</param>
/// <param name="portingProjectFileHandler">A instance of a handler object to run the porting</param>
public PortingHandler(ILogger<PortingHandler> logger, IPortingProjectFileHandler portingProjectFileHandler)
{
_logger = logger;
_portingProjectFileHandler = portingProjectFileHandler;
}
/// <summary>
/// Ports a list of projects
/// </summary>
/// <param name="projectPaths">List of projects paths</param>
/// <param name="solutionPath">Path to solution file</param>
/// <param name="targetFramework">Target framework to be used when porting</param>
/// <param name="upgradeVersions">List of key/value pairs where key is package and value is version number</param>
/// <returns>A PortingProjectFileResult object, representing the result of the porting operation</returns>
public List<PortingResult> ApplyPortProjectFileChanges(
List<string> projectPaths, string solutionPath, string targetFramework,
Dictionary<string, string> upgradeVersions)
{
return _portingProjectFileHandler.ApplyProjectChanges(projectPaths, solutionPath, targetFramework, upgradeVersions);
}
}
}
| 44.073171 | 128 | 0.696735 | [
"Apache-2.0"
] | eduherminio/porting-assistant-dotnet-client | src/PortingAssistant.Client.Porting/PortingHandler.cs | 1,809 | C# |
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
namespace Fluid.Ast
{
public class WhenStatement : TagStatement
{
private readonly List<Expression> _options;
public WhenStatement(List<Expression> options, List<Statement> statements) : base(statements)
{
_options = options;
}
public List<Expression> Options
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _options;
}
public override async Task<Completion> WriteToAsync(TextWriter writer, TextEncoder encoder, TemplateContext context)
{
// Process statements until next block or end of statements
for (var index = 0; index < Statements.Count; index++)
{
var completion = await Statements[index].WriteToAsync(writer, encoder, context);
if (completion != Completion.Normal)
{
// Stop processing the block statements
// We return the completion to flow it to the outer loop
return completion;
}
}
return Completion.Normal;
}
}
}
| 29.840909 | 124 | 0.597867 | [
"MIT"
] | tgrandgent/fluid | Fluid/Ast/WhenStatement.cs | 1,315 | C# |
/*
MIT LICENSE
Copyright 2017 Digital Ruby, LLC - http://www.digitalruby.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ExchangeSharp
{
public sealed partial class ExchangeBinanceAPI : ExchangeAPI
{
public override string BaseUrl { get; set; } = "https://api.binance.com/api/v1";
public override string BaseUrlWebSocket { get; set; } = "wss://stream.binance.com:9443";
public string BaseUrlPrivate { get; set; } = "https://api.binance.com/api/v3";
public string WithdrawalUrlPrivate { get; set; } = "https://api.binance.com/wapi/v3";
public override string Name => ExchangeName.Binance;
static ExchangeBinanceAPI()
{
ExchangeGlobalCurrencyReplacements[typeof(ExchangeBinanceAPI)] = new KeyValuePair<string, string>[]
{
new KeyValuePair<string, string>("BCC", "BCH")
};
}
private string GetWebSocketStreamUrlForSymbols(string suffix, params string[] symbols)
{
if (symbols == null || symbols.Length == 0)
{
symbols = GetSymbols().ToArray();
}
StringBuilder streams = new StringBuilder("/stream?streams=");
for (int i = 0; i < symbols.Length; i++)
{
string symbol = NormalizeSymbol(symbols[i]).ToLowerInvariant();
streams.Append(symbol);
streams.Append(suffix);
streams.Append('/');
}
streams.Length--; // remove last /
return streams.ToString();
}
public ExchangeBinanceAPI()
{
// give binance plenty of room to accept requests
RequestWindow = TimeSpan.FromMinutes(15.0);
NonceStyle = NonceStyle.UnixMilliseconds;
NonceOffset = TimeSpan.FromSeconds(10.0);
SymbolSeparator = string.Empty;
SymbolIsReversed = true;
}
public override string NormalizeSymbol(string symbol)
{
return (symbol ?? string.Empty).Replace("-", string.Empty).Replace("_", string.Empty).Replace("/", string.Empty).ToUpperInvariant();
}
public override string ExchangeSymbolToGlobalSymbol(string symbol)
{
// All pairs in Binance end with BTC, ETH, BNB or USDT
if (symbol.EndsWith("BTC") || symbol.EndsWith("ETH") || symbol.EndsWith("BNB"))
{
string baseSymbol = symbol.Substring(symbol.Length - 3);
return ExchangeSymbolToGlobalSymbolWithSeparator((symbol.Replace(baseSymbol, "") + GlobalSymbolSeparator + baseSymbol), GlobalSymbolSeparator);
}
if (symbol.EndsWith("USDT"))
{
string baseSymbol = symbol.Substring(symbol.Length - 4);
return ExchangeSymbolToGlobalSymbolWithSeparator((symbol.Replace(baseSymbol, "") + GlobalSymbolSeparator + baseSymbol), GlobalSymbolSeparator);
}
return ExchangeSymbolToGlobalSymbolWithSeparator(symbol.Substring(0, symbol.Length - 3) + GlobalSymbolSeparator + (symbol.Substring(symbol.Length - 3, 3)), GlobalSymbolSeparator);
}
/// <summary>
/// Get the details of all trades
/// </summary>
/// <param name="symbol">Symbol to get trades for or null for all</param>
/// <param name="afterDate">Only returns trades on or after the specified date/time</param>
/// <returns>All trades for the specified symbol, or all if null symbol</returns>
public IEnumerable<ExchangeOrderResult> GetMyTrades(string symbol = null, DateTime? afterDate = null) => GetMyTradesAsync(symbol, afterDate).GetAwaiter().GetResult();
/// <summary>
/// ASYNC - Get the details of all trades
/// </summary>
/// <param name="symbol">Symbol to get trades for or null for all</param>
/// <returns>All trades for the specified symbol, or all if null symbol</returns>
public async Task<IEnumerable<ExchangeOrderResult>> GetMyTradesAsync(string symbol = null, DateTime? afterDate = null)
{
await new SynchronizationContextRemover();
return await OnGetMyTradesAsync(symbol, afterDate);
}
protected override async Task<IEnumerable<string>> OnGetSymbolsAsync()
{
if (ReadCache("GetSymbols", out List<string> symbols))
{
return symbols;
}
symbols = new List<string>();
JToken obj = await MakeJsonRequestAsync<JToken>("/ticker/allPrices");
foreach (JToken token in obj)
{
// bug I think in the API returns numbers as symbol names... WTF.
string symbol = token["symbol"].ToStringInvariant();
if (!long.TryParse(symbol, out long tmp))
{
symbols.Add(symbol);
}
}
WriteCache("GetSymbols", TimeSpan.FromMinutes(60.0), symbols);
return symbols;
}
protected override async Task<IEnumerable<ExchangeMarket>> OnGetSymbolsMetadataAsync()
{
/*
* {
"symbol": "QTUMETH",
"status": "TRADING",
"baseAsset": "QTUM",
"baseAssetPrecision": 8,
"quoteAsset": "ETH",
"quotePrecision": 8,
"orderTypes": [
"LIMIT",
"LIMIT_MAKER",
"MARKET",
"STOP_LOSS_LIMIT",
"TAKE_PROFIT_LIMIT"
],
"icebergAllowed": true,
"filters": [
{
"filterType": "PRICE_FILTER",
"minPrice": "0.00000100",
"maxPrice": "100000.00000000",
"tickSize": "0.00000100"
},
{
"filterType": "LOT_SIZE",
"minQty": "0.01000000",
"maxQty": "90000000.00000000",
"stepSize": "0.01000000"
},
{
"filterType": "MIN_NOTIONAL",
"minNotional": "0.01000000"
}
]
},
*/
var markets = new List<ExchangeMarket>();
JToken obj = await MakeJsonRequestAsync<JToken>("/exchangeInfo");
JToken allSymbols = obj["symbols"];
foreach (JToken symbol in allSymbols)
{
var market = new ExchangeMarket
{
MarketName = symbol["symbol"].ToStringUpperInvariant(),
IsActive = ParseMarketStatus(symbol["status"].ToStringUpperInvariant()),
BaseCurrency = symbol["quoteAsset"].ToStringUpperInvariant(),
MarketCurrency = symbol["baseAsset"].ToStringUpperInvariant()
};
// "LOT_SIZE"
JToken filters = symbol["filters"];
JToken lotSizeFilter = filters?.FirstOrDefault(x => string.Equals(x["filterType"].ToStringUpperInvariant(), "LOT_SIZE"));
if (lotSizeFilter != null)
{
market.MaxTradeSize = lotSizeFilter["maxQty"].ConvertInvariant<decimal>();
market.MinTradeSize = lotSizeFilter["minQty"].ConvertInvariant<decimal>();
market.QuantityStepSize = lotSizeFilter["stepSize"].ConvertInvariant<decimal>();
}
// PRICE_FILTER
JToken priceFilter = filters?.FirstOrDefault(x => string.Equals(x["filterType"].ToStringUpperInvariant(), "PRICE_FILTER"));
if (priceFilter != null)
{
market.MaxPrice = priceFilter["maxPrice"].ConvertInvariant<decimal>();
market.MinPrice = priceFilter["minPrice"].ConvertInvariant<decimal>();
market.PriceStepSize = priceFilter["tickSize"].ConvertInvariant<decimal>();
}
markets.Add(market);
}
return markets;
}
protected override Task<IReadOnlyDictionary<string, ExchangeCurrency>> OnGetCurrenciesAsync()
{
throw new NotSupportedException("Binance does not provide data about its currencies via the API");
}
protected override async Task<ExchangeTicker> OnGetTickerAsync(string symbol)
{
symbol = NormalizeSymbol(symbol);
JToken obj = await MakeJsonRequestAsync<JToken>("/ticker/24hr?symbol=" + symbol);
return ParseTicker(symbol, obj);
}
protected override async Task<IEnumerable<KeyValuePair<string, ExchangeTicker>>> OnGetTickersAsync()
{
List<KeyValuePair<string, ExchangeTicker>> tickers = new List<KeyValuePair<string, ExchangeTicker>>();
string symbol;
JToken obj = await MakeJsonRequestAsync<JToken>("/ticker/24hr");
foreach (JToken child in obj)
{
symbol = child["symbol"].ToStringInvariant();
tickers.Add(new KeyValuePair<string, ExchangeTicker>(symbol, ParseTicker(symbol, child)));
}
return tickers;
}
protected override IWebSocket OnGetTickersWebSocket(Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)
{
if (callback == null)
{
return null;
}
return ConnectWebSocket("/stream?streams=!ticker@arr", (msg, _socket) =>
{
try
{
JToken token = JToken.Parse(msg.UTF8String());
List<KeyValuePair<string, ExchangeTicker>> tickerList = new List<KeyValuePair<string, ExchangeTicker>>();
ExchangeTicker ticker;
foreach (JToken childToken in token["data"])
{
ticker = ParseTickerWebSocket(childToken);
tickerList.Add(new KeyValuePair<string, ExchangeTicker>(ticker.Volume.BaseSymbol, ticker));
}
if (tickerList.Count != 0)
{
callback(tickerList);
}
}
catch
{
}
});
}
protected override IWebSocket OnGetTradesWebSocket(Action<KeyValuePair<string, ExchangeTrade>> callback, params string[] symbols)
{
if (callback == null)
{
return null;
}
/*
{
"e": "trade", // Event type
"E": 123456789, // Event time
"s": "BNBBTC", // Symbol
"t": 12345, // Trade ID
"p": "0.001", // Price
"q": "100", // Quantity
"b": 88, // Buyer order Id
"a": 50, // Seller order Id
"T": 123456785, // Trade time
"m": true, // Is the buyer the market maker?
"M": true // Ignore.
}
*/
string url = GetWebSocketStreamUrlForSymbols("@trade", symbols);
return ConnectWebSocket(url, (msg, _socket) =>
{
try
{
JToken token = JToken.Parse(msg.UTF8String());
string name = token["stream"].ToStringInvariant();
token = token["data"];
string symbol = NormalizeSymbol(name.Substring(0, name.IndexOf('@')));
// buy=0 -> m = true (The buyer is maker, while the seller is taker).
// buy=1 -> m = false(The seller is maker, while the buyer is taker).
ExchangeTrade trade = new ExchangeTrade
{
Amount = token["q"].ConvertInvariant<decimal>(),
Id = token["t"].ConvertInvariant<long>(),
IsBuy = !token["m"].ConvertInvariant<bool>(),
Price = token["p"].ConvertInvariant<decimal>(),
Timestamp = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(token["E"].ConvertInvariant<long>())
};
callback(new KeyValuePair<string, ExchangeTrade>(symbol, trade));
}
catch
{
}
});
}
protected override IWebSocket OnGetOrderBookDeltasWebSocket(Action<ExchangeOrderBook> callback, int maxCount = 20, params string[] symbols)
{
if (callback == null || symbols == null || !symbols.Any())
{
return null;
}
string combined = string.Join("/", symbols.Select(s => this.NormalizeSymbol(s).ToLowerInvariant() + "@depth"));
return ConnectWebSocket($"/stream?streams={combined}", (msg, _socket) =>
{
try
{
string json = msg.UTF8String();
var update = JsonConvert.DeserializeObject<BinanceMultiDepthStream>(json);
string symbol = update.Data.Symbol;
ExchangeOrderBook book = new ExchangeOrderBook { SequenceId = update.Data.FinalUpdate, Symbol = symbol };
foreach (List<object> ask in update.Data.Asks)
{
var depth = new ExchangeOrderPrice { Price = ask[0].ConvertInvariant<decimal>(), Amount = ask[1].ConvertInvariant<decimal>() };
book.Asks[depth.Price] = depth;
}
foreach (List<object> bid in update.Data.Bids)
{
var depth = new ExchangeOrderPrice { Price = bid[0].ConvertInvariant<decimal>(), Amount = bid[1].ConvertInvariant<decimal>() };
book.Bids[depth.Price] = depth;
}
callback(book);
}
catch
{
}
});
}
protected override async Task<ExchangeOrderBook> OnGetOrderBookAsync(string symbol, int maxCount = 100)
{
symbol = NormalizeSymbol(symbol);
JToken obj = await MakeJsonRequestAsync<JToken>("/depth?symbol=" + symbol + "&limit=" + maxCount);
return ExchangeAPIExtensions.ParseOrderBookFromJTokenArrays(obj, sequence: "lastUpdateId", maxCount: maxCount);
}
protected override async Task OnGetHistoricalTradesAsync(Func<IEnumerable<ExchangeTrade>, bool> callback, string symbol, DateTime? startDate = null, DateTime? endDate = null)
{
/* [ {
"a": 26129, // Aggregate tradeId
"p": "0.01633102", // Price
"q": "4.70443515", // Quantity
"f": 27781, // First tradeId
"l": 27781, // Last tradeId
"T": 1498793709153, // Timestamp
"m": true, // Was the buyer the maker?
"M": true // Was the trade the best price match?
} ] */
HistoricalTradeHelperState state = new HistoricalTradeHelperState(this)
{
Callback = callback,
EndDate = endDate,
ParseFunction = (JToken token) =>
{
DateTime timestamp = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(token["T"].ConvertInvariant<long>());
return new ExchangeTrade
{
Amount = token["q"].ConvertInvariant<decimal>(),
Price = token["p"].ConvertInvariant<decimal>(),
Timestamp = timestamp,
Id = token["a"].ConvertInvariant<long>(),
IsBuy = token["m"].ConvertInvariant<bool>()
};
},
StartDate = startDate,
Symbol = symbol,
TimestampFunction = (DateTime dt) => ((long)CryptoUtility.UnixTimestampFromDateTimeMilliseconds(dt)).ToStringInvariant(),
Url = "/aggTrades?symbol=[symbol]&startTime={0}&endTime={1}",
};
await state.ProcessHistoricalTrades();
}
protected override async Task<IEnumerable<MarketCandle>> OnGetCandlesAsync(string symbol, int periodSeconds, DateTime? startDate = null, DateTime? endDate = null, int? limit = null)
{
/* [
[
1499040000000, // Open time
"0.01634790", // Open
"0.80000000", // High
"0.01575800", // Low
"0.01577100", // Close
"148976.11427815", // Volume
1499644799999, // Close time
"2434.19055334", // Quote asset volume
308, // Number of trades
"1756.87402397", // Taker buy base asset volume
"28.46694368", // Taker buy quote asset volume
"17928899.62484339" // Can be ignored
]] */
List<MarketCandle> candles = new List<MarketCandle>();
symbol = NormalizeSymbol(symbol);
string url = "/klines?symbol=" + symbol;
if (startDate != null)
{
url += "&startTime=" + (long)startDate.Value.UnixTimestampFromDateTimeMilliseconds();
url += "&endTime=" + ((endDate == null ? long.MaxValue : (long)endDate.Value.UnixTimestampFromDateTimeMilliseconds())).ToStringInvariant();
}
if (limit != null)
{
url += "&limit=" + (limit.Value.ToStringInvariant());
}
string periodString = CryptoUtility.SecondsToPeriodString(periodSeconds);
url += "&interval=" + periodString;
JToken obj = await MakeJsonRequestAsync<JToken>(url);
foreach (JArray array in obj)
{
candles.Add(new MarketCandle
{
ClosePrice = array[4].ConvertInvariant<decimal>(),
ExchangeName = Name,
HighPrice = array[2].ConvertInvariant<decimal>(),
LowPrice = array[3].ConvertInvariant<decimal>(),
Name = symbol,
OpenPrice = array[1].ConvertInvariant<decimal>(),
PeriodSeconds = periodSeconds,
Timestamp = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(array[0].ConvertInvariant<long>()),
BaseVolume = array[5].ConvertInvariant<double>(),
ConvertedVolume = array[7].ConvertInvariant<double>(),
WeightedAverage = 0m
});
}
return candles;
}
protected override async Task<Dictionary<string, decimal>> OnGetAmountsAsync()
{
JToken token = await MakeJsonRequestAsync<JToken>("/account", BaseUrlPrivate, await OnGetNoncePayloadAsync());
Dictionary<string, decimal> balances = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);
foreach (JToken balance in token["balances"])
{
decimal amount = balance["free"].ConvertInvariant<decimal>() + balance["locked"].ConvertInvariant<decimal>();
if (amount > 0m)
{
balances[balance["asset"].ToStringInvariant()] = amount;
}
}
return balances;
}
protected override async Task<Dictionary<string, decimal>> OnGetAmountsAvailableToTradeAsync()
{
JToken token = await MakeJsonRequestAsync<JToken>("/account", BaseUrlPrivate, await OnGetNoncePayloadAsync());
Dictionary<string, decimal> balances = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);
foreach (JToken balance in token["balances"])
{
decimal amount = balance["free"].ConvertInvariant<decimal>();
if (amount > 0m)
{
balances[balance["asset"].ToStringInvariant()] = amount;
}
}
return balances;
}
protected override async Task<ExchangeOrderResult> OnPlaceOrderAsync(ExchangeOrderRequest order)
{
string symbol = NormalizeSymbol(order.Symbol);
Dictionary<string, object> payload = await OnGetNoncePayloadAsync();
payload["symbol"] = symbol;
payload["side"] = order.IsBuy ? "BUY" : "SELL";
payload["type"] = order.OrderType.ToStringUpperInvariant();
// Binance has strict rules on which prices and quantities are allowed. They have to match the rules defined in the market definition.
decimal outputQuantity = await ClampOrderQuantity(symbol, order.Amount);
decimal outputPrice = await ClampOrderPrice(symbol, order.Price);
// Binance does not accept quantities with more than 20 decimal places.
payload["quantity"] = Math.Round(outputQuantity, 20);
payload["newOrderRespType"] = "FULL";
if (order.OrderType != OrderType.Market)
{
payload["timeInForce"] = "GTC";
payload["price"] = outputPrice;
}
order.ExtraParameters.CopyTo(payload);
JToken token = await MakeJsonRequestAsync<JToken>("/order", BaseUrlPrivate, payload, "POST");
return ParseOrder(token);
}
protected override async Task<ExchangeOrderResult> OnGetOrderDetailsAsync(string orderId, string symbol = null)
{
Dictionary<string, object> payload = await OnGetNoncePayloadAsync();
if (string.IsNullOrEmpty(symbol))
{
throw new InvalidOperationException("Binance single order details request requires symbol");
}
symbol = NormalizeSymbol(symbol);
payload["symbol"] = symbol;
payload["orderId"] = orderId;
JToken token = await MakeJsonRequestAsync<JToken>("/order", BaseUrlPrivate, payload);
ExchangeOrderResult result = ParseOrder(token);
// Add up the fees from each trade in the order
Dictionary<string, object> feesPayload = await OnGetNoncePayloadAsync();
feesPayload["symbol"] = symbol;
JToken feesToken = await MakeJsonRequestAsync<JToken>("/myTrades", BaseUrlPrivate, feesPayload);
ParseFees(feesToken, result);
return result;
}
/// <summary>Process the trades that executed as part of your order and sum the fees.</summary>
/// <param name="feesToken">The trades executed for a specific currency pair.</param>
/// <param name="result">The result object to append to.</param>
private static void ParseFees(JToken feesToken, ExchangeOrderResult result)
{
var tradesInOrder = feesToken.Where(x => x["orderId"].ToStringInvariant() == result.OrderId);
bool currencySet = false;
foreach (var trade in tradesInOrder)
{
result.Fees += trade["commission"].ConvertInvariant<decimal>();
// TODO: Not sure how to handle commissions in different currencies, for example if you run out of BNB mid-trade
if (!currencySet)
{
result.FeesCurrency = trade["commissionAsset"].ToStringInvariant();
currencySet = true;
}
}
}
protected override async Task<IEnumerable<ExchangeOrderResult>> OnGetOpenOrderDetailsAsync(string symbol = null)
{
List<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();
Dictionary<string, object> payload = await OnGetNoncePayloadAsync();
if (!string.IsNullOrWhiteSpace(symbol))
{
payload["symbol"] = NormalizeSymbol(symbol);
}
JToken token = await MakeJsonRequestAsync<JToken>("/openOrders", BaseUrlPrivate, payload);
foreach (JToken order in token)
{
orders.Add(ParseOrder(order));
}
return orders;
}
private async Task<IEnumerable<ExchangeOrderResult>> GetCompletedOrdersForAllSymbolsAsync(DateTime? afterDate)
{
// TODO: This is a HACK, Binance API needs to add a single API call to get all orders for all symbols, terrible...
List<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();
Exception ex = null;
string failedSymbol = null;
Parallel.ForEach((await GetSymbolsAsync()).Where(s => s.IndexOf("BTC", StringComparison.OrdinalIgnoreCase) >= 0), async (s) =>
{
try
{
foreach (ExchangeOrderResult order in (await GetCompletedOrderDetailsAsync(s, afterDate)))
{
lock (orders)
{
orders.Add(order);
}
}
}
catch (Exception _ex)
{
failedSymbol = s;
ex = _ex;
}
});
if (ex != null)
{
throw new APIException("Failed to get completed order details for symbol " + failedSymbol, ex);
}
// sort timestamp desc
orders.Sort((o1, o2) =>
{
return o2.OrderDate.CompareTo(o1.OrderDate);
});
return orders;
}
protected override async Task<IEnumerable<ExchangeOrderResult>> OnGetCompletedOrderDetailsAsync(string symbol = null, DateTime? afterDate = null)
{
List<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();
if (string.IsNullOrWhiteSpace(symbol))
{
orders.AddRange(await GetCompletedOrdersForAllSymbolsAsync(afterDate));
}
else
{
Dictionary<string, object> payload = await OnGetNoncePayloadAsync();
payload["symbol"] = NormalizeSymbol(symbol);
if (afterDate != null)
{
// TODO: timestamp param is causing duplicate request errors which is a bug in the Binance API
// payload["timestamp"] = afterDate.Value.UnixTimestampFromDateTimeMilliseconds();
}
JToken token = await MakeJsonRequestAsync<JToken>("/allOrders", BaseUrlPrivate, payload);
foreach (JToken order in token)
{
orders.Add(ParseOrder(order));
}
}
return orders;
}
private async Task<IEnumerable<ExchangeOrderResult>> GetMyTradesForAllSymbols(DateTime? afterDate)
{
// TODO: This is a HACK, Binance API needs to add a single API call to get all orders for all symbols, terrible...
List<ExchangeOrderResult> trades = new List<ExchangeOrderResult>();
Exception ex = null;
string failedSymbol = null;
Parallel.ForEach((await GetSymbolsAsync()).Where(s => s.IndexOf("BTC", StringComparison.OrdinalIgnoreCase) >= 0), async (s) =>
{
try
{
foreach (ExchangeOrderResult trade in (await GetMyTradesAsync(s, afterDate)))
{
lock (trades)
{
trades.Add(trade);
}
}
}
catch (Exception _ex)
{
failedSymbol = s;
ex = _ex;
}
});
if (ex != null)
{
throw new APIException("Failed to get my trades for symbol " + failedSymbol, ex);
}
// sort timestamp desc
trades.Sort((o1, o2) =>
{
return o2.OrderDate.CompareTo(o1.OrderDate);
});
return trades;
}
private async Task<IEnumerable<ExchangeOrderResult>> OnGetMyTradesAsync(string symbol = null, DateTime? afterDate = null)
{
List<ExchangeOrderResult> trades = new List<ExchangeOrderResult>();
if (string.IsNullOrWhiteSpace(symbol))
{
trades.AddRange(await GetCompletedOrdersForAllSymbolsAsync(afterDate));
}
else
{
Dictionary<string, object> payload = await OnGetNoncePayloadAsync();
payload["symbol"] = NormalizeSymbol(symbol);
if (afterDate != null)
{
payload["timestamp"] = afterDate.Value.UnixTimestampFromDateTimeMilliseconds();
}
JToken token = await MakeJsonRequestAsync<JToken>("/myTrades", BaseUrlPrivate, payload);
foreach (JToken trade in token)
{
trades.Add(ParseTrade(trade, symbol));
}
}
return trades;
}
protected override async Task OnCancelOrderAsync(string orderId, string symbol = null)
{
Dictionary<string, object> payload = await OnGetNoncePayloadAsync();
if (string.IsNullOrEmpty(symbol))
{
throw new InvalidOperationException("Binance cancel order request requires symbol");
}
payload["symbol"] = NormalizeSymbol(symbol);
payload["orderId"] = orderId;
JToken token = await MakeJsonRequestAsync<JToken>("/order", BaseUrlPrivate, payload, "DELETE");
}
/// <summary>A withdrawal request. Fee is automatically subtracted from the amount.</summary>
/// <param name="withdrawalRequest">The withdrawal request.</param>
/// <returns>Withdrawal response from Binance</returns>
protected override async Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)
{
if (string.IsNullOrWhiteSpace(withdrawalRequest.Symbol))
{
throw new ArgumentException("Symbol must be provided for Withdraw");
}
else if (string.IsNullOrWhiteSpace(withdrawalRequest.Address))
{
throw new ArgumentException("Address must be provided for Withdraw");
}
else if (withdrawalRequest.Amount <= 0)
{
throw new ArgumentException("Withdrawal amount must be positive and non-zero");
}
Dictionary<string, object> payload = await OnGetNoncePayloadAsync();
payload["asset"] = withdrawalRequest.Symbol;
payload["address"] = withdrawalRequest.Address;
payload["amount"] = withdrawalRequest.Amount;
payload["name"] = withdrawalRequest.Description ?? "apiwithdrawal"; // Contrary to what the API docs say, name is required
if (!string.IsNullOrWhiteSpace(withdrawalRequest.AddressTag))
{
payload["addressTag"] = withdrawalRequest.AddressTag;
}
JToken response = await MakeJsonRequestAsync<JToken>("/withdraw.html", WithdrawalUrlPrivate, payload, "POST");
ExchangeWithdrawalResponse withdrawalResponse = new ExchangeWithdrawalResponse
{
Id = response["id"].ToStringInvariant(),
Message = response["msg"].ToStringInvariant(),
};
return withdrawalResponse;
}
private bool ParseMarketStatus(string status)
{
bool isActive = false;
if (!string.IsNullOrWhiteSpace(status))
{
switch (status)
{
case "TRADING":
case "PRE_TRADING":
case "POST_TRADING":
isActive = true;
break;
/* case "END_OF_DAY":
case "HALT":
case "AUCTION_MATCH":
case "BREAK": */
}
}
return isActive;
}
private ExchangeTicker ParseTicker(string symbol, JToken token)
{
// {"priceChange":"-0.00192300","priceChangePercent":"-4.735","weightedAvgPrice":"0.03980955","prevClosePrice":"0.04056700","lastPrice":"0.03869000","lastQty":"0.69300000","bidPrice":"0.03858500","bidQty":"38.35000000","askPrice":"0.03869000","askQty":"31.90700000","openPrice":"0.04061300","highPrice":"0.04081900","lowPrice":"0.03842000","volume":"128015.84300000","quoteVolume":"5096.25362239","openTime":1512403353766,"closeTime":1512489753766,"firstId":4793094,"lastId":4921546,"count":128453}
return new ExchangeTicker
{
Ask = token["askPrice"].ConvertInvariant<decimal>(),
Bid = token["bidPrice"].ConvertInvariant<decimal>(),
Last = token["lastPrice"].ConvertInvariant<decimal>(),
Volume = new ExchangeVolume
{
BaseVolume = token["volume"].ConvertInvariant<decimal>(),
BaseSymbol = symbol,
ConvertedVolume = token["quoteVolume"].ConvertInvariant<decimal>(),
ConvertedSymbol = symbol,
Timestamp = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(token["closeTime"].ConvertInvariant<long>())
}
};
}
private ExchangeTicker ParseTickerWebSocket(JToken token)
{
return new ExchangeTicker
{
Ask = token["a"].ConvertInvariant<decimal>(),
Bid = token["b"].ConvertInvariant<decimal>(),
Last = token["c"].ConvertInvariant<decimal>(),
Volume = new ExchangeVolume
{
BaseVolume = token["v"].ConvertInvariant<decimal>(),
BaseSymbol = token["s"].ToStringInvariant(),
ConvertedVolume = token["q"].ConvertInvariant<decimal>(),
ConvertedSymbol = token["s"].ToStringInvariant(),
Timestamp = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(token["E"].ConvertInvariant<long>())
}
};
}
private ExchangeOrderResult ParseOrder(JToken token)
{
/*
"symbol": "IOTABTC",
"orderId": 1,
"clientOrderId": "12345",
"transactTime": 1510629334993,
"price": "1.00000000",
"origQty": "1.00000000",
"executedQty": "0.00000000",
"status": "NEW",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "SELL",
"fills": [
{
"price": "4000.00000000",
"qty": "1.00000000",
"commission": "4.00000000",
"commissionAsset": "USDT"
},
{
"price": "3999.00000000",
"qty": "5.00000000",
"commission": "19.99500000",
"commissionAsset": "USDT"
},
{
"price": "3998.00000000",
"qty": "2.00000000",
"commission": "7.99600000",
"commissionAsset": "USDT"
},
{
"price": "3997.00000000",
"qty": "1.00000000",
"commission": "3.99700000",
"commissionAsset": "USDT"
},
{
"price": "3995.00000000",
"qty": "1.00000000",
"commission": "3.99500000",
"commissionAsset": "USDT"
}
]
*/
ExchangeOrderResult result = new ExchangeOrderResult
{
Amount = token["origQty"].ConvertInvariant<decimal>(),
AmountFilled = token["executedQty"].ConvertInvariant<decimal>(),
Price = token["price"].ConvertInvariant<decimal>(),
IsBuy = token["side"].ToStringInvariant() == "BUY",
OrderDate = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(token["time"].ConvertInvariant<long>(token["transactTime"].ConvertInvariant<long>())),
OrderId = token["orderId"].ToStringInvariant(),
Symbol = token["symbol"].ToStringInvariant()
};
switch (token["status"].ToStringInvariant())
{
case "NEW":
result.Result = ExchangeAPIOrderResult.Pending;
break;
case "PARTIALLY_FILLED":
result.Result = ExchangeAPIOrderResult.FilledPartially;
break;
case "FILLED":
result.Result = ExchangeAPIOrderResult.Filled;
break;
case "CANCELED":
case "PENDING_CANCEL":
case "EXPIRED":
case "REJECTED":
result.Result = ExchangeAPIOrderResult.Canceled;
break;
default:
result.Result = ExchangeAPIOrderResult.Error;
break;
}
ParseAveragePriceAndFeesFromFills(result, token["fills"]);
return result;
}
private ExchangeOrderResult ParseTrade(JToken token, string symbol)
{
/*
[
{
"id": 28457,
"orderId": 100234,
"price": "4.00000100",
"qty": "12.00000000",
"commission": "10.10000000",
"commissionAsset": "BNB",
"time": 1499865549590,
"isBuyer": true,
"isMaker": false,
"isBestMatch": true
}
]
*/
ExchangeOrderResult result = new ExchangeOrderResult
{
Result = ExchangeAPIOrderResult.Filled,
Amount = token["qty"].ConvertInvariant<decimal>(),
AmountFilled = token["qty"].ConvertInvariant<decimal>(),
Price = token["price"].ConvertInvariant<decimal>(),
AveragePrice = token["price"].ConvertInvariant<decimal>(),
IsBuy = token["isBuyer"].ConvertInvariant<bool>() == true,
OrderDate = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(token["time"].ConvertInvariant<long>()),
OrderId = token["orderId"].ToStringInvariant(),
Fees = token["commission"].ConvertInvariant<decimal>(),
FeesCurrency = token["commissionAsset"].ToStringInvariant(),
Symbol = symbol
};
return result;
}
private void ParseAveragePriceAndFeesFromFills(ExchangeOrderResult result, JToken fillsToken)
{
decimal totalCost = 0;
decimal totalQuantity = 0;
bool currencySet = false;
if (fillsToken is JArray)
{
foreach (var fill in fillsToken)
{
if (!currencySet)
{
result.FeesCurrency = fill["commissionAsset"].ToStringInvariant();
currencySet = true;
}
result.Fees += fill["commission"].ConvertInvariant<decimal>();
decimal price = fill["price"].ConvertInvariant<decimal>();
decimal quantity = fill["qty"].ConvertInvariant<decimal>();
totalCost += price * quantity;
totalQuantity += quantity;
}
}
result.AveragePrice = (totalQuantity == 0 ? 0 : totalCost / totalQuantity);
}
protected override Task ProcessRequestAsync(HttpWebRequest request, Dictionary<string, object> payload)
{
if (CanMakeAuthenticatedRequest(payload))
{
request.Headers["X-MBX-APIKEY"] = PublicApiKey.ToUnsecureString();
}
return base.ProcessRequestAsync(request, payload);
}
protected override Uri ProcessRequestUrl(UriBuilder url, Dictionary<string, object> payload, string method)
{
if (CanMakeAuthenticatedRequest(payload))
{
// payload is ignored, except for the nonce which is added to the url query - bittrex puts all the "post" parameters in the url query instead of the request body
var query = HttpUtility.ParseQueryString(url.Query);
string newQuery = "timestamp=" + payload["nonce"].ToStringInvariant() + (query.Count == 0 ? string.Empty : "&" + query.ToString()) +
(payload.Count > 1 ? "&" + CryptoUtility.GetFormForPayload(payload, false) : string.Empty);
string signature = CryptoUtility.SHA256Sign(newQuery, CryptoUtility.ToBytes(PrivateApiKey));
newQuery += "&signature=" + signature;
url.Query = newQuery;
return url.Uri;
}
return base.ProcessRequestUrl(url, payload, method);
}
/// <summary>
/// Gets the address to deposit to and applicable details.
/// </summary>
/// <param name="symbol">Symbol to get address for</param>
/// <param name="forceRegenerate">(ignored) Binance does not provide the ability to generate new addresses</param>
/// <returns>
/// Deposit address details (including tag if applicable, such as XRP)
/// </returns>
protected override async Task<ExchangeDepositDetails> OnGetDepositAddressAsync(string symbol, bool forceRegenerate = false)
{
/*
* TODO: Binance does not offer a "regenerate" option in the API, but a second IOTA deposit to the same address will not be credited
* How does Binance handle GetDepositAddress for IOTA after it's been used once?
* Need to test calling this API after depositing IOTA.
*/
Dictionary<string, object> payload = await OnGetNoncePayloadAsync();
payload["asset"] = NormalizeSymbol(symbol);
JToken response = await MakeJsonRequestAsync<JToken>("/depositAddress.html", WithdrawalUrlPrivate, payload);
ExchangeDepositDetails depositDetails = new ExchangeDepositDetails
{
Symbol = response["asset"].ToStringInvariant(),
Address = response["address"].ToStringInvariant(),
AddressTag = response["addressTag"].ToStringInvariant()
};
return depositDetails;
}
/// <summary>Gets the deposit history for a symbol</summary>
/// <param name="symbol">The symbol to check. Null for all symbols.</param>
/// <returns>Collection of ExchangeCoinTransfers</returns>
protected override async Task<IEnumerable<ExchangeTransaction>> OnGetDepositHistoryAsync(string symbol)
{
// TODO: API supports searching on status, startTime, endTime
Dictionary<string, object> payload = await OnGetNoncePayloadAsync();
if (!string.IsNullOrWhiteSpace(symbol))
{
payload["asset"] = NormalizeSymbol(symbol);
}
JToken response = await MakeJsonRequestAsync<JToken>("/depositHistory.html", WithdrawalUrlPrivate, payload);
var transactions = new List<ExchangeTransaction>();
foreach (JToken token in response["depositList"])
{
var transaction = new ExchangeTransaction
{
Timestamp = token["insertTime"].ConvertInvariant<double>().UnixTimeStampToDateTimeMilliseconds(),
Amount = token["amount"].ConvertInvariant<decimal>(),
Symbol = token["asset"].ToStringUpperInvariant(),
Address = token["address"].ToStringInvariant(),
AddressTag = token["addressTag"].ToStringInvariant(),
BlockchainTxId = token["txId"].ToStringInvariant()
};
int status = token["status"].ConvertInvariant<int>();
switch (status)
{
case 0:
transaction.Status = TransactionStatus.Processing;
break;
case 1:
transaction.Status = TransactionStatus.Complete;
break;
default:
// If new states are added, see https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md
transaction.Status = TransactionStatus.Unknown;
transaction.Notes = "Unknown transaction status: " + status;
break;
}
transactions.Add(transaction);
}
return transactions;
}
}
}
| 44.487713 | 510 | 0.541366 | [
"MIT"
] | Daiwv/ExchangeSharp | ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs | 47,070 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
//
// Microsoft Cognitive Services (formerly Project Oxford) GitHub:
// https://github.com/Microsoft/Cognitive-Common-Windows
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace SampleUserControlLibrary
{
/// <summary>
/// Interaction logic for VideoResultControl.xaml
/// </summary>
public partial class VideoResultControl : UserControl
{
private static readonly Brush HighlightRectangleBrush = new SolidColorBrush(Color.FromRgb(255, 0, 0));
private static readonly int HighlightRectangleThickness = 2;
private static readonly TimeSpan HighlightTimerInterval = TimeSpan.FromSeconds(0.03);
public static DependencyProperty SourceUriProperty =
DependencyProperty.Register("SourceUri", typeof(Uri), typeof(VideoResultControl), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, VideoSourceChanged));
public static DependencyProperty ResultUriProperty =
DependencyProperty.Register("ResultUri", typeof(Uri), typeof(VideoResultControl));
public static DependencyProperty ResultTextProperty =
DependencyProperty.Register("ResultText", typeof(string), typeof(VideoResultControl));
public static DependencyProperty IsWorkingProperty =
DependencyProperty.Register("IsWorking", typeof(bool), typeof(VideoResultControl));
public static DependencyProperty IsVideoResultProperty =
DependencyProperty.Register("IsVideoResult", typeof(bool), typeof(VideoResultControl));
public static DependencyProperty FrameHighlightsProperty =
DependencyProperty.Register("FrameHighlights", typeof(IList<FrameHighlight>), typeof(VideoResultControl));
public static DependencyProperty ResultControlProperty =
DependencyProperty.Register("ResultControl", typeof(FrameworkElement), typeof(VideoResultControl));
private readonly DispatcherTimer _highlightTimer = new DispatcherTimer();
private int _highlightIndex;
public VideoResultControl()
{
InitializeComponent();
_highlightTimer.Interval = HighlightTimerInterval;
_highlightTimer.Tick += HighlightTimerOnTick;
}
/// <summary>
/// Represents the video Uri of orginal video player (left panel)
/// </summary>
public Uri SourceUri
{
get { return (Uri)GetValue(SourceUriProperty); }
set { SetValue(SourceUriProperty, value); }
}
/// <summary>
/// Represents the video Uri of result video player (right panel)
/// </summary>
public Uri ResultUri
{
get { return (Uri)GetValue(ResultUriProperty); }
set { SetValue(ResultUriProperty, value); }
}
/// <summary>
/// Represents the text of result text box (right panel)
/// </summary>
public string ResultText
{
get { return (string)GetValue(ResultTextProperty); }
set { SetValue(ResultTextProperty, value); }
}
/// <summary>
/// Indicates whether to show a waiting screen and disable all operations
/// </summary>
public bool IsWorking
{
get { return (bool)GetValue(IsWorkingProperty); }
set { SetValue(IsWorkingProperty, value); }
}
/// <summary>
/// Indicates whether to show result video player, otherwise, result text box is shown
/// </summary>
public bool IsVideoResult
{
get { return (bool)GetValue(IsVideoResultProperty); }
set { SetValue(IsVideoResultProperty, value); }
}
/// <summary>
/// A sequence of time frames with highlight information, which will be used to draw during video playing
/// </summary>
public IList<FrameHighlight> FrameHighlights
{
get { return (IList<FrameHighlight>)GetValue(FrameHighlightsProperty); }
set { SetValue(FrameHighlightsProperty, value); }
}
/// <summary>
/// Set a custom control to show as the result
/// </summary>
public FrameworkElement ResultControl
{
get { return (FrameworkElement)GetValue(ResultControlProperty); }
set { SetValue(ResultControlProperty, value); }
}
/// <summary>
/// Gets the current time of the source video
/// </summary>
public TimeSpan CurrentTime
{
get
{
return this.originalVideo.Position;
}
}
/// <summary>
/// Gets a value indicating if there is a custom result control set
/// </summary>
public bool IsCustomResult => this.ResultControl != null;
/// <summary>
/// Gets a value indicating if a text result should be shown
/// </summary>
public bool IsTextResult => !(this.IsVideoResult || this.IsCustomResult);
private void ButtonPlay_OnClick(object sender, RoutedEventArgs e)
{
StopVideo();
PlayVideo();
}
private void ButtonStop_OnClick(object sender, RoutedEventArgs e)
{
StopVideo();
}
private void PlayVideo()
{
originalVideo.Play();
resultVideo.Play();
Debug.Assert(!_highlightTimer.IsEnabled);
if (FrameHighlights != null && FrameHighlights.Count > 0)
{
// Creates highlight controls before playing
int numOfRects = FrameHighlights.First().HighlightRects.Length;
for (int i = 0; i < numOfRects; i++)
{
rectangleAreas.Children.Add(new Rectangle()
{
Visibility = Visibility.Hidden,
StrokeThickness = HighlightRectangleThickness,
Stroke = HighlightRectangleBrush
});
}
_highlightIndex = 0;
_highlightTimer.Start();
}
}
private void StopVideo()
{
originalVideo.Stop();
resultVideo.Stop();
_highlightTimer.Stop();
rectangleAreas.Children.Clear();
}
private void HighlightTimerOnTick(object sender, EventArgs eventArgs)
{
double currentSecond = originalVideo.Position.TotalSeconds;
// finds the neareast time frame
while (_highlightIndex < FrameHighlights.Count && FrameHighlights[_highlightIndex].Time <= currentSecond)
_highlightIndex++;
if (_highlightIndex > FrameHighlights.Count) return;
if (_highlightIndex == 0) return;
Rect[] positions = FrameHighlights[_highlightIndex - 1].HighlightRects;
for (int i = 0; i < positions.Length; i++)
{
// relayouts highlight controls based on video player size
Rectangle rect = (Rectangle) rectangleAreas.Children[i];
rect.Visibility = Visibility.Hidden;
double w = originalVideoHolder.ActualWidth;
double h = originalVideoHolder.ActualHeight;
double vw = (double) originalVideo.NaturalVideoWidth;
double vh = (double) originalVideo.NaturalVideoHeight;
if (h > 0 && vh > 0)
{
double vr = vw/vh;
double offsetX = Math.Max((w - h*vr)/2, 0);
double offsetY = Math.Max((h - w/vr)/2, 0);
double realWidth = w - 2*offsetX;
double realHeight = h - 2*offsetY;
Canvas.SetLeft(rect, offsetX + positions[i].X*realWidth);
Canvas.SetTop(rect, offsetY + positions[i].Y*realHeight);
rect.Width = positions[i].Width*realWidth;
rect.Height = positions[i].Height*realHeight;
rect.Visibility = Visibility.Visible;
}
}
}
private static void VideoSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
VideoResultControl thiz = (VideoResultControl)obj;
thiz.StopVideo();
}
}
public class BoolToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Hidden;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return ((Visibility)value == Visibility.Visible);
}
}
public class InvertBoolToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return (value is bool && (bool)value) ? Visibility.Hidden : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return ((Visibility)value != Visibility.Visible);
}
}
public class FrameHighlight
{
/// <summary>
/// Start time (in seconds) of the frame
/// </summary>
public double Time { get; set; }
/// <summary>
/// Rectangles of highlight regions in the frame
/// </summary>
public Rect[] HighlightRects { get; set; }
}
}
| 36.925325 | 206 | 0.616724 | [
"MIT"
] | Bhaskers-Blu-Org2/Cognitive-EventKnowledge-Windows | Cognitive-Common-Windows/SampleUserControlLibrary/VideoResultControl.xaml.cs | 11,375 | C# |
using System;
using UnityEngine;
public class BitUtil
{
public static UInt32 ReadBits(UInt32 input, ref Byte startBit, Byte numBits)
{
UInt32 num = (UInt32) Mathf.Pow(2f, (Single) numBits) - 1u;
UInt32 result = input >> (Int32) startBit & num;
startBit = (Byte) (startBit + numBits);
return result;
}
public static Byte InvertFlag(Byte value, Byte flag)
{
return (value & flag) == flag
? (Byte) (value & ~flag)
: (Byte) (value | flag);
}
} | 23.2 | 77 | 0.663793 | [
"MIT"
] | Albeoris/Memoria | Assembly-CSharp/Global/BitUtil.cs | 466 | C# |
using System;
namespace JsxbinToJsx.JsxbinDecoding
{
public interface IReferenceDecoder
{
double JsxbinVersion { get; }
Tuple<string, bool> Decode(INode node);
}
}
| 17.636364 | 47 | 0.664948 | [
"MIT"
] | rikuayanokozy/jsxbin-to-jsx-converter | JsxbinToJsx/JsxbinDecoding/IReferenceDecoder.cs | 196 | C# |
////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Daniel Kollmann
// 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 Daniel Kollmann 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.
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The above software in this distribution may have been modified by THL A29 Limited ("Tencent Modifications").
//
// All Tencent Modifications are Copyright (C) 2015 THL A29 Limited.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
using Behaviac.Design.Attributes;
using Behaviac.Design.Properties;
using Behaviac.Design.Attachments.Overrides;
namespace Behaviac.Design.Nodes
{
/// <summary>
/// This is the class for all nodes which are part of a behaviour tree and are not view data.
/// </summary>
public abstract partial class Node : BaseNode, DefaultObject, ICloneable
{
public enum ColorThemes {
Default,
Modern
}
private static ColorThemes _colorTheme = ColorThemes.Default;
public static ColorThemes ColorTheme {
get { return _colorTheme; }
set { _colorTheme = value; }
}
public static Dictionary<string, Brush> BackgroundBrushes = new Dictionary<string, Brush>();
protected readonly static Brush __backgroundBrush = new SolidBrush(Color.FromArgb(30, 99, 120));
public Brush BackgroundBrush {
get
{
if (ColorTheme == ColorThemes.Default)
{ return DefaultBackgroundBrush; }
string nodeName = this.GetType().FullName;
if (BackgroundBrushes.ContainsKey(nodeName))
{ return BackgroundBrushes[nodeName]; }
return __backgroundBrush;
}
}
protected virtual Brush DefaultBackgroundBrush {
get { return __backgroundBrush; }
}
public virtual Behaviac.Design.ObjectUI.ObjectUIPolicy CreateUIPolicy() {
return new Behaviac.Design.ObjectUI.ObjectUIPolicy();
}
public virtual bool CanBeDragged() {
return true;
}
public virtual bool CanBeDeleted() {
return this.ParentCanAdoptChildren || this.IsFSM;
}
public bool CanBeDisabled() {
return this.Enable ? (Parent != null && Parent.Children.Count > 1) : true;
}
public virtual bool AlwaysExpanded() {
return false;
}
public virtual bool HasPrefixLabel {
get { return true; }
}
public virtual string MiddleLabel {
get { return null; }
}
public virtual bool HasFirstLabel {
get { return false; }
}
/// <summary>
/// Add a new child but the behaviour does not need to be saved.
/// Used for collapsed referenced behaviours which show the behaviours they reference.
/// </summary>
/// <param name="connector">The connector the node will be added to. Use null for default connector.</param>
/// <param name="node">The node you want to append.</param>
/// <returns>Returns true if the child could be added.</returns>
public virtual bool AddChildNotModified(Connector connector, Node node) {
Debug.Check(connector != null && _children.HasConnector(connector));
if (!connector.AcceptsChild(node)) {
//throw new Exception(Resources.ExceptionNodeHasTooManyChildren);
return false;
}
if (!connector.AddChild(node)) {
return false;
}
node._parent = this;
return true;
}
public void AddChild(string connectorStr, Node node) {
Connector connector = this.GetConnector(connectorStr);
this.AddChild(connector, node);
}
/// <summary>
/// Add a new child node.
/// </summary>
/// <param name="connector">The connector the node will be added to. Use null for default connector.</param>
/// <param name="node">The node you want to append.</param>
/// <returns>Returns true if the child could be added.</returns>
public virtual bool AddChild(Connector connector, Node node) {
if (!AddChildNotModified(connector, node))
{ return false; }
return true;
}
/// <summary>
/// Add a new child node.
/// </summary>
/// <param name="connector">The connector the node will be added to. Use null for default connector.</param>
/// <param name="node">The node you want to append.</param>
/// <param name="index">The index of the new node.</param>
/// <returns>Returns true if the child could be added.</returns>
public virtual bool AddChild(Connector connector, Node node, int index) {
Debug.Check(connector != null && _children.HasConnector(connector));
if (!connector.AcceptsChild(node)) {
throw new Exception(Resources.ExceptionNodeHasTooManyChildren);
}
if (!connector.AddChild(node, index)) {
return false;
}
node._parent = this;
return true;
}
/// <summary>
/// Removes a child node.
/// </summary>
/// <param name="connector">The connector the child is attached to.</param>
/// <param name="node">The child node we want to remove.</param>
public virtual void RemoveChild(Connector connector, Node node) {
Debug.Check(connector != null && _children.HasConnector(connector));
if (!connector.RemoveChild(node))
{ throw new Exception(Resources.ExceptionNodeIsNoChild); }
node._parent = null;
}
//a chance to modify the structure or data
public virtual void PostCreate(List<Node.ErrorCheck> result, int version, System.Xml.XmlNode xmlNode)
{
}
public virtual void PostCreatedByEditor()
{
}
public new BehaviorNode Behavior {
get { return ((BaseNode)this).Behavior; }
}
public virtual List<ParInfo> LocalVars {
get { return null; }
}
/// <summary>
/// Determines if an attachment of a certain type is aceepted by this node or not.
/// </summary>
/// <param name="type">The type of the attachment we want to add.</param>
/// <returns>Returns if the attachment may be added or not</returns>
public virtual bool AcceptsAttachment(DefaultObject obj) {
return (obj != null) && !obj.IsFSM && obj.CanBeAttached;
}
protected List<Attachments.Attachment> _attachments;
private void sortAttachments() {
List<Attachments.Attachment> bottomAttachments = new List<Attachments.Attachment>();
for (int i = _attachments.Count - 1; i >= 0; i--) {
if (!_attachments[i].IsPrecondition) {
bottomAttachments.Add(_attachments[i]);
_attachments.RemoveAt(i);
}
}
for (int i = bottomAttachments.Count - 1; i >= 0; i--) {
_attachments.Add(bottomAttachments[i]);
}
}
public IList<Attachments.Attachment> Attachments {
get { return _attachments; }
}
public void AddAttachment(Attachments.Attachment attach) {
Debug.Check(attach != null);
_attachments.Add(attach);
sortAttachments();
attach.ResetId();
}
public void AddAttachment(Attachments.Attachment attach, int index) {
Debug.Check(attach != null);
_attachments.Insert(index, attach);
sortAttachments();
attach.ResetId();
}
public void RemoveAttachment(Attachments.Attachment attach) {
_attachments.Remove(attach);
}
protected string _exportName = string.Empty;
/// <summary>
/// The name of the node used for the export process.
/// </summary>
public string ExportName {
get { return _exportName; }
}
protected string _label;
/// <summary>
/// The label shown of the node.
/// </summary>
public string Label {
get { return _label; }
set { _label = value; }
}
protected readonly string _description;
/// <summary>
/// The description of this node.
/// </summary>
public virtual string Description {
get { return /*Resources.ResourceManager.GetString(*/_description/*, Resources.Culture)*/; }
}
public virtual object[] GetExcludedEnums(DesignerEnum enumAttr) {
return null;
}
/// <summary>
/// Creates a new behaviour node.
/// </summary>
/// <param name="label">The label of the behaviour node.</param>
/// <returns>Returns the created behaviour node.</returns>
public static BehaviorNode CreateBehaviorNode(string label) {
BehaviorNode node = (BehaviorNode)Plugin.BehaviorNodeType.InvokeMember(string.Empty, BindingFlags.CreateInstance, null, null, new object[] { label, true });
if (node == null)
{ throw new Exception(Resources.ExceptionMissingNodeConstructor); }
return node;
}
/// <summary>
/// Creates a new referenced behaviour node.
/// </summary>
/// <param name="rootBehavior">The behaviour we are adding the reference to.</param>
/// <param name="referencedBehavior">The behaviour we are referencing.</param>
/// <returns>Returns the created referenced behaviour node.</returns>
public static ReferencedBehaviorNode CreateReferencedBehaviorNode(BehaviorNode rootBehavior, BehaviorNode referencedBehavior, bool isFSM = false) {
Type type = isFSM ? Plugin.FSMReferencedBehaviorNodeType : Plugin.ReferencedBehaviorNodeType;
Debug.Check(type != null);
ReferencedBehaviorNode node = (ReferencedBehaviorNode)type.InvokeMember(string.Empty, BindingFlags.CreateInstance, null, null, new object[] { rootBehavior, referencedBehavior });
if (node == null)
{ throw new Exception(Resources.ExceptionMissingNodeConstructor); }
return node;
}
/// <summary>
/// Creates a node from a given type.
/// </summary>
/// <param name="type">The type we want to create a node of.</param>
/// <returns>Returns the created node.</returns>
public static Node Create(Type type) {
Debug.Check(type != null);
// use the type overrides when set
if (type == typeof(BehaviorNode))
{ type = Plugin.BehaviorNodeType; }
else if (type == typeof(ReferencedBehaviorNode))
{ type = Plugin.ReferencedBehaviorNodeType; }
Debug.Check(type != null);
Debug.Check(!type.IsAbstract);
Node node = (Node)type.InvokeMember(string.Empty, BindingFlags.CreateInstance, null, null, new object[0]);
if (node == null)
{ throw new Exception(Resources.ExceptionMissingNodeConstructor); }
return node;
}
/// <summary>
/// Determines if the children of this node will be saved. Required for referenced behaviours.
/// </summary>
public virtual bool SaveChildren {
get { return true; }
}
/// <summary>
/// The name of the class we want to use for the exporter. This is usually the implemented node of the game.
/// </summary>
public virtual string ExportClass {
get { return GetType().FullName; }
}
private Comment _comment = new Comment("");
/// <summary>
/// The comment object of the node.
/// </summary>
public Comment CommentObject {
get { return _comment; }
set { _comment = value; }
}
private bool _enable = true;
[DesignerBoolean("Enable", "EnableDesc", "Debug", DesignerProperty.DisplayMode.NoDisplay, 0, DesignerProperty.DesignerFlags.NoDisplay | DesignerProperty.DesignerFlags.NoExport)]
public bool Enable
{
get { return _enable; }
set { _enable = value; }
}
private int _id = -1;
[DesignerInteger("NodeId", "NodeIdDesc", "Debug", DesignerProperty.DisplayMode.NoDisplay, 1, DesignerProperty.DesignerFlags.ReadOnly | DesignerProperty.DesignerFlags.NoExport | DesignerProperty.DesignerFlags.NotPrefabRelated, null, int.MinValue, int.MaxValue, 1, null)]
public int Id {
get { return _id; }
set { _id = value; }
}
/// <summary>
/// The relative path of the prefab behavior
/// </summary>
private string _prefabName = string.Empty;
[DesignerString("PrefabName", "PrefabNameDesc", "Prefab", DesignerProperty.DisplayMode.NoDisplay, 0, DesignerProperty.DesignerFlags.NoDisplay | DesignerProperty.DesignerFlags.NoExport | DesignerProperty.DesignerFlags.NotPrefabRelated)]
public string PrefabName {
get { return _prefabName; }
set { _prefabName = value; }
}
/// <summary>
/// The node id in the prefab behavior
/// </summary>
private int _prefabNodeId = -1;
[DesignerInteger("PrefabNodeId", "PrefabNodeIdDesc", "Prefab", DesignerProperty.DisplayMode.NoDisplay, 1, DesignerProperty.DesignerFlags.NoDisplay | DesignerProperty.DesignerFlags.NoExport | DesignerProperty.DesignerFlags.NotPrefabRelated, null, int.MinValue, int.MaxValue, 1, null)]
public int PrefabNodeId {
get { return _prefabNodeId; }
set { _prefabNodeId = value; }
}
/// <summary>
/// If modifying the prefab data in the current node
/// </summary>
private bool _hasOwnPrefabData = false;
[DesignerBoolean("HasOwnPrefabData", "HasOwnPrefabDataDesc", "Prefab", DesignerProperty.DisplayMode.NoDisplay, 2, DesignerProperty.DesignerFlags.NoDisplay | DesignerProperty.DesignerFlags.NoExport | DesignerProperty.DesignerFlags.NotPrefabRelated)]
public bool HasOwnPrefabData {
get { return _hasOwnPrefabData; }
set { _hasOwnPrefabData = value; }
}
public bool IsPrefabDataDirty() {
if (this.HasOwnPrefabData)
{ return true; }
foreach(Node child in this.Children) {
if (child.IsPrefabDataDirty())
{ return true; }
}
return false;
}
/// <summary>
/// The text of the comment shown for the node and its children.
/// </summary>
[DesignerString("NodeCommentText", "NodeCommentTextDesc", "CategoryComment", DesignerProperty.DisplayMode.NoDisplay, 10, DesignerProperty.DesignerFlags.NoExport | DesignerProperty.DesignerFlags.NoSave | DesignerProperty.DesignerFlags.NotPrefabRelated)]
public string CommentText {
get { return _comment == null ? string.Empty : _comment.Text; }
set
{
string str = value.Trim();
if (str.Length < 1) {
_comment = null;
} else
{
if (_comment == null)
{ _comment = new Comment(str); }
else
{ _comment.Text = str; }
if (_comment.Background == CommentColor.NoColor && !string.IsNullOrEmpty(str))
{ _comment.Background = CommentColor.Gray; }
}
}
}
/// <summary>
/// The color of the comment shown for the node and its children.
/// </summary>
[DesignerEnum("NodeCommentBackground", "NodeCommentBackgroundDesc", "CategoryComment", DesignerProperty.DisplayMode.NoDisplay, 20, DesignerProperty.DesignerFlags.NoExport | DesignerProperty.DesignerFlags.NoSave | DesignerProperty.DesignerFlags.NotPrefabRelated, "")]
public CommentColor CommentBackground {
get { return _comment == null ? CommentColor.NoColor : _comment.Background; }
set
{
if (_comment != null)
{ _comment.Background = value; }
}
}
public void ResetId(bool setChildren) {
Node root = (Node)this.Behavior;
if (Id == -1 || null != Plugin.GetPreviousObjectById(root, Id, this)) {
Id = Plugin.NewNodeId(root);
}
foreach(Attachments.Attachment attach in this.Attachments) {
attach.Id = Plugin.NewNodeId(root);
}
if (setChildren && !(this is ReferencedBehavior)) {
foreach(Node child in this.GetChildNodes()) {
child.ResetId(setChildren);
}
}
}
private void checkId() {
Node root = (Node)this.Behavior;
// If its id has existed, reset it.
if (null != Plugin.GetPreviousObjectById(root, Id, this)) {
ResetId(false);
if (this.PrefabNodeId < 0)
this.Behavior.TriggerWasModified(this);
}
}
/// <summary>
/// Creates a new node and attaches the default attributes DebugName and ExportType.
/// </summary>
/// <param name="label">The default label of the node.</param>
/// <param name="description">The description of the node shown to the designer.</param>
protected Node(string label, string description) {
_children = new ConnectedChildren(this);
_label = label;
_description = description;
_attachments = new List<Attachments.Attachment>();
}
public virtual void OnPropertyValueChanged(DesignerPropertyInfo property) {
}
/// <summary>
/// Is called when one of the node's properties were modified.
/// </summary>
/// <param name="wasModified">Holds if the event was modified.</param>
public void OnPropertyValueChanged(bool wasModified) {
if (wasModified) {
BehaviorNode root = this.Behavior;
if (root != null)
{ root.TriggerWasModified(this); }
}
}
public delegate void SubItemAddedEventDelegate(Node node, DesignerPropertyInfo property);
public event SubItemAddedEventDelegate SubItemAdded;
public void DoSubItemAdded(DesignerPropertyInfo property) {
if (SubItemAdded != null)
{ SubItemAdded(this, property); }
}
/// <summary>
/// Is called after the behaviour was loaded.
/// </summary>
/// <param name="behavior">The behaviour this node belongs to.</param>
public void PostLoad(BehaviorNode behavior) {
checkId();
}
/// <summary>
/// Is called before the behaviour is saved.
/// </summary>
/// <param name="behavior">The behaviour this node belongs to.</param>
public void PreSave(BehaviorNode behavior) {
}
/// <summary>
/// Returns the name of the node's type for the attribute ExportType.
/// This is done as the class attribute can be quite long and bad to handle.
/// </summary>
/// <returns>Returns the value for ExportType</returns>
protected virtual string GetExportType() {
return GetType().Name;
}
public bool SetPrefab(string prefabName, bool prefabDirty = false, string oldPrefabName = "") {
bool resetName = false;
if (!string.IsNullOrEmpty(oldPrefabName)) {
if (this.PrefabName == oldPrefabName) {
this.PrefabName = prefabName;
resetName = true;
}
} else if (string.IsNullOrEmpty(this.PrefabName)) {
this.PrefabName = prefabName;
this.PrefabNodeId = this.Id;
this.HasOwnPrefabData = prefabDirty;
}
if (!(this is ReferencedBehavior)) {
foreach(Node child in this.Children) {
resetName |= child.SetPrefab(prefabName, prefabDirty, oldPrefabName);
}
}
return resetName;
}
public bool ClearPrefab(string prefabName) {
if (string.IsNullOrEmpty(prefabName))
{ return false; }
bool clear = false;
if (this.PrefabName == prefabName) {
clear = true;
this.PrefabName = string.Empty;
this.PrefabNodeId = -1;
this.HasOwnPrefabData = false;
}
if (!(this is ReferencedBehavior)) {
foreach(Node child in this.Children) {
clear |= child.ClearPrefab(prefabName);
}
}
return clear;
}
private void ClearPrefabDirty(string prefabName) {
if (this.PrefabName == prefabName) {
this.HasOwnPrefabData = false;
}
if (!(this is ReferencedBehavior)) {
foreach(Node child in this.Children) {
child.ClearPrefabDirty(prefabName);
}
}
}
public void RestorePrefab(string prefabName) {
if (this.PrefabName == prefabName) {
this.PrefabName = string.Empty;
this.Id = this.PrefabNodeId;
this.PrefabNodeId = -1;
this.HasOwnPrefabData = false;
}
if (!(this is ReferencedBehavior)) {
foreach(Node child in this.Children) {
child.RestorePrefab(prefabName);
}
}
}
public bool ResetPrefabInstances(string prefabName, Node instanceRootNode) {
bool reset = instanceRootNode.ResetByPrefab(prefabName, this);
if (!(this is ReferencedBehavior)) {
foreach(Node child in this.Children) {
reset |= child.ResetPrefabInstances(prefabName, instanceRootNode);
}
}
return reset;
}
public bool ResetByPrefab(string prefabName, Node prefabNode) {
bool reset = false;
if (!this.HasOwnPrefabData && this.PrefabName == prefabName && this.PrefabNodeId == prefabNode.Id) {
reset = true;
int preId = this.Id;
string prePrefabName = this.PrefabName;
int prePrefabNodeId = this.PrefabNodeId;
Comment preComment = (this.CommentObject != null) ? this.CommentObject.Clone() : null;
prefabNode.CloneProperties(this);
this.Id = preId;
this.PrefabName = prePrefabName;
this.PrefabNodeId = prePrefabNodeId;
this.HasOwnPrefabData = false;
this.CommentObject = preComment;
// check the deleted children by the prefab node
List<Node> deletedChildren = new List<Node>();
foreach(Node child in this.Children) {
if (!child.HasOwnPrefabData && child.PrefabName == prefabName) {
bool bFound = false;
foreach(Node prefabChild in prefabNode.Children) {
if (child.PrefabNodeId == prefabChild.Id) {
bFound = true;
break;
}
}
if (!bFound) {
deletedChildren.Add(child);
}
}
}
foreach(Node child in deletedChildren) {
((Node)child.Parent).RemoveChild(child.ParentConnector, child);
}
// check the added children by the prefab node
List<Node> addedChildren = new List<Node>();
List<int> indexes = new List<int>();
for (int i = 0; i < prefabNode.Children.Count; ++i) {
Node prefabChild = (Node)prefabNode.Children[i];
bool bFound = false;
foreach(Node child in this.Children) {
if (!string.IsNullOrEmpty(prefabChild.PrefabName) && child.PrefabName == prefabChild.PrefabName && child.PrefabNodeId == prefabChild.PrefabNodeId ||
child.PrefabName == prefabName && child.PrefabNodeId == prefabChild.Id) {
bFound = true;
break;
}
}
if (!bFound) {
addedChildren.Add(prefabChild);
indexes.Add(i);
}
}
for (int i = 0; i < addedChildren.Count; ++i) {
Node child = addedChildren[i].CloneBranch();
child.SetPrefab(prefabName);
Node.Connector conn = addedChildren[i].ParentConnector;
Debug.Check(conn != null);
Node.Connector childconn = this.GetConnector(conn.Identifier);
Debug.Check(childconn != null);
if (indexes[i] < this.Children.Count)
{ this.AddChild(childconn, child, indexes[i]); }
else
{ this.AddChild(childconn, child); }
child.ResetId(true);
}
}
if (!(this is ReferencedBehavior)) {
foreach(Node child in this.Children) {
reset |= child.ResetByPrefab(prefabName, prefabNode);
}
}
return reset;
}
public Node GetPrefabRoot() {
string prefabName = this.PrefabName;
if (!string.IsNullOrEmpty(prefabName)) {
Node node = this;
Node root = this;
while (node.Parent != null) {
string parentPrefabName = ((Node)node.Parent).PrefabName;
if (!string.IsNullOrEmpty(parentPrefabName)) {
if (parentPrefabName == prefabName)
{ root = (Node)node.Parent; }
else
{ break; }
}
node = (Node)node.Parent;
}
return root;
}
return null;
}
public BehaviorNode ApplyPrefabInstance() {
string prefabName = this.PrefabName;
if (!string.IsNullOrEmpty(prefabName)) {
Node root = this.GetPrefabRoot();
if (root != null) {
string fullpath = FileManagers.FileManager.GetFullPath(prefabName);
BehaviorNode prefabBehavior = BehaviorManager.Instance.LoadBehavior(fullpath);
if (prefabBehavior != null) {
Behavior b = this.Behavior as Behavior;
Debug.Check(b != null);
b.AgentType.AddPars(b.LocalVars);
root.ClearPrefabDirty(prefabName);
if (((Node)prefabBehavior).Children.Count > 0) {
((Node)prefabBehavior).RemoveChild(prefabBehavior.GenericChildren, (Node)((Node)prefabBehavior).Children[0]);
}
Node newnode = root.CloneBranch();
newnode.RestorePrefab(prefabName);
((Node)prefabBehavior).AddChild(prefabBehavior.GenericChildren, newnode);
return prefabBehavior;
}
}
}
return null;
}
public bool BreakPrefabInstance() {
string prefabName = this.PrefabName;
if (!string.IsNullOrEmpty(prefabName)) {
Node root = this.GetPrefabRoot();
string fullpath = FileManagers.FileManager.GetFullPath(prefabName);
Nodes.BehaviorNode prefabBehavior = BehaviorManager.Instance.LoadBehavior(fullpath);
if (prefabBehavior != null) {
Behavior b = this.Behavior as Behavior;
Debug.Check(b != null);
b.AgentType.AddPars(b.LocalVars);
root.ResetByPrefab(prefabName, (Node)prefabBehavior);
}
return root.ClearPrefab(prefabName);
}
return false;
}
public void SetEnterExitSlot(List<Nodes.Node.ErrorCheck> result, string actionStr, bool bEnter)
{
Type t = null;
if (bEnter)
{
t = Plugin.GetType("PluginBehaviac.Events.Precondition");
}
else
{
t = Plugin.GetType("PluginBehaviac.Events.Effector");
}
Behaviac.Design.Attachments.Attachment a = Behaviac.Design.Attachments.Attachment.Create(t, this);
this.AddAttachment(a);
IList<DesignerPropertyInfo> properties = a.GetDesignerProperties();
foreach (DesignerPropertyInfo p in properties)
{
if (p.Property.Name == "Opl")
{
p.SetValueFromString(result, a, actionStr);
}
else if (p.Property.Name == "Opr")
{
p.SetValueFromString(result, a, "const bool true");
}
else if (!bEnter && p.Property.Name == "Phase")
{
p.SetValueFromString(result, a, "Both");
}
}
}
/// <summary>
/// Checks the current node and its children for errors.
/// </summary>
/// <param name="rootBehavior">The behaviour we are currently checking.</param>
/// <param name="result">The list the errors are added to.</param>
public virtual void CheckForErrors(BehaviorNode rootBehavior, List<ErrorCheck> result) {
if (Plugin.EditMode == EditModes.Design) {
if (!Enable) {
result.Add(new Node.ErrorCheck(this, ErrorCheckLevel.Warning, Resources.Disabled));
}
//don't check locals for ReferencedBehavior and Event
if (this is Behavior) {
Behavior behavior = this as Behavior;
CheckPars(behavior.LocalVars, ref result);
}
foreach(Node node in _children) {
if (node.Enable)
{ node.CheckForErrors(rootBehavior, result); }
}
foreach(Node node in this.FSMNodes) {
node.CheckForErrors(rootBehavior, result);
}
foreach(Attachments.Attachment attachment in _attachments) {
attachment.CheckForErrors(rootBehavior, result);
}
}
}
private void CheckPars(List<ParInfo> pars, ref List<ErrorCheck> result) {
foreach(ParInfo par in pars) {
if (par.Display) {
List<ErrorCheck> parResult = new List<ErrorCheck>();
Plugin.CheckPar(this, par, ref parResult);
if (parResult.Count == 0) {
string info = string.Format(Resources.ParWarningInfo, par.Name);
result.Add(new Node.ErrorCheck(this, ErrorCheckLevel.Warning, info));
}
}
}
}
public virtual bool ResetMembers(bool check, AgentType agentType, bool clear, MethodDef method = null, PropertyDef property = null) {
bool bReset = false;
foreach(Attachments.Attachment attach in this.Attachments) {
bReset |= attach.ResetMembers(check, agentType, clear, method, property);
}
foreach(Node child in this.GetChildNodes()) {
bReset |= child.ResetMembers(check, agentType, clear, method, property);
}
return bReset;
}
public virtual void GetReferencedFiles(ref List<string> referencedFiles) {
foreach(Attachments.Attachment attach in this.Attachments) {
attach.GetReferencedFiles(ref referencedFiles);
}
foreach(Node child in this.GetChildNodes()) {
child.GetReferencedFiles(ref referencedFiles);
}
}
public virtual bool ResetReferenceBehavior(string referenceFilename) {
bool reset = false;
foreach(Node child in this.GetChildNodes()) {
reset |= child.ResetReferenceBehavior(referenceFilename);
}
return reset;
}
public virtual void GetObjectsByType(Nodes.Node root, string nodeType, bool matchCase, bool matchWholeWord, ref List<ObjectPair> objects) {
if (root == null || string.IsNullOrEmpty(nodeType))
{ return; }
GetObjectsBySelfType(root, nodeType, matchCase, matchWholeWord, ref objects);
foreach(Attachments.Attachment attach in this.Attachments) {
if (!Plugin.ContainObjectPair(objects, root, attach) && Plugin.CompareTwoTypes(attach.GetType().Name, nodeType, matchCase, matchWholeWord))
{ objects.Add(new ObjectPair(root, attach)); }
}
foreach(Nodes.Node child in this.GetChildNodes()) {
child.GetObjectsByType(root, nodeType, matchCase, matchWholeWord, ref objects);
}
}
protected void GetObjectsBySelfType(Nodes.Node root, string nodeType, bool matchCase, bool matchWholeWord, ref List<ObjectPair> objects) {
if (root == null || string.IsNullOrEmpty(nodeType))
{ return; }
if (!Plugin.ContainObjectPair(objects, root, this) && Plugin.CompareTwoTypes(this.GetType().Name, nodeType, matchCase, matchWholeWord))
{ objects.Add(new ObjectPair(root, this)); }
}
public virtual void GetObjectsByPropertyMethod(Nodes.Node root, string propertyName, bool matchCase, bool matchWholeWord, ref List<ObjectPair> objects) {
if (root == null || string.IsNullOrEmpty(propertyName))
{ return; }
Plugin.GetObjectsBySelfPropertyMethod(root, this, propertyName, matchCase, matchWholeWord, ref objects);
foreach(Attachments.Attachment attach in this.Attachments) {
Plugin.GetObjectsBySelfPropertyMethod(root, attach, propertyName, matchCase, matchWholeWord, ref objects);
}
foreach(Nodes.BaseNode child in this.GetChildNodes()) {
if (child is Nodes.Node) {
Nodes.Node childNode = child as Nodes.Node;
childNode.GetObjectsByPropertyMethod(root, propertyName, matchCase, matchWholeWord, ref objects);
}
}
}
/// <summary>
/// Creates a view for this node. Allows you to return your own class and store additional data.
/// </summary>
/// <param name="rootBehavior">The root of the graph of the current view.</param>
/// <param name="parent">The parent of the NodeViewData created.</param>
/// <returns>Returns a new NodeViewData object for this node.</returns>
public virtual NodeViewData CreateNodeViewData(NodeViewData parent, BehaviorNode rootBehavior) {
return new NodeViewDataStyled(parent, rootBehavior, this, null, BackgroundBrush, _label, _description);
}
/// <summary>
/// Searches a list for NodeViewData for this node. Internal use only.
/// </summary>
/// <param name="list">The list which is searched for the NodeViewData.</param>
/// <returns>Returns null if no fitting NodeViewData could be found.</returns>
public virtual NodeViewData FindNodeViewData(List<NodeViewData> list) {
foreach(NodeViewData nvd in list) {
if (nvd.Node == this)
{ return nvd; }
}
return null;
}
/// <summary>
/// Internally used by CloneBranch.
/// </summary>
/// <param name="newparent">The parent the clone children will be added to.</param>
private void CloneChildNodes(Node newparent) {
// we may not clone children of a referenced behavior
if (newparent is ReferencedBehaviorNode)
{ return; }
// for each connector
foreach(Connector connector in _children.Connectors) {
// find the one from the new node...
Connector localconn = newparent.GetConnector(connector.Identifier);
Debug.Check(localconn != null);
// and duplicate its children into the new node's connector
for (int i = 0; i < connector.ChildCount; ++i) {
Node child = (Node)connector.GetChild(i);
Node newchild = (Node)child.Clone();
newparent.AddChild(localconn, newchild);
// do this for the children as well
child.CloneChildNodes(newchild);
}
}
// for each FSM node
foreach(Node child in this.FSMNodes) {
Node newchild = (Node)child.Clone();
newparent.AddFSMNode(newchild);
// do this for the children as well
child.CloneChildNodes(newchild);
}
}
public string GetFullId() {
string fullId = this.Id.ToString();
BaseNode n = this;
while (n != null) {
if (n is Behavior) {
Behavior b = n as Behavior;
if (b.ParentNode != null) {
fullId = string.Format("{0}:{1}", b.ParentNode.Id, fullId);
}
n = b.ParentNode;
} else {
n = n.Parent;
}
}
return fullId;
}
/// <summary>
/// Duplicates a node and all of its children.
/// </summary>
/// <returns>New node with new children.</returns>
public Node CloneBranch() {
Node newnode;
if (this is ReferencedBehaviorNode) {
// if we want to clone the branch of a referenced behaviour we have to create a new behaviour node for that.
// this should only be used to visualise stuff, never in the behaviour tree itself!
newnode = Create(typeof(BehaviorNode));
//newnode.Label= Label;
} else {
newnode = Create(GetType());
CloneProperties(newnode);
}
CloneChildNodes(newnode);
newnode.OnPropertyValueChanged(false);
return newnode;
}
/// <summary>
/// Duplicates this node. Parent and children are not copied.
/// </summary>
/// <returns>New node without parent and children.</returns>
public virtual object Clone() {
Node newnode = Create(GetType());
CloneProperties(newnode);
newnode.OnPropertyValueChanged(false);
return newnode;
}
private void checkPrefabFile() {
if (!string.IsNullOrEmpty(this.PrefabName)) {
string prefabName = FileManagers.FileManager.GetFullPath(this.PrefabName);
if (!System.IO.File.Exists(prefabName)) {
this.PrefabName = string.Empty;
this.PrefabNodeId = -1;
this.HasOwnPrefabData = false;
}
}
}
/// <summary>
/// Used to duplicate all properties. Any property added must be duplicated here as well.
/// </summary>
/// <param name="newnode">The new node which is supposed to get a copy of the properties.</param>
protected virtual void CloneProperties(Node newnode) {
Debug.Check(newnode != null);
// clone properties
newnode.ScreenLocation = this.ScreenLocation;
newnode.Id = this.Id;
newnode.Enable = this.Enable;
if (this.CommentObject != null) {
newnode.CommentObject = this.CommentObject.Clone();
}
checkPrefabFile();
newnode.PrefabName = this.PrefabName;
newnode.PrefabNodeId = this.PrefabNodeId;
newnode.HasOwnPrefabData = this.HasOwnPrefabData;
// clone pars.
if (this is Behavior) {
Behavior bnew = newnode as Behavior;
bnew.LocalVars.Clear();
foreach(ParInfo par in((Behavior)this).LocalVars) {
bnew.LocalVars.Add(par.Clone(bnew));
}
}
// clone attachements
newnode.Attachments.Clear();
foreach(Attachments.Attachment attach in _attachments) {
newnode.AddAttachment(attach.Clone(newnode));
}
}
/// <summary>
/// This node will be removed from its parent and its children. The parent tries to adopt all children.
/// </summary>
/// <returns>Returns false if the parent cannot apobt the children and the operation fails.</returns>
public bool ExtractNode() {
// we cannot adopt children from a referenced behavior
if (this is ReferencedBehaviorNode && _parent != null) {
((Node)_parent).RemoveChild(_parentConnector, this);
return true;
}
// check if the parent is allowed to adopt the children
if (ParentCanAdoptChildren) {
Connector conn = _parentConnector;
Node parent = (Node)_parent;
int n = conn.GetChildIndex(this);
Debug.Check(n >= 0);
parent.RemoveChild(conn, this);
// let the node's parent adopt all the children
foreach(Connector connector in _children.Connectors) {
for (int i = 0; i < connector.ChildCount; ++i, ++n)
{ parent.AddChild(conn, (Node)connector[i], n); }
// remove the adopted children from the old connector. Do NOT clear the _connector member which already points to the new connector.
connector.ClearChildrenInternal();
}
return true;
}
return false;
}
/// <summary>
/// Returns a list of all properties which have a designer attribute attached.
/// </summary>
/// <returns>A list of all properties relevant to the designer.</returns>
public IList<DesignerPropertyInfo> GetDesignerProperties() {
return DesignerProperty.GetDesignerProperties(this.GetType());
}
/// <summary>
/// Returns a list of all properties which have a designer attribute attached.
/// </summary>
/// <param name="comparison">The comparison used to sort the design properties.</param>
/// <returns>A list of all properties relevant to the designer.</returns>
public IList<DesignerPropertyInfo> GetDesignerProperties(Comparison<DesignerPropertyInfo> comparison) {
return DesignerProperty.GetDesignerProperties(this.GetType(), comparison);
}
public bool AcceptDefaultPropertyByDragAndDrop() {
return GetDefaultPropertyByDragAndDrop().Property != null;
}
public bool SetDefaultPropertyByDragAndDrop(string value) {
return SetPropertyValue(GetDefaultPropertyNameByDragAndDrop(), value);
}
protected virtual string GetDefaultPropertyNameByDragAndDrop() {
return "Method";
}
private DesignerPropertyInfo GetDefaultPropertyByDragAndDrop() {
IList<DesignerPropertyInfo> properties = this.GetDesignerProperties();
foreach(DesignerPropertyInfo property in properties) {
if (property.Property != null && property.Property.Name == GetDefaultPropertyNameByDragAndDrop())
{ return property; }
}
return new DesignerPropertyInfo();
}
private bool SetPropertyValue(string propName, string value)
{
DesignerPropertyInfo property = GetDefaultPropertyByDragAndDrop();
if (property.Property != null) {
property.SetValueFromString(null, this, value);
return true;
}
return false;
}
public override string ToString() {
return _label;
}
/// <summary>
/// Used when a DesignerNodeProperty property is exported to format the output.
/// </summary>
/// <returns>The format string used to write out the value.</returns>
public virtual string GetNodePropertyExportString() {
return "\"{0}\"";
}
/// <summary>
/// Returns a list of properties that cannot be selected by a DesignerNodeProperty.
/// </summary>
/// <returns>Returns names of properties not allowed.</returns>
public virtual string[] GetNodePropertyExcludedProperties() {
return new string[] { "ClassVersion", "Version" };
}
/// <summary>
/// Checks if this node has an override for a given property name.
/// </summary>
/// <param name="propertyName">The name of the property we are checking.</param>
/// <returns>Returns true if there is an attachement override.</returns>
public bool HasOverrride(string propertyName) {
foreach(Attachments.Attachment attach in _attachments) {
Override overr = attach as Override;
if (overr != null && overr.PropertyToOverride == propertyName) {
return true;
}
}
return false;
}
public virtual string GenerateNewLabel() {
// generate the new label with the arguments
string newlabel = string.Empty;
// check all properties for one which must be shown as a parameter on the node
IList<DesignerPropertyInfo> properties = this.GetDesignerProperties(DesignerProperty.SortByDisplayOrder);
int paramCount = 0;
for (int p = 0; p < properties.Count; ++p) {
// property must be shown as a parameter on the node
if (properties[p].Attribute.Display == DesignerProperty.DisplayMode.Parameter) {
string strProperty = properties[p].GetDisplayValue(this);
if (paramCount > 0)
{ newlabel += !string.IsNullOrEmpty(this.MiddleLabel) ? this.MiddleLabel : " "; }
if (paramCount == 1 && this.HasFirstLabel) {
newlabel += " = ";
} else {
if (paramCount > 0) {
newlabel += " ";
}
}
newlabel += strProperty;
paramCount++;
}
}
if (paramCount > 0 && this.HasPrefixLabel)
{ newlabel = this.Label + "(" + newlabel + ")"; }
return newlabel;
}
}
}
| 37.989402 | 291 | 0.557429 | [
"BSD-3-Clause"
] | TonnyQ/behaviac | tools/designer/BehaviacDesignerBase/Nodes/Node.cs | 50,184 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using ShoelessJoeWebApi.DataAccess.DataModels;
namespace ShoelessJoeWebApi.DataAccess.Migrations
{
[DbContext(typeof(ShoelessdevContext))]
[Migration("20210518213528_AddedSite")]
partial class AddedSite
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.3")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Address", b =>
{
b.Property<int>("AddressId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("City")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<int>("StateId")
.HasColumnType("int");
b.Property<string>("Street")
.IsRequired()
.HasMaxLength(150)
.HasColumnType("nvarchar(150)");
b.Property<string>("ZipCode")
.IsRequired()
.HasMaxLength(5)
.HasColumnType("nvarchar(5)");
b.HasKey("AddressId");
b.HasIndex("StateId");
b.ToTable("Addresses");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Comment", b =>
{
b.Property<int>("BuyerId")
.HasColumnType("int");
b.Property<int>("SellerId")
.HasColumnType("int");
b.Property<string>("CommentBody")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("nvarchar(255)");
b.Property<string>("CommentHeader")
.IsRequired()
.HasMaxLength(70)
.HasColumnType("nvarchar(70)");
b.Property<DateTime>("DatePosted")
.ValueGeneratedOnAdd()
.HasColumnType("datetime2");
b.Property<int>("ShoeId")
.HasColumnType("int");
b.HasKey("BuyerId", "SellerId");
b.HasIndex("SellerId");
b.HasIndex("ShoeId");
b.ToTable("Comments");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Friend", b =>
{
b.Property<int>("SenderId")
.HasColumnType("int");
b.Property<int>("RecieverId")
.HasColumnType("int");
b.Property<DateTime?>("DateAccepted")
.ValueGeneratedOnAdd()
.HasColumnType("datetime2");
b.HasKey("SenderId", "RecieverId");
b.HasIndex("RecieverId");
b.ToTable("Friends");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Manufacter", b =>
{
b.Property<int>("ManufacterId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("AddressId")
.HasColumnType("int");
b.Property<bool>("IsApproved")
.HasColumnType("bit");
b.Property<string>("Name")
.HasMaxLength(75)
.HasColumnType("nvarchar(75)");
b.HasKey("ManufacterId");
b.HasIndex("AddressId")
.IsUnique();
b.ToTable("Manufacters");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Model", b =>
{
b.Property<int>("ModelId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("ManufacterId")
.HasColumnType("int");
b.Property<string>("ModelName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("ModelId");
b.HasIndex("ManufacterId");
b.ToTable("Models");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Reply", b =>
{
b.Property<int>("ReplyId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CommentBuyerId")
.HasColumnType("int");
b.Property<int>("CommentSellerId")
.HasColumnType("int");
b.Property<DateTime>("DatePosted")
.ValueGeneratedOnAdd()
.HasColumnType("datetime2");
b.Property<string>("ReplyBody")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("nvarchar(255)");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("ReplyId");
b.HasIndex("UserId");
b.HasIndex("CommentBuyerId", "CommentSellerId");
b.ToTable("Replies");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.School", b =>
{
b.Property<int>("SchoolId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("AddressId")
.HasColumnType("int");
b.Property<string>("SchoolName")
.IsRequired()
.HasMaxLength(75)
.HasColumnType("nvarchar(75)");
b.HasKey("SchoolId");
b.HasIndex("AddressId")
.IsUnique();
b.ToTable("Schools");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Shoe", b =>
{
b.Property<int>("ShoeId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<bool?>("BothShoes")
.HasColumnType("bit");
b.Property<double?>("LeftSize")
.HasColumnType("float");
b.Property<int>("ModelId")
.HasColumnType("int");
b.Property<double?>("RightSize")
.HasColumnType("float");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("ShoeId");
b.HasIndex("ModelId");
b.HasIndex("UserId");
b.ToTable("Shoes");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.ShoeImage", b =>
{
b.Property<int>("ImgGroupId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("LeftShoeLeft")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("nvarchar(255)");
b.Property<string>("LeftShoeRight")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("nvarchar(255)");
b.Property<string>("RightShoeLeft")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("nvarchar(255)");
b.Property<string>("RightShoeRight")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("nvarchar(255)");
b.Property<int>("ShoeId")
.HasColumnType("int");
b.HasKey("ImgGroupId");
b.HasIndex("ShoeId")
.IsUnique();
b.ToTable("ShoeImages");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Site", b =>
{
b.Property<int>("SiteId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("SiteName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("SiteId");
b.ToTable("Sites");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.State", b =>
{
b.Property<int>("StateId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("StateAbr")
.IsRequired()
.HasMaxLength(2)
.HasColumnType("nvarchar(2)");
b.Property<string>("StateName")
.IsRequired()
.HasMaxLength(75)
.HasColumnType("nvarchar(75)");
b.HasKey("StateId");
b.ToTable("States");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.User", b =>
{
b.Property<int>("UserId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<string>("FirstName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<bool?>("IsAdmin")
.HasColumnType("bit");
b.Property<string>("LastName")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("nvarchar(60)");
b.Property<string>("Password")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("nvarchar(255)");
b.Property<int?>("SchoolId")
.HasColumnType("int");
b.HasKey("UserId");
b.HasIndex("SchoolId");
b.ToTable("Users");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Address", b =>
{
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.State", "State")
.WithMany("Addresses")
.HasForeignKey("StateId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("State");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Comment", b =>
{
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.User", "Buyer")
.WithMany("BuyerComments")
.HasForeignKey("BuyerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.User", "Seller")
.WithMany("SellerComments")
.HasForeignKey("SellerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.Shoe", "Shoe")
.WithMany("Comments")
.HasForeignKey("ShoeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Buyer");
b.Navigation("Seller");
b.Navigation("Shoe");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Friend", b =>
{
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.User", "Reciever")
.WithMany("RecieverFriends")
.HasForeignKey("RecieverId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.User", "Sender")
.WithMany("SenderFriends")
.HasForeignKey("SenderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Reciever");
b.Navigation("Sender");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Manufacter", b =>
{
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.Address", "Address")
.WithOne("Manufacter")
.HasForeignKey("ShoelessJoeWebApi.DataAccess.DataModels.Manufacter", "AddressId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Address");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Model", b =>
{
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.Manufacter", "Manufacter")
.WithMany("Models")
.HasForeignKey("ManufacterId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacter");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Reply", b =>
{
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.User", "User")
.WithMany("Replies")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.Comment", "Comment")
.WithMany("Replies")
.HasForeignKey("CommentBuyerId", "CommentSellerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Comment");
b.Navigation("User");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.School", b =>
{
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.Address", "Address")
.WithOne("School")
.HasForeignKey("ShoelessJoeWebApi.DataAccess.DataModels.School", "AddressId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Address");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Shoe", b =>
{
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.Model", "Model")
.WithMany("Shoes")
.HasForeignKey("ModelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.User", "User")
.WithMany("Shoes")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Model");
b.Navigation("User");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.ShoeImage", b =>
{
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.Shoe", "Shoe")
.WithOne("ShoeImage")
.HasForeignKey("ShoelessJoeWebApi.DataAccess.DataModels.ShoeImage", "ShoeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Shoe");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.User", b =>
{
b.HasOne("ShoelessJoeWebApi.DataAccess.DataModels.School", "School")
.WithMany("Students")
.HasForeignKey("SchoolId");
b.Navigation("School");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Address", b =>
{
b.Navigation("Manufacter");
b.Navigation("School");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Comment", b =>
{
b.Navigation("Replies");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Manufacter", b =>
{
b.Navigation("Models");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Model", b =>
{
b.Navigation("Shoes");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.School", b =>
{
b.Navigation("Students");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.Shoe", b =>
{
b.Navigation("Comments");
b.Navigation("ShoeImage");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.State", b =>
{
b.Navigation("Addresses");
});
modelBuilder.Entity("ShoelessJoeWebApi.DataAccess.DataModels.User", b =>
{
b.Navigation("BuyerComments");
b.Navigation("RecieverFriends");
b.Navigation("Replies");
b.Navigation("SellerComments");
b.Navigation("SenderFriends");
b.Navigation("Shoes");
});
#pragma warning restore 612, 618
}
}
}
| 37.386926 | 125 | 0.459997 | [
"MIT"
] | TClaypool00/ShoelessJoeApiV2 | ShoelessJoeWebApi.DataAccess/Migrations/20210518213528_AddedSite.Designer.cs | 21,163 | 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.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.HttpRepl.Commands;
using Microsoft.HttpRepl.Fakes;
using Microsoft.HttpRepl.Preferences;
using Microsoft.HttpRepl.Resources;
using Microsoft.Repl.ConsoleHandling;
using Microsoft.Repl.Parsing;
using Xunit;
namespace Microsoft.HttpRepl.Tests.Commands
{
public class OptionsCommandTests : CommandTestsBase
{
private string _baseAddress;
private string _path;
private IDictionary<string, string> _urlsWithResponse = new Dictionary<string, string>();
public OptionsCommandTests()
{
_baseAddress = "http://localhost:5050/";
_path = "this/is/a/test/route";
_urlsWithResponse.Add(_baseAddress, "Header value for root OPTIONS request.");
_urlsWithResponse.Add(_baseAddress + _path, "Header value for OPTIONS request with route.");
}
[Fact]
public async Task ExecuteAsync_WithNoBasePath_VerifyError()
{
ArrangeInputs(commandText: "OPTIONS",
baseAddress: null,
path: null,
urlsWithResponse: null,
out MockedShellState shellState,
out HttpState httpState,
out ICoreParseResult parseResult,
out MockedFileSystem fileSystem,
out IPreferences preferences);
string expectedErrorMessage = Strings.Error_NoBasePath.SetColor(httpState.ErrorColor);
OptionsCommand optionsCommand = new OptionsCommand(fileSystem, preferences);
await optionsCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);
Assert.Equal(expectedErrorMessage, shellState.ErrorMessage);
}
[Fact]
public async Task ExecuteAsync_WithMultipartRoute_VerifyOutput()
{
ArrangeInputs(commandText: "OPTIONS",
baseAddress: _baseAddress,
path: _path,
urlsWithResponse: _urlsWithResponse,
out MockedShellState shellState,
out HttpState httpState,
out ICoreParseResult parseResult,
out MockedFileSystem fileSystem,
out IPreferences preferences,
header: "X-HTTPREPL-TESTHEADER");
OptionsCommand optionsCommand = new OptionsCommand(fileSystem, preferences);
await optionsCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);
string expectedHeader = "X-HTTPREPL-TESTHEADER: Header value for OPTIONS request with route.";
List<string> result = shellState.Output;
Assert.Equal(2, result.Count);
Assert.Contains("HTTP/1.1 200 OK", result);
Assert.Contains(expectedHeader, result);
}
[Fact]
public async Task ExecuteAsync_WithOnlyBaseAddress_VerifyOutput()
{
ArrangeInputs(commandText: "Options",
baseAddress: _baseAddress,
path: null,
urlsWithResponse: _urlsWithResponse,
out MockedShellState shellState,
out HttpState httpState,
out ICoreParseResult parseResult,
out MockedFileSystem fileSystem,
out IPreferences preferences,
header: "X-HTTPREPL-TESTHEADER");
OptionsCommand optionsCommand = new OptionsCommand(fileSystem, preferences);
await optionsCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);
string expectedHeader = "X-HTTPREPL-TESTHEADER: Header value for root OPTIONS request.";
List<string> result = shellState.Output;
Assert.Equal(2, result.Count);
Assert.Contains("HTTP/1.1 200 OK", result);
Assert.Contains(expectedHeader, result);
}
}
}
| 39.711538 | 111 | 0.646247 | [
"Apache-2.0"
] | Tadimsky/HttpRepl | src/Microsoft.HttpRepl.Tests/Commands/OptionsCommandTests.cs | 4,130 | C# |
using System.IO;
using System.Threading.Tasks;
namespace CrossImageHandling
{
public interface IImageHandlingService
{
Task<Stream> PickImageFromGalleryAsync();
int[] GetImageSizeFromStream(byte[] streamData);
byte[] GetImagePixelsFromStream(byte[] streamData);
byte[] GetImageStreamFromPixels(byte[] pixelData, int width, int height);
byte[] GetImageStreamAtSizeFromStream(byte[] streamData, int targetWidth, int targetHeight);
bool SaveImageToGallery(byte[] streamData);
}
} | 35.866667 | 100 | 0.72119 | [
"MIT"
] | Jannik0/Xamarin.CrossImageHandling | CrossImageHandling/CrossImageHandling/IImageHandlingService.cs | 540 | C# |
using System;
using System.Linq.Expressions;
namespace FlexLabs.EntityFrameworkCore.Upsert
{
/// <summary>
/// A class that represents a known type of expression
/// </summary>
public class KnownExpressions
{
/// <summary>
/// Initialises a new instance of the class
/// </summary>
/// <param name="sourceType">The type of the object that the property is read from</param>
/// <param name="sourceProperty">The name of the property that is read</param>
/// <param name="expressionType">The type of the operation being executed</param>
/// <param name="value">The value used in the expression</param>
public KnownExpressions(Type sourceType, string sourceProperty, ExpressionType expressionType, object value)
{
SourceType = sourceType;
SourceProperty = sourceProperty;
ExpressionType = expressionType;
Value = value;
}
/// <summary>
/// The type of the object that the property is read from
/// </summary>
public Type SourceType { get; }
/// <summary>
/// The name of the property that is read
/// </summary>
public string SourceProperty { get; }
/// <summary>
/// The type of the operation being executed
/// </summary>
public ExpressionType ExpressionType { get; }
/// <summary>
/// The value used in the expression
/// </summary>
public object Value { get; }
}
}
| 33 | 116 | 0.594455 | [
"MIT"
] | LonghronShen/FlexLabs.Upsert | src/FlexLabs.EntityFrameworkCore.Upsert/KnownExpressions.cs | 1,553 | C# |
using BinaryGo.Binary.Deserialize;
using BinaryGo.Interfaces;
using BinaryGo.IO;
using BinaryGo.Json;
using System;
namespace BinaryGo.Runtime.Variables.Nullables
{
/// <summary>
/// Date and time serializer and deserializer
/// </summary>
public class DateTimeNullableVariable : BaseVariable, ISerializationVariable<DateTime?>
{
/// <summary>
/// default constructor to initialize
/// </summary>
public DateTimeNullableVariable() : base(typeof(DateTime?))
{
}
/// <summary>
/// Initalizes TypeGo variable
/// </summary>
/// <param name="typeGoInfo">TypeGo variable to initialize</param>
/// <param name="options">Serializer or deserializer options</param>
public void Initialize(TypeGoInfo<DateTime?> typeGoInfo, ITypeOptions options)
{
typeGoInfo.IsNoQuotesValueType = false;
//set the default value of variable
typeGoInfo.DefaultValue = default;
//set delegates to access faster and make it pointer directly usage
typeGoInfo.JsonSerialize = JsonSerialize;
//set delegates to access faster and make it pointer directly usage for json deserializer
typeGoInfo.JsonDeserialize = JsonDeserialize;
//set delegates to access faster and make it pointer directly usage for binary serializer
typeGoInfo.BinarySerialize = BinarySerialize;
//set delegates to access faster and make it pointer directly usage for binary deserializer
typeGoInfo.BinaryDeserialize = BinaryDeserialize;
}
/// <summary>
/// format of datetime serialization
/// </summary>
public string Format = "yyyy-MM-ddTHH\\:mm\\:sszzz";
/// <summary>
/// json serialize
/// </summary>
/// <param name="handler"></param>
/// <param name="value"></param>
public void JsonSerialize(ref JsonSerializeHandler handler, ref DateTime? value)
{
if (value.HasValue)
{
handler.TextWriter.Write(JsonConstantsString.Quotes);
handler.TextWriter.Write(value.Value.ToString(Format, CurrentCulture));
handler.TextWriter.Write(JsonConstantsString.Quotes);
}
else
handler.TextWriter.Write(JsonConstantsString.Null);
}
/// <summary>
/// json deserialize
/// </summary>
/// <param name="text">json text</param>
/// <returns>convert text to type</returns>
public DateTime? JsonDeserialize(ref ReadOnlySpan<char> text)
{
if (DateTime.TryParse(text, out DateTime value))
return value;
return default;
}
/// <summary>
/// Binary serialize
/// </summary>
/// <param name="stream">stream to write</param>
/// <param name="value">value to serialize</param>
public void BinarySerialize(ref BufferBuilder stream, ref DateTime? value)
{
if (value.HasValue)
{
stream.Write(1);
stream.Write(BitConverter.GetBytes(value.Value.Ticks).AsSpan());
}
else
stream.Write(0);
}
/// <summary>
/// Binary deserialize
/// </summary>
/// <param name="reader">Reader of binary</param>
public DateTime? BinaryDeserialize(ref BinarySpanReader reader)
{
if (reader.Read() == 1)
return new DateTime(BitConverter.ToInt64(reader.Read(sizeof(long))));
return default;
}
}
}
| 34.5 | 103 | 0.58642 | [
"MIT"
] | Ali-YousefiTelori/BinaryGo | Engine/BinaryGo/Runtime/Variables/Nullables/DateTimeNullableVariable.cs | 3,728 | C# |
// this class generates OnSerialize/OnDeserialize for SyncListStructs
using Mono.Cecil;
using Mono.Cecil.Cil;
namespace Mirror.Weaver
{
static class SyncListStructProcessor
{
public static void Process(TypeDefinition td)
{
// find item type
GenericInstanceType gt = (GenericInstanceType)td.BaseType;
if (gt.GenericArguments.Count == 0)
{
Weaver.fail = true;
Log.Error("SyncListStructProcessor no generic args");
return;
}
TypeReference itemType = Weaver.scriptDef.MainModule.ImportReference(gt.GenericArguments[0]);
Weaver.DLog(td, "SyncListStructProcessor Start item:" + itemType.FullName);
Weaver.ResetRecursionCount();
MethodReference writeItemFunc = GenerateSerialization(td, itemType);
if (Weaver.fail)
{
return;
}
MethodReference readItemFunc = GenerateDeserialization(td, itemType);
if (readItemFunc == null || writeItemFunc == null)
return;
Weaver.DLog(td, "SyncListStructProcessor Done");
}
// serialization of individual element
static MethodReference GenerateSerialization(TypeDefinition td, TypeReference itemType)
{
Weaver.DLog(td, " GenerateSerialization");
foreach (var m in td.Methods)
{
if (m.Name == "SerializeItem")
return m;
}
MethodDefinition serializeFunc = new MethodDefinition("SerializeItem", MethodAttributes.Public |
MethodAttributes.Virtual |
MethodAttributes.Public |
MethodAttributes.HideBySig,
Weaver.voidType);
serializeFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.scriptDef.MainModule.ImportReference(Weaver.NetworkWriterType)));
serializeFunc.Parameters.Add(new ParameterDefinition("item", ParameterAttributes.None, itemType));
ILProcessor serWorker = serializeFunc.Body.GetILProcessor();
if (itemType.IsGenericInstance)
{
Weaver.fail = true;
Log.Error("GenerateSerialization for " + Helpers.PrettyPrintType(itemType) + " failed. Struct passed into SyncListStruct<T> can't have generic parameters");
return null;
}
foreach (FieldDefinition field in itemType.Resolve().Fields)
{
if (field.IsStatic || field.IsPrivate || field.IsSpecialName)
continue;
FieldReference importedField = Weaver.scriptDef.MainModule.ImportReference(field);
TypeDefinition ft = importedField.FieldType.Resolve();
if (ft.HasGenericParameters)
{
Weaver.fail = true;
Log.Error("GenerateSerialization for " + td.Name + " [" + ft + "/" + ft.FullName + "]. [SyncListStruct] member cannot have generic parameters.");
return null;
}
if (ft.IsInterface)
{
Weaver.fail = true;
Log.Error("GenerateSerialization for " + td.Name + " [" + ft + "/" + ft.FullName + "]. [SyncListStruct] member cannot be an interface.");
return null;
}
MethodReference writeFunc = Weaver.GetWriteFunc(field.FieldType);
if (writeFunc != null)
{
serWorker.Append(serWorker.Create(OpCodes.Ldarg_1));
serWorker.Append(serWorker.Create(OpCodes.Ldarg_2));
serWorker.Append(serWorker.Create(OpCodes.Ldfld, importedField));
serWorker.Append(serWorker.Create(OpCodes.Call, writeFunc));
}
else
{
Weaver.fail = true;
Log.Error("GenerateSerialization for " + td.Name + " unknown type [" + ft + "/" + ft.FullName + "]. [SyncListStruct] member variables must be basic types.");
return null;
}
}
serWorker.Append(serWorker.Create(OpCodes.Ret));
td.Methods.Add(serializeFunc);
return serializeFunc;
}
static MethodReference GenerateDeserialization(TypeDefinition td, TypeReference itemType)
{
Weaver.DLog(td, " GenerateDeserialization");
foreach (var m in td.Methods)
{
if (m.Name == "DeserializeItem")
return m;
}
MethodDefinition serializeFunc = new MethodDefinition("DeserializeItem", MethodAttributes.Public |
MethodAttributes.Virtual |
MethodAttributes.Public |
MethodAttributes.HideBySig,
itemType);
serializeFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.scriptDef.MainModule.ImportReference(Weaver.NetworkReaderType)));
ILProcessor serWorker = serializeFunc.Body.GetILProcessor();
serWorker.Body.InitLocals = true;
serWorker.Body.Variables.Add(new VariableDefinition(itemType));
// init item instance
serWorker.Append(serWorker.Create(OpCodes.Ldloca, 0));
serWorker.Append(serWorker.Create(OpCodes.Initobj, itemType));
foreach (FieldDefinition field in itemType.Resolve().Fields)
{
if (field.IsStatic || field.IsPrivate || field.IsSpecialName)
continue;
FieldReference importedField = Weaver.scriptDef.MainModule.ImportReference(field);
TypeDefinition ft = importedField.FieldType.Resolve();
MethodReference readerFunc = Weaver.GetReadFunc(field.FieldType);
if (readerFunc != null)
{
serWorker.Append(serWorker.Create(OpCodes.Ldloca, 0));
serWorker.Append(serWorker.Create(OpCodes.Ldarg_1));
serWorker.Append(serWorker.Create(OpCodes.Call, readerFunc));
serWorker.Append(serWorker.Create(OpCodes.Stfld, importedField));
}
else
{
Weaver.fail = true;
Log.Error("GenerateDeserialization for " + td.Name + " unknown type [" + ft + "]. [SyncListStruct] member variables must be basic types.");
return null;
}
}
serWorker.Append(serWorker.Create(OpCodes.Ldloc_0));
serWorker.Append(serWorker.Create(OpCodes.Ret));
td.Methods.Add(serializeFunc);
return serializeFunc;
}
}
}
| 42.212121 | 177 | 0.568701 | [
"MIT"
] | Alkanov/Mirror | Mirror/Weaver/Processors/SyncListStructProcessor.cs | 6,965 | C# |
using System.Collections.Generic;
using System.Web.Routing;
using DynamicMVC.UI.DynamicMVC.ViewModels.DynamicPropertyViewModels;
namespace DynamicMVC.UI.DynamicMVC.ViewModels
{
public class DynamicIndexItemViewModel
{
public DynamicIndexItemViewModel()
{
DynamicPropertyIndexViewModels = new List<DynamicPropertyIndexViewModel>();
}
public bool ShowDelete { get; set; }
public bool ShowEdit { get; set; }
public bool ShowDetails { get; set; }
public dynamic Item { get; set; }
public string TypeName { get; set; }
public RouteValueDictionaryWrapper RouteValueDictionaryWrapper { get; set; }
public List<DynamicPropertyIndexViewModel> DynamicPropertyIndexViewModels { get; set; }
}
}
| 33.25 | 95 | 0.692982 | [
"Apache-2.0"
] | PrecisionWebTechnologies/DynamicMVC | DynamicMVC.UI/DynamicMVC/ViewModels/DynamicIndexItemViewModel.cs | 798 | C# |
using System;
namespace OurUmbraco.MarketPlace.Interfaces
{
public interface IVendor
{
IMember Member { get; set; }
string VendorCompanyName { get; set; }
string VendorDescription { get; set; }
IMediaFile VendorLogo { get; set; }
string VendorUrl { get; set; }
string SupportUrl { get; set; }
string BillingContactEmail { get; set; }
string SupportContactEmail { get; set; }
string VendorCountry { get; set; }
string BaseCurrency { get; set; }
string PayPalAccount { get; set; }
string IBAN { get; set; }
string SWIFT { get; set; }
string BSB { get; set; }
string AccountNumber { get; set; }
string VATNumber { get; set; }
string TaxId { get; set; }
int EconomicId { get; set; }
DateTime DeliTermsAgreementDate { get; set; }
}
}
| 31.964286 | 53 | 0.582123 | [
"MIT"
] | AaronSadlerUK/OurUmbraco | OurUmbraco/MarketPlace/Interfaces/IVendor.cs | 897 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace QuicDataServer.Models
{
public class RpsTestPublishResult : IAuthorizable
{
public string? MachineName { get; set; }
[Required]
public string PlatformName { get; set; } = null!;
[Required]
public string TestName { get; set; } = null!;
[Required]
public string CommitHash { get; set; } = null!;
[Required]
public string AuthKey { get; set; } = null!;
[Required]
public IEnumerable<double> IndividualRunResults { get; set; } = null!;
[Required]
public int ConnectionCount { get; set; }
[Required]
public int RequestSize { get; set; }
[Required]
public int ResponseSize { get; set; }
[Required]
public int ParallelRequests { get; set; }
}
}
| 29.393939 | 78 | 0.609278 | [
"MIT"
] | CH-ND-N/msquic | src/perf/dbserver/Models/RpsTestPublishResult .cs | 972 | C# |
namespace Ryujinx.HLE.HOS.Services.Bgct
{
[Service("bgtc:sc")]
class IStateControlService : IpcService
{
public IStateControlService(ServiceCtx context) { }
}
} | 23.125 | 59 | 0.675676 | [
"MIT"
] | 0MrDarn0/Ryujinx | Ryujinx.HLE/HOS/Services/Bgtc/IStateControlService.cs | 187 | C# |
// Copyright 2008-2010 Portland State University, Conservation Biology Institute
// Authors: Brendan C. Ward, Robert M. Scheller
using Landis.Utilities;
using Landis.Core;
using Landis.SpatialModeling;
using System.Collections.Generic;
namespace Landis.Extension.Output.CohortStats
{
/// <summary>
/// A parser that reads the plug-in's parameters from text input.
/// </summary>
public class InputParameterParser
: TextParser<IInputParameters>
{
public override string LandisDataValue
{
get
{
return PlugIn.ExtensionName;
}
}
//---------------------------------------------------------------------
public InputParameterParser()
{
}
//---------------------------------------------------------------------
protected override IInputParameters Parse()
{
InputVar<string> landisData = new InputVar<string>("LandisData");
ReadVar(landisData);
if (landisData.Value.Actual != PlugIn.ExtensionName)
throw new InputValueException(landisData.Value.String, "The value is not \"{0}\"", PlugIn.ExtensionName);
InputParameters parameters = new InputParameters();
parameters.AgeStatSpecies = new Dictionary<string, IEnumerable<ISpecies>>();
parameters.SiteAgeStats = new List<string>();
parameters.SiteSppStats = new List<string>();
Dictionary<string,int> statLines = new Dictionary<string, int>();
InputVar<string> sectionNameVar = new InputVar<string>("Section Names");
InputVar<string> statLineVar = new InputVar<string>("");
int lineNumber = 0;
StringReader currentLine;
string word="";
string stat = "";
List<string> sectionNames = new List<string>();
sectionNames.Add("SpeciesAgeStats");
sectionNames.Add("SiteAgeStats");
sectionNames.Add("SiteSpeciesStats");
List<string> spp_age_statsNames = new List<string>();
spp_age_statsNames.Add("MAX");
spp_age_statsNames.Add("MIN");
spp_age_statsNames.Add("MED");
spp_age_statsNames.Add("AVG");
spp_age_statsNames.Add("SD");
//spp_age_statsNames.Add("RICH");
List<string> site_age_statsNames = new List<string>();
site_age_statsNames.Add("MAX");
site_age_statsNames.Add("MIN");
site_age_statsNames.Add("MED");
site_age_statsNames.Add("AVG");
site_age_statsNames.Add("SD");
site_age_statsNames.Add("RICH");
site_age_statsNames.Add("EVEN");
site_age_statsNames.Add("COUNT");
List<string> site_spp_statsNames = new List<string>();
site_spp_statsNames.Add("RICH");
InputVar<int> timestep = new InputVar<int>("Timestep");
ReadVar(timestep);
parameters.Timestep = timestep.Value;
SkipBlankLines();
while (!AtEndOfInput)
{
currentLine = new StringReader(CurrentLine);
TextReader.SkipWhitespace(currentLine);
word = TextReader.ReadWord(currentLine);
if (word != "")
{
if (!sectionNames.Contains(word))
throw new InputVariableException(sectionNameVar, "Found the name {0} but expected one of {1}", word, ListToString(sectionNames));
GetNextLine();
SkipBlankLines();
if (word == "SpeciesAgeStats")
{
ISpecies species;
List<ISpecies> selectedSpecies;
statLines = new Dictionary<string, int>();
InputVar<string> mapNames = new InputVar<string>("MapNames");
ReadVar(mapNames);
parameters.SppAgeStats_MapNames = mapNames.Value;
while (!AtEndOfInput && !sectionNames.Contains(CurrentName))
{
selectedSpecies = new List<ISpecies>();
currentLine = new StringReader(CurrentLine);
TextReader.SkipWhitespace(currentLine);
stat = TextReader.ReadWord(currentLine);
if (!spp_age_statsNames.Contains(stat))
throw new InputVariableException(statLineVar, "Found the name {0} but expected one of {1}", stat, ListToString(spp_age_statsNames));
if (statLines.TryGetValue(stat, out lineNumber))
{
throw new InputVariableException(statLineVar, "The statistic {0} was previously used on line {1}",
stat, lineNumber);
}
statLines[stat] = LineNumber;
TextReader.SkipWhitespace(currentLine);
word = TextReader.ReadWord(currentLine);
if (word == "all" || word == "All")
{
parameters.AgeStatSpecies[word] = PlugIn.ModelCore.Species;
CheckNoDataAfter("the " + word + " parameter");
}
else if (word!="")
{
List<string> species_added = new List<string>();
species = GetSpecies(word);
selectedSpecies.Add(species);
species_added.Add(word);
TextReader.SkipWhitespace(currentLine);
while (currentLine.Peek() != -1)
{
word = TextReader.ReadWord(currentLine);
if (word == "all" || word == "All")
throw new InputVariableException(statLineVar, "Line {0}: Cannot use the keyword {1} with a list of species",
LineNumber, word);
if (species_added.Contains(word))
throw new InputVariableException(statLineVar, "The species {0} was previously used on line {1}",
word, LineNumber);
species = GetSpecies(word);
selectedSpecies.Add(species);
species_added.Add(word);
TextReader.SkipWhitespace(currentLine);
}
parameters.AgeStatSpecies[stat] = selectedSpecies;
}
GetNextLine();
SkipBlankLines();
if (selectedSpecies.Count == 0)
{
throw new InputVariableException(statLineVar, "No species were entered for the statistic {0} on line {1}",
stat, LineNumber);
}
}
}
else if (word == "SiteAgeStats")
{
statLines = new Dictionary<string, int>();
List<string> selectedAgeStats = new List<string>();
InputVar<string> mapNames = new InputVar<string>("MapNames");
ReadVar(mapNames);
parameters.SiteAgeStats_MapNames = mapNames.Value;
while (!AtEndOfInput && !sectionNames.Contains(CurrentName))
{
currentLine = new StringReader(CurrentLine);
TextReader.SkipWhitespace(currentLine);
stat = TextReader.ReadWord(currentLine);
if (!site_age_statsNames.Contains(stat))
throw new InputVariableException(statLineVar, "Found the name {0} but expected one of {1}", stat, ListToString(site_age_statsNames));
if (statLines.TryGetValue(stat, out lineNumber))
{
throw new InputVariableException(statLineVar, "The statistic {0} was previously used on line {1}",
stat, lineNumber);
}
statLines[stat] = LineNumber;
selectedAgeStats.Add(stat);
GetNextLine();
SkipBlankLines();
}
parameters.SiteAgeStats = selectedAgeStats;
}
else if (word == "SiteSpeciesStats")
{
statLines = new Dictionary<string, int>();
List<string> selectedSiteSppStats = new List<string>();
InputVar<string> mapNames = new InputVar<string>("MapNames");
ReadVar(mapNames);
parameters.SiteSppStats_MapNames = mapNames.Value;
while (!AtEndOfInput && !sectionNames.Contains(CurrentName))
{
currentLine = new StringReader(CurrentLine);
TextReader.SkipWhitespace(currentLine);
stat = TextReader.ReadWord(currentLine);
if (!site_spp_statsNames.Contains(stat))
throw new InputVariableException(statLineVar, "Found the name {0} but expected one of {1}", stat, ListToString(site_spp_statsNames));
if (statLines.TryGetValue(stat, out lineNumber))
{
throw new InputVariableException(statLineVar, "The statistic {0} was previously used on line {1}",
stat, lineNumber);
}
statLines[stat] = LineNumber;
selectedSiteSppStats.Add(stat);
GetNextLine();
SkipBlankLines();
}
parameters.SiteSppStats = selectedSiteSppStats;
}
}
else
{
GetNextLine();
SkipBlankLines();
}
}
return parameters; //.GetComplete();
}
//---------------------------------------------------------------------
protected ISpecies GetSpecies(InputValue<string> name)
{
ISpecies species = PlugIn.ModelCore.Species[name.Actual];
if (species == null)
throw new InputValueException(name.String,
"{0} is not a species name.",
name.String);
return species;
}
//---------------------------------------------------------------------
protected ISpecies GetSpecies(string name)
{
ISpecies species = PlugIn.ModelCore.Species[name];
if (species == null)
throw new InputValueException(name,
"{0} is not a species name.",
name);
return species;
}
//---------------------------------------------------------------------
private string ListToString(List<string> curList)
{
string enum_string = "";
foreach (string entry in curList)
{
enum_string += entry + " ";
}
return enum_string;
}
//---------------------------------------------------------------------
private void SkipBlankLines()
{
while (!AtEndOfInput)
{
StringReader currentLine = new StringReader(CurrentLine);
TextReader.SkipWhitespace(currentLine);
string word = TextReader.ReadWord(currentLine);
if (word != "")
return;
GetNextLine();
}
}
}
}
| 44.527397 | 165 | 0.445854 | [
"Apache-2.0"
] | mshukuno/Extension-Output-Cohort-Statistics | src/InputParametersParser.cs | 13,002 | C# |
using System.Collections.Generic;
using System.Text;
using CssUI.CSS.Serialization;
using CssUI.DOM;
namespace CssUI.CSS.Media
{
public class MediaCondition : IMediaCondition, ICssSerializeable
{/* https://www.w3.org/TR/mediaqueries-4/#media-condition */
#region Properites
private readonly LinkedList<IMediaCondition> Conditions;
private readonly EMediaCombinator Op;
#endregion
#region Constructor
public MediaCondition(EMediaCombinator op, IEnumerable<IMediaCondition> conditions)
{
Conditions = new LinkedList<IMediaCondition>(conditions);
Op = op;
}
#endregion
public bool Matches(Document document)
{
bool matches = true;
if (Op == EMediaCombinator.OR) matches = false;
foreach (IMediaCondition condition in Conditions)
{
if (condition.Matches(document))
{
if (Op == EMediaCombinator.NOT)
{
return false;
}
else if (Op == EMediaCombinator.OR)
{
matches = true;
return true;
}
}
else
{
if (Op == EMediaCombinator.AND)
{
matches = false;
}
}
}
return matches;
}
public string Serialize()
{
if (Conditions.Count <= 0)
{
return string.Empty;
}
StringBuilder sb = new StringBuilder();
sb.Append(UnicodeCommon.CHAR_LEFT_PARENTHESES);
bool first = true;
foreach (IMediaCondition Condition in Conditions)
{
if (!first)
{
sb.Append(UnicodeCommon.CHAR_SPACE);
sb.Append(Lookup.Keyword(Op));
sb.Append(UnicodeCommon.CHAR_SPACE);
}
sb.Append(Condition.Serialize());
first = false;
}
sb.Append(UnicodeCommon.CHAR_RIGHT_PARENTHESES);
return sb.ToString();
}
}
}
| 26.222222 | 91 | 0.474576 | [
"MIT"
] | dsisco11/CssUI | CssUI/CSS/Media/MediaCondition.cs | 2,362 | C# |
using System;
using System.Reflection;
namespace SimpleExpressionEvaluator.Utilities
{
public class FieldMemberAccessor : IMemberAccessor
{
private readonly FieldInfo _field;
public FieldMemberAccessor(FieldInfo field)
{
_field = field;
}
public object GetValue(object target)
{
return _field.GetValue(target);
}
public bool IsStatic
{
get { return _field.IsStatic; }
}
public Type MemberType
{
get { return _field.FieldType;}
}
}
}
| 19.451613 | 54 | 0.568823 | [
"MIT"
] | Plankankul/SharpDevelop-w-Framework | src/AddIns/Misc/Reports/ICSharpCode.Reports.Core/Project/Expressions/SimpleExpressionEvaluator/Utilities/FieldMemberAccessor.cs | 605 | C# |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
namespace BeardedManStudios.Forge.Networking.Unity.Lobby
{
public class LobbyPlayerItem : MonoBehaviour
{
public Color[] TeamColors;
public Color[] AvatarColors;
public GameObject KickButton;
public Image AvatarBG;
public Text AvatarID;
public InputField PlayerName;
public Text PlayerTeamID;
public Button[] Buttons;
[HideInInspector]
public Transform ThisTransform;
[HideInInspector]
public GameObject ThisGameObject;
public LobbyPlayer AssociatedPlayer { get; private set; }
private LobbyManager _manager;
public void Init(LobbyManager manager)
{
ThisGameObject = gameObject;
ThisTransform = transform;
_manager = manager;
}
public void Setup(LobbyPlayer associatedPlayer, bool interactableValue)
{
ToggleInteractables(interactableValue);
AssociatedPlayer = associatedPlayer;
ChangeAvatarID(associatedPlayer.AvatarID);
ChangeName(associatedPlayer.Name);
ChangeTeam(associatedPlayer.TeamID);
}
public void SetParent(Transform parent)
{
ThisTransform.SetParent(parent);
ThisTransform.localPosition = Vector3.zero;
ThisTransform.localScale = Vector3.one;
}
public void KickPlayer()
{
_manager.KickPlayer(this);
}
public void RequestChangeTeam()
{
int nextID = AssociatedPlayer.TeamID + 1;
if (nextID >= TeamColors.Length)
nextID = 0;
_manager.ChangeTeam(this, nextID);
}
public void RequestChangeAvatarID()
{
int nextID = AssociatedPlayer.AvatarID + 1;
if (nextID >= AvatarColors.Length)
nextID = 0;
_manager.ChangeAvatarID(this, nextID);
}
public void RequestChangeName()
{
_manager.ChangeName(this, PlayerName.text);
}
public void ChangeAvatarID(int id)
{
Color avatarColor = Color.white;
//Note: This is just an example, you are free to make your own team colors and
// change this to however you see fit
if (TeamColors.Length > id && id >= 0)
avatarColor = AvatarColors[id];
AvatarID.text = id.ToString();
AvatarBG.color = avatarColor;
}
public void ChangeName(string name)
{
PlayerName.text = name;
}
public void ChangeTeam(int id)
{
PlayerTeamID.text = string.Format("Team {0}", id);
}
public void ToggleInteractables(bool value)
{
for (int i = 0; i < Buttons.Length; ++i)
Buttons[i].interactable = value;
AvatarBG.raycastTarget = value;
PlayerTeamID.raycastTarget = value;
PlayerName.interactable = value;
}
public void ToggleObject(bool value)
{
ThisGameObject.SetActive(value);
}
}
} | 22.752137 | 81 | 0.69985 | [
"MIT"
] | AzeeSoft/Forge-Networking-Test | Assets/Bearded Man Studios Inc/Modules/LobbySystem/LobbyPlayerItem.cs | 2,664 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Agent.Sdk;
using Agent.Sdk.Knob;
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Build
{
[ServiceLocator(Default = typeof(GitCommandManager))]
public interface IGitCommandManager : IAgentService
{
bool EnsureGitVersion(Version requiredVersion, bool throwOnNotMatch);
bool EnsureGitLFSVersion(Version requiredVersion, bool throwOnNotMatch);
// setup git execution info, git location, version, useragent, execpath
Task LoadGitExecutionInfo(IExecutionContext context, bool useBuiltInGit);
// git init <LocalDir>
Task<int> GitInit(IExecutionContext context, string repositoryPath);
// git fetch --tags --prune --progress --no-recurse-submodules [--depth=15] origin [+refs/pull/*:refs/remote/pull/*]
Task<int> GitFetch(IExecutionContext context, string repositoryPath, string remoteName, int fetchDepth, List<string> refSpec, string additionalCommandLine, CancellationToken cancellationToken);
// git lfs fetch origin [ref]
Task<int> GitLFSFetch(IExecutionContext context, string repositoryPath, string remoteName, string refSpec, string additionalCommandLine, CancellationToken cancellationToken);
// git checkout -f --progress <commitId/branch>
Task<int> GitCheckout(IExecutionContext context, string repositoryPath, string committishOrBranchSpec, CancellationToken cancellationToken);
// git clean -ffdx
Task<int> GitClean(IExecutionContext context, string repositoryPath);
// git reset --hard HEAD
Task<int> GitReset(IExecutionContext context, string repositoryPath);
// get remote add <origin> <url>
Task<int> GitRemoteAdd(IExecutionContext context, string repositoryPath, string remoteName, string remoteUrl);
// get remote set-url <origin> <url>
Task<int> GitRemoteSetUrl(IExecutionContext context, string repositoryPath, string remoteName, string remoteUrl);
// get remote set-url --push <origin> <url>
Task<int> GitRemoteSetPushUrl(IExecutionContext context, string repositoryPath, string remoteName, string remoteUrl);
// git submodule foreach --recursive "git clean -ffdx"
Task<int> GitSubmoduleClean(IExecutionContext context, string repositoryPath);
// git submodule foreach --recursive "git reset --hard HEAD"
Task<int> GitSubmoduleReset(IExecutionContext context, string repositoryPath);
// git submodule update --init --force [--depth=15] [--recursive]
Task<int> GitSubmoduleUpdate(IExecutionContext context, string repositoryPath, int fetchDepth, string additionalCommandLine, bool recursive, CancellationToken cancellationToken);
// git submodule sync [--recursive]
Task<int> GitSubmoduleSync(IExecutionContext context, string repositoryPath, bool recursive, CancellationToken cancellationToken);
// git config --get remote.origin.url
Task<Uri> GitGetFetchUrl(IExecutionContext context, string repositoryPath);
// git config <key> <value>
Task<int> GitConfig(IExecutionContext context, string repositoryPath, string configKey, string configValue);
// git config --get-all <key>
Task<bool> GitConfigExist(IExecutionContext context, string repositoryPath, string configKey);
// git config --unset-all <key>
Task<int> GitConfigUnset(IExecutionContext context, string repositoryPath, string configKey);
// git config gc.auto 0
Task<int> GitDisableAutoGC(IExecutionContext context, string repositoryPath);
// git lfs version
Task<Version> GitLfsVersion(IExecutionContext context);
// git lfs install --local
Task<int> GitLFSInstall(IExecutionContext context, string repositoryPath);
// git lfs logs last
Task<int> GitLFSLogs(IExecutionContext context, string repositoryPath);
// git repack -adfl
Task<int> GitRepack(IExecutionContext context, string repositoryPath);
// git prune
Task<int> GitPrune(IExecutionContext context, string repositoryPath);
// git lfs prune
Task<int> GitLFSPrune(IExecutionContext context, string repositoryPath);
// git count-objects -v -H
Task<int> GitCountObjects(IExecutionContext context, string repositoryPath);
// git version
Task<Version> GitVersion(IExecutionContext context);
}
public class GitCommandManager : AgentService, IGitCommandManager
{
private static Encoding _encoding
{
get => PlatformUtil.RunningOnWindows
? Encoding.UTF8
: null;
}
private string _gitHttpUserAgentEnv = null;
private string _gitPath = null;
private Version _gitVersion = null;
private string _gitLfsPath = null;
private Version _gitLfsVersion = null;
public bool EnsureGitVersion(Version requiredVersion, bool throwOnNotMatch)
{
ArgUtil.NotNull(_gitVersion, nameof(_gitVersion));
if (_gitPath == null)
{
throw new InvalidOperationException("Could not find Git installed on the system. Please make sure GIT is installed and available in the PATH.");
}
if (_gitVersion < requiredVersion && throwOnNotMatch)
{
throw new NotSupportedException(StringUtil.Loc("MinRequiredGitVersion", requiredVersion, _gitPath, _gitVersion));
}
return _gitVersion >= requiredVersion;
}
public bool EnsureGitLFSVersion(Version requiredVersion, bool throwOnNotMatch)
{
ArgUtil.NotNull(_gitLfsVersion, nameof(_gitLfsVersion));
if (_gitLfsPath == null)
{
throw new InvalidOperationException("Could not find Git LFS installed on the system. Please make sure GIT LFS is installed and available in the PATH.");
}
if (_gitLfsVersion < requiredVersion && throwOnNotMatch)
{
throw new NotSupportedException(StringUtil.Loc("MinRequiredGitLfsVersion", requiredVersion, _gitLfsPath, _gitLfsVersion));
}
return _gitLfsVersion >= requiredVersion;
}
public async Task LoadGitExecutionInfo(IExecutionContext context, bool useBuiltInGit)
{
// Resolve the location of git.
if (useBuiltInGit)
{
_gitPath = null;
// The Windows agent ships a copy of Git
if (PlatformUtil.RunningOnWindows)
{
_gitPath = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Externals), "git", "cmd", $"git{IOUtil.ExeExtension}");
_gitLfsPath = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Externals), "git", PlatformUtil.BuiltOnX86 ? "mingw32" : "mingw64", "bin", "git-lfs.exe");
// Prepend the PATH.
context.Output(StringUtil.Loc("Prepending0WithDirectoryContaining1", Constants.PathVariable, Path.GetFileName(_gitPath)));
// We need to prepend git-lfs path first so that we call
// externals/git/cmd/git.exe instead of externals/git/mingw**/bin/git.exe
PathUtil.PrependPath(Path.GetDirectoryName(_gitLfsPath));
PathUtil.PrependPath(Path.GetDirectoryName(_gitPath));
context.Debug($"{Constants.PathVariable}: '{Environment.GetEnvironmentVariable(Constants.PathVariable)}'");
}
}
else
{
_gitPath = WhichUtil.Which("git", require: true, trace: Trace);
_gitLfsPath = WhichUtil.Which("git-lfs", require: false, trace: Trace);
}
ArgUtil.File(_gitPath, nameof(_gitPath));
// Get the Git version.
_gitVersion = await GitVersion(context);
ArgUtil.NotNull(_gitVersion, nameof(_gitVersion));
context.Debug($"Detect git version: {_gitVersion.ToString()}.");
// Get the Git-LFS version if git-lfs exist in %PATH%.
if (!string.IsNullOrEmpty(_gitLfsPath))
{
_gitLfsVersion = await GitLfsVersion(context);
context.Debug($"Detect git-lfs version: '{_gitLfsVersion?.ToString() ?? string.Empty}'.");
}
// required 2.0, all git operation commandline args need min git version 2.0
Version minRequiredGitVersion = new Version(2, 0);
EnsureGitVersion(minRequiredGitVersion, throwOnNotMatch: true);
// suggest user upgrade to 2.17 for better git experience
Version recommendGitVersion = new Version(2, 17);
if (!EnsureGitVersion(recommendGitVersion, throwOnNotMatch: false))
{
context.Output(StringUtil.Loc("UpgradeToLatestGit", recommendGitVersion, _gitVersion));
}
// Set the user agent.
_gitHttpUserAgentEnv = $"git/{_gitVersion.ToString()} (vsts-agent-git/{BuildConstants.AgentPackage.Version})";
context.Debug($"Set git useragent to: {_gitHttpUserAgentEnv}.");
}
// git init <LocalDir>
public async Task<int> GitInit(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
ArgUtil.NotNull(repositoryPath, nameof(repositoryPath));
context.Debug($"Init git repository at: {repositoryPath}.");
string repoRootEscapeSpace = StringUtil.Format(@"""{0}""", repositoryPath.Replace(@"""", @"\"""));
return await ExecuteGitCommandAsync(context, repositoryPath, "init", StringUtil.Format($"{repoRootEscapeSpace}"));
}
// git fetch --tags --prune --progress --no-recurse-submodules [--depth=15] origin [+refs/pull/*:refs/remote/pull/*]
public async Task<int> GitFetch(IExecutionContext context, string repositoryPath, string remoteName, int fetchDepth, List<string> refSpec, string additionalCommandLine, CancellationToken cancellationToken)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Fetch git repository at: {repositoryPath} remote: {remoteName}.");
if (refSpec != null && refSpec.Count > 0)
{
refSpec = refSpec.Where(r => !string.IsNullOrEmpty(r)).ToList();
}
// insert prune-tags if DisableFetchPruneTags knob is false and Git version is above 2.17
string pruneTags = string.Empty;
if (EnsureGitVersion(new Version(2, 17), throwOnNotMatch: false) && !AgentKnobs.DisableFetchPruneTags.GetValue(context).AsBoolean())
{
pruneTags = "--prune-tags";
}
// If shallow fetch add --depth arg
// If the local repository is shallowed but there is no fetch depth provide for this build,
// add --unshallow to convert the shallow repository to a complete repository
string depth = fetchDepth > 0 ? $"--depth={fetchDepth}" : (File.Exists(Path.Combine(repositoryPath, ".git", "shallow")) ? "--unshallow" : string.Empty );
//define options for fetch
string options = $"--tags --prune {pruneTags} --progress --no-recurse-submodules {remoteName} {depth} {string.Join(" ", refSpec)}";
return await ExecuteGitCommandAsync(context, repositoryPath, "fetch", options, additionalCommandLine, cancellationToken);
}
// git lfs fetch origin [ref]
public async Task<int> GitLFSFetch(IExecutionContext context, string repositoryPath, string remoteName, string refSpec, string additionalCommandLine, CancellationToken cancellationToken)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Fetch LFS objects for git repository at: {repositoryPath} remote: {remoteName}.");
// default options for git lfs fetch.
string options = StringUtil.Format($"fetch origin {refSpec}");
return await ExecuteGitCommandAsync(context, repositoryPath, "lfs", options, additionalCommandLine, cancellationToken);
}
// git checkout -f --progress <commitId/branch>
public async Task<int> GitCheckout(IExecutionContext context, string repositoryPath, string committishOrBranchSpec, CancellationToken cancellationToken)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Checkout {committishOrBranchSpec}.");
// Git 2.7 support report checkout progress to stderr during stdout/err redirect.
string options;
if (_gitVersion >= new Version(2, 7))
{
options = StringUtil.Format("--progress --force {0}", committishOrBranchSpec);
}
else
{
options = StringUtil.Format("--force {0}", committishOrBranchSpec);
}
return await ExecuteGitCommandAsync(context, repositoryPath, "checkout", options, cancellationToken);
}
// git clean -ffdx
public async Task<int> GitClean(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Delete untracked files/folders for repository at {repositoryPath}.");
// Git 2.4 support git clean -ffdx.
string options;
if (_gitVersion >= new Version(2, 4))
{
options = "-ffdx";
}
else
{
options = "-fdx";
}
return await ExecuteGitCommandAsync(context, repositoryPath, "clean", options);
}
// git reset --hard HEAD
public async Task<int> GitReset(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Undo any changes to tracked files in the working tree for repository at {repositoryPath}.");
return await ExecuteGitCommandAsync(context, repositoryPath, "reset", "--hard HEAD");
}
// get remote set-url <origin> <url>
public async Task<int> GitRemoteAdd(IExecutionContext context, string repositoryPath, string remoteName, string remoteUrl)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Add git remote: {remoteName} to url: {remoteUrl} for repository under: {repositoryPath}.");
return await ExecuteGitCommandAsync(context, repositoryPath, "remote", StringUtil.Format($"add {remoteName} {remoteUrl}"));
}
// get remote set-url <origin> <url>
public async Task<int> GitRemoteSetUrl(IExecutionContext context, string repositoryPath, string remoteName, string remoteUrl)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Set git fetch url to: {remoteUrl} for remote: {remoteName}.");
return await ExecuteGitCommandAsync(context, repositoryPath, "remote", StringUtil.Format($"set-url {remoteName} {remoteUrl}"));
}
// get remote set-url --push <origin> <url>
public async Task<int> GitRemoteSetPushUrl(IExecutionContext context, string repositoryPath, string remoteName, string remoteUrl)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Set git push url to: {remoteUrl} for remote: {remoteName}.");
return await ExecuteGitCommandAsync(context, repositoryPath, "remote", StringUtil.Format($"set-url --push {remoteName} {remoteUrl}"));
}
// git submodule foreach --recursive "git clean -ffdx"
public async Task<int> GitSubmoduleClean(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Delete untracked files/folders for submodules at {repositoryPath}.");
// Git 2.4 support git clean -ffdx.
string options;
if (_gitVersion >= new Version(2, 4))
{
options = "-ffdx";
}
else
{
options = "-fdx";
}
return await ExecuteGitCommandAsync(context, repositoryPath, "submodule", $"foreach --recursive \"git clean {options}\"");
}
// git submodule foreach --recursive "git reset --hard HEAD"
public async Task<int> GitSubmoduleReset(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Undo any changes to tracked files in the working tree for submodules at {repositoryPath}.");
return await ExecuteGitCommandAsync(context, repositoryPath, "submodule", "foreach --recursive \"git reset --hard HEAD\"");
}
// git submodule update --init --force [--depth=15] [--recursive]
public async Task<int> GitSubmoduleUpdate(IExecutionContext context, string repositoryPath, int fetchDepth, string additionalCommandLine, bool recursive, CancellationToken cancellationToken)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug("Update the registered git submodules.");
string options = "update --init --force";
if (fetchDepth > 0)
{
options = options + $" --depth={fetchDepth}";
}
if (recursive)
{
options = options + " --recursive";
}
return await ExecuteGitCommandAsync(context, repositoryPath, "submodule", options, additionalCommandLine, cancellationToken);
}
// git submodule sync [--recursive]
public async Task<int> GitSubmoduleSync(IExecutionContext context, string repositoryPath, bool recursive, CancellationToken cancellationToken)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug("Synchronizes submodules' remote URL configuration setting.");
string options = "sync";
if (recursive)
{
options = options + " --recursive";
}
return await ExecuteGitCommandAsync(context, repositoryPath, "submodule", options, cancellationToken);
}
// git config --get remote.origin.url
public async Task<Uri> GitGetFetchUrl(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Inspect remote.origin.url for repository under {repositoryPath}");
Uri fetchUrl = null;
List<string> outputStrings = new List<string>();
int exitCode = await ExecuteGitCommandAsync(context, repositoryPath, "config", "--get remote.origin.url", outputStrings);
if (exitCode != 0)
{
context.Warning($"'git config --get remote.origin.url' failed with exit code: {exitCode}, output: '{string.Join(Environment.NewLine, outputStrings)}'");
}
else
{
// remove empty strings
outputStrings = outputStrings.Where(o => !string.IsNullOrEmpty(o)).ToList();
if (outputStrings.Count == 1 && !string.IsNullOrEmpty(outputStrings.First()))
{
string remoteFetchUrl = outputStrings.First();
if (Uri.IsWellFormedUriString(remoteFetchUrl, UriKind.Absolute))
{
context.Debug($"Get remote origin fetch url from git config: {remoteFetchUrl}");
fetchUrl = new Uri(remoteFetchUrl);
}
else
{
context.Debug($"The Origin fetch url from git config: {remoteFetchUrl} is not a absolute well formed url.");
}
}
else
{
context.Debug($"Unable capture git remote fetch uri from 'git config --get remote.origin.url' command's output, the command's output is not expected: {string.Join(Environment.NewLine, outputStrings)}.");
}
}
return fetchUrl;
}
// git config <key> <value>
public async Task<int> GitConfig(IExecutionContext context, string repositoryPath, string configKey, string configValue)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Set git config {configKey} {configValue}");
return await ExecuteGitCommandAsync(context, repositoryPath, "config", StringUtil.Format($"{configKey} {configValue}"));
}
// git config --get-all <key>
public async Task<bool> GitConfigExist(IExecutionContext context, string repositoryPath, string configKey)
{
ArgUtil.NotNull(context, nameof(context));
// git config --get-all {configKey} will return 0 and print the value if the config exist.
context.Debug($"Checking git config {configKey} exist or not");
// ignore any outputs by redirect them into a string list, since the output might contains secrets.
List<string> outputStrings = new List<string>();
int exitcode = await ExecuteGitCommandAsync(context, repositoryPath, "config", StringUtil.Format($"--get-all {configKey}"), outputStrings);
return exitcode == 0;
}
// git config --unset-all <key>
public async Task<int> GitConfigUnset(IExecutionContext context, string repositoryPath, string configKey)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug($"Unset git config --unset-all {configKey}");
return await ExecuteGitCommandAsync(context, repositoryPath, "config", StringUtil.Format($"--unset-all {configKey}"));
}
// git config gc.auto 0
public async Task<int> GitDisableAutoGC(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug("Disable git auto garbage collection.");
return await ExecuteGitCommandAsync(context, repositoryPath, "config", "gc.auto 0");
}
// git repack -adfl
public async Task<int> GitRepack(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug("Compress .git directory.");
return await ExecuteGitCommandAsync(context, repositoryPath, "repack", "-adfl");
}
// git prune
public async Task<int> GitPrune(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug("Delete unreachable objects under .git directory.");
return await ExecuteGitCommandAsync(context, repositoryPath, "prune", "-v");
}
// git lfs prune
public async Task<int> GitLFSPrune(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug("Deletes local copies of LFS files which are old, thus freeing up disk space. Prune operates by enumerating all the locally stored objects, and then deleting any which are not referenced by at least ONE of the following:");
return await ExecuteGitCommandAsync(context, repositoryPath, "lfs", "prune");
}
// git count-objects -v -H
public async Task<int> GitCountObjects(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug("Inspect .git directory.");
return await ExecuteGitCommandAsync(context, repositoryPath, "count-objects", "-v -H");
}
// git lfs install --local
public async Task<int> GitLFSInstall(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug("Ensure git-lfs installed.");
return await ExecuteGitCommandAsync(context, repositoryPath, "lfs", "install --local");
}
// git lfs logs last
public async Task<int> GitLFSLogs(IExecutionContext context, string repositoryPath)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug("Get git-lfs logs.");
return await ExecuteGitCommandAsync(context, repositoryPath, "lfs", "logs last");
}
// git version
public async Task<Version> GitVersion(IExecutionContext context)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug("Get git version.");
Version version = null;
List<string> outputStrings = new List<string>();
int exitCode = await ExecuteGitCommandAsync(context, HostContext.GetDirectory(WellKnownDirectory.Work), "version", null, outputStrings);
context.Output($"{string.Join(Environment.NewLine, outputStrings)}");
if (exitCode == 0)
{
// remove any empty line.
outputStrings = outputStrings.Where(o => !string.IsNullOrEmpty(o)).ToList();
if (outputStrings.Count == 1 && !string.IsNullOrEmpty(outputStrings.First()))
{
string verString = outputStrings.First();
// we interested about major.minor.patch version
Regex verRegex = new Regex("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
var matchResult = verRegex.Match(verString);
if (matchResult.Success && !string.IsNullOrEmpty(matchResult.Value))
{
if (!Version.TryParse(matchResult.Value, out version))
{
version = null;
}
}
}
}
return version;
}
// git lfs version
public async Task<Version> GitLfsVersion(IExecutionContext context)
{
ArgUtil.NotNull(context, nameof(context));
context.Debug("Get git-lfs version.");
Version version = null;
List<string> outputStrings = new List<string>();
int exitCode = await ExecuteGitCommandAsync(context, HostContext.GetDirectory(WellKnownDirectory.Work), "lfs version", null, outputStrings);
context.Output($"{string.Join(Environment.NewLine, outputStrings)}");
if (exitCode == 0)
{
// remove any empty line.
outputStrings = outputStrings.Where(o => !string.IsNullOrEmpty(o)).ToList();
if (outputStrings.Count == 1 && !string.IsNullOrEmpty(outputStrings.First()))
{
string verString = outputStrings.First();
// we interested about major.minor.patch version
Regex verRegex = new Regex("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
var matchResult = verRegex.Match(verString);
if (matchResult.Success && !string.IsNullOrEmpty(matchResult.Value))
{
if (!Version.TryParse(matchResult.Value, out version))
{
version = null;
}
}
}
}
return version;
}
private async Task<int> ExecuteGitCommandAsync(IExecutionContext context, string repoRoot, string command, string options, CancellationToken cancellationToken = default(CancellationToken))
{
string arg = StringUtil.Format($"{command} {options}").Trim();
context.Command($"git {arg}");
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
context.Output(message.Data);
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
context.Output(message.Data);
};
return await processInvoker.ExecuteAsync(
workingDirectory: repoRoot,
fileName: _gitPath,
arguments: arg,
environment: GetGitEnvironmentVariables(context),
requireExitCodeZero: false,
outputEncoding: _encoding,
cancellationToken: cancellationToken);
}
private async Task<int> ExecuteGitCommandAsync(IExecutionContext context, string repoRoot, string command, string options, IList<string> output)
{
string arg = StringUtil.Format($"{command} {options}").Trim();
context.Command($"git {arg}");
if (output == null)
{
output = new List<string>();
}
object outputLock = new object();
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
lock (outputLock)
{
output.Add(message.Data);
}
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
lock (outputLock)
{
output.Add(message.Data);
}
};
return await processInvoker.ExecuteAsync(
workingDirectory: repoRoot,
fileName: _gitPath,
arguments: arg,
environment: GetGitEnvironmentVariables(context),
requireExitCodeZero: false,
outputEncoding: _encoding,
cancellationToken: default(CancellationToken));
}
private async Task<int> ExecuteGitCommandAsync(IExecutionContext context, string repoRoot, string command, string options, string additionalCommandLine, CancellationToken cancellationToken)
{
string arg = StringUtil.Format($"{additionalCommandLine} {command} {options}").Trim();
context.Command($"git {arg}");
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
context.Output(message.Data);
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
context.Output(message.Data);
};
return await processInvoker.ExecuteAsync(
workingDirectory: repoRoot,
fileName: _gitPath,
arguments: arg,
environment: GetGitEnvironmentVariables(context),
requireExitCodeZero: false,
outputEncoding: _encoding,
cancellationToken: cancellationToken);
}
private IDictionary<string, string> GetGitEnvironmentVariables(IExecutionContext context)
{
Dictionary<string, string> gitEnv = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "GIT_TERMINAL_PROMPT", "0" },
};
if (!string.IsNullOrEmpty(_gitHttpUserAgentEnv))
{
gitEnv["GIT_HTTP_USER_AGENT"] = _gitHttpUserAgentEnv;
}
// Add the public variables.
foreach (KeyValuePair<string, string> pair in context.Variables.Public)
{
// Add the variable using the formatted name.
string formattedKey = (pair.Key ?? string.Empty).Replace('.', '_').Replace(' ', '_').ToUpperInvariant();
// Skip any GIT_TRACE variable since GIT_TRACE will affect ouput from every git command.
// This will fail the parse logic for detect git version, remote url, etc.
// Ex.
// SET GIT_TRACE=true
// git version
// 11:39:58.295959 git.c:371 trace: built-in: git 'version'
// git version 2.11.1.windows.1
if (formattedKey == "GIT_TRACE" || formattedKey.StartsWith("GIT_TRACE_"))
{
continue;
}
gitEnv[formattedKey] = pair.Value ?? string.Empty;
}
return gitEnv;
}
}
}
| 45.289009 | 249 | 0.614117 | [
"MIT"
] | 82amp/azure-pipelines-agent | src/Agent.Worker/Build/GitCommandManager.cs | 33,378 | C# |
using AdministrationGateway.Services;
using Grpc.Core;
using HostingHelpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AdministrationGateway.Controllers
{
[Route("api/Catalog/Object/Comment")]
[Authorize("Admin")]
public class ObjectCommentController : MyControllerBase
{
private CommentAggregator _commentAggregator;
public ObjectCommentController(CommentAggregator commentAggregator)
{
_commentAggregator = commentAggregator;
}
[Route("forObject")]
[HttpGet]
public async Task<IActionResult> GetObjectComments()
{
var result = await _commentAggregator.AggregateComments();
return StatusCode(result);
}
}
}
| 26.411765 | 75 | 0.707127 | [
"MIT"
] | Abdulrhman5/StreetOfThings | src/Gateways/AdministrationGateway/Controllers/ObjectCommentController.cs | 900 | C# |
using CompanyName.ProjectName.DataDictionaryManagement.DataDictionaries.Aggregates;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
namespace CompanyName.ProjectName.DataDictionaryManagement.EntityFrameworkCore
{
[ConnectionStringName(DataDictionaryManagementDbProperties.ConnectionStringName)]
public interface IDataDictionaryManagementDbContext : IEfCoreDbContext
{
/* Add DbSet for each Aggregate Root here. Example:
* DbSet<Question> Questions { get; }
*/
DbSet<DataDictionary> DataDictionary { get; }
}
} | 37.9375 | 85 | 0.777595 | [
"MIT"
] | shuangbaojun/abp-vnext-pro | aspnet-core/modules/DataDictionaryManagement/src/CompanyName.ProjectName.DataDictionaryManagement.EntityFrameworkCore/EntityFrameworkCore/IDataDictionaryManagementDbContext.cs | 609 | C# |
using System.Diagnostics.CodeAnalysis;
static class GitRepoDirectoryFinder
{
public static string Find()
{
if (TryFind(out var rootDirectory))
{
return rootDirectory;
}
throw new Exception("Could not find root git directory");
}
public static bool TryFind([NotNullWhen(true)] out string? path)
{
var currentDirectory = AssemblyLocation.CurrentDirectory;
do
{
if (Directory.Exists(Path.Combine(currentDirectory, ".git")))
{
path = currentDirectory;
return true;
}
var parent = Directory.GetParent(currentDirectory);
if (parent == null)
{
path = null;
return false;
}
currentDirectory = parent.FullName;
} while (true);
}
} | 25.611111 | 74 | 0.515184 | [
"MIT"
] | SimonCropp/PackageUpdate | src/Tests/GitRepoDirectoryFinder.cs | 924 | 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 MidTermReviewPowers.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MidTermReviewPowers.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 38.819444 | 185 | 0.605367 | [
"MIT"
] | Woobly-Shnufflepops/Year-2-Quarter-1 | MidTermReviewPowers/MidTermReviewPowers/Properties/Resources.Designer.cs | 2,797 | 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.
*/
using Xunit;
namespace Transcoder.Samples.Tests
{
[Collection(nameof(TranscoderFixture))]
public class CreateJobWithSetNumberImagesSpritesheetTest
{
private TranscoderFixture _fixture;
private readonly CreateJobWithSetNumberImagesSpritesheetSample _createSample;
private readonly GetJobStateSample _getSample;
public CreateJobWithSetNumberImagesSpritesheetTest(TranscoderFixture fixture)
{
_fixture = fixture;
_createSample = new CreateJobWithSetNumberImagesSpritesheetSample();
_getSample = new GetJobStateSample();
}
[Fact]
public void CreatesJobWithSetNumberImagesSpritesheet()
{
string outputUri = $"gs://{_fixture.BucketName}/test-output-set-number-spritesheet/";
// Run the sample code.
var result = _createSample.CreateJobWithSetNumberImagesSpritesheet(
_fixture.ProjectId, _fixture.Location,
_fixture.InputUri, outputUri);
_fixture.JobIds.Add(result.JobName.JobId);
Assert.Equal(_fixture.Location, result.JobName.LocationId);
// Job resource name uses project number for the identifier.
Assert.Equal(_fixture.ProjectNumber, result.JobName.ProjectId);
_fixture.JobPoller.Eventually(() =>
Assert.Equal(_fixture.JobStateSucceeded, _getSample.GetJobState(_fixture.ProjectId, _fixture.Location, result.JobName.JobId)
));
}
}
}
| 38.545455 | 141 | 0.692925 | [
"Apache-2.0"
] | BearerPipelineTest/dotnet-docs-samples | media/transcoder/api/Transcoder.Samples.Tests/CreateJobWithSetNumberImagesSpritesheetTests.cs | 2,120 | C# |
using UnityEngine;
using System.Collections;
public class DeactivateAfterSeconds : MonoBehaviour
{
[SerializeField] private float _waitSeconds;
[SerializeField] private bool _useTimeScale = false;
void OnEnable()
{
StartCoroutine(DeactiavteRoutine());
}
private IEnumerator DeactiavteRoutine()
{
if (_useTimeScale)
yield return new WaitForSeconds(_waitSeconds);
else
yield return new WaitForSecondsRealtime(_waitSeconds);
gameObject.SetActive(false);
}
} | 20.083333 | 57 | 0.775934 | [
"MIT"
] | Sweaty-Chair/SC-Essentials | Assets/SweatyChair/Essentials/Helpers/DeactivateAfterSeconds.cs | 484 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using Observatory.UI.Models;
using ReactiveUI;
using System.Reactive.Linq;
using Observatory.Framework;
namespace Observatory.UI.ViewModels
{
public class BasicUIViewModel : ViewModelBase
{
private ObservableCollection<object> basicUIGrid;
public ObservableCollection<object> BasicUIGrid
{
get => basicUIGrid;
set
{
basicUIGrid = value;
this.RaisePropertyChanged(nameof(BasicUIGrid));
}
}
public BasicUIViewModel(ObservableCollection<object> BasicUIGrid)
{
this.BasicUIGrid = BasicUIGrid;
}
private PluginUI.UIType uiType;
public PluginUI.UIType UIType
{
get => uiType;
set
{
uiType = value;
this.RaisePropertyChanged(nameof(UIType));
}
}
}
}
| 22.979167 | 73 | 0.598368 | [
"MIT"
] | Xjph/ObservatoryCore | ObservatoryCore/UI/ViewModels/BasicUIViewModel.cs | 1,105 | C# |
using ExifInfo.Models;
using System;
using System.Collections.Generic;
using Windows.ApplicationModel.DataTransfer;
using Windows.Services.Store;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Input;
// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236
namespace ExifInfo.Controls
{
public sealed partial class PurchaseControl : UserControl
{
StoreProductQueryResult _queryResult;
Popup m_Popup;
public PurchaseControl(StoreProductQueryResult queryResult)
{
this.InitializeComponent();
//m_Popup = new Popup();
m_Popup = (Application.Current as App).gPopup;
MeasurePopupSize();
m_Popup.Child = this;
this.Loaded += MessagePopupWindow_Loaded;
this.Unloaded += MessagePopupWindow_Unloaded;
_queryResult = queryResult;
List<Product> lProducts = new List<Product>();
foreach (KeyValuePair<string, StoreProduct> item in _queryResult.Products)
{
// Access the Store product info for the add-on.
StoreProduct product = item.Value;
// Use members of the product object to access listing info for the add-on...
Product pd = new Product()
{
StoreId = product.StoreId,
Title = product.Title,
Price = product.Price.FormattedPrice,
Description = product.Description,
ProductImage = product.Images[0].Uri.OriginalString
};
lProducts.Add(pd);
}
listProducts.ItemsSource = lProducts;
}
private async void listProducts_ItemClick(object sender, ItemClickEventArgs e)
{
StoreContext context = StoreContext.GetDefault();
var product = e.ClickedItem as Product;
var result = await context.RequestPurchaseAsync(product.StoreId);
if (result.Status == StorePurchaseStatus.Succeeded)
{
// 成功购买
textPurchaseResult.Text = "Thank you.";
}
else if (result.Status == StorePurchaseStatus.AlreadyPurchased)
{
// 已经购买过了
textPurchaseResult.Text = "You have already purchased.";
}
else if (result.Status == StorePurchaseStatus.NotPurchased)
{
// 用户没购买,即用户中途取消了操作
textPurchaseResult.Text = "You have canceled the purchase.";
}
else if (result.Status == StorePurchaseStatus.ServerError || result.Status == StorePurchaseStatus.NetworkError)
{
// 发生错误
textPurchaseResult.Text = "Sorry, something went wrong with the microsoft server or something else.";
}
}
public void ShowWindow()
{
m_Popup.IsOpen = true;
}
private void DismissWindow()
{
m_Popup.IsOpen = false;
}
//public PurchaseControl(StoreProductQueryResult queryResult) : this()
//{
// this._queryResult = queryResult;
//}
private void OutBorder_Tapped(object sender, TappedRoutedEventArgs e)
{
m_Popup.IsOpen = false;
}
private void MeasurePopupSize()
{
this.Width = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBounds.Width;
double marginTop = 0;
if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
marginTop = Windows.UI.ViewManagement.StatusBar.GetForCurrentView().OccludedRect.Height;
this.Height = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBounds.Height;
this.Margin = new Thickness(0, marginTop, 0, 0);
}
private void MessagePopupWindow_Loaded(object sender, RoutedEventArgs e)
{
Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBoundsChanged += MessagePopupWindow_VisibleBoundsChanged;
}
private void MessagePopupWindow_Unloaded(object sender, RoutedEventArgs e)
{
Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBoundsChanged -= MessagePopupWindow_VisibleBoundsChanged;
}
private void MessagePopupWindow_VisibleBoundsChanged(Windows.UI.ViewManagement.ApplicationView sender, object args)
{
MeasurePopupSize();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
m_Popup.IsOpen = false;
}
private async void imgPayPal_Tapped(object sender, TappedRoutedEventArgs e)
{
Uri uri = new Uri("https://www.paypal.me/hupo376787");
await Windows.System.Launcher.LaunchUriAsync(uri);
textPurchaseResult.Text = "Opening PayPal :)";
}
private void imgWeChat_Tapped(object sender, TappedRoutedEventArgs e)
{
textPurchaseResult.Text = "请直接扫码转账,谢谢 :)";
}
private void imgZhiFuBiao_Tapped(object sender, TappedRoutedEventArgs e)
{
string str = "376787823@qq.com";
DataPackage dp = new DataPackage();
dp.SetText(str);
Clipboard.SetContent(dp);
textPurchaseResult.Text = "支付婊账号已复制 :)";
}
}
}
| 37.270968 | 139 | 0.592176 | [
"MIT"
] | hupo376787/WindowsTemplateStudio---Master-Detail-View-bug | ExifInfo/Controls/PurchaseControl.xaml.cs | 5,875 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace Xamarin.Forms.RadialMenu.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main(args, null, "AppDelegate");
}
}
}
| 23.619048 | 91 | 0.639113 | [
"MIT"
] | arqueror/Xamarin.Forms-RadialMenu | Xamarin.Forms.RadialMenu/Xamarin.Forms.RadialMenu.iOS/Main.cs | 498 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
namespace Microsoft.AspNetCore.Http.Result;
internal sealed class AcceptedResult : ObjectResult
{
/// <summary>
/// Initializes a new instance of the <see cref="AcceptedResult"/> class with the values
/// provided.
/// </summary>
public AcceptedResult()
: base(value: null, StatusCodes.Status202Accepted)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AcceptedResult"/> class with the values
/// provided.
/// </summary>
/// <param name="location">The location at which the status of requested content can be monitored.</param>
/// <param name="value">The value to format in the entity body.</param>
public AcceptedResult(string? location, object? value)
: base(value, StatusCodes.Status202Accepted)
{
Location = location;
}
/// <summary>
/// Initializes a new instance of the <see cref="AcceptedResult"/> class with the values
/// provided.
/// </summary>
/// <param name="locationUri">The location at which the status of requested content can be monitored.</param>
/// <param name="value">The value to format in the entity body.</param>
public AcceptedResult(Uri locationUri, object? value)
: base(value, StatusCodes.Status202Accepted)
{
if (locationUri == null)
{
throw new ArgumentNullException(nameof(locationUri));
}
if (locationUri.IsAbsoluteUri)
{
Location = locationUri.AbsoluteUri;
}
else
{
Location = locationUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped);
}
}
/// <summary>
/// Gets or sets the location at which the status of the requested content can be monitored.
/// </summary>
public string? Location { get; set; }
/// <inheritdoc />
protected override void ConfigureResponseHeaders(HttpContext context)
{
if (!string.IsNullOrEmpty(Location))
{
context.Response.Headers.Location = Location;
}
}
}
| 32.362319 | 113 | 0.642185 | [
"MIT"
] | AndrewTriesToCode/aspnetcore | src/Http/Http.Results/src/AcceptedResult.cs | 2,233 | C# |
using System.Text.RegularExpressions;
using System;
namespace SearchSharp.ViewModels
{
public class RegexWindowViewModel : ViewModel
{
private string _regexString;
private bool _multiLine;
private bool _singleLine;
private bool _settingInput;
private string _inputString;
public RegexWindowViewModel()
{
TitleText = "Regex Options";
TextContentViewModel = new TextContentViewModel() { SelectedFileCount = 1, ShowFullContent = true };
}
public bool Apply { get; set; }
public TextContentViewModel TextContentViewModel { get; private set; }
public void UseInput()
{
TextContentViewModel.SelectedFileContent = InputString;
SettingInput = false;
}
public void CancelInput()
{
SettingInput = false;
}
public bool SettingInput
{
get { return _settingInput; }
set
{
_settingInput = value;
RaisePropertyChanged("SettingInput");
}
}
public string InputString
{
get { return _inputString; }
set
{
_inputString = value;
RaisePropertyChanged("InputString");
}
}
public string RegexString
{
get { return _regexString; }
set
{
_regexString = value;
RaisePropertyChanged("RegexString");
RaisePropertyChanged("RegexIsValid");
UpdateTestContent();
}
}
public bool RegexIsValid
{
get { return RegexTester.IsValid(RegexString); }
}
private void UpdateTestContent()
{
TextContentViewModel.ExecutedFileContentSearchParameters = new FileContentSearchParameters(RegexString, false, false, true, Options, TextContentViewModel);
}
public bool MultiLine
{
get { return _multiLine; }
set
{
_multiLine = value;
RaisePropertyChanged("MultiLine");
UpdateTestContent();
}
}
public bool SingleLine
{
get { return _singleLine; }
set
{
_singleLine = value;
RaisePropertyChanged("SingleLine");
UpdateTestContent();
}
}
public RegexOptions Options
{
get
{
RegexOptions options = RegexOptions.None;
if (MultiLine)
{
options |= RegexOptions.Multiline;
}
if (SingleLine)
{
options |= RegexOptions.Singleline;
}
return options;
}
set
{
MultiLine = (value & RegexOptions.Multiline) == RegexOptions.Multiline;
SingleLine = (value & RegexOptions.Singleline) == RegexOptions.Singleline;
}
}
public string TitleText { get; set; }
public void CopyAsCSharp()
{
var options = "";
const string multiLine = "RegexOptions.Multiline";
const string singleLine = "RegexOptions.Singleline";
if (MultiLine && SingleLine)
{
options = String.Format(", {0} | {1}", multiLine, singleLine);
}
else if (MultiLine)
{
options = ", " + multiLine;
}
else if (SingleLine)
{
options = ", " + singleLine;
}
var csharp = String.Format("var regex = new Regex(@\"{0}\"{1});", RegexString, options);
System.Windows.Clipboard.SetDataObject(csharp);
}
}
} | 28.22449 | 168 | 0.474813 | [
"MIT"
] | peterhorsley/searchsharp | ViewModels/RegexWindowViewModel.cs | 4,151 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Covid_19.Models
{
public class map
{
public string countrycode { get; set; }
public string country { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public int confirmed { get; set; }
public int? deaths { get; set; }
public int? recovered { get; set; }
public int? active { get; set; }
}
}
| 25.7 | 47 | 0.610895 | [
"MIT"
] | engolos/Covid-19 | Covid-19/Models/map.cs | 516 | 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("FinalBackEndProjectTask")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FinalBackEndProjectTask")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[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("ef52380a-a42d-434c-9fa6-28b92f508a20")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.305556 | 84 | 0.752719 | [
"MIT"
] | f115/FinalBackEndProjectTask | FinalBackEndProjectTask/Properties/AssemblyInfo.cs | 1,382 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Discounts;
using Nop.Data;
using Nop.Services.Customers;
using Nop.Services.Discounts;
using Nop.Services.Localization;
using Nop.Services.Security;
using Nop.Services.Stores;
namespace Nop.Services.Catalog
{
/// <summary>
/// Category service
/// </summary>
public partial class CategoryService : ICategoryService
{
#region Fields
private readonly IAclService _aclService;
private readonly ICustomerService _customerService;
private readonly ILocalizationService _localizationService;
private readonly IRepository<Category> _categoryRepository;
private readonly IRepository<DiscountCategoryMapping> _discountCategoryMappingRepository;
private readonly IRepository<Product> _productRepository;
private readonly IRepository<ProductCategory> _productCategoryRepository;
private readonly IStaticCacheManager _staticCacheManager;
private readonly IStoreContext _storeContext;
private readonly IStoreMappingService _storeMappingService;
private readonly IWorkContext _workContext;
#endregion
#region Ctor
public CategoryService(
IAclService aclService,
ICustomerService customerService,
ILocalizationService localizationService,
IRepository<Category> categoryRepository,
IRepository<DiscountCategoryMapping> discountCategoryMappingRepository,
IRepository<Product> productRepository,
IRepository<ProductCategory> productCategoryRepository,
IStaticCacheManager staticCacheManager,
IStoreContext storeContext,
IStoreMappingService storeMappingService,
IWorkContext workContext)
{
_aclService = aclService;
_customerService = customerService;
_localizationService = localizationService;
_categoryRepository = categoryRepository;
_discountCategoryMappingRepository = discountCategoryMappingRepository;
_productRepository = productRepository;
_productCategoryRepository = productCategoryRepository;
_staticCacheManager = staticCacheManager;
_storeContext = storeContext;
_storeMappingService = storeMappingService;
_workContext = workContext;
}
#endregion
#region Utilities
/// <summary>
/// Gets a product category mapping collection
/// </summary>
/// <param name="productId">Product identifier</param>
/// <param name="storeId">Store identifier (used in multi-store environment). "showHidden" parameter should also be "true"</param>
/// <param name="showHidden"> A value indicating whether to show hidden records</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the product category mapping collection
/// </returns>
protected virtual async Task<IList<ProductCategory>> GetProductCategoriesByProductIdAsync(int productId, int storeId,
bool showHidden = false)
{
if (productId == 0)
return new List<ProductCategory>();
var customer = await _workContext.GetCurrentCustomerAsync();
return await _productCategoryRepository.GetAllAsync(async query =>
{
if (!showHidden)
{
var categoriesQuery = _categoryRepository.Table.Where(c => c.Published);
//apply store mapping constraints
categoriesQuery = await _storeMappingService.ApplyStoreMapping(categoriesQuery, storeId);
//apply ACL constraints
categoriesQuery = await _aclService.ApplyAcl(categoriesQuery, customer);
query = query.Where(pc => categoriesQuery.Any(c => !c.Deleted && c.Id == pc.CategoryId));
}
return query
.Where(pc => pc.ProductId == productId)
.OrderBy(pc => pc.DisplayOrder)
.ThenBy(pc => pc.Id);
}, cache => _staticCacheManager.PrepareKeyForDefaultCache(NopCatalogDefaults.ProductCategoriesByProductCacheKey,
productId, showHidden, customer, storeId));
}
/// <summary>
/// Sort categories for tree representation
/// </summary>
/// <param name="source">Source</param>
/// <param name="parentId">Parent category identifier</param>
/// <param name="ignoreCategoriesWithoutExistingParent">A value indicating whether categories without parent category in provided category list (source) should be ignored</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the sorted categories
/// </returns>
protected virtual async Task<IList<Category>> SortCategoriesForTreeAsync(IList<Category> source, int parentId = 0,
bool ignoreCategoriesWithoutExistingParent = false)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
var result = new List<Category>();
foreach (var cat in source.Where(c => c.ParentCategoryId == parentId).ToList())
{
result.Add(cat);
result.AddRange(await SortCategoriesForTreeAsync(source, cat.Id, true));
}
if (ignoreCategoriesWithoutExistingParent || result.Count == source.Count)
return result;
//find categories without parent in provided category source and insert them into result
foreach (var cat in source)
if (result.FirstOrDefault(x => x.Id == cat.Id) == null)
result.Add(cat);
return result;
}
#endregion
#region Methods
/// <summary>
/// Clean up category references for a specified discount
/// </summary>
/// <param name="discount">Discount</param>
/// <returns>A task that represents the asynchronous operation</returns>
public virtual async Task ClearDiscountCategoryMappingAsync(Discount discount)
{
if (discount is null)
throw new ArgumentNullException(nameof(discount));
var mappings = _discountCategoryMappingRepository.Table.Where(dcm => dcm.DiscountId == discount.Id);
await _discountCategoryMappingRepository.DeleteAsync(mappings.ToList());
}
/// <summary>
/// Delete category
/// </summary>
/// <param name="category">Category</param>
/// <returns>A task that represents the asynchronous operation</returns>
public virtual async Task DeleteCategoryAsync(Category category)
{
await _categoryRepository.DeleteAsync(category);
//reset a "Parent category" property of all child subcategories
var subcategories = await GetAllCategoriesByParentCategoryIdAsync(category.Id, true);
foreach (var subcategory in subcategories)
{
subcategory.ParentCategoryId = 0;
await UpdateCategoryAsync(subcategory);
}
}
/// <summary>
/// Delete Categories
/// </summary>
/// <param name="categories">Categories</param>
/// <returns>A task that represents the asynchronous operation</returns>
public virtual async Task DeleteCategoriesAsync(IList<Category> categories)
{
if (categories == null)
throw new ArgumentNullException(nameof(categories));
foreach (var category in categories)
await DeleteCategoryAsync(category);
}
/// <summary>
/// Gets all categories
/// </summary>
/// <param name="storeId">Store identifier; 0 if you want to get all records</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the categories
/// </returns>
public virtual async Task<IList<Category>> GetAllCategoriesAsync(int storeId = 0, bool showHidden = false)
{
var key = _staticCacheManager.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoriesAllCacheKey,
storeId,
await _customerService.GetCustomerRoleIdsAsync(await _workContext.GetCurrentCustomerAsync()),
showHidden);
var categories = await _staticCacheManager
.GetAsync(key, async () => (await GetAllCategoriesAsync(string.Empty, storeId, showHidden: showHidden)).ToList());
return categories;
}
/// <summary>
/// Gets all categories
/// </summary>
/// <param name="categoryName">Category name</param>
/// <param name="storeId">Store identifier; 0 if you want to get all records</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <param name="overridePublished">
/// null - process "Published" property according to "showHidden" parameter
/// true - load only "Published" products
/// false - load only "Unpublished" products
/// </param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the categories
/// </returns>
public virtual async Task<IPagedList<Category>> GetAllCategoriesAsync(string categoryName, int storeId = 0,
int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false, bool? overridePublished = null)
{
var unsortedCategories = await _categoryRepository.GetAllAsync(async query =>
{
if (!showHidden)
query = query.Where(c => c.Published);
else if (overridePublished.HasValue)
query = query.Where(c => c.Published == overridePublished.Value);
//apply store mapping constraints
query = await _storeMappingService.ApplyStoreMapping(query, storeId);
//apply ACL constraints
if (!showHidden)
{
var customer = await _workContext.GetCurrentCustomerAsync();
query = await _aclService.ApplyAcl(query, customer);
}
if (!string.IsNullOrWhiteSpace(categoryName))
query = query.Where(c => c.Name.Contains(categoryName));
query = query.Where(c => !c.Deleted);
return query.OrderBy(c => c.ParentCategoryId).ThenBy(c => c.DisplayOrder).ThenBy(c => c.Id);
});
//sort categories
var sortedCategories = await SortCategoriesForTreeAsync(unsortedCategories);
//paging
return new PagedList<Category>(sortedCategories, pageIndex, pageSize);
}
/// <summary>
/// Gets all categories filtered by parent category identifier
/// </summary>
/// <param name="parentCategoryId">Parent category identifier</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the categories
/// </returns>
public virtual async Task<IList<Category>> GetAllCategoriesByParentCategoryIdAsync(int parentCategoryId,
bool showHidden = false)
{
var store = await _storeContext.GetCurrentStoreAsync();
var customer = await _workContext.GetCurrentCustomerAsync();
var categories = await _categoryRepository.GetAllAsync(async query =>
{
if (!showHidden)
{
query = query.Where(c => c.Published);
//apply store mapping constraints
query = await _storeMappingService.ApplyStoreMapping(query, store.Id);
//apply ACL constraints
query = await _aclService.ApplyAcl(query, customer);
}
query = query.Where(c => !c.Deleted && c.ParentCategoryId == parentCategoryId);
return query.OrderBy(c => c.DisplayOrder).ThenBy(c => c.Id);
}, cache => cache.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoriesByParentCategoryCacheKey,
parentCategoryId, showHidden, customer, store));
return categories;
}
/// <summary>
/// Gets all categories displayed on the home page
/// </summary>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the categories
/// </returns>
public virtual async Task<IList<Category>> GetAllCategoriesDisplayedOnHomepageAsync(bool showHidden = false)
{
var categories = await _categoryRepository.GetAllAsync(query =>
{
return from c in query
orderby c.DisplayOrder, c.Id
where c.Published &&
!c.Deleted &&
c.ShowOnHomepage
select c;
}, cache => cache.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoriesHomepageCacheKey));
if (showHidden)
return categories;
var cacheKey = _staticCacheManager.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoriesHomepageWithoutHiddenCacheKey,
await _storeContext.GetCurrentStoreAsync(), await _customerService.GetCustomerRoleIdsAsync(await _workContext.GetCurrentCustomerAsync()));
var result = await _staticCacheManager.GetAsync(cacheKey, async () =>
{
return await categories
.WhereAwait(async c => await _aclService.AuthorizeAsync(c) && await _storeMappingService.AuthorizeAsync(c))
.ToListAsync();
});
return result;
}
/// <summary>
/// Get category identifiers to which a discount is applied
/// </summary>
/// <param name="discount">Discount</param>
/// <param name="customer">Customer</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the category identifiers
/// </returns>
public virtual async Task<IList<int>> GetAppliedCategoryIdsAsync(Discount discount, Customer customer)
{
if (discount == null)
throw new ArgumentNullException(nameof(discount));
var cacheKey = _staticCacheManager.PrepareKeyForDefaultCache(NopDiscountDefaults.CategoryIdsByDiscountCacheKey,
discount,
await _customerService.GetCustomerRoleIdsAsync(customer),
await _storeContext.GetCurrentStoreAsync());
var result = await _staticCacheManager.GetAsync(cacheKey, async () =>
{
var ids = await _discountCategoryMappingRepository.Table
.Where(dmm => dmm.DiscountId == discount.Id).Select(dmm => dmm.EntityId)
.Distinct()
.ToListAsync();
if (!discount.AppliedToSubCategories)
return ids;
ids.AddRange(await ids.SelectManyAwait(async categoryId =>
await GetChildCategoryIdsAsync(categoryId, (await _storeContext.GetCurrentStoreAsync()).Id))
.ToListAsync());
return ids.Distinct().ToList();
});
return result;
}
/// <summary>
/// Gets child category identifiers
/// </summary>
/// <param name="parentCategoryId">Parent category identifier</param>
/// <param name="storeId">Store identifier; 0 if you want to get all records</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the category identifiers
/// </returns>
public virtual async Task<IList<int>> GetChildCategoryIdsAsync(int parentCategoryId, int storeId = 0, bool showHidden = false)
{
var cacheKey = _staticCacheManager.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoriesChildIdsCacheKey,
parentCategoryId,
await _customerService.GetCustomerRoleIdsAsync(await _workContext.GetCurrentCustomerAsync()),
storeId,
showHidden);
return await _staticCacheManager.GetAsync(cacheKey, async () =>
{
//little hack for performance optimization
//there's no need to invoke "GetAllCategoriesByParentCategoryId" multiple times (extra SQL commands) to load childs
//so we load all categories at once (we know they are cached) and process them server-side
var categoriesIds = new List<int>();
var categories = (await GetAllCategoriesAsync(storeId: storeId, showHidden: showHidden))
.Where(c => c.ParentCategoryId == parentCategoryId)
.Select(c => c.Id)
.ToList();
categoriesIds.AddRange(categories);
categoriesIds.AddRange(await categories.SelectManyAwait(async cId => await GetChildCategoryIdsAsync(cId, storeId, showHidden)).ToListAsync());
return categoriesIds;
});
}
/// <summary>
/// Gets a category
/// </summary>
/// <param name="categoryId">Category identifier</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the category
/// </returns>
public virtual async Task<Category> GetCategoryByIdAsync(int categoryId)
{
return await _categoryRepository.GetByIdAsync(categoryId, cache => default);
}
/// <summary>
/// Get categories for which a discount is applied
/// </summary>
/// <param name="discountId">Discount identifier; pass null to load all records</param>
/// <param name="showHidden">A value indicating whether to load deleted categories</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the list of categories
/// </returns>
public virtual async Task<IPagedList<Category>> GetCategoriesByAppliedDiscountAsync(int? discountId = null,
bool showHidden = false, int pageIndex = 0, int pageSize = int.MaxValue)
{
var categories = _categoryRepository.Table;
if (discountId.HasValue)
categories = from category in categories
join dcm in _discountCategoryMappingRepository.Table on category.Id equals dcm.EntityId
where dcm.DiscountId == discountId.Value
select category;
if (!showHidden)
categories = categories.Where(category => !category.Deleted);
categories = categories.OrderBy(category => category.DisplayOrder).ThenBy(category => category.Id);
return await categories.ToPagedListAsync(pageIndex, pageSize);
}
/// <summary>
/// Inserts category
/// </summary>
/// <param name="category">Category</param>
/// <returns>A task that represents the asynchronous operation</returns>
public virtual async Task InsertCategoryAsync(Category category)
{
await _categoryRepository.InsertAsync(category);
}
/// <summary>
/// Get a value indicating whether discount is applied to category
/// </summary>
/// <param name="categoryId">Category identifier</param>
/// <param name="discountId">Discount identifier</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the result
/// </returns>
public virtual async Task<DiscountCategoryMapping> GetDiscountAppliedToCategoryAsync(int categoryId, int discountId)
{
return await _discountCategoryMappingRepository.Table
.FirstOrDefaultAsync(dcm => dcm.EntityId == categoryId && dcm.DiscountId == discountId);
}
/// <summary>
/// Inserts a discount-category mapping record
/// </summary>
/// <param name="discountCategoryMapping">Discount-category mapping</param>
/// <returns>A task that represents the asynchronous operation</returns>
public virtual async Task InsertDiscountCategoryMappingAsync(DiscountCategoryMapping discountCategoryMapping)
{
await _discountCategoryMappingRepository.InsertAsync(discountCategoryMapping);
}
/// <summary>
/// Deletes a discount-category mapping record
/// </summary>
/// <param name="discountCategoryMapping">Discount-category mapping</param>
/// <returns>A task that represents the asynchronous operation</returns>
public virtual async Task DeleteDiscountCategoryMappingAsync(DiscountCategoryMapping discountCategoryMapping)
{
await _discountCategoryMappingRepository.DeleteAsync(discountCategoryMapping);
}
/// <summary>
/// Updates the category
/// </summary>
/// <param name="category">Category</param>
/// <returns>A task that represents the asynchronous operation</returns>
public virtual async Task UpdateCategoryAsync(Category category)
{
if (category == null)
throw new ArgumentNullException(nameof(category));
//validate category hierarchy
var parentCategory = await GetCategoryByIdAsync(category.ParentCategoryId);
while (parentCategory != null)
{
if (category.Id == parentCategory.Id)
{
category.ParentCategoryId = 0;
break;
}
parentCategory = await GetCategoryByIdAsync(parentCategory.ParentCategoryId);
}
await _categoryRepository.UpdateAsync(category);
}
/// <summary>
/// Deletes a product category mapping
/// </summary>
/// <param name="productCategory">Product category</param>
/// <returns>A task that represents the asynchronous operation</returns>
public virtual async Task DeleteProductCategoryAsync(ProductCategory productCategory)
{
await _productCategoryRepository.DeleteAsync(productCategory);
}
/// <summary>
/// Gets product category mapping collection
/// </summary>
/// <param name="categoryId">Category identifier</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the product a category mapping collection
/// </returns>
public virtual async Task<IPagedList<ProductCategory>> GetProductCategoriesByCategoryIdAsync(int categoryId,
int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
{
if (categoryId == 0)
return new PagedList<ProductCategory>(new List<ProductCategory>(), pageIndex, pageSize);
var query = from pc in _productCategoryRepository.Table
join p in _productRepository.Table on pc.ProductId equals p.Id
where pc.CategoryId == categoryId && !p.Deleted
orderby pc.DisplayOrder, pc.Id
select pc;
if (!showHidden)
{
var categoriesQuery = _categoryRepository.Table.Where(c => c.Published);
//apply store mapping constraints
var store = await _storeContext.GetCurrentStoreAsync();
categoriesQuery = await _storeMappingService.ApplyStoreMapping(categoriesQuery, store.Id);
//apply ACL constraints
var customer = await _workContext.GetCurrentCustomerAsync();
categoriesQuery = await _aclService.ApplyAcl(categoriesQuery, customer);
query = query.Where(pc => categoriesQuery.Any(c => c.Id == pc.CategoryId));
}
return await query.ToPagedListAsync(pageIndex, pageSize);
}
/// <summary>
/// Gets a product category mapping collection
/// </summary>
/// <param name="productId">Product identifier</param>
/// <param name="showHidden"> A value indicating whether to show hidden records</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the product category mapping collection
/// </returns>
public virtual async Task<IList<ProductCategory>> GetProductCategoriesByProductIdAsync(int productId, bool showHidden = false)
{
return await GetProductCategoriesByProductIdAsync(productId, (await _storeContext.GetCurrentStoreAsync()).Id, showHidden);
}
/// <summary>
/// Gets a product category mapping
/// </summary>
/// <param name="productCategoryId">Product category mapping identifier</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the product category mapping
/// </returns>
public virtual async Task<ProductCategory> GetProductCategoryByIdAsync(int productCategoryId)
{
return await _productCategoryRepository.GetByIdAsync(productCategoryId, cache => default);
}
/// <summary>
/// Inserts a product category mapping
/// </summary>
/// <param name="productCategory">>Product category mapping</param>
/// <returns>A task that represents the asynchronous operation</returns>
public virtual async Task InsertProductCategoryAsync(ProductCategory productCategory)
{
await _productCategoryRepository.InsertAsync(productCategory);
}
/// <summary>
/// Updates the product category mapping
/// </summary>
/// <param name="productCategory">>Product category mapping</param>
/// <returns>A task that represents the asynchronous operation</returns>
public virtual async Task UpdateProductCategoryAsync(ProductCategory productCategory)
{
await _productCategoryRepository.UpdateAsync(productCategory);
}
/// <summary>
/// Returns a list of names of not existing categories
/// </summary>
/// <param name="categoryIdsNames">The names and/or IDs of the categories to check</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the list of names and/or IDs not existing categories
/// </returns>
public virtual async Task<string[]> GetNotExistingCategoriesAsync(string[] categoryIdsNames)
{
if (categoryIdsNames == null)
throw new ArgumentNullException(nameof(categoryIdsNames));
var query = _categoryRepository.Table;
var queryFilter = categoryIdsNames.Distinct().ToArray();
//filtering by name
var filter = await query.Select(c => c.Name)
.Where(c => queryFilter.Contains(c))
.ToListAsync();
queryFilter = queryFilter.Except(filter).ToArray();
//if some names not found
if (!queryFilter.Any())
return queryFilter.ToArray();
//filtering by IDs
filter = await query.Select(c => c.Id.ToString())
.Where(c => queryFilter.Contains(c))
.ToListAsync();
return queryFilter.Except(filter).ToArray();
}
/// <summary>
/// Get category IDs for products
/// </summary>
/// <param name="productIds">Products IDs</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the category IDs for products
/// </returns>
public virtual async Task<IDictionary<int, int[]>> GetProductCategoryIdsAsync(int[] productIds)
{
var query = _productCategoryRepository.Table;
return (await query.Where(p => productIds.Contains(p.ProductId))
.Select(p => new { p.ProductId, p.CategoryId })
.ToListAsync())
.GroupBy(a => a.ProductId)
.ToDictionary(items => items.Key, items => items.Select(a => a.CategoryId).ToArray());
}
/// <summary>
/// Gets categories by identifier
/// </summary>
/// <param name="categoryIds">Category identifiers</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the categories
/// </returns>
public virtual async Task<IList<Category>> GetCategoriesByIdsAsync(int[] categoryIds)
{
return await _categoryRepository.GetByIdsAsync(categoryIds, includeDeleted: false);
}
/// <summary>
/// Returns a ProductCategory that has the specified values
/// </summary>
/// <param name="source">Source</param>
/// <param name="productId">Product identifier</param>
/// <param name="categoryId">Category identifier</param>
/// <returns>A ProductCategory that has the specified values; otherwise null</returns>
public virtual ProductCategory FindProductCategory(IList<ProductCategory> source, int productId, int categoryId)
{
foreach (var productCategory in source)
if (productCategory.ProductId == productId && productCategory.CategoryId == categoryId)
return productCategory;
return null;
}
/// <summary>
/// Get formatted category breadcrumb
/// Note: ACL and store mapping is ignored
/// </summary>
/// <param name="category">Category</param>
/// <param name="allCategories">All categories</param>
/// <param name="separator">Separator</param>
/// <param name="languageId">Language identifier for localization</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the formatted breadcrumb
/// </returns>
public virtual async Task<string> GetFormattedBreadCrumbAsync(Category category, IList<Category> allCategories = null,
string separator = ">>", int languageId = 0)
{
var result = string.Empty;
var breadcrumb = await GetCategoryBreadCrumbAsync(category, allCategories, true);
for (var i = 0; i <= breadcrumb.Count - 1; i++)
{
var categoryName = await _localizationService.GetLocalizedAsync(breadcrumb[i], x => x.Name, languageId);
result = string.IsNullOrEmpty(result) ? categoryName : $"{result} {separator} {categoryName}";
}
return result;
}
/// <summary>
/// Get category breadcrumb
/// </summary>
/// <param name="category">Category</param>
/// <param name="allCategories">All categories</param>
/// <param name="showHidden">A value indicating whether to load hidden records</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the category breadcrumb
/// </returns>
public virtual async Task<IList<Category>> GetCategoryBreadCrumbAsync(Category category, IList<Category> allCategories = null, bool showHidden = false)
{
if (category == null)
throw new ArgumentNullException(nameof(category));
var breadcrumbCacheKey = _staticCacheManager.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoryBreadcrumbCacheKey,
category,
await _customerService.GetCustomerRoleIdsAsync(await _workContext.GetCurrentCustomerAsync()),
await _storeContext.GetCurrentStoreAsync(),
await _workContext.GetWorkingLanguageAsync());
return await _staticCacheManager.GetAsync(breadcrumbCacheKey, async () =>
{
var result = new List<Category>();
//used to prevent circular references
var alreadyProcessedCategoryIds = new List<int>();
while (category != null && //not null
!category.Deleted && //not deleted
(showHidden || category.Published) && //published
(showHidden || await _aclService.AuthorizeAsync(category)) && //ACL
(showHidden || await _storeMappingService.AuthorizeAsync(category)) && //Store mapping
!alreadyProcessedCategoryIds.Contains(category.Id)) //prevent circular references
{
result.Add(category);
alreadyProcessedCategoryIds.Add(category.Id);
category = allCategories != null
? allCategories.FirstOrDefault(c => c.Id == category.ParentCategoryId)
: await GetCategoryByIdAsync(category.ParentCategoryId);
}
result.Reverse();
return result;
});
}
#endregion
}
} | 44.238335 | 186 | 0.612183 | [
"CC0-1.0"
] | peterthomet/BioPuur | nopCommerce 4.4/src/Libraries/Nop.Services/Catalog/CategoryService.cs | 35,083 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class hitboxDestroyer : MonoBehaviour
{
float lifetime = 0.1f;
blindEnemyController blindGuardCon;
public bool playerHit = false;
// Start is called before the first frame update
void Start()
{
GameObject blindGuard = GameObject.Find("blindGuard");
blindGuardCon = blindGuard.GetComponent<blindEnemyController>();
}
// Update is called once per frame
void Update()
{
if (lifetime > 0)
{
lifetime = lifetime - Time.deltaTime;
}
else
{
if(!blindGuardCon.spawnHitbox)
{
Destroy(this.gameObject);
}
Destroy(this.gameObject);
}
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Player")
{
Debug.Log("Player hit by boss!");
playerHit = true;
}
playerHit = false;
}
}
| 23.155556 | 72 | 0.56334 | [
"MIT"
] | TobyAtkinson/Team8GameProject | SteamPunkStealth/Assets/hitboxDestroyer.cs | 1,044 | C# |
using CSM.API.Commands;
using ProtoBuf;
namespace CSM.BaseGame.Commands.Data.Events
{
/// <summary>
/// Called when the ticket price of an event was changed.
/// </summary>
/// Sent by:
/// - EventHandler
[ProtoContract]
public class EventSetTicketPriceCommand : CommandBase
{
/// <summary>
/// The id of the event that was modified.
/// </summary>
[ProtoMember(1)]
public ushort Event { get; set; }
/// <summary>
/// The new ticket price.
/// </summary>
[ProtoMember(2)]
public int Price { get; set; }
}
}
| 23.592593 | 65 | 0.546311 | [
"MIT"
] | DominicMaas/Tango | src/basegame/Commands/Data/Events/EventSetTicketPriceCommand.cs | 637 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the sdb-2009-04-15.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.SimpleDB.Model
{
///<summary>
/// SimpleDB exception
/// </summary>
public class NumberDomainAttributesExceededException : AmazonSimpleDBException
{
/// <summary>
/// Constructs a new NumberDomainAttributesExceededException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public NumberDomainAttributesExceededException(string message)
: base(message) {}
/// <summary>
/// Construct instance of NumberDomainAttributesExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public NumberDomainAttributesExceededException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of NumberDomainAttributesExceededException
/// </summary>
/// <param name="innerException"></param>
public NumberDomainAttributesExceededException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of NumberDomainAttributesExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public NumberDomainAttributesExceededException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of NumberDomainAttributesExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public NumberDomainAttributesExceededException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Gets and sets the BoxUsage property.
/// </summary>
public float BoxUsage { get; set; }
}
} | 40.202381 | 181 | 0.642582 | [
"Apache-2.0"
] | jasoncwik/aws-sdk-net | sdk/src/Services/SimpleDB/Generated/Model/NumberDomainAttributesExceededException.cs | 3,377 | C# |
// <auto-generated />
namespace PhotoMSK.Data.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class DateFix : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(DateFix));
string IMigrationMetadata.Id
{
get { return "201508111848356_DateFix"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 26.866667 | 90 | 0.614144 | [
"MIT"
] | MarkusMokler/photomsmsk-by | PhotoMSK/Core/PhotoMSK.Data/Migrations/201508111848356_DateFix.Designer.cs | 806 | C# |
using System;
namespace Hillinworks.TiledImage.Imaging
{
partial struct TileIndex
{
public struct LOD
{
public static explicit operator TileIndex(LOD index)
{
return new TileIndex(index.Column, index.Row);
}
public int Row { get; }
public int Column { get; }
public int LODLevel { get; }
public LOD(int column, int row, int lodLevel)
{
// todo: restore these checks after normalizing column and row
//if (column < 0)
//{
// throw new ArgumentOutOfRangeException(nameof(column));
//}
//if (row < 0)
//{
// throw new ArgumentOutOfRangeException(nameof(row));
//}
if (lodLevel < 0)
{
throw new ArgumentOutOfRangeException(nameof(lodLevel));
}
this.Column = column;
this.Row = row;
this.LODLevel = lodLevel;
}
public override int GetHashCode()
{
return (this.LODLevel << 24) + (this.Column << 12) + this.Row;
}
public override string ToString()
{
return $"{this.Column}, {this.Row}, LOD{this.LODLevel}";
}
public Full ToFull(int layer)
{
return new Full(this.Column, this.Row, layer, this.LODLevel);
}
}
}
} | 27.517241 | 78 | 0.451754 | [
"MIT"
] | hillinworks/TiledImageView | Hillinworks.TiledImage.Core/Imaging/TileIndex.LOD.cs | 1,598 | 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.AwsNative.EC2.Inputs
{
public sealed class InstanceElasticGpuSpecificationArgs : Pulumi.ResourceArgs
{
[Input("type", required: true)]
public Input<string> Type { get; set; } = null!;
public InstanceElasticGpuSpecificationArgs()
{
}
}
}
| 26.391304 | 81 | 0.693575 | [
"Apache-2.0"
] | AaronFriel/pulumi-aws-native | sdk/dotnet/EC2/Inputs/InstanceElasticGpuSpecificationArgs.cs | 607 | 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("GoogleTagManager")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GoogleTagManager")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[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("e2b4d291-cfee-4a66-a169-c579fe006434")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.916667 | 84 | 0.750183 | [
"MIT"
] | Bradinz/Vanjaro.Platform | DesktopModules/Vanjaro/UXManager/Extensions/Menu/GoogleTagManager/Properties/AssemblyInfo.cs | 1,368 | 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("WindowsFormsApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WindowsFormsApplication1")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("c03c1c4b-a82d-4dd9-be69-215f5fb2ae13")]
// 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.405405 | 84 | 0.749472 | [
"MIT"
] | aaronuhmgmailcom/Financel | PDFView(32bit Office) v2/PDFView(32bit Office) v2/PDFView(32bit Office) v2/WindowsFormsApplication1/Properties/AssemblyInfo.cs | 1,424 | C# |
namespace MiniUML.Plugins.UmlClassDiagram.Controls.ViewModel.Shape
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
using MiniUML.Model.ViewModels;
using MiniUML.Model.ViewModels.Shapes;
using MiniUML.Plugins.UmlClassDiagram.Controls.ViewModel.Shape.Base;
using MiniUML.Plugins.UmlClassDiagram.Controls.ViewModel.UmlElements;
using MiniUML.Plugins.UmlClassDiagram.Converter;
/// <summary>
/// This class implements the viewmodel for the Uml Use Case shape
/// that users can draw on a UML canvas.
/// </summary>
public class UmlUseCaseShapeViewModel : UmlShapeBaseViewModel
{
#region fields
private string mStroke = string.Empty;
private string mStrokeDashArray = string.Empty;
#endregion fields
#region constructor
/// <summary>
/// Standard contructor hidding XElement constructor
/// </summary>
public UmlUseCaseShapeViewModel(IShapeParent parent,
UmlTypes umlType)
: base(parent,
ShapeViewModelKey.UseCaseShape, ShapeViewModelSubKeys.None,
umlType)
{
this.MinHeight = 50;
this.MinWidth = 50;
}
#endregion constructor
#region properties
public string Stroke
{
get
{
return this.mStroke;
}
set
{
if (this.mStroke != value)
{
this.mStroke = value;
this.NotifyPropertyChanged(() => this.Stroke);
}
}
}
public string StrokeDashArray
{
get
{
return this.mStrokeDashArray;
}
set
{
if (this.mStrokeDashArray != value)
{
this.mStrokeDashArray = value;
this.NotifyPropertyChanged(() => this.StrokeDashArray);
}
}
}
#endregion properties
#region methods
/// <summary>
/// Read shape data from XML stream and return it.
/// </summary>
/// <param name="reader"></param>
/// <param name="parent"></param>
/// <param name="umlType"></param>
/// <returns></returns>
public static UmlUseCaseShapeViewModel ReadDocument(XmlReader reader,
IShapeParent parent,
UmlTypes umlType)
{
UmlUseCaseShapeViewModel ret = UmlElementDataDef.CreateShape(umlType, new System.Windows.Point(UmlTypeToStringConverter.DefaultX,
UmlTypeToStringConverter.DefaultY), parent)
as UmlUseCaseShapeViewModel;
reader.ReadToNextSibling(ret.UmlDataTypeString);
while (reader.MoveToNextAttribute())
{
if (ret.ReadAttributes(reader.Name, reader.Value) == false)
{
if (reader.Name.Trim().Length > 0 && reader.Name != UmlShapeBaseViewModel.XmlComment)
throw new ArgumentException("XML node:'" + reader.Name + "' as child of '" + ret.XElementName + "' is not supported.");
}
}
// Read common model information (eg. comments)
UmlShapeBaseViewModel.ReadDocument(reader, ret);
return ret;
}
/// <summary>
/// Persist the contents of this object into the given
/// parameter <paramref name="writer"/> object.
/// </summary>
/// <param name="writer"></param>
public override void SaveDocument(System.Xml.XmlWriter writer,
IEnumerable<ShapeViewModelBase> root)
{
writer.WriteStartElement(this.mElementName);
this.SaveAttributes(writer);
// Save common model information (eg. comments)
base.SaveDocument(writer);
if (root != null)
{
foreach (var item in root)
{
item.SaveDocument(writer, item.Elements());
}
}
writer.WriteEndElement();
}
#endregion methods
}
}
| 29.955556 | 144 | 0.581108 | [
"MIT"
] | Dirkster99/Edi | MiniUML/Plugins/src/MiniUML.Plugins.UmlClassDiagram/Controls/ViewModel/Shape/UmlUseCaseShapeViewModel.cs | 4,046 | C# |
/*
Copyright 2012-2020 Marco De Salvo
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using RDFSharp.Query;
using System.Collections.Generic;
using System.Linq;
namespace RDFSharp.Model
{
/// <summary>
/// RDFHasValueConstraint represents a SHACL constraint on a required value for a given RDF term
/// </summary>
public class RDFHasValueConstraint : RDFConstraint
{
#region Properties
/// <summary>
/// Value required on the given RDF term
/// </summary>
public RDFPatternMember Value { get; internal set; }
#endregion
#region Ctors
/// <summary>
/// Default-ctor to build a hasValue constraint with the given resource value
/// </summary>
public RDFHasValueConstraint(RDFResource value) : base()
{
if (value != null)
{
this.Value = value;
}
else
{
throw new RDFModelException("Cannot create RDFHasValueConstraint because given \"value\" parameter is null.");
}
}
/// <summary>
/// Default-ctor to build a hasValue constraint with the given literal value
/// </summary>
public RDFHasValueConstraint(RDFLiteral value) : base()
{
if (value != null)
{
this.Value = value;
}
else
{
throw new RDFModelException("Cannot create RDFHasValueConstraint because given \"value\" parameter is null.");
}
}
#endregion
#region Methods
/// <summary>
/// Evaluates this constraint against the given data graph
/// </summary>
internal override RDFValidationReport ValidateConstraint(RDFShapesGraph shapesGraph, RDFGraph dataGraph, RDFShape shape, RDFPatternMember focusNode, List<RDFPatternMember> valueNodes)
{
RDFValidationReport report = new RDFValidationReport();
#region Evaluation
if (!valueNodes.Any(v => v.Equals(this.Value)))
{
report.AddResult(new RDFValidationResult(shape,
RDFVocabulary.SHACL.HAS_VALUE_CONSTRAINT_COMPONENT,
focusNode,
shape is RDFPropertyShape ? ((RDFPropertyShape)shape).Path : null,
null,
shape.Messages,
shape.Severity));
}
#endregion
return report;
}
/// <summary>
/// Gets a graph representation of this constraint
/// </summary>
internal override RDFGraph ToRDFGraph(RDFShape shape)
{
RDFGraph result = new RDFGraph();
if (shape != null)
{
//sh:hasValue
if (this.Value is RDFResource)
result.AddTriple(new RDFTriple(shape, RDFVocabulary.SHACL.HAS_VALUE, (RDFResource)this.Value));
else
result.AddTriple(new RDFTriple(shape, RDFVocabulary.SHACL.HAS_VALUE, (RDFLiteral)this.Value));
}
return result;
}
#endregion
}
} | 34.938053 | 191 | 0.548632 | [
"Apache-2.0"
] | BME-MIT-IET/iet-hf2021-create-a-new-team | RDFSharp/Model/Validation/Abstractions/Constraints/RDFHasValueConstraint.cs | 3,950 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the swf-2012-01-25.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.SimpleWorkflow
{
/// <summary>
/// Configuration for accessing Amazon SimpleWorkflow service
/// </summary>
public partial class AmazonSimpleWorkflowConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.3.0.47");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonSimpleWorkflowConfig()
{
this.AuthenticationServiceName = "swf";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "swf";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2012-01-25";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.2125 | 101 | 0.58846 | [
"Apache-2.0"
] | InsiteVR/aws-sdk-net | sdk/src/Services/SimpleWorkflow/Generated/AmazonSimpleWorkflowConfig.cs | 2,097 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Threading;
using ARKBreedingStats.Library;
using ARKBreedingStats.Properties;
using ARKBreedingStats.raising;
using ARKBreedingStats.species;
using ARKBreedingStats.uiControls;
using ARKBreedingStats.utils;
using ARKBreedingStats.values;
namespace ARKBreedingStats
{
public partial class BreedingPlan : UserControl
{
public event Action<Creature, bool> EditCreature;
public event Action<Creature> BestBreedingPartners;
public event Action<Creature> DisplayInPedigree;
public event PedigreeCreature.ExportToClipboardEventHandler ExportToClipboard;
public event Raising.createIncubationEventHandler CreateIncubationTimer;
public event Form1.SetMessageLabelTextEventHandler SetMessageLabelText;
public event Action<Species> SetGlobalSpecies;
private Creature[] _females;
private Creature[] _males;
private List<BreedingPair> _breedingPairs;
private Species _currentSpecies;
/// <summary>
/// how much are the stats weighted when looking for the best
/// </summary>
private double[] _statWeights = new double[Values.STATS_COUNT];
/// <summary>
/// The best possible levels of the selected species for each stat.
/// If the weighting is negative, a low level is considered better.
/// </summary>
private readonly int[] _bestLevels = new int[Values.STATS_COUNT];
private readonly List<PedigreeCreature> _pcs = new List<PedigreeCreature>();
private readonly List<PictureBox> _pbs = new List<PictureBox>();
private bool[] _enabledColorRegions;
private TimeSpan _incubationTime;
private Creature _chosenCreature;
private BreedingMode _breedingMode;
public readonly StatWeighting statWeighting;
public bool breedingPlanNeedsUpdate;
private bool _speciesInfoNeedsUpdate;
private Debouncer _breedingPlanDebouncer = new Debouncer();
/// <summary>
/// Set to false if settings are changed and update should only performed after that.
/// </summary>
private bool _updateBreedingPlanAllowed;
public CreatureCollection CreatureCollection;
private readonly ToolTip _tt = new ToolTip();
#region inheritance probabilities
public const double ProbabilityHigherLevel = 0.55; // probability of inheriting the higher level-stat
public const double ProbabilityLowerLevel = 1 - ProbabilityHigherLevel; // probability of inheriting the lower level-stat
private const double ProbabilityOfMutation = 0.025;
//private const int maxMutationRolls = 3;
/// <summary>
/// A mutation is possible if the Mutations are less than this number.
/// </summary>
private const int MutationPossibleWithLessThan = 20;
/// <summary>
/// The probability that at least one mutation happens if both parents have a mutation counter of less than 20.
/// </summary>
private const double ProbabilityOfOneMutation = 1 - (1 - ProbabilityOfMutation) * (1 - ProbabilityOfMutation) * (1 - ProbabilityOfMutation);
/// <summary>
/// The approximate probability of at least one mutation if one parent has less and one parent has larger or equal 20 mutation.
/// It's assumed that the stats of the mutated stat are the same for the parents.
/// If they differ, the probability for a mutation from the parent with the higher stat is probabilityHigherLevel * probabilityOfMutation etc.
/// </summary>
private const double ProbabilityOfOneMutationFromOneParent = 1 - (1 - ProbabilityOfMutation / 2) * (1 - ProbabilityOfMutation / 2) * (1 - ProbabilityOfMutation / 2);
#endregion
public BreedingPlan()
{
InitializeComponent();
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
for (int i = 0; i < Values.STATS_COUNT; i++)
_statWeights[i] = 1;
_breedingMode = BreedingMode.TopStatsConservative;
_breedingPairs = new List<BreedingPair>();
pedigreeCreatureBest.SetIsVirtual(true);
pedigreeCreatureWorst.SetIsVirtual(true);
pedigreeCreatureBestPossibleInSpecies.SetIsVirtual(true);
pedigreeCreatureBest.OnlyLevels = true;
pedigreeCreatureWorst.OnlyLevels = true;
pedigreeCreatureBestPossibleInSpecies.OnlyLevels = true;
pedigreeCreatureBest.Clear();
pedigreeCreatureWorst.Clear();
pedigreeCreatureBestPossibleInSpecies.Clear();
pedigreeCreatureBest.HandCursor = false;
pedigreeCreatureWorst.HandCursor = false;
pedigreeCreatureBestPossibleInSpecies.HandCursor = false;
statWeighting = statWeighting1;
statWeighting.WeightingsChanged += StatWeighting_WeightingsChanged;
breedingPlanNeedsUpdate = false;
cbServerFilterLibrary.Checked = Settings.Default.UseServerFilterForBreedingPlan;
cbOwnerFilterLibrary.Checked = Settings.Default.UseOwnerFilterForBreedingPlan;
cbBPIncludeCooldowneds.Checked = Settings.Default.IncludeCooldownsInBreedingPlan;
cbBPIncludeCryoCreatures.Checked = Settings.Default.IncludeCryoedInBreedingPlan;
cbBPOnlyOneSuggestionForFemales.Checked = Settings.Default.BreedingPlanOnlyBestSuggestionForEachFemale;
cbBPMutationLimitOnlyOnePartner.Checked = Settings.Default.BreedingPlanOnePartnerMoreMutationsThanLimit;
tagSelectorList1.OnTagChanged += TagSelectorList1_OnTagChanged;
_updateBreedingPlanAllowed = true;
}
private void StatWeighting_WeightingsChanged()
{
// check if sign of a weighting changed (then the best levels change)
bool signChanged = false;
var newWeightings = statWeighting.Weightings;
for (int s = 0; s < Values.STATS_COUNT; s++)
{
if (Math.Sign(_statWeights[s]) != Math.Sign(newWeightings[s]))
{
signChanged = true;
break;
}
}
_statWeights = newWeightings;
if (signChanged) DetermineBestLevels();
CalculateBreedingScoresAndDisplayPairs();
}
private void TagSelectorList1_OnTagChanged()
{
CalculateBreedingScoresAndDisplayPairs();
}
public void BindChildrenControlEvents()
{
// has to be done after the BreedingPlan-class got the binding
pedigreeCreatureBest.CreatureEdit += EditCreature;
pedigreeCreatureWorst.CreatureEdit += EditCreature;
pedigreeCreatureBestPossibleInSpecies.CreatureEdit += EditCreature;
pedigreeCreatureBest.ExportToClipboard += ExportToClipboard;
pedigreeCreatureWorst.ExportToClipboard += ExportToClipboard;
pedigreeCreatureBestPossibleInSpecies.ExportToClipboard += ExportToClipboard;
pedigreeCreatureBest.CreatureClicked += CreatureClicked;
pedigreeCreatureWorst.CreatureClicked += CreatureClicked;
}
/// <summary>
/// Set species or specific creature and calculate the breeding pairs.
/// </summary>
/// <param name="chosenCreature"></param>
/// <param name="forceUpdate"></param>
/// <param name="setSpecies"></param>
public void DetermineBestBreeding(Creature chosenCreature = null, bool forceUpdate = false, Species setSpecies = null)
{
if (CreatureCollection == null) return;
Species selectedSpecies = chosenCreature?.Species;
_speciesInfoNeedsUpdate = false;
if (selectedSpecies == null)
selectedSpecies = setSpecies ?? _currentSpecies;
if (selectedSpecies != null && _currentSpecies != selectedSpecies)
{
CurrentSpecies = selectedSpecies;
_speciesInfoNeedsUpdate = true;
EnabledColorRegions = _currentSpecies?.EnabledColorRegions;
breedingPlanNeedsUpdate = true;
}
_statWeights = statWeighting.Weightings;
if (forceUpdate || breedingPlanNeedsUpdate)
Creatures = CreatureCollection.creatures
.Where(c => c.speciesBlueprint == _currentSpecies.blueprintPath
&& (c.Status == CreatureStatus.Available
|| (c.Status == CreatureStatus.Cryopod && cbBPIncludeCryoCreatures.Checked))
&& !c.flags.HasFlag(CreatureFlags.Neutered)
&& (cbBPIncludeCooldowneds.Checked
|| !(c.cooldownUntil > DateTime.Now
|| c.growingUntil > DateTime.Now
)
)
)
.ToList();
_chosenCreature = chosenCreature;
CalculateBreedingScoresAndDisplayPairs();
breedingPlanNeedsUpdate = false;
}
private IEnumerable<Creature> FilterByTags(IEnumerable<Creature> cl)
{
List<string> excludingTagList = tagSelectorList1.excludingTags;
List<string> includingTagList = tagSelectorList1.includingTags;
List<Creature> filteredList = new List<Creature>();
if (excludingTagList.Any() || cbBPTagExcludeDefault.Checked)
{
foreach (Creature c in cl)
{
bool exclude = cbBPTagExcludeDefault.Checked;
if (!exclude && excludingTagList.Any())
{
foreach (string t in c.tags)
{
if (excludingTagList.Contains(t))
{
exclude = true;
break;
}
}
}
if (exclude && includingTagList.Any())
{
foreach (string t in c.tags)
{
if (includingTagList.Contains(t))
{
exclude = false;
break;
}
}
}
if (!exclude)
filteredList.Add(c);
}
return filteredList;
}
return cl;
}
/// <summary>
/// Update breeding plan with current settings and current species.
/// </summary>
private void CalculateBreedingScoresAndDisplayPairs()
{
if (_updateBreedingPlanAllowed && _currentSpecies != null)
_breedingPlanDebouncer.Debounce(400, DoCalculateBreedingScoresAndDisplayPairs, Dispatcher.CurrentDispatcher);
}
private void DoCalculateBreedingScoresAndDisplayPairs()
{
if (_currentSpecies == null
|| _females == null
|| _males == null
)
return;
SuspendLayout();
this.SuspendDrawing();
ClearControls();
// chosen Creature (only consider this one for its sex)
bool considerChosenCreature = _chosenCreature != null;
bool considerMutationLimit = nudBPMutationLimit.Value >= 0;
bool creaturesMutationsFilteredOut = false;
// filter by tags
int crCountF = _females.Length;
int crCountM = _males.Length;
IEnumerable<Creature> selectFemales;
IEnumerable<Creature> selectMales;
if (considerChosenCreature && _chosenCreature.sex == Sex.Female)
selectFemales = new List<Creature>();
else if (!cbBPMutationLimitOnlyOnePartner.Checked && considerMutationLimit)
{
selectFemales = FilterByTags(_females.Where(c => c.Mutations <= nudBPMutationLimit.Value));
creaturesMutationsFilteredOut = _females.Any(c => c.Mutations > nudBPMutationLimit.Value);
}
else selectFemales = FilterByTags(_females);
if (considerChosenCreature && _chosenCreature.sex == Sex.Male)
selectMales = new List<Creature>();
else if (!cbBPMutationLimitOnlyOnePartner.Checked && considerMutationLimit)
{
selectMales = FilterByTags(_males.Where(c => c.Mutations <= nudBPMutationLimit.Value));
creaturesMutationsFilteredOut = creaturesMutationsFilteredOut || _males.Any(c => c.Mutations > nudBPMutationLimit.Value);
}
else selectMales = FilterByTags(_males);
// filter by servers
if (cbServerFilterLibrary.Checked && (Settings.Default.FilterHideServers?.Any() ?? false))
{
selectFemales = selectFemales.Where(c => !Settings.Default.FilterHideServers.Contains(c.server));
selectMales = selectMales.Where(c => !Settings.Default.FilterHideServers.Contains(c.server));
}
// filter by owner
if (cbOwnerFilterLibrary.Checked && (Settings.Default.FilterHideOwners?.Any() ?? false))
{
selectFemales = selectFemales.Where(c => !Settings.Default.FilterHideOwners.Contains(c.owner));
selectMales = selectMales.Where(c => !Settings.Default.FilterHideOwners.Contains(c.owner));
}
// filter by tribe
if (cbTribeFilterLibrary.Checked && (Settings.Default.FilterHideTribes?.Any() ?? false))
{
selectFemales = selectFemales.Where(c => !Settings.Default.FilterHideTribes.Contains(c.tribe));
selectMales = selectMales.Where(c => !Settings.Default.FilterHideTribes.Contains(c.tribe));
}
Creature[] selectedFemales = selectFemales.ToArray();
Creature[] selectedMales = selectMales.ToArray();
bool creaturesTagFilteredOut = (crCountF != selectedFemales.Length)
|| (crCountM != selectedMales.Length);
bool displayFilterWarning = true;
lbBreedingPlanHeader.Text = _currentSpecies.DescriptiveNameAndMod + (considerChosenCreature ? " (" + string.Format(Loc.S("onlyPairingsWith"), _chosenCreature.name) + ")" : string.Empty);
if (considerChosenCreature && (_chosenCreature.flags.HasFlag(CreatureFlags.Neutered) || _chosenCreature.Status != CreatureStatus.Available))
lbBreedingPlanHeader.Text += $"{Loc.S("BreedingNotPossible")} ! ({(_chosenCreature.flags.HasFlag(CreatureFlags.Neutered) ? Loc.S("Neutered") : Loc.S("notAvailable"))})";
var combinedCreatures = new List<Creature>(selectedFemales);
combinedCreatures.AddRange(selectedMales);
if (Settings.Default.IgnoreSexInBreedingPlan)
{
selectedFemales = combinedCreatures.ToArray();
selectedMales = combinedCreatures.ToArray();
}
// if only pairings for one specific creatures are shown, add the creature after the filtering
if (considerChosenCreature)
{
if (_chosenCreature.sex == Sex.Female)
selectedFemales = new[] { _chosenCreature };
if (_chosenCreature.sex == Sex.Male)
selectedMales = new[] { _chosenCreature };
}
if (selectedFemales.Any() && selectedMales.Any())
{
pedigreeCreature1.Show();
pedigreeCreature2.Show();
lbBPBreedingScore.Show();
_breedingPairs.Clear();
short[] bestPossLevels = new short[Values.STATS_COUNT]; // best possible levels
for (int fi = 0; fi < selectedFemales.Length; fi++)
{
var female = selectedFemales[fi];
for (int mi = 0; mi < selectedMales.Length; mi++)
{
var male = selectedMales[mi];
// if Properties.Settings.Default.IgnoreSexInBreedingPlan (useful when using S+ mutator), skip pair if
// creatures are the same, or pair has already been added
if (Settings.Default.IgnoreSexInBreedingPlan)
{
if (considerChosenCreature)
{
if (male == female)
continue;
}
else if (fi == mi)
break;
}
// if mutation limit is set, only skip pairs where both parents exceed that limit. One parent is enough to trigger a mutation.
if (considerMutationLimit && female.Mutations > nudBPMutationLimit.Value && male.Mutations > nudBPMutationLimit.Value)
{
creaturesMutationsFilteredOut = true;
continue;
}
double t = 0;
int nrTS = 0;
double eTS = 0;
int topFemale = 0;
int topMale = 0;
for (int s = 0; s < Values.STATS_COUNT; s++)
{
if (s == (int)StatNames.Torpidity) continue;
bestPossLevels[s] = 0;
int higherLevel = Math.Max(female.levelsWild[s], male.levelsWild[s]);
int lowerLevel = Math.Min(female.levelsWild[s], male.levelsWild[s]);
if (higherLevel < 0) higherLevel = 0;
if (lowerLevel < 0) lowerLevel = 0;
bool higherIsBetter = _statWeights[s] >= 0;
double tt = _statWeights[s] * (ProbabilityHigherLevel * higherLevel + ProbabilityLowerLevel * lowerLevel) / 40;
if (tt != 0)
{
if (_breedingMode == BreedingMode.TopStatsLucky)
{
if (female.levelsWild[s] == _bestLevels[s] || male.levelsWild[s] == _bestLevels[s])
{
if (female.levelsWild[s] == _bestLevels[s] && male.levelsWild[s] == _bestLevels[s])
tt *= 1.142;
}
else if (_bestLevels[s] > 0)
tt *= .01;
}
else if (_breedingMode == BreedingMode.TopStatsConservative && _bestLevels[s] > 0)
{
bestPossLevels[s] = (short)(higherIsBetter ? Math.Max(female.levelsWild[s], male.levelsWild[s]) : Math.Min(female.levelsWild[s], male.levelsWild[s]));
tt *= .01;
if (female.levelsWild[s] == _bestLevels[s] || male.levelsWild[s] == _bestLevels[s])
{
nrTS++;
eTS += female.levelsWild[s] == _bestLevels[s] && male.levelsWild[s] == _bestLevels[s] ? 1 : ProbabilityHigherLevel;
if (female.levelsWild[s] == _bestLevels[s])
topFemale++;
if (male.levelsWild[s] == _bestLevels[s])
topMale++;
}
}
}
t += tt;
}
if (_breedingMode == BreedingMode.TopStatsConservative)
{
if (topFemale < nrTS && topMale < nrTS)
t += eTS;
else
t += .1 * eTS;
// check if the best possible stat outcome already exists in a male
bool maleExists = false;
foreach (Creature cr in selectedMales)
{
maleExists = true;
for (int s = 0; s < Values.STATS_COUNT; s++)
{
if (s == (int)StatNames.Torpidity
|| !cr.Species.UsesStat(s)
|| cr.levelsWild[s] == bestPossLevels[s])
continue;
maleExists = false;
break;
}
if (maleExists)
break;
}
if (maleExists)
t *= .4; // another male with the same stats is not worth much, the mating-cooldown of males is short.
else
{
// check if the best possible stat outcome already exists in a female
bool femaleExists = false;
foreach (Creature cr in selectedFemales)
{
femaleExists = true;
for (int s = 0; s < Values.STATS_COUNT; s++)
{
if (s == (int)StatNames.Torpidity
|| !cr.Species.UsesStat(s)
|| cr.levelsWild[s] == bestPossLevels[s])
continue;
femaleExists = false;
break;
}
if (femaleExists)
break;
}
if (femaleExists)
t *= .8; // another female with the same stats may be useful, but not so much in conservative breeding
}
//t *= 2; // scale conservative mode as it rather displays improvement, but only scarcely
}
int mutationPossibleFrom = female.Mutations < MutationPossibleWithLessThan && male.Mutations < MutationPossibleWithLessThan ? 2
: female.Mutations < MutationPossibleWithLessThan || male.Mutations < MutationPossibleWithLessThan ? 1 : 0;
_breedingPairs.Add(new BreedingPair(female, male, t * 1.25, (mutationPossibleFrom == 2 ? ProbabilityOfOneMutation : mutationPossibleFrom == 1 ? ProbabilityOfOneMutationFromOneParent : 0)));
}
}
_breedingPairs = _breedingPairs.OrderByDescending(p => p.BreedingScore).ToList();
if (cbBPOnlyOneSuggestionForFemales.Checked)
{
var onlyOneSuggestionPerFemale = new List<BreedingPair>();
foreach (var bp in _breedingPairs)
{
if (!onlyOneSuggestionPerFemale.Any(p => p.Female == bp.Female))
onlyOneSuggestionPerFemale.Add(bp);
}
_breedingPairs = onlyOneSuggestionPerFemale;
}
double minScore = _breedingPairs.LastOrDefault()?.BreedingScore ?? 0;
if (minScore < 0)
{
foreach (BreedingPair bp in _breedingPairs)
bp.BreedingScore -= minScore;
}
// draw best parents
for (int i = 0; i < _breedingPairs.Count && i < CreatureCollection.maxBreedingSuggestions; i++)
{
PedigreeCreature pc;
if (2 * i < _pcs.Count)
{
_pcs[2 * i].Creature = _breedingPairs[i].Female;
_pcs[2 * i].enabledColorRegions = _enabledColorRegions;
_pcs[2 * i].comboId = i;
_pcs[2 * i].Show();
}
else
{
pc = new PedigreeCreature(_breedingPairs[i].Female, _enabledColorRegions, i, true);
pc.CreatureClicked += CreatureClicked;
pc.CreatureEdit += CreatureEdit;
pc.RecalculateBreedingPlan += RecalculateBreedingPlan;
pc.BestBreedingPartners += BestBreedingPartners;
pc.DisplayInPedigree += DisplayInPedigree;
pc.ExportToClipboard += ExportToClipboard;
flowLayoutPanelPairs.Controls.Add(pc);
_pcs.Add(pc);
}
// draw score
PictureBox pb;
if (i < _pbs.Count)
{
pb = _pbs[i];
_pbs[i].Show();
}
else
{
pb = new PictureBox
{
Size = new Size(87, 35)
};
_pbs.Add(pb);
flowLayoutPanelPairs.Controls.Add(pb);
}
if (2 * i + 1 < _pcs.Count)
{
_pcs[2 * i + 1].Creature = _breedingPairs[i].Male;
_pcs[2 * i + 1].enabledColorRegions = _enabledColorRegions;
_pcs[2 * i + 1].comboId = i;
_pcs[2 * i + 1].Show();
}
else
{
pc = new PedigreeCreature(_breedingPairs[i].Male, _enabledColorRegions, i, true);
pc.CreatureClicked += CreatureClicked;
pc.CreatureEdit += CreatureEdit;
pc.RecalculateBreedingPlan += RecalculateBreedingPlan;
pc.BestBreedingPartners += BestBreedingPartners;
pc.DisplayInPedigree += DisplayInPedigree;
pc.ExportToClipboard += ExportToClipboard;
flowLayoutPanelPairs.Controls.Add(pc);
flowLayoutPanelPairs.SetFlowBreak(pc, true);
_pcs.Add(pc);
}
Bitmap bm = new Bitmap(pb.Width, pb.Height);
using (Graphics g = Graphics.FromImage(bm))
{
g.TextRenderingHint = TextRenderingHint.AntiAlias;
using (Brush br = new SolidBrush(Utils.GetColorFromPercent((int)(_breedingPairs[i].BreedingScore * 12.5), 0.5)))
using (Brush brOutline = new SolidBrush(Utils.GetColorFromPercent((int)(_breedingPairs[i].BreedingScore * 12.5), -.2)))
using (Brush bb = new SolidBrush(Color.Black))
using (Brush bMut = new SolidBrush(Utils.MutationColor))
{
if (_breedingPairs[i].Female.Mutations < MutationPossibleWithLessThan)
g.FillRectangle(bMut, 0, 5, 10, 10);
if (_breedingPairs[i].Male.Mutations < MutationPossibleWithLessThan)
g.FillRectangle(bMut, 77, 5, 10, 10);
g.FillRectangle(brOutline, 0, 15, 87, 5);
g.FillRectangle(brOutline, 20, 10, 47, 15);
g.FillRectangle(br, 1, 16, 85, 3);
g.FillRectangle(br, 21, 11, 45, 13);
g.DrawString(_breedingPairs[i].BreedingScore.ToString("N4"), new Font("Microsoft Sans Serif", 8.25f), bb, 24, 12);
}
pb.Image = bm;
}
}
// hide unused controls
for (int i = CreatureCollection.maxBreedingSuggestions; 2 * i + 1 < _pcs.Count && i < _pbs.Count; i++)
{
_pcs[2 * i].Hide();
_pcs[2 * i + 1].Hide();
_pbs[i].Hide();
}
if (_breedingPairs.Any())
{
SetParents(0);
// if breeding mode is conservative and a creature with top-stats already exists, the scoring might seem off
if (_breedingMode == BreedingMode.TopStatsConservative)
{
bool bestCreatureAlreadyAvailable = true;
Creature bestCreature = null;
List<Creature> chosenFemalesAndMales = selectedFemales.Concat(selectedMales).ToList();
foreach (Creature cr in chosenFemalesAndMales)
{
bestCreatureAlreadyAvailable = true;
for (int s = 0; s < Values.STATS_COUNT; s++)
{
// if the stat is not a top stat and the stat is leveled in wild creatures
if (cr.Species.UsesStat(s) && cr.levelsWild[s] != _bestLevels[s])
{
bestCreatureAlreadyAvailable = false;
break;
}
}
if (bestCreatureAlreadyAvailable)
{
bestCreature = cr;
break;
}
}
if (bestCreatureAlreadyAvailable)
{
displayFilterWarning = false;
SetMessageLabelText(string.Format(Loc.S("AlreadyCreatureWithTopStats"), bestCreature.name, Utils.SexSymbol(bestCreature.sex)), MessageBoxIcon.Warning);
}
}
}
else
SetParents(-1);
}
else
{
// hide unused controls
pedigreeCreature1.Hide();
pedigreeCreature2.Hide();
lbBPBreedingScore.Hide();
for (int i = 0; i < CreatureCollection.maxBreedingSuggestions && 2 * i + 1 < _pcs.Count && i < _pbs.Count; i++)
{
_pcs[2 * i].Hide();
_pcs[2 * i + 1].Hide();
_pbs[i].Hide();
}
lbBreedingPlanInfo.Text = string.Format(Loc.S("NoPossiblePairingForSpeciesFound"), _currentSpecies);
lbBreedingPlanInfo.Visible = true;
}
if (_speciesInfoNeedsUpdate)
SetBreedingData(_currentSpecies);
if (displayFilterWarning)
{
// display warning if breeding pairs are filtered out
string warningText = null;
if (creaturesTagFilteredOut) warningText = Loc.S("BPsomeCreaturesAreFilteredOutTags") + ".\n" + Loc.S("BPTopStatsShownMightNotTotalTopStats");
if (creaturesMutationsFilteredOut) warningText = (!string.IsNullOrEmpty(warningText) ? warningText + "\n" : string.Empty) + Loc.S("BPsomePairingsAreFilteredOutMutations");
if (!string.IsNullOrEmpty(warningText)) SetMessageLabelText(warningText, MessageBoxIcon.Warning);
}
this.ResumeDrawing();
if (considerChosenCreature) btShowAllCreatures.Text = string.Format(Loc.S("BPCancelRestrictionOn"), _chosenCreature.name);
btShowAllCreatures.Visible = considerChosenCreature;
ResumeLayout();
}
/// <summary>
/// Recreates the breeding plan after the same library is loaded.
/// </summary>
/// <param name="isActiveControl">if true, the data is updated immediately.</param>
public void RecreateAfterLoading(bool isActiveControl = false)
{
if (_chosenCreature != null)
_chosenCreature = CreatureCollection.creatures.FirstOrDefault(c => c.guid == _chosenCreature.guid);
if (_currentSpecies != null)
{
_currentSpecies = Values.V.SpeciesByBlueprint(_currentSpecies.blueprintPath);
if (isActiveControl)
DetermineBestBreeding(_chosenCreature, true);
else
breedingPlanNeedsUpdate = true;
}
}
private void RecalculateBreedingPlan()
{
DetermineBestBreeding(_chosenCreature, true);
}
internal void UpdateIfNeeded()
{
if (breedingPlanNeedsUpdate)
DetermineBestBreeding(_chosenCreature);
}
private void ClearControls()
{
// hide unused controls
for (int i = 0; i < CreatureCollection.maxBreedingSuggestions && 2 * i + 1 < _pcs.Count && i < _pbs.Count; i++)
{
_pcs[2 * i].Hide();
_pcs[2 * i + 1].Hide();
_pbs[i].Hide();
}
// remove controls outside of the limit
if (_pbs.Count > CreatureCollection.maxBreedingSuggestions)
{
for (int i = _pbs.Count - 1; i > CreatureCollection.maxBreedingSuggestions && i >= 0; i--)
{
_pcs[2 * i + 1].Dispose();
_pcs.RemoveAt(2 * i + 1);
_pcs[2 * i].Dispose();
_pcs.RemoveAt(2 * i);
_pbs[i].Dispose();
_pbs.RemoveAt(i);
}
}
pedigreeCreatureBest.Clear();
pedigreeCreatureWorst.Clear();
lbBreedingPlanInfo.Visible = false;
lbBPProbabilityBest.Text = string.Empty;
lbMutationProbability.Text = string.Empty;
offspringPossibilities1.Clear();
SetMessageLabelText();
}
public void Clear()
{
ClearControls();
SetBreedingData();
listViewRaisingTimes.Items.Clear();
_currentSpecies = null;
_males = null;
_females = null;
lbBreedingPlanHeader.Text = Loc.S("SelectSpeciesBreedingPlanner");
}
private void SetBreedingData(Species species = null)
{
listViewRaisingTimes.Items.Clear();
if (species?.breeding == null)
{
listViewRaisingTimes.Items.Add(Loc.S("naYet"));
labelBreedingInfos.Text = string.Empty;
}
else
{
pedigreeCreature1.SetCustomStatNames(species.statNames);
pedigreeCreature2.SetCustomStatNames(species.statNames);
if (Raising.GetRaisingTimes(species, out TimeSpan matingTime, out string incubationMode, out _incubationTime, out TimeSpan babyTime, out TimeSpan maturationTime, out TimeSpan nextMatingMin, out TimeSpan nextMatingMax))
{
if (matingTime != TimeSpan.Zero)
listViewRaisingTimes.Items.Add(new ListViewItem(new[] { Loc.S("matingTime"), matingTime.ToString("d':'hh':'mm':'ss") }));
TimeSpan totalTime = _incubationTime;
DateTime until = DateTime.Now.Add(totalTime);
string[] times = { incubationMode, _incubationTime.ToString("d':'hh':'mm':'ss"), totalTime.ToString("d':'hh':'mm':'ss"), Utils.ShortTimeDate(until) };
listViewRaisingTimes.Items.Add(new ListViewItem(times));
totalTime += babyTime;
until = DateTime.Now.Add(totalTime);
times = new[] { Loc.S("Baby"), babyTime.ToString("d':'hh':'mm':'ss"), totalTime.ToString("d':'hh':'mm':'ss"), Utils.ShortTimeDate(until) };
listViewRaisingTimes.Items.Add(new ListViewItem(times));
totalTime = _incubationTime + maturationTime;
until = DateTime.Now.Add(totalTime);
times = new[] { Loc.S("Maturation"), maturationTime.ToString("d':'hh':'mm':'ss"), totalTime.ToString("d':'hh':'mm':'ss"), Utils.ShortTimeDate(until) };
listViewRaisingTimes.Items.Add(new ListViewItem(times));
string eggInfo = Raising.EggTemperature(species);
labelBreedingInfos.Text = (nextMatingMin != TimeSpan.Zero ? $"{Loc.S("TimeBetweenMating")}: {nextMatingMin:d':'hh':'mm':'ss} to {nextMatingMax:d':'hh':'mm':'ss}" : string.Empty)
+ ((!string.IsNullOrEmpty(eggInfo) ? "\n" + eggInfo : string.Empty));
}
}
_speciesInfoNeedsUpdate = false;
}
public void CreateTagList()
{
tagSelectorList1.tags = CreatureCollection.tags;
foreach (string t in CreatureCollection.tagsInclude)
tagSelectorList1.setTagStatus(t, TagSelector.tagStatus.include);
foreach (string t in CreatureCollection.tagsExclude)
tagSelectorList1.setTagStatus(t, TagSelector.tagStatus.exclude);
}
private List<Creature> Creatures
{
set
{
if (value == null) return;
_females = value.Where(c => c.sex == Sex.Female).ToArray();
_males = value.Where(c => c.sex == Sex.Male).ToArray();
DetermineBestLevels(value);
}
}
private void DetermineBestLevels(List<Creature> creatures = null)
{
if (creatures == null)
{
if (_females == null || _males == null) return;
creatures = _females.ToList();
creatures.AddRange(_males);
}
if (!creatures.Any()) return;
for (int s = 0; s < Values.STATS_COUNT; s++)
_bestLevels[s] = -1;
foreach (Creature c in creatures)
{
for (int s = 0; s < Values.STATS_COUNT; s++)
{
if ((s == (int)StatNames.Torpidity || _statWeights[s] >= 0) && c.levelsWild[s] > _bestLevels[s])
_bestLevels[s] = c.levelsWild[s];
else if (s != (int)StatNames.Torpidity && _statWeights[s] < 0 && c.levelsWild[s] >= 0 && (c.levelsWild[s] < _bestLevels[s] || _bestLevels[s] < 0))
_bestLevels[s] = c.levelsWild[s];
}
}
// display top levels in species
int? levelStep = CreatureCollection.getWildLevelStep();
Creature crB = new Creature(_currentSpecies, string.Empty, string.Empty, string.Empty, 0, new int[Values.STATS_COUNT], null, 100, true, levelStep: levelStep)
{
name = string.Format(Loc.S("BestPossibleSpeciesLibrary"), _currentSpecies.name)
};
bool totalLevelUnknown = false;
for (int s = 0; s < Values.STATS_COUNT; s++)
{
if (s == (int)StatNames.Torpidity) continue;
crB.levelsWild[s] = _bestLevels[s];
if (crB.levelsWild[s] == -1)
totalLevelUnknown = true;
crB.topBreedingStats[s] = (crB.levelsWild[s] > 0);
}
crB.levelsWild[(int)StatNames.Torpidity] = crB.levelsWild.Sum();
crB.RecalculateCreatureValues(levelStep);
pedigreeCreatureBestPossibleInSpecies.TotalLevelUnknown = totalLevelUnknown;
pedigreeCreatureBestPossibleInSpecies.Creature = crB;
}
private void CreatureClicked(Creature c, int comboIndex, MouseEventArgs e)
{
if (comboIndex >= 0)
SetParents(comboIndex);
}
private void CreatureEdit(Creature c, bool isVirtual)
{
EditCreature?.Invoke(c, isVirtual);
}
private void SetParents(int comboIndex)
{
if (comboIndex < 0 || comboIndex >= _breedingPairs.Count)
{
pedigreeCreatureBest.Clear();
pedigreeCreatureWorst.Clear();
lbBreedingPlanInfo.Visible = false;
lbBPProbabilityBest.Text = string.Empty;
lbMutationProbability.Text = string.Empty;
return;
}
int? levelStep = CreatureCollection.getWildLevelStep();
Creature crB = new Creature(_currentSpecies, string.Empty, string.Empty, string.Empty, 0, new int[Values.STATS_COUNT], null, 100, true, levelStep: levelStep);
Creature crW = new Creature(_currentSpecies, string.Empty, string.Empty, string.Empty, 0, new int[Values.STATS_COUNT], null, 100, true, levelStep: levelStep);
Creature mother = _breedingPairs[comboIndex].Female;
Creature father = _breedingPairs[comboIndex].Male;
crB.Mother = mother;
crB.Father = father;
crW.Mother = mother;
crW.Father = father;
double probabilityBest = 1;
bool totalLevelUnknown = false; // if stats are unknown, total level is as well (==> oxygen, speed)
for (int s = 0; s < Values.STATS_COUNT; s++)
{
if (s == (int)StatNames.Torpidity) continue;
crB.levelsWild[s] = _statWeights[s] < 0 ? Math.Min(mother.levelsWild[s], father.levelsWild[s]) : Math.Max(mother.levelsWild[s], father.levelsWild[s]);
crB.valuesBreeding[s] = StatValueCalculation.CalculateValue(_currentSpecies, s, crB.levelsWild[s], 0, true, 1, 0);
crB.topBreedingStats[s] = (_currentSpecies.stats[s].IncPerTamedLevel != 0 && crB.levelsWild[s] == _bestLevels[s]);
crW.levelsWild[s] = _statWeights[s] < 0 ? Math.Max(mother.levelsWild[s], father.levelsWild[s]) : Math.Min(mother.levelsWild[s], father.levelsWild[s]);
crW.valuesBreeding[s] = StatValueCalculation.CalculateValue(_currentSpecies, s, crW.levelsWild[s], 0, true, 1, 0);
crW.topBreedingStats[s] = (_currentSpecies.stats[s].IncPerTamedLevel != 0 && crW.levelsWild[s] == _bestLevels[s]);
if (crB.levelsWild[s] == -1 || crW.levelsWild[s] == -1)
totalLevelUnknown = true;
if (crB.levelsWild[s] > crW.levelsWild[s])
probabilityBest *= ProbabilityHigherLevel;
else if (crB.levelsWild[s] < crW.levelsWild[s])
probabilityBest *= ProbabilityLowerLevel;
}
crB.levelsWild[(int)StatNames.Torpidity] = crB.levelsWild.Sum();
crW.levelsWild[(int)StatNames.Torpidity] = crW.levelsWild.Sum();
crB.name = Loc.S("BestPossible");
crW.name = Loc.S("WorstPossible");
crB.RecalculateCreatureValues(levelStep);
crW.RecalculateCreatureValues(levelStep);
pedigreeCreatureBest.TotalLevelUnknown = totalLevelUnknown;
pedigreeCreatureWorst.TotalLevelUnknown = totalLevelUnknown;
int mutationCounterMaternal = mother.Mutations;
int mutationCounterPaternal = father.Mutations;
crB.mutationsMaternal = mutationCounterMaternal;
crB.mutationsPaternal = mutationCounterPaternal;
crW.mutationsMaternal = mutationCounterMaternal;
crW.mutationsPaternal = mutationCounterPaternal;
pedigreeCreatureBest.Creature = crB;
pedigreeCreatureWorst.Creature = crW;
lbBPProbabilityBest.Text = $"{Loc.S("ProbabilityForBest")}: {Math.Round(100 * probabilityBest, 1)} %";
lbMutationProbability.Text = $"{Loc.S("ProbabilityForOneMutation")}: {Math.Round(100 * _breedingPairs[comboIndex].MutationProbability, 1)} %";
// set probability barChart
offspringPossibilities1.Calculate(_currentSpecies, mother.levelsWild, father.levelsWild);
// highlight parents
int hiliId = comboIndex * 2;
for (int i = 0; i < _pcs.Count; i++)
_pcs[i].Highlight = (i == hiliId || i == hiliId + 1);
}
public bool[] EnabledColorRegions
{
set
{
if (value != null && value.Length == 6)
{
_enabledColorRegions = value;
}
else
{
_enabledColorRegions = new[] { true, true, true, true, true, true };
}
}
}
private void buttonJustMated_Click(object sender, EventArgs e)
{
CreateIncubationEntry();
}
public Species CurrentSpecies
{
get => _currentSpecies;
set
{
_currentSpecies = value;
statWeighting.SetSpecies(value);
}
}
private void listViewSpeciesBP_SelectedIndexChanged(object sender, EventArgs e)
{
if (listViewSpeciesBP.SelectedIndices.Count > 0
&& !string.IsNullOrEmpty(listViewSpeciesBP.SelectedItems[0]?.Text)
&& (_currentSpecies == null
|| listViewSpeciesBP.SelectedItems[0].Text != _currentSpecies.DescriptiveNameAndMod)
)
{
SetGlobalSpecies?.Invoke((Species)listViewSpeciesBP.SelectedItems[0].Tag);
}
}
public int MaxWildLevels
{
set => offspringPossibilities1.maxWildLevel = value;
}
public void SetSpecies(Species species)
{
if (_currentSpecies == species) return;
// automatically set preset if preset with the speciesname exists
_updateBreedingPlanAllowed = false;
if (!statWeighting.TrySetPresetByName(species.name))
statWeighting.TrySetPresetByName("Default");
_updateBreedingPlanAllowed = true;
DetermineBestBreeding(setSpecies: species);
//// update listviewSpeciesBP
// deselect currently selected species
if (listViewSpeciesBP.SelectedItems.Count > 0)
listViewSpeciesBP.SelectedItems[0].Selected = false;
for (int i = 0; i < listViewSpeciesBP.Items.Count; i++)
{
if (listViewSpeciesBP.Items[i].Text == _currentSpecies.DescriptiveNameAndMod)
{
listViewSpeciesBP.Items[i].Focused = true;
listViewSpeciesBP.Items[i].Selected = true;
break;
}
}
}
private void checkBoxIncludeCooldowneds_CheckedChanged(object sender, EventArgs e)
{
Settings.Default.IncludeCooldownsInBreedingPlan = cbBPIncludeCooldowneds.Checked;
DetermineBestBreeding(_chosenCreature, true);
}
private void cbBPIncludeCryoCreatures_CheckedChanged(object sender, EventArgs e)
{
Settings.Default.IncludeCryoedInBreedingPlan = cbBPIncludeCryoCreatures.Checked;
DetermineBestBreeding(_chosenCreature, true);
}
private void nudMutationLimit_ValueChanged(object sender, EventArgs e)
{
DetermineBestBreeding(_chosenCreature, true);
}
private void radioButtonBPTopStatsCn_CheckedChanged(object sender, EventArgs e)
{
if (rbBPTopStatsCn.Checked)
{
_breedingMode = BreedingMode.TopStatsConservative;
CalculateBreedingScoresAndDisplayPairs();
}
}
private void radioButtonBPTopStats_CheckedChanged(object sender, EventArgs e)
{
if (rbBPTopStats.Checked)
{
_breedingMode = BreedingMode.TopStatsLucky;
CalculateBreedingScoresAndDisplayPairs();
}
}
private void radioButtonBPHighStats_CheckedChanged(object sender, EventArgs e)
{
if (rbBPHighStats.Checked)
{
_breedingMode = BreedingMode.BestNextGen;
CalculateBreedingScoresAndDisplayPairs();
}
}
public void SetSpeciesList(List<Species> species, List<Creature> creatures)
{
Species previouslySelectedSpecies = listViewSpeciesBP.SelectedItems.Count > 0 ? listViewSpeciesBP.SelectedItems[0].Tag as Species : null;
listViewSpeciesBP.Items.Clear();
foreach (Species s in species)
{
ListViewItem lvi = new ListViewItem { Text = s.DescriptiveNameAndMod, Tag = s };
// check if species has both available males and females
if (s.breeding == null || !creatures.Any(c => c.Species == s && c.Status == CreatureStatus.Available && c.sex == Sex.Female) || !creatures.Any(c => c.Species == s && c.Status == CreatureStatus.Available && c.sex == Sex.Male))
lvi.ForeColor = Color.LightGray;
listViewSpeciesBP.Items.Add(lvi);
}
// select previous selected species again
if (previouslySelectedSpecies != null)
{
for (int i = 0; i < listViewSpeciesBP.Items.Count; i++)
{
if (listViewSpeciesBP.Items[i].Tag is Species s
&& s == previouslySelectedSpecies)
{
listViewSpeciesBP.Items[i].Focused = true;
listViewSpeciesBP.Items[i].Selected = true;
break;
}
}
}
}
private void CreateIncubationEntry(bool startNow = true)
{
if (pedigreeCreatureBest.Creature?.Mother != null && pedigreeCreatureBest.Creature.Father != null)
{
CreateIncubationTimer?.Invoke(pedigreeCreatureBest.Creature.Mother, pedigreeCreatureBest.Creature.Father, _incubationTime, startNow);
// set cooldown for mother
Species species = pedigreeCreatureBest.Creature.Mother.Species;
if (species?.breeding != null)
{
pedigreeCreatureBest.Creature.Mother.cooldownUntil = DateTime.Now.AddSeconds(species.breeding.matingCooldownMinAdjusted);
// update breeding plan
DetermineBestBreeding(_chosenCreature, true);
}
}
}
public void UpdateBreedingData()
{
SetBreedingData(_currentSpecies);
}
public int MutationLimit
{
get => (int)nudBPMutationLimit.Value;
set => nudBPMutationLimit.Value = value;
}
private enum BreedingMode
{
BestNextGen,
TopStatsLucky,
TopStatsConservative
}
private void cbTagExcludeDefault_CheckedChanged(object sender, EventArgs e)
{
CalculateBreedingScoresAndDisplayPairs();
}
public void SetLocalizations()
{
Loc.ControlText(lbBreedingPlanHeader, "SelectSpeciesBreedingPlanner");
Loc.ControlText(gbBPOffspring);
Loc.ControlText(gbBPBreedingMode);
Loc.ControlText(rbBPTopStatsCn);
Loc.ControlText(rbBPTopStats);
Loc.ControlText(rbBPHighStats);
Loc.ControlText(cbBPIncludeCooldowneds);
Loc.ControlText(gbBPBreedingMode);
Loc.ControlText(lbBPBreedingTimes);
Loc.ControlText(btBPJustMated);
Loc.ControlText(cbBPOnlyOneSuggestionForFemales);
Loc.ControlText(cbBPMutationLimitOnlyOnePartner);
columnHeader2.Text = Loc.S("Time");
columnHeader3.Text = Loc.S("TotalTime");
columnHeader4.Text = Loc.S("FinishedAt");
// tooltips
Loc.ControlText(lbBPBreedingScore, _tt);
Loc.ControlText(rbBPTopStatsCn, _tt);
Loc.ControlText(rbBPTopStats, _tt);
Loc.ControlText(rbBPHighStats, _tt);
Loc.ControlText(btBPJustMated, _tt);
Loc.SetToolTip(nudBPMutationLimit, _tt);
Loc.SetToolTip(cbBPTagExcludeDefault, _tt);
}
private void cbServerFilterLibrary_CheckedChanged(object sender, EventArgs e)
{
Settings.Default.UseServerFilterForBreedingPlan = cbServerFilterLibrary.Checked;
CalculateBreedingScoresAndDisplayPairs();
}
private void btShowAllCreatures_Click(object sender, EventArgs e)
{
// remove restriction on one creature
_chosenCreature = null;
CalculateBreedingScoresAndDisplayPairs();
}
private void cbOwnerFilterLibrary_CheckedChanged(object sender, EventArgs e)
{
Settings.Default.UseOwnerFilterForBreedingPlan = cbOwnerFilterLibrary.Checked;
CalculateBreedingScoresAndDisplayPairs();
}
private void cbOnlyOneSuggestionForFemales_CheckedChanged(object sender, EventArgs e)
{
Settings.Default.BreedingPlanOnlyBestSuggestionForEachFemale = cbBPOnlyOneSuggestionForFemales.Checked;
CalculateBreedingScoresAndDisplayPairs();
}
private void cbMutationLimitOnlyOnePartner_CheckedChanged(object sender, EventArgs e)
{
Settings.Default.BreedingPlanOnePartnerMoreMutationsThanLimit = cbBPMutationLimitOnlyOnePartner.Checked;
CalculateBreedingScoresAndDisplayPairs();
}
}
}
| 46.837288 | 241 | 0.535717 | [
"MIT"
] | JaymeiF/ARKStatsExtractor | ARKBreedingStats/BreedingPlan.cs | 55,270 | C# |
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using Catan.Proxy;
using CatanService;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
using Xunit.Abstractions;
namespace ServiceTests
{
public class DevCardTests
{
private readonly ITestOutputHelper output;
public DevCardTests(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
async Task DevCardPurchase()
{
int maxCards = 2;
GameInfo gameInfo = new GameInfo()
{
YearOfPlenty = maxCards,
Knight = maxCards,
VictoryPoint = maxCards,
Monopoly = maxCards,
RoadBuilding = maxCards
};
using (var helper = new TestHelper(gameInfo))
{
string player = (await helper.CreateGame())[0]; // game is now started
//
// get enough resources to buy all the cards - 5 * maxCards worth of devcarts
var tr = new TradeResources()
{
Ore = maxCards * 5,
Wheat = maxCards * 5,
Sheep = maxCards * 5
};
var resources = await helper.GrantResourcesAndAssertResult(player, tr);
Assert.Empty(resources.PlayedDevCards);
//
// buy dev cards
for (int i = 0; i < maxCards * 5; i++)
{
resources = await helper.Proxy.DevCardPurchase(helper.GameName, player);
Assert.Equal(maxCards * 5 - i - 1, resources.Ore);
Assert.Equal(maxCards * 5 - i - 1, resources.Wheat);
Assert.Equal(maxCards * 5 - i - 1, resources.Sheep);
Assert.Equal(i+1, resources.UnplayedDevCards);
Assert.Null(helper.Proxy.LastError);
Assert.Empty(helper.Proxy.LastErrorString);
PurchaseLog purchaseLog = await helper.MonitorGetLastRecord<PurchaseLog>(player);
Assert.Equal(CatanAction.Purchased, purchaseLog.Action);
Assert.Equal(player, purchaseLog.PlayerName);
Assert.Equal(Entitlement.DevCard, purchaseLog.Entitlement);
Assert.Null(purchaseLog.UndoRequest);
}
Assert.Equal(0, resources.Wood);
Assert.Equal(0, resources.Wheat);
Assert.Equal(0, resources.Sheep);
Assert.Equal(0, resources.Brick);
Assert.Equal(0, resources.Ore);
Assert.Equal(0, resources.GoldMine);
//
// these are for the "normal" game
Assert.Equal(gameInfo.Knight, resources.Knights);
Assert.Equal(gameInfo.VictoryPoint, resources.VictoryPoints);
Assert.Equal(gameInfo.YearOfPlenty, resources.YearOfPlenty);
Assert.Equal(gameInfo.Monopoly, resources.Monopoly);
Assert.Equal(gameInfo.RoadBuilding, resources.RoadBuilding);
//
// try to buy a card w/ no resources
resources = await helper.Proxy.DevCardPurchase(helper.GameName, player);
Assert.Null(resources);
Assert.NotNull(helper.Proxy.LastError);
Assert.NotEmpty(helper.Proxy.LastErrorString);
Assert.Equal(CatanError.DevCardsSoldOut, helper.Proxy.LastError.Error);
//
// grant resources for a devcard
tr.Ore = tr.Wheat = tr.Sheep = 1;
resources = await helper.Proxy.GrantResources(helper.GameName, player, tr);
Assert.Equal(1, resources.Ore);
Assert.Equal(1, resources.Wheat);
Assert.Equal(1, resources.Sheep);
Assert.Null(helper.Proxy.LastError);
Assert.Empty(helper.Proxy.LastErrorString);
var resourceLog = await helper.MonitorGetLastRecord<ResourceLog>(player);
//
// try to buy when you have resources -- still get an error
resources = await helper.Proxy.DevCardPurchase(helper.GameName, player);
Assert.Null(resources);
Assert.NotNull(helper.Proxy.LastError);
Assert.NotEmpty(helper.Proxy.LastErrorString);
Assert.Equal(CatanError.DevCardsSoldOut, helper.Proxy.LastError.Error);
//
// setup to play YoP
tr = new TradeResources()
{
Wood = 1,
Brick = 1
};
tr.Brick = 1;
for (int i = 0; i < resources.YearOfPlenty; i++)
{
resources = await helper.Proxy.PlayYearOfPlenty(helper.GameName, player, tr);
Assert.NotNull(resources);
Assert.Equal(1, resources.Ore);
Assert.Equal(1, resources.Wheat);
Assert.Equal(1, resources.Sheep);
Assert.Equal(i + 1, resources.Wood);
Assert.Equal(i + 1, resources.Brick);
Assert.Equal(0, resources.GoldMine);
}
resources = await helper.Proxy.PlayRoadBuilding(helper.GameName, player);
Assert.NotNull(resources);
resources = await helper.Proxy.PlayRoadBuilding(helper.GameName, player);
Assert.NotNull(resources);
resources = await helper.Proxy.PlayRoadBuilding(helper.GameName, player);
Assert.Equal(CatanError.NoMoreResource, helper.Proxy.LastError.Error);
}
}
[Fact]
async Task MonopolyTest()
{
GameInfo gameInfo = new GameInfo()
{
YearOfPlenty = 0,
Knight = 0,
VictoryPoint = 0,
Monopoly = 1,
RoadBuilding = 0
};
using (var helper = new TestHelper(gameInfo))
{
var players = await helper.CreateGame();
var tr = new TradeResources()
{
Ore = 1,
Wheat = 1,
Sheep = 1,
Brick = 1,
Wood = 1
};
//
// give 1 of each resource to everybody
foreach (string p in players)
{
_ = await helper.GrantResourcesAndAssertResult(p, tr);
}
// buy a dev card - gameInfo says there is only 1 of them and it is Monopoly
var resources = await helper.Proxy.DevCardPurchase(helper.GameName, players[0]);
Assert.NotNull(resources);
Assert.True(resources.Monopoly > 0);
resources = await helper.Proxy.PlayMonopoly(helper.GameName, players[0], ResourceType.Wood);
Assert.Equal(4, resources.Wood);
Assert.Equal(0, resources.Ore);
Assert.Equal(0, resources.Wheat);
Assert.Equal(0, resources.Sheep);
Assert.Equal(1, resources.Brick);
Assert.Equal(0, resources.GoldMine);
for (int i = 1; i < players.Count; i++)
{
resources = await helper.Proxy.GetResources(helper.GameName, players[i]);
Assert.Equal(1, resources.Ore);
Assert.Equal(1, resources.Wheat);
Assert.Equal(1, resources.Sheep);
Assert.Equal(0, resources.Wood);
Assert.Equal(1, resources.Brick);
Assert.Equal(0, resources.GoldMine);
}
//
// try to play it again
resources = await helper.Proxy.PlayMonopoly(helper.GameName, players[0], ResourceType.Wood);
Assert.Null(resources);
Assert.NotEmpty(helper.Proxy.LastErrorString);
Assert.NotNull(helper.Proxy.LastError);
Assert.Equal(CatanError.NoResource, helper.Proxy.LastError.Error);
}
}
[Fact]
async Task YearOfPlenty()
{
GameInfo gameInfo = new GameInfo()
{
YearOfPlenty = 1,
Knight = 0,
VictoryPoint = 0,
Monopoly = 0,
RoadBuilding = 0
};
using (var helper = new TestHelper(gameInfo))
{
var players = await helper.CreateGame();
var tr = new TradeResources()
{
Ore = 1,
Wheat = 1,
Sheep = 1,
Brick = 1,
Wood = 0
};
//
// give 1 of each resource to everybody
foreach (string p in players)
{
_ = await helper.GrantResourcesAndAssertResult(p, tr);
}
PlayerResources resources = await helper.BuyDevCard(players[0], DevCardType.YearOfPlenty);
Assert.NotNull(resources);
Assert.True(resources.YearOfPlenty > 0);
resources = await helper.Proxy.PlayYearOfPlenty(helper.GameName, players[0], tr);
Assert.Null(resources);
Assert.Equal(CatanError.BadTradeResources, helper.Proxy.LastError.Error);
Assert.NotNull(helper.Proxy.LastError.CantanRequest.Body);
Assert.Equal(BodyType.TradeResources, helper.Proxy.LastError.CantanRequest.BodyType);
tr = helper.Proxy.LastError.CantanRequest.Body as TradeResources;
Assert.NotNull(tr);
tr = new TradeResources()
{
Ore = 1,
Wheat = 1,
Sheep = 0,
Brick = 0,
Wood = 0
};
resources = await helper.Proxy.PlayYearOfPlenty(helper.GameName, players[0], tr);
Assert.NotNull(resources);
Assert.Equal(2, resources.Ore);
Assert.Equal(2, resources.Wheat);
Assert.Equal(1, resources.Sheep);
Assert.Equal(1, resources.Brick);
Assert.Equal(0, resources.Wood);
Assert.Equal(0, resources.GoldMine);
//
// make sure we didn't impact other players
for (int i = 1; i < players.Count; i++)
{
resources = await helper.Proxy.GetResources(helper.GameName, players[i]);
Assert.Equal(1, resources.Ore);
Assert.Equal(1, resources.Wheat);
Assert.Equal(1, resources.Sheep);
Assert.Equal(1, resources.Brick);
Assert.Equal(0, resources.Wood);
Assert.Equal(0, resources.GoldMine);
}
}
}
[Fact]
async Task RoadBuilding()
{
GameInfo gameInfo = new GameInfo()
{
YearOfPlenty = 0,
Knight = 0,
VictoryPoint = 0,
Monopoly = 0,
RoadBuilding = 1
};
using (var helper = new TestHelper(gameInfo))
{
var players = await helper.CreateGame();
var tr = new TradeResources()
{
Ore = 1,
Wheat = 1,
Sheep = 1
};
_ = await helper.GrantResourcesAndAssertResult(players[0], tr);
PlayerResources resources = await helper.BuyDevCard(players[0], DevCardType.RoadBuilding);
Assert.Equal(0, resources.Roads);
Assert.NotNull(resources);
Assert.True(resources.RoadBuilding > 0);
resources = await helper.Proxy.PlayRoadBuilding(helper.GameName, players[0]);
Assert.NotNull(resources);
Assert.Equal(2, resources.Roads);
}
}
[Fact]
async Task Knight()
{
GameInfo gameInfo = new GameInfo()
{
YearOfPlenty = 0,
Knight = 1,
VictoryPoint = 0,
Monopoly = 0,
RoadBuilding = 0
};
using (var helper = new TestHelper(gameInfo))
{
var players = await helper.CreateGame();
var tr = new TradeResources()
{
Ore = 1,
Wheat = 1,
Sheep = 1
};
_ = await helper.GrantResourcesAndAssertResult(players[0], tr);
PlayerResources resources = await helper.BuyDevCard(players[0], DevCardType.Knight);
Assert.Equal(0, resources.Roads);
Assert.NotNull(resources);
Assert.True(resources.Knights > 0);
resources = await helper.Proxy.KnightPlayed(helper.GameName, players[0], null);
Assert.NotNull(resources);
Assert.Contains(DevCardType.Knight, resources.PlayedDevCards);
}
}
}
}
| 38.135359 | 108 | 0.489967 | [
"MIT"
] | joelong01/CatanService | ServiceTests/DevCardTests.cs | 13,807 | C# |
/*
Copyright 2018 Digimarc, 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.
SPDX-License-Identifier: Apache-2.0
*/
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Whalerator.Content
{
public class LayerExtractor : ILayerExtractor
{
public Task<Stream> ExtractFileAsync(string layerFile, string path)
{
path = path.TrimStart('/');
// can't put in using block as we're (hopefully) returning all these items nested in the final SubStream
var stream = new FileStream(layerFile, FileMode.Open, FileAccess.Read, FileShare.Read);
var gzipStream = new GZipInputStream(stream);
var tarStream = new TarInputStream(gzipStream);
try
{
Stream foundStream = null;
var entry = tarStream.GetNextEntry();
while (entry != null)
{
if (entry.Name.Equals(path))
{
foundStream = new SubStream(tarStream, entry.Size) { OwnInnerStream = true };
break;
}
entry = tarStream.GetNextEntry();
}
if (foundStream != null)
{
return Task.FromResult(foundStream);
}
else
{
// tarStream will dispose the entire chain for us
tarStream.Dispose();
throw new FileNotFoundException();
}
}
catch (GZipException)
{
throw new ArgumentException($"Layer appears invalid");
}
}
/// <summary>
/// Extracts a raw list of file entries from a tar'd/gzipped layer
/// </summary>
/// <param name="layerArchive"></param>
/// <returns></returns>
public IEnumerable<string> ExtractFiles(Stream stream)
{
using (var gzipStream = new GZipInputStream(stream) { IsStreamOwner = false })
using (var tarStream = new TarInputStream(gzipStream) { IsStreamOwner = false })
{
var entry = tarStream.GetNextEntry();
while (entry != null)
{
if (!entry.IsDirectory)
{
yield return entry.Name;
}
entry = tarStream.GetNextEntry();
}
}
}
}
}
| 33.557895 | 116 | 0.547679 | [
"Apache-2.0"
] | abowergroup/whalerator | lib/Whalerator/Content/LayerExtractor.cs | 3,190 | C# |
using UnityEngine;
public class ErrorSolution : MonoBehaviour {
void Update () {
Debug.Log(transform.childCount);
if (transform.childCount >= 12 && !Input.GetKey(KeyCode.Mouse0))
{
Destroy(transform.GetChild(11).gameObject);
}
}
}
| 21.846154 | 72 | 0.609155 | [
"Apache-2.0"
] | SrtaEnne/ProKid | Assets/Scripts/Interface/ErrorSolution.cs | 286 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AlibabaCloud.SDK.Rds20140815.Models
{
public class DescribeSQLCollectorRetentionResponse : TeaModel {
[NameInMap("RequestId")]
[Validation(Required=true)]
public string RequestId { get; set; }
[NameInMap("ConfigValue")]
[Validation(Required=true)]
public string ConfigValue { get; set; }
}
}
| 21.521739 | 67 | 0.676768 | [
"Apache-2.0"
] | atptro/alibabacloud-sdk | rds-20140815/csharp/core/Models/DescribeSQLCollectorRetentionResponse.cs | 495 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Windows.Markup;
namespace ConsoleApp2
{
public class Coins
{
public int minReplacement(int[] A)
{
//Two possible choices
//A first element is 1 or first element is 0
var x1 = CountFlips(A, 1);
var x2 = CountFlips(A, 0);
return Math.Min(x1, x2);
}
private static int CountFlips(int[] A, int expected)
{
var flips = 0;
int notExpected = expected == 1 ? 0 : 1;
for (int i = 0; i < A.Length; i++)
{
// If there is expected at even index positions
// OR If there is notExpected at odd index positions
if ((i % 2 == 0 && A[i] == expected) ||
(i % 2 == 1 && A[i] == notExpected)
)
{
flips++;
}
}
return flips;
}
}
} | 27.552632 | 69 | 0.430755 | [
"MIT"
] | jennyraj/react | Coins.cs | 1,049 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Kusto.V20191109.Outputs
{
/// <summary>
/// A class that contains database statistics information.
/// </summary>
[OutputType]
public sealed class DatabaseStatisticsResponse
{
/// <summary>
/// The database size - the total size of compressed data and index in bytes.
/// </summary>
public readonly double? Size;
[OutputConstructor]
private DatabaseStatisticsResponse(double? size)
{
Size = size;
}
}
}
| 27 | 85 | 0.657109 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Kusto/V20191109/Outputs/DatabaseStatisticsResponse.cs | 837 | C# |
using Catalog.Api.Data;
using Catalog.Api.Entities;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catalog.Api.Repositories
{
public class ProductRepository : IProductRepository
{
private readonly ICatalogContext _context;
public ProductRepository(ICatalogContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public async Task<IEnumerable<Product>> GetProducts()
{
return await _context
.Products
.Find(p => true)
.ToListAsync();
}
public async Task<Product> GetProduct(string id)
{
return await _context
.Products
.Find(p => p.Id == id)
.FirstOrDefaultAsync();
}
public async Task<IEnumerable<Product>> GetProductByName(string name)
{
FilterDefinition<Product> filter = Builders<Product>.Filter.Eq(p => p.Name, name);
return await _context
.Products
.Find(filter)
.ToListAsync();
}
public async Task<IEnumerable<Product>> GetProductByCategory(string categoryName)
{
FilterDefinition<Product> filter = Builders<Product>.Filter.Eq(p => p.Category, categoryName);
return await _context
.Products
.Find(filter)
.ToListAsync();
}
public async Task CreateProduct(Product product)
{
await _context.Products.InsertOneAsync(product);
}
public async Task<bool> UpdateProduct(Product product)
{
var updateResult = await _context
.Products
.ReplaceOneAsync(filter: g => g.Id == product.Id, replacement: product);
return updateResult.IsAcknowledged
&& updateResult.ModifiedCount > 0;
}
public async Task<bool> DeleteProduct(string id)
{
FilterDefinition<Product> filter = Builders<Product>.Filter.Eq(p => p.Id, id);
DeleteResult deleteResult = await _context
.Products
.DeleteOneAsync(filter);
return deleteResult.IsAcknowledged
&& deleteResult.DeletedCount > 0;
}
}
} | 32.440476 | 112 | 0.52 | [
"MIT"
] | Amitpnk/Microservice-Architecture-ASP.NET-Core | src/Services/Catalog/Catalog.Api/Repositories/ProductRepository.cs | 2,727 | C# |
using SeqcosFilterTools.Trim;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Bio;
namespace FilterTools.Tests
{
/// <summary>
///This is a test class for TrimByQualityTest and is intended
///to contain all TrimByQualityTest Unit Tests
///</summary>
[TestClass()]
public class TrimByQualityTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
/// <summary>
///A test for Trim
///</summary>
[TestMethod()]
//public void TrimTest()
//{
// TrimByQuality target = new TrimByQuality(); // TODO: Initialize to an appropriate value
// ISequence seqObj = null; // TODO: Initialize to an appropriate value
// ISequence expected = null; // TODO: Initialize to an appropriate value
// ISequence actual;
// actual = target.Trim(seqObj);
// Assert.AreEqual(expected, actual);
// Assert.Inconclusive("Verify the correctness of this test method.");
//}
}
}
| 29.154762 | 102 | 0.536954 | [
"Apache-2.0"
] | kcha/seqcos | Seqcos/Tests/SeqcosFilterTools.Tests/Trim/TrimByQualityTest.cs | 2,451 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CTS.Core.Domain.Attr;
namespace CTS.W._150901.Models.Domain.Object.Client.Page
{
public class PageObject
{
[OutputText]
public string LocaleCd { get; set; }
[OutputText]
public string PageCd { get; set; }
[OutputText]
public string PageName { get; set; }
[OutputText]
public string Slug { get; set; }
[OutputText]
public string Content { get; set; }
}
}
| 24.434783 | 57 | 0.594306 | [
"Apache-2.0"
] | ctsoftvn/cts-w-1509-01 | Src/CTS.W.150901/CTS.W.150901.Models/Domain/Object/Client/Page/PageObject.cs | 564 | C# |
public class Test
{
public static int Main()
{
return 0;
}
}
| 10.25 | 28 | 0.5 | [
"MIT"
] | openmailbox/RustExamples | test/Test.cs | 84 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.CDRS.Model.V20201101
{
public class ListDeviceGenderStatisticsResponse : AcsResponse
{
private string code;
private string message;
private string requestId;
private long? totalCount;
private List<ListDeviceGenderStatistics_Datas> data;
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public long? TotalCount
{
get
{
return totalCount;
}
set
{
totalCount = value;
}
}
public List<ListDeviceGenderStatistics_Datas> Data
{
get
{
return data;
}
set
{
data = value;
}
}
public class ListDeviceGenderStatistics_Datas
{
private string dataSourceId;
private string gender;
private string number;
public string DataSourceId
{
get
{
return dataSourceId;
}
set
{
dataSourceId = value;
}
}
public string Gender
{
get
{
return gender;
}
set
{
gender = value;
}
}
public string Number
{
get
{
return number;
}
set
{
number = value;
}
}
}
}
}
| 16.227586 | 63 | 0.60051 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-cdrs/CDRS/Model/V20201101/ListDeviceGenderStatisticsResponse.cs | 2,353 | C# |
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Collections.Specialized;
using PCAxis.Sql.DbConfig;
namespace PCAxis.Sql.QueryLib_24
{
public partial class MetaQuery
{
/// <summary>
/// Returns the default valueset or an empty string for no default.
/// </summary>
/// <param name="maintable"></param>
/// <param name="variable"></param>
/// <returns></returns>
public string GetValuesetIdDefaultInGui(string maintable, string variable)
{
string myOut = "";
string sqlString = "SELECT DISTINCT " +
DB.SubTableVariable.ValueSetCol.ForSelect();
sqlString += " /" + "*** SQLID: SubTableVariable_03 ***" + "/";
sqlString += " FROM " + DB.SubTableVariable.GetNameAndAlias();
sqlString += " WHERE " + DB.SubTableVariable.MainTableCol.Is() +
" AND " + DB.SubTableVariable.VariableCol.Is() +
" AND " + DB.SubTableVariable.DefaultInGuiCol.Is();
System.Data.Common.DbParameter[] parameters = new System.Data.Common.DbParameter[3];
parameters[0] = DB.SubTableVariable.MainTableCol.GetStringParameter(maintable);
parameters[1] = DB.SubTableVariable.VariableCol.GetStringParameter(variable);
parameters[2] = DB.SubTableVariable.DefaultInGuiCol.GetStringParameter(DB.Codes.Yes);
DataSet ds = mSqlCommand.ExecuteSelect(sqlString, parameters);
DataRowCollection myRows = ds.Tables[0].Rows;
if (myRows.Count > 1)
{
throw new PCAxis.Sql.Exceptions.DbException(48, maintable, variable);
}
foreach (DataRow myRow in myRows)
{
myOut = myRow[DB.SubTableVariable.ValueSetCol.Label()].ToString();
}
return myOut;
}
public List<string> GetValuesetIdsFromSubTableVariableOrderedBySortcode(string maintable, string variable)
{
string sqlString = "SELECT DISTINCT " +
DB.SubTableVariable.ValueSetCol.ForSelect() + ", " +
DB.SubTableVariable.SortCodeCol.ForSelect() ;
sqlString += " /" + "*** SQLID: SubTableVariable_02 ***" + "/";
sqlString += " FROM " + DB.SubTableVariable.GetNameAndAlias() ;
sqlString += " WHERE " + DB.SubTableVariable.MainTableCol.Is() +
" AND " + DB.SubTableVariable.VariableCol.Is();
sqlString += " ORDER BY " + DB.SubTableVariable.SortCodeCol.Id();
System.Data.Common.DbParameter[] parameters = new System.Data.Common.DbParameter[2];
parameters[0] = DB.SubTableVariable.MainTableCol.GetStringParameter(maintable);
parameters[1] = DB.SubTableVariable.VariableCol.GetStringParameter(variable);
DataSet ds = mSqlCommand.ExecuteSelect(sqlString, parameters);
DataRowCollection myRows = ds.Tables[0].Rows;
List<string> myOut = new List<string>();
foreach (DataRow myRow in myRows)
{
string valuesetId = myRow[DB.SubTableVariable.ValueSetCol.Label()].ToString();
if (myOut.Contains(valuesetId))
{
throw new PCAxis.Sql.Exceptions.DbException(49, maintable, variable,valuesetId);
}
myOut.Add(valuesetId);
}
return myOut;
}
public bool ShouldSubTableVarablesBeSortedAlphabetical(string MainTable, string Variable)
{
var sqlString = new StringBuilder();
sqlString.AppendLine("SELECT COUNT(*) AS SORTCODECOUNT");
sqlString.AppendLine("FROM " + DB.SubTableVariable.GetNameAndAlias());
sqlString.AppendLine("WHERE " + DB.SubTableVariable.MainTableCol.Is());
sqlString.AppendLine("AND " + DB.SubTableVariable.VariableCol.Is());
sqlString.AppendLine("AND " + DB.SubTableVariable.Alias + "." + DB.SubTableVariable.SortCodeCol.PureColumnName() + " IS NOT NULL");
System.Data.Common.DbParameter[] parameters = new System.Data.Common.DbParameter[2];
parameters[0] = DB.SubTableVariable.MainTableCol.GetStringParameter(MainTable);
parameters[1] = DB.SubTableVariable.VariableCol.GetStringParameter(Variable);
DataSet ds = mSqlCommand.ExecuteSelect(sqlString.ToString(), parameters);
var sortCodeCount = System.Convert.ToInt32(ds.Tables[0].Rows[0]["SORTCODECOUNT"]);
return sortCodeCount == 0;
}
}
}
| 41.633929 | 143 | 0.612481 | [
"Apache-2.0"
] | I3S-ESSnet/PxWeb | PCAxis.Sql/QueryLib_24/MetaQuery_SubTableVariable.cs | 4,663 | C# |
// <copyright file="ProxyJsonConverter.cs" company="WebDriver Committers">
// Copyright 2007-2011 WebDriver committers
// Copyright 2007-2011 Google Inc.
// Portions copyright 2011 Software Freedom Conservancy
//
// 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Newtonsoft.Json;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// Provides a way to convert a <see cref="Proxy"/> arry to JSON
/// </summary>
internal class ProxyJsonConverter : JsonConverter
{
/// <summary>
/// Checks if the object can be converted
/// </summary>
/// <param name="objectType">Type of the object</param>
/// <returns>A value indicating if it can be converted</returns>
public override bool CanConvert(Type objectType)
{
return objectType != null && objectType.IsAssignableFrom(typeof(Proxy));
}
/// <summary>
/// Get the platform from the JSON reader
/// </summary>
/// <param name="reader">JSON Reader instance</param>
/// <param name="objectType">Object type being read</param>
/// <param name="existingValue">The exisiting value of the object</param>
/// <param name="serializer">JSON Serializer instance</param>
/// <returns>Platform from JSON reader</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// This JsonConverter is only used for one-way conversions of Proxy objects to JSON objects.
return null;
}
/// <summary>
/// Create a JSON string representation of the Proxy
/// </summary>
/// <param name="writer">The JSON writer with a string</param>
/// <param name="value">Value of the string</param>
/// <param name="serializer">JSON serializer instance</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (writer != null)
{
Proxy proxyValue = value as Proxy;
if (proxyValue != null)
{
writer.WriteStartObject();
writer.WritePropertyName("proxyType");
writer.WriteValue(proxyValue.Kind.ToString("G").ToUpper(CultureInfo.InvariantCulture));
if (!string.IsNullOrEmpty(proxyValue.FtpProxy))
{
writer.WritePropertyName("ftpProxy");
writer.WriteValue(proxyValue.FtpProxy);
}
if (!string.IsNullOrEmpty(proxyValue.HttpProxy))
{
writer.WritePropertyName("httpProxy");
writer.WriteValue(proxyValue.HttpProxy);
}
if (!string.IsNullOrEmpty(proxyValue.NoProxy))
{
writer.WritePropertyName("noProxy");
writer.WriteValue(proxyValue.NoProxy);
}
if (!string.IsNullOrEmpty(proxyValue.ProxyAutoConfigUrl))
{
writer.WritePropertyName("proxyAutoconfigUrl");
writer.WriteValue(proxyValue.ProxyAutoConfigUrl);
}
if (!string.IsNullOrEmpty(proxyValue.ProxyAutoConfigUrl))
{
writer.WritePropertyName("proxyAutoconfigUrl");
writer.WriteValue(proxyValue.ProxyAutoConfigUrl);
}
if (!string.IsNullOrEmpty(proxyValue.SslProxy))
{
writer.WritePropertyName("sslProxy");
writer.WriteValue(proxyValue.SslProxy);
}
writer.WritePropertyName("autodetect");
writer.WriteValue(proxyValue.IsAutoDetect);
writer.WriteEndObject();
}
}
}
}
}
| 41.247863 | 125 | 0.562785 | [
"Apache-2.0"
] | saucelabs/Selenium2 | dotnet/src/WebDriver/Remote/JsonConverters/ProxyJsonConverter.cs | 4,828 | C# |
using System;
using System.Globalization;
using HotChocolate.Utilities.Properties;
namespace HotChocolate.Utilities;
public class ServiceFactory : IServiceProvider
{
private static readonly IServiceProvider _empty = new EmptyServiceProvider();
public IServiceProvider? Services { get; set; }
public object? CreateInstance(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
try
{
return ActivatorHelper.CompileFactory(type).Invoke(Services ?? _empty);
}
catch (Exception ex)
{
throw new ServiceException(
string.Format(
CultureInfo.InvariantCulture,
UtilityResources.ServiceFactory_CreateInstanceFailed,
type.FullName),
ex);
}
}
object? IServiceProvider.GetService(Type serviceType) =>
CreateInstance(serviceType);
}
| 25.947368 | 83 | 0.615619 | [
"MIT"
] | ChilliCream/prometheus | src/HotChocolate/Utilities/src/Utilities/ServiceFactory.cs | 988 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.AzureMarkdownRewriters
{
using System.Text.RegularExpressions;
using Microsoft.DocAsCode.MarkdownLite;
public class AzureMigrationVideoBlockRule : IMarkdownRule
{
public virtual string Name => "AZURE.MIGRATION.VIDEO.BLOCK";
private static readonly Regex _azureMigrationVideoRegex = new Regex(@"^ *\[AZURE.VIDEO\s*([^\]]*?)\s*\](?:\n|$)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public virtual Regex AzureMigrationVideoRegex => _azureMigrationVideoRegex;
public IMarkdownToken TryMatch(IMarkdownParser engine, IMarkdownParsingContext context)
{
var match = AzureMigrationVideoRegex.Match(context.CurrentMarkdown);
if (match.Length == 0)
{
return null;
}
var sourceInfo = context.Consume(match.Length);
// Sample: [AZURE.VIDEO video-id-string]. Get video id here
var videoId = match.Groups[1].Value;
return new AzureVideoBlockToken(this, engine.Context, videoId, sourceInfo);
}
}
}
| 37.058824 | 171 | 0.672222 | [
"MIT"
] | 928PJY/docfx | src/Microsoft.DocAsCode.AzureMarkdownRewriters/AzureBlockRules/AzureMigrationVideoBlockRule.cs | 1,262 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Microsoft.Xunit.Performance;
namespace Functions
{
public static partial class MathTests
{
// Tests Math.Asin(double) over 5000 iterations for the domain -1, +1
private const double asinDoubleDelta = 0.0004;
private const double asinDoubleExpectedResult = 1.5707959028763392;
[Benchmark(InnerIterationCount = AsinDoubleIterations)]
public static void AsinDoubleBenchmark()
{
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
AsinDoubleTest();
}
}
}
}
public static void AsinDoubleTest()
{
var result = 0.0;
var value = -1.0;
for (var iteration = 0; iteration < iterations; iteration++)
{
value += asinDoubleDelta;
result += Math.Asin(value);
}
var diff = Math.Abs(asinDoubleExpectedResult - result);
if (diff > doubleEpsilon)
{
throw new Exception(
$"Expected Result {asinDoubleExpectedResult, 20:g17}; Actual Result {result, 20:g17}"
);
}
}
}
}
| 29.433962 | 105 | 0.532051 | [
"MIT"
] | belav/runtime | src/tests/JIT/Performance/CodeQuality/Math/Functions/Double/AsinDouble.cs | 1,560 | C# |
using NUnit.Framework;
using Unity.Entities;
namespace pl.breams.SimpleDOTSUndo.Systems
{
public class SystemTestBase<T> where T:SystemBase
{
protected World _TestWord;
protected EntityManager _EntityManager;
protected T _System;
[SetUp]
public void SetUp()
{
_TestWord = new World("TestWorld");
_EntityManager = _TestWord.EntityManager;
_System = _TestWord.GetOrCreateSystem<T>();
}
[TearDown]
public void TearDown()
{
_TestWord?.Dispose();
}
protected void SystemUpdate()
{
var version = _System.GlobalSystemVersion;
_System.Update();
Assert.AreEqual(version+1, _System.GlobalSystemVersion);
}
protected void SystemUpdateNoExecution()
{
var version = _System.GlobalSystemVersion;
_System.Update();
Assert.AreEqual(version, _System.GlobalSystemVersion);
}
}
} | 25.825 | 68 | 0.585673 | [
"MIT"
] | micz84/SimpleDOTSUndu | Tests/Editor/Systems/SystemTestBase.cs | 1,033 | C# |
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using OrchardCore.Environment.Shell;
using SeedCore.Data.Migrations;
namespace SeedCore.Data
{
public class ModuleDbContext : DbContext, IDbContext
{
readonly IEnumerable<object> _entityConfigurations;
readonly ShellSettings _settings;
public DbContext Context => this;
public DbSet<Document> Document { get; set; }
public DbSet<MigrationRecord> Migrations { get; set; }
public ModuleDbContext(
DbContextOptions options,
ShellSettings settings,
IEnumerable<object> entityConfigurations)
: base(options)
{
_entityConfigurations = entityConfigurations;
_settings = settings;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new MigrationRecordTypeConfiguration());
foreach (var configuration in _entityConfigurations)
{
modelBuilder.ApplyConfiguration((dynamic)configuration);
}
modelBuilder.Model
.GetEntityTypes()
.ToList()
.ForEach(e => modelBuilder.Entity(e.Name).ToTable($"{_settings["TablePrefix"]}_{e.GetTableName()}"));
base.OnModelCreating(modelBuilder);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { }
public override DbSet<TEntity> Set<TEntity>()
{
return Model.FindEntityType(typeof(TEntity)) != null
? base.Set<TEntity>()
: new DocumentDbSet<TEntity>(this);
}
}
}
| 30.719298 | 117 | 0.628784 | [
"MIT"
] | fyl080801/SeedCore | SeedCore/SeedCore.Data/ModuleDbContext.cs | 1,753 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace QuantConnect.Brokerages.InteractiveBrokers.Client
{
/// <summary>
/// Event arguments class for the <see cref="InteractiveBrokersClient.OrderStatus"/> event
/// </summary>
public sealed class OrderStatusEventArgs : EventArgs
{
/// <summary>
/// The order Id that was specified previously in the call to placeOrder()
/// </summary>
public int OrderId { get; }
/// <summary>
/// The order status.
/// </summary>
public string Status { get; }
/// <summary>
/// Specifies the number of shares that have been executed.
/// </summary>
public int Filled { get; }
/// <summary>
/// Specifies the number of shares still outstanding.
/// </summary>
public int Remaining { get; }
/// <summary>
/// The average price of the shares that have been executed.
/// This parameter is valid only if the filled parameter value is greater than zero.
/// Otherwise, the price parameter will be zero.
/// </summary>
public double AverageFillPrice { get; }
/// <summary>
/// The TWS id used to identify orders. Remains the same over TWS sessions.
/// </summary>
public int PermId { get; }
/// <summary>
/// The order ID of the parent order, used for bracket and auto trailing stop orders.
/// </summary>
public int ParentId { get; }
/// <summary>
/// The last price of the shares that have been executed.
/// This parameter is valid only if the filled parameter value is greater than zero.
/// Otherwise, the price parameter will be zero.
/// </summary>
public double LastFillPrice { get; }
/// <summary>
/// The ID of the client (or TWS) that placed the order.
/// Note that TWS orders have a fixed clientId and orderId of 0 that distinguishes them from API orders.
/// </summary>
public int ClientId { get; }
/// <summary>
/// This field is used to identify an order held when TWS is trying to locate shares for a short sell.
/// The value used to indicate this is 'locate'.
/// </summary>
public string WhyHeld { get; }
/// <summary>
/// If an order has been capped, this indicates the current capped price.
/// Requires TWS 967+ and API v973.04+. Python API specifically requires API v973.06+.
/// </summary>
public double MktCapPrice { get; }
/// <summary>
/// Initializes a new instance of the <see cref="OrderStatusEventArgs"/> class
/// </summary>
public OrderStatusEventArgs(int orderId, string status, int filled, int remaining, double averageFillPrice, int permId, int parentId, double lastFillPrice, int clientId, string whyHeld, double mktCapPrice)
{
OrderId = orderId;
Status = status;
Filled = filled;
Remaining = remaining;
AverageFillPrice = averageFillPrice;
PermId = permId;
ParentId = parentId;
LastFillPrice = lastFillPrice;
ClientId = clientId;
WhyHeld = whyHeld;
MktCapPrice = mktCapPrice;
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
public override string ToString()
{
return $"OrderId: {OrderId.ToStringInvariant()}, " +
$"Status: {Status}, " +
$"Filled: {Filled.ToStringInvariant()}, " +
$"Remaining: {Remaining.ToStringInvariant()}, " +
$"AverageFillPrice: {AverageFillPrice.ToStringInvariant()}, " +
$"PermId: {PermId.ToStringInvariant()}, " +
$"ParentId: {ParentId.ToStringInvariant()}, " +
$"LastFillPrice: {LastFillPrice.ToStringInvariant()}, " +
$"ClientId: {ClientId.ToStringInvariant()}, " +
$"WhyHeld: {WhyHeld}," +
$"MktCapPrice: {MktCapPrice}";
}
}
} | 39.793651 | 213 | 0.593139 | [
"Apache-2.0"
] | 3ai-co/Lean | Brokerages/InteractiveBrokers/Client/OrderStatusEventArgs.cs | 5,014 | C# |
//
// IHttpRequestInterceptor.cs
//
// Author:
// David Kopack <d@trusona.com>
//
// Copyright (c) 2018 Trusona, Inc.
using System;
using System.Net.Http;
namespace TrusonaSDK.HTTP.Client.Interceptor
{
public interface IHttpInterceptor
{
void InterceptRequest(HttpRequestMessage message, ICredentialProvider credentialProvider);
void InterceptResponse(HttpResponseMessage message, ICredentialProvider credentialProvider);
}
}
| 22.4 | 96 | 0.765625 | [
"Apache-2.0"
] | trusona/trusona-server-sdk-dotnet | TrusonaSDK.HTTP/Client/Interceptor/IHttpInterceptor.cs | 448 | C# |
namespace Be.Vlaanderen.Basisregisters.Testing.Infrastructure.Events
{
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using EventHandling;
using FluentAssertions;
using System.Reflection;
using System.Runtime.CompilerServices;
using AggregateSource;
using Newtonsoft.Json;
/// <summary>
/// This class was generated using a nuget package called Be.Vlaanderen.Basisregisters.Testing.Infrastructure.Events.
/// If you want to make significant changes to it, that would also make sense for other registries using these tests,
/// consider updating the nuget package (repository: bitbucket.org:vlaamseoverheid/infrastructure-tests.git)
/// </summary>
public class InfrastructureEventsTests
{
private readonly IEnumerable<Type> _eventTypes;
public InfrastructureEventsTests()
{
// Attempt to auto-discover the domain assembly using a type called "DomainAssemblyMarker".
// If this class is not present, these tests will fail.
var domainAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => GetAssemblyTypesSafe(a).Any(t => t?.Name == "DomainAssemblyMarker"));
if (domainAssembly == null)
{
_eventTypes = Enumerable.Empty<Type>();
return;
}
bool IsEventNamespace(Type t) => t.Namespace.EndsWith("Events");
bool IsNotCompilerGenerated(MemberInfo t) => Attribute.GetCustomAttribute(t, typeof(CompilerGeneratedAttribute)) == null;
_eventTypes = domainAssembly
.GetTypes()
.Where(t => t.IsClass && t.Namespace != null && IsEventNamespace(t) && IsNotCompilerGenerated(t));
}
[Fact]
public void HasEventNameAttribute()
{
foreach (var type in _eventTypes)
type
.GetCustomAttributes(typeof(EventNameAttribute), true)
.Should()
.NotBeEmpty($"Forgot EventName attribute on {type.FullName}");
}
[Fact]
public void HasEventDescriptionAttributes()
{
foreach (var type in _eventTypes)
type
.GetCustomAttributes(typeof(EventDescriptionAttribute), true)
.Should()
.NotBeEmpty($"Forgot EventDescription attribute on {type.FullName}");
}
[Fact]
public void HasNoDuplicateEventNameAttributes()
{
var eventNames = new List<string>();
foreach (var eventType in _eventTypes)
{
var newNames = eventType
.GetCustomAttributes(typeof(EventNameAttribute), true)
.OfType<EventNameAttribute>()
.Select(s => s.Value);
foreach (var newName in newNames)
{
eventNames.Contains(newName).Should().BeFalse($"Duplicate event name {newName}");
eventNames.Add(newName);
}
}
}
[Fact]
public void HasNoValueObjectProperty()
{
foreach (var type in _eventTypes)
{
type
.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy)
.SelectMany(s => GetParentTypes(s.PropertyType))
.Where(s => s.IsGenericType && typeof(ValueObject<>).IsAssignableFrom(s.GetGenericTypeDefinition()))
.Should()
.BeEmpty($"Value objects detected as property on {type.FullName}");
}
}
[Fact]
public void HasJsonConstructor()
{
foreach (var type in _eventTypes)
{
type
.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)
.SelectMany(s => s.GetCustomAttributes(typeof(JsonConstructorAttribute), true))
.Should()
.NotBeEmpty($"Forgot JsonConstructor on {type.FullName}");
}
}
[Fact]
public void HasNoPublicFields()
{
foreach (var type in _eventTypes)
{
type.GetFields(BindingFlags.Public | BindingFlags.Instance)
.Should()
.BeEmpty($"{type.FullName} has a public field");
}
}
public static IEnumerable<Type> GetParentTypes(Type type)
{
// is there any base type?
if (type == null || type.BaseType == null)
yield break;
// return all implemented or inherited interfaces
foreach (var i in type.GetInterfaces())
yield return i;
// return all inherited types
var currentBaseType = type.BaseType;
while (currentBaseType != null)
{
yield return currentBaseType;
currentBaseType = currentBaseType.BaseType;
}
}
public static IEnumerable<Type> GetAssemblyTypesSafe(Assembly assembly)
{
List<Type> types;
try
{
types = assembly.GetTypes().ToList();
}
catch (ReflectionTypeLoadException e)
{
types = e.Types.Where(t => t != null).ToList();
}
return types;
}
}
}
| 35.858974 | 162 | 0.555417 | [
"MIT"
] | CumpsD/infrastructure-tests | src/Be.Vlaanderen.Basisregisters.Testing.Infrastructure.Events/InfrastructureEventsTests.cs | 5,594 | C# |
using FluentAssertions;
using LazyEntityGraph.Core;
using LazyEntityGraph.Core.Constraints;
using AutoFixture;
using System.Linq;
using Xunit;
using LazyEntityGraph.TestUtils;
namespace LazyEntityGraph.Tests.Integration
{
public class ManyToManyConstraintTest
{
[Fact]
public void AddsItemToGeneratedCollection()
{
// arrange
var fixture = IntegrationTest.GetFixture(ExpectedConstraints.CreateManyToMany<Foo, Bar>(f => f.Bars, b => b.Foos));
var foo = fixture.Create<Foo>();
// act
var bars = foo.Bars;
// assert
foreach (var bar in bars)
bar.Foos.Should().Contain(foo);
}
[Fact]
public void AddsItemToDerivedGeneratedCollection()
{
// arrange
var fixture = IntegrationTest.GetFixture(ExpectedConstraints.CreateManyToMany<Foo, Bar>(f => f.Bars, b => b.Foos));
var foo = fixture.Create<Faz>();
// act
var bars = foo.Bars;
// assert
foreach (var bar in bars)
bar.Foos.Should().Contain(foo);
}
[Fact]
public void RemovesItemFromCollection()
{
// arrange
var fixture = IntegrationTest.GetFixture(ExpectedConstraints.CreateManyToMany<Foo, Bar>(f => f.Bars, b => b.Foos));
var foo = fixture.Create<Foo>();
var bar = foo.Bars.First();
// act
foo.Bars.Remove(bar);
var foos = bar.Foos;
// assert
foos.Should().NotContain(foo);
}
[Fact]
public void ConstraintsAreEqualWhenPropertiesAreEqual()
{
// arrange
var first = ExpectedConstraints.CreateManyToMany<Foo, Bar>(f => f.Bars, b => b.Foos);
var second = ExpectedConstraints.CreateManyToMany<Foo, Bar>(x => x.Bars, x => x.Foos);
// act and assert
first.Should().Be(second);
}
}
} | 29.128571 | 127 | 0.556155 | [
"MIT"
] | dbroudy/LazyEntityGraph | src/LazyEntityGraph.Tests/Integration/ManyToManyConstraintTest.cs | 2,039 | C# |
using Grynwald.MdDocs.ApiReference.Configuration;
using Grynwald.MdDocs.ApiReference.Templates;
using Grynwald.MdDocs.Common.Configuration;
using Grynwald.MdDocs.Common.Templates;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace Grynwald.MdDocs.CommandLineHelp.Test.Templates
{
/// <summary>
/// Tests for <see cref="CommandLineHelpTemplateProvider"/>
/// </summary>
public class ApiReferenceTemplateProviderTest
{
private readonly ILogger m_Logger = NullLogger.Instance;
[Fact]
public void GetTemplate_throws_InvalidTemplateConfigurationException_for_unknown_template_name()
{
var configuration = new ConfigurationProvider().GetDefaultApiReferenceConfiguration();
configuration.Template.Name = (ApiReferenceConfiguration.TemplateName)(-1);
Assert.Throws<InvalidTemplateConfigurationException>(
() => ApiReferenceTemplateProvider.GetTemplate(m_Logger, configuration)
);
}
[Theory]
[CombinatorialData]
public void GetTemplate_accepts_all_template_names(ApiReferenceConfiguration.TemplateName templateName)
{
var configuration = new ConfigurationProvider().GetDefaultApiReferenceConfiguration();
configuration.Template.Name = templateName;
var template = ApiReferenceTemplateProvider.GetTemplate(m_Logger, configuration);
Assert.NotNull(template);
}
}
}
| 37.390244 | 111 | 0.723418 | [
"MIT"
] | ap0llo/mddocs | src/MdDocs.ApiReference.Test/Templates/ApiReferenceTemplateProviderTest.cs | 1,535 | C# |
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2020 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------
using System;
namespace GameFramework.WebRequest
{
/// <summary>
/// Web 请求代理辅助器接口。
/// </summary>
public interface IWebRequestAgentHelper
{
/// <summary>
/// Web 请求代理辅助器完成事件。
/// </summary>
event EventHandler<WebRequestAgentHelperCompleteEventArgs> WebRequestAgentHelperComplete;
/// <summary>
/// Web 请求代理辅助器错误事件。
/// </summary>
event EventHandler<WebRequestAgentHelperErrorEventArgs> WebRequestAgentHelperError;
/// <summary>
/// 通过 Web 请求代理辅助器发送 Web 请求。
/// </summary>
/// <param name="webRequestUri">Web 请求地址。</param>
/// <param name="userData">用户自定义数据。</param>
void Request(string webRequestUri, object userData);
/// <summary>
/// 通过 Web 请求代理辅助器发送 Web 请求。
/// </summary>
/// <param name="webRequestUri">Web 请求地址。</param>
/// <param name="postData">要发送的数据流。</param>
/// <param name="userData">用户自定义数据。</param>
void Request(string webRequestUri, byte[] postData, object userData);
/// <summary>
/// 重置 Web 请求代理辅助器。
/// </summary>
void Reset();
}
}
| 30.5625 | 97 | 0.543286 | [
"MIT"
] | 297496732/GameFramework | GameFramework/WebRequest/IWebRequestAgentHelper.cs | 1,682 | C# |
using System.Linq;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(NavigationNodeComponent))]
[CanEditMultipleObjects]
public class NavigationNodeEditor : Editor
{
SerializedProperty nodeType;
SerializedProperty nextNodes;
SerializedProperty lookList;
SerializedProperty enableNavigationLines;
SerializedProperty navigationLineMaterial;
SerializedProperty onActivate;
SerializedProperty onEnter;
SerializedProperty onExit;
void OnEnable()
{
nodeType = serializedObject.FindProperty("NavigationNodeType");
nextNodes = serializedObject.FindProperty("NextNodes");
lookList = serializedObject.FindProperty("LookList");
enableNavigationLines = serializedObject.FindProperty("EnableNavigationLines");
navigationLineMaterial = serializedObject.FindProperty("NavigationLineMaterial");
onActivate = serializedObject.FindProperty("OnActivate");
onEnter = serializedObject.FindProperty("OnEnter");
onExit = serializedObject.FindProperty("OnExit");
}
public override void OnInspectorGUI()
{
var node = target as NavigationNodeComponent;
serializedObject.Update();
GUILayout.Label("Spawn navigation node");
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Empty"))
{
node.NextNodes.Add(new TransitionInfo());
}
if (GUILayout.Button("One way"))
{
var obj = new GameObject("Navigation Node");
obj.transform.localPosition = node.transform.position;
var objComp = obj.AddComponent<NavigationNodeComponent>();
AddTransition(node, objComp);
node.LookList.Add(objComp);
objComp.LookList.Add(node);
Selection.activeGameObject = obj;
}
if (GUILayout.Button("Two way"))
{
var obj = new GameObject("Navigation Node");
obj.transform.localPosition = node.transform.position;
var objComp = obj.AddComponent<NavigationNodeComponent>();
AddTransition(node, objComp);
AddTransition(objComp, node);
node.LookList.Add(objComp);
objComp.LookList.Add(node);
Selection.activeGameObject = obj;
}
EditorGUILayout.EndHorizontal();
if (GUILayout.Button("Spawn look node"))
{
var obj = new GameObject("Look Node");
obj.transform.parent = node.transform;
obj.transform.localPosition = Vector3.zero;
var objComp = obj.AddComponent<LookNodeComponent>();
objComp.ParentNode = node;
node.LookList.Add(objComp);
Selection.activeGameObject = obj;
}
EditorGUILayout.Space();
EditorGUILayout.PropertyField(nodeType);
EditorGUILayout.PropertyField(nextNodes, true);
EditorGUILayout.PropertyField(lookList);
EditorGUILayout.Space();
var oldWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 140f;
EditorGUILayout.PropertyField(enableNavigationLines);
if (enableNavigationLines.boolValue) EditorGUILayout.PropertyField(navigationLineMaterial, true);
EditorGUIUtility.labelWidth = oldWidth;
EditorGUILayout.Space();
EditorGUILayout.PropertyField(onActivate);
EditorGUILayout.PropertyField(onEnter);
EditorGUILayout.PropertyField(onExit);
if (node.NextNodes == null || node.NextNodes.Count == 0 || node.NextNodes.All(n => n == null))
{
EditorGUILayout.HelpBox("Node has no outgoing paths, user will be stuck in this point", MessageType.Warning);
}
else if (node.NextNodes.Any(n => n == null))
{
EditorGUILayout.HelpBox("Node has an invalid null path", MessageType.Error);
}
if (node.NextNodes.Any(n => n.NextNode == node))
{
EditorGUILayout.HelpBox("Cannot be set as a next node to itself", MessageType.Error);
}
if (node.NavigationNodeType == NavigationNodeComponent.NavigationNodeTypeEnum.PathPoint && node.NextNodes?.Count > 1)
{
EditorGUILayout.HelpBox("Too many possible nodes", MessageType.Error);
}
serializedObject.ApplyModifiedProperties();
}
[DrawGizmo(GizmoType.InSelectionHierarchy | GizmoType.NotInSelectionHierarchy | GizmoType.Pickable)]
public static void DrawHandles(NavigationNodeComponent t, GizmoType gizmoType)
{
if (t.NavigationNodeType == NavigationNodeComponent.NavigationNodeTypeEnum.StopPoint) Gizmos.color = Color.blue;
else Gizmos.color = Color.red;
Matrix4x4 oldMatrix = Gizmos.matrix;
Gizmos.matrix = Matrix4x4.TRS(t.transform.position, Quaternion.identity, new Vector3(1, 0.1f, 1));
Gizmos.DrawSphere(Vector3.zero, 0.5f);
Gizmos.matrix = oldMatrix;
Gizmos.color = Color.white;
var position = t.transform.position;
if (t.NextNodes == null) return;
foreach (var node in t.NextNodes)
{
if (node == null || node.NextNode == null) continue;
var nodePosition = node.NextNode.transform.position;
var angle = Quaternion.LookRotation(nodePosition - position, Vector3.up);
Gizmos.DrawLine(position, nodePosition);
// This could be probably replaced by a gizmo but it doesn't really matter, all we lose is occlusion and hit detection
Handles.ArrowHandleCap(0, position, angle, 1f, EventType.Repaint);
}
}
private static void AddTransition(NavigationNodeComponent parent, NavigationNodeComponent target)
{
parent.NextNodes.Add(new TransitionInfo
{
NextNode = target
});
}
}
| 35.75 | 130 | 0.65342 | [
"MIT"
] | iimcz/ipw-firmware | Assets/Editor/NavigationNodeEditor.cs | 5,863 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
using Entitas.Unity;
using Entitas.VisualDebugging.Unity;
using Lockstep.Game.Interfaces;
public interface IEventListener
{
void RegisterListeners(GameEntity entity);
void UnregisterListeners();
}
public interface IComponentSetter
{
void SetComponent(GameEntity entity);
}
public class UnityGameService : IViewService
{
private readonly RTSEntityDatabase _entityDatabase;
private Dictionary<uint, GameObject> linkedEntities = new Dictionary<uint, GameObject>();
public UnityGameService(RTSEntityDatabase entityDatabase)
{
_entityDatabase = entityDatabase;
}
public void LoadView(GameEntity entity, int configId)
{
//TODO: pooling
var viewGo = UnityEngine.Object.Instantiate(_entityDatabase.Entities[configId]).gameObject;
if (viewGo != null)
{
viewGo.Link(entity);
var componentSetters = viewGo.GetComponents<IComponentSetter>();
foreach (var componentSetter in componentSetters)
{
componentSetter.SetComponent(entity);
UnityEngine.Object.Destroy((MonoBehaviour)componentSetter);
}
var eventListeners = viewGo.GetComponents<IEventListener>();
foreach (var listener in eventListeners)
{
listener.RegisterListeners(entity);
}
linkedEntities.Add(entity.localId.value, viewGo);
}
}
public void DeleteView(uint entityId)
{
var viewGo = linkedEntities[entityId];
var eventListeners = viewGo.GetComponents<IEventListener>();
foreach (var listener in eventListeners)
{
listener.UnregisterListeners();
}
linkedEntities[entityId].Unlink();
linkedEntities[entityId].DestroyGameObject();
linkedEntities.Remove(entityId);
}
} | 29.852941 | 99 | 0.636946 | [
"MIT"
] | 654306663/UnityLockstep | Unity/Assets/Scripts/UnityServices.cs | 2,032 | C# |
using System;
using static Vanara.PInvoke.AdvApi32;
namespace Vanara.PInvoke.Tests
{
public partial class EvnTraceTests
{
public class ProviderInfo
{
public const ulong DefaultKeywords = 0;
public const TRACE_LEVEL DefaultLevel = (TRACE_LEVEL)0xFF; // Match any level
// Match all events
public ProviderInfo(Guid id, ulong keywords = DefaultKeywords, TRACE_LEVEL level = DefaultLevel)
{
if (id == Guid.Empty)
throw new ArgumentException(nameof(id));
Id = id;
Keywords = keywords;
Level = level;
}
public Guid Id { get; private set; }
public ulong Keywords { get; private set; }
public TRACE_LEVEL Level { get; private set; }
}
}
} | 22.935484 | 99 | 0.675105 | [
"MIT"
] | AndreGleichner/Vanara | UnitTests/PInvoke/Security/AdvApi32/ProviderInfo.cs | 713 | C# |
namespace ClientClassLibrary
{
public class SomeThing
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
} | 18.545455 | 45 | 0.588235 | [
"MIT"
] | StefH/PactExample | ClientClassLibrary/SomeThing.cs | 206 | C# |
using TreniniDotNet.Common.UseCases.Boundaries.Outputs.Ports;
using TreniniDotNet.Domain.Collecting.Collections;
namespace TreniniDotNet.Application.Collecting.Collections.RemoveItemFromCollection
{
public interface IRemoveItemFromCollectionOutputPort : IStandardOutputPort<RemoveItemFromCollectionOutput>
{
void CollectionNotFound(CollectionId collectionId);
void CollectionItemNotFound(CollectionId collectionId, CollectionItemId itemId);
}
}
| 36.615385 | 110 | 0.827731 | [
"MIT"
] | CarloMicieli/TreniniDotNet | Src/Application/Collecting/Collections/RemoveItemFromCollection/IRemoveItemFromCollectionOutputPort.cs | 478 | C# |
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Xunit;
namespace UnitsNet.Serialization.JsonNet.Tests
{
public sealed class UnitsNetBaseJsonConverterTest
{
private readonly TestConverter _sut;
public UnitsNetBaseJsonConverterTest()
{
_sut = new TestConverter();
}
[Fact]
public void UnitsNetBaseJsonConverter_ConvertIQuantity_works_with_double_type()
{
var result = _sut.Test_ConvertDoubleIQuantity(Length.FromMeters(10.2365));
Assert.Equal("LengthUnit.Meter", result.Unit);
Assert.Equal(10.2365, result.Value);
}
[Fact]
public void UnitsNetBaseJsonConverter_ConvertIQuantity_works_with_decimal_type()
{
var result = _sut.Test_ConvertDecimalIQuantity(Power.FromWatts(10.2365m));
Assert.Equal("PowerUnit.Watt", result.Unit);
Assert.Equal(10.2365m, result.Value);
}
[Fact]
public void UnitsNetBaseJsonConverter_ConvertIQuantity_throws_ArgumentNullException_when_quantity_is_NULL()
{
var result = Assert.Throws<ArgumentNullException>(() => _sut.Test_ConvertDoubleIQuantity(null));
Assert.Equal($"Value cannot be null.{Environment.NewLine}Parameter name: quantity", result.Message);
}
[Fact]
public void UnitsNetBaseJsonConverter_ConvertValueUnit_works_as_expected()
{
var result = _sut.Test_ConvertDecimalValueUnit("PowerUnit.Watt", 10.2365m);
Assert.NotNull(result);
Assert.IsType<Power>(result);
Assert.True(Power.FromWatts(10.2365m).Equals((Power)result, 1E-5, ComparisonType.Absolute));
}
[Fact]
public void UnitsNetBaseJsonConverter_ConvertValueUnit_works_with_NULL_value()
{
var result = _sut.Test_ConvertValueUnit();
Assert.Null(result);
}
[Fact]
public void UnitsNetBaseJsonConverter_ConvertValueUnit_throws_UnitsNetException_when_unit_does_not_exist()
{
var result = Assert.Throws<UnitsNetException>(() => _sut.Test_ConvertDoubleValueUnit("SomeImaginaryUnit.Watt", 10.2365D));
Assert.Equal("Unable to find enum type.", result.Message);
Assert.True(result.Data.Contains("type"));
Assert.Equal("UnitsNet.Units.SomeImaginaryUnit,UnitsNet", result.Data["type"]);
}
[Fact]
public void UnitsNetBaseJsonConverter_ConvertValueUnit_throws_UnitsNetException_when_unit_is_in_unexpected_format()
{
var result = Assert.Throws<UnitsNetException>(() => _sut.Test_ConvertDecimalValueUnit("PowerUnit Watt", 10.2365m));
Assert.Equal("\"PowerUnit Watt\" is not a valid unit.", result.Message);
Assert.True(result.Data.Contains("type"));
Assert.Equal("PowerUnit Watt", result.Data["type"]);
}
[Fact]
public void UnitsNetBaseJsonConverter_CreateLocalSerializer_works_as_expected()
{
//Possible improvement: Set all possible settings and test each one. But the main goal of CreateLocalSerializer is that the current serializer is left out.
var serializer = JsonSerializer.Create(new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Arrays,
Converters = new List<JsonConverter>()
{
new BinaryConverter(),
_sut,
new DataTableConverter()
},
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
var result = _sut.Test_CreateLocalSerializer(serializer);
Assert.Equal(TypeNameHandling.Arrays, result.TypeNameHandling);
Assert.Equal(2, result.Converters.Count);
Assert.Collection(result.Converters,
(converter) => Assert.IsType<BinaryConverter>(converter),
(converter) => Assert.IsType<DataTableConverter>(converter));
Assert.IsType<CamelCasePropertyNamesContractResolver>(result.ContractResolver);
}
[Fact]
public void UnitsNetBaseJsonConverter_ReadValueUnit_works_with_double_quantity()
{
var token = new JObject {{"Unit", "LengthUnit.Meter"}, {"Value", 10.2365}};
var result = _sut.Test_ReadDoubleValueUnit(token);
Assert.NotNull(result);
Assert.Equal("LengthUnit.Meter", result?.Unit);
Assert.Equal(10.2365, result?.Value);
}
[Fact]
public void UnitsNetBaseJsonConverter_ReadValueUnit_works_with_decimal_quantity()
{
var token = new JObject {{"Unit", "PowerUnit.Watt"}, {"Value", 10.2365m}, {"ValueString", "10.2365"}, {"ValueType", "decimal"}};
var result = _sut.Test_ReadDecimalValueUnit(token);
Assert.NotNull(result);
Assert.Equal("PowerUnit.Watt", result?.Unit);
Assert.Equal(10.2365m, result?.Value);
}
[Fact]
public void UnitsNetBaseJsonConverter_ReadValueUnit_returns_null_when_value_is_a_string()
{
var token = new JObject {{"Unit", "PowerUnit.Watt"}, {"Value", "10.2365"}};
var result = _sut.Test_ReadDecimalValueUnit(token);
Assert.Null(result);
}
[Fact]
public void UnitsNetBaseJsonConverter_ReadValueUnit_returns_null_when_value_type_is_not_a_string()
{
var token = new JObject {{"Unit", "PowerUnit.Watt"}, {"Value", 10.2365}, {"ValueType", 123}};
var result = _sut.Test_ReadDecimalValueUnit(token);
Assert.Null(result);
}
[Fact]
public void UnitsNetBaseJsonConverter_ReadDoubleValueUnit_works_with_empty_token()
{
var token = new JObject();
var result = _sut.Test_ReadDoubleValueUnit(token);
Assert.Null(result);
}
[Theory]
[InlineData(false, true)]
[InlineData(true, false)]
public void UnitsNetBaseJsonConverter_ReadValueUnit_returns_null_when_unit_or_value_is_missing(bool withUnit, bool withValue)
{
var token = new JObject();
if (withUnit)
{
token.Add("Unit", "PowerUnit.Watt");
}
if (withValue)
{
token.Add("Value", 10.2365m);
}
var result = _sut.Test_ReadDecimalValueUnit(token);
Assert.Null(result);
}
[Theory]
[InlineData("Unit", "Value", "ValueString", "ValueType")]
[InlineData("unit", "Value", "ValueString", "ValueType")]
[InlineData("Unit", "value", "valueString", "valueType")]
[InlineData("unit", "value", "valueString", "valueType")]
[InlineData("unIT", "vAlUe", "vAlUeString", "vAlUeType")]
public void UnitsNetBaseJsonConverter_ReadValueUnit_works_case_insensitive(
string unitPropertyName,
string valuePropertyName,
string valueStringPropertyName,
string valueTypePropertyName)
{
var token = new JObject
{
{unitPropertyName, "PowerUnit.Watt"},
{valuePropertyName, 10.2365m},
{valueStringPropertyName, 10.2365m.ToString(CultureInfo.InvariantCulture)},
{valueTypePropertyName, "decimal"}
};
var result = _sut.Test_ReadDecimalValueUnit(token);
Assert.NotNull(result);
Assert.Equal("PowerUnit.Watt", result?.Unit);
Assert.Equal(10.2365m, result?.Value);
}
/// <summary>
/// Dummy converter, used to access protected methods on abstract UnitsNetBaseJsonConverter{T}
/// </summary>
private class TestConverter : UnitsNetBaseJsonConverter<string>
{
public override bool CanRead => false;
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer) => throw new NotImplementedException();
public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException();
public (string Unit, double Value) Test_ConvertDoubleIQuantity(IQuantity value)
{
var result = ConvertIQuantity(value);
return (result.Unit, result.Value);
}
public (string Unit, decimal Value) Test_ConvertDecimalIQuantity(IQuantity value)
{
var result = ConvertIQuantity(value);
if (result is ExtendedValueUnit {ValueType: "decimal"} decimalResult)
{
return (result.Unit, decimal.Parse(decimalResult.ValueString, CultureInfo.InvariantCulture));
}
throw new ArgumentException("The quantity does not have a decimal value", nameof(value));
}
public IQuantity Test_ConvertDoubleValueUnit(string unit, double value) => Test_ConvertValueUnit(new ValueUnit {Unit = unit, Value = value});
public IQuantity Test_ConvertDecimalValueUnit(string unit, decimal value) => Test_ConvertValueUnit(new ExtendedValueUnit
{
Unit = unit, Value = (double) value, ValueString = value.ToString(CultureInfo.InvariantCulture), ValueType = "decimal"
});
public IQuantity Test_ConvertValueUnit() => Test_ConvertValueUnit(null);
private IQuantity Test_ConvertValueUnit(ValueUnit valueUnit) => ConvertValueUnit(valueUnit);
public JsonSerializer Test_CreateLocalSerializer(JsonSerializer serializer) => CreateLocalSerializer(serializer, this);
public (string Unit, double Value)? Test_ReadDoubleValueUnit(JToken jsonToken)
{
var result = ReadValueUnit(jsonToken);
if (result == null)
{
return null;
}
return (result.Unit, result.Value);
}
public (string Unit, decimal Value)? Test_ReadDecimalValueUnit(JToken jsonToken)
{
var result = ReadValueUnit(jsonToken);
if (result is ExtendedValueUnit {ValueType: "decimal"} decimalResult)
{
return (result.Unit, decimal.Parse(decimalResult.ValueString, CultureInfo.InvariantCulture));
}
return null;
}
}
}
}
| 38.744755 | 191 | 0.623861 | [
"MIT-feh"
] | lipchev/UnitsNet | UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs | 11,083 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.