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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using RepoDb.Contexts.Execution;
using RepoDb.Exceptions;
using RepoDb.Extensions;
using RepoDb.Interfaces;
using RepoDb.Requests;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace RepoDb
{
/// <summary>
/// Contains the extension methods for <see cref="IDbConnection"/> object.
/// </summary>
public static partial class DbConnectionExtension
{
#region MergeAll<TEntity>
/// <summary>
/// Merges the multiple data entity objects into the database.
/// </summary>
/// <typeparam name="TEntity">The type of the data entity object.</typeparam>
/// <param name="connection">The connection object to be used.</param>
/// <param name="entities">The list of data entity objects to be merged.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
public static int MergeAll<TEntity>(this IDbConnection connection,
IEnumerable<TEntity> entities,
int batchSize = Constant.DefaultBatchOperationSize,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
where TEntity : class
{
return MergeAll<TEntity>(connection: connection,
entities: entities,
qualifiers: null,
batchSize: batchSize,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
/// <summary>
/// Merges the multiple data entity objects into the database.
/// </summary>
/// <typeparam name="TEntity">The type of the data entity object.</typeparam>
/// <param name="connection">The connection object to be used.</param>
/// <param name="entities">The list of data entity objects to be merged.</param>
/// <param name="qualifier">The qualifer field to be used during merge operation.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
public static int MergeAll<TEntity>(this IDbConnection connection,
IEnumerable<TEntity> entities,
Field qualifier,
int batchSize = Constant.DefaultBatchOperationSize,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
where TEntity : class
{
return MergeAll(connection: connection,
entities: entities,
qualifiers: qualifier.AsEnumerable(),
batchSize: batchSize,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
/// <summary>
/// Merges the multiple data entity objects into the database.
/// </summary>
/// <typeparam name="TEntity">The type of the data entity object.</typeparam>
/// <param name="connection">The connection object to be used.</param>
/// <param name="entities">The list of data entity objects to be merged.</param>
/// <param name="qualifiers">The list of qualifer fields to be used.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
public static int MergeAll<TEntity>(this IDbConnection connection,
IEnumerable<TEntity> entities,
IEnumerable<Field> qualifiers,
int batchSize = Constant.DefaultBatchOperationSize,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
where TEntity : class
{
return MergeAllInternal<TEntity>(connection: connection,
entities: entities,
qualifiers: qualifiers,
batchSize: batchSize,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
/// <summary>
/// Merges the multiple data entity objects into the database.
/// </summary>
/// <typeparam name="TEntity">The type of the data entity object.</typeparam>
/// <param name="connection">The connection object to be used.</param>
/// <param name="entities">The list of data entity objects to be merged.</param>
/// <param name="qualifiers">The list of qualifer fields to be used.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
internal static int MergeAllInternal<TEntity>(this IDbConnection connection,
IEnumerable<TEntity> entities,
IEnumerable<Field> qualifiers,
int batchSize = Constant.DefaultBatchOperationSize,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
where TEntity : class
{
// Check the qualifiers
if (qualifiers?.Any() != true)
{
var primary = GetAndGuardPrimaryKey<TEntity>(connection, transaction);
qualifiers = primary.AsField().AsEnumerable();
}
// Variables needed
var setting = connection.GetDbSetting();
// Return the result
if (setting.IsUseUpsert == false)
{
return MergeAllInternalBase<TEntity>(connection: connection,
tableName: ClassMappedNameCache.Get<TEntity>(),
entities: entities,
qualifiers: qualifiers,
batchSize: batchSize,
fields: FieldCache.Get<TEntity>(),
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
else
{
return UpsertAllInternalBase<TEntity>(connection: connection,
tableName: ClassMappedNameCache.Get<TEntity>(),
entities: entities,
qualifiers: qualifiers,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
}
#endregion
#region MergeAllAsync<TEntity>
/// <summary>
/// Merges a data entity object into an existing data in the database in an asychronous way.
/// </summary>
/// <typeparam name="TEntity">The type of the data entity object.</typeparam>
/// <param name="connection">The connection object to be used.</param>
/// <param name="entities">The list of data entity objects to be merged.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
public static Task<int> MergeAllAsync<TEntity>(this IDbConnection connection,
IEnumerable<TEntity> entities,
int batchSize = Constant.DefaultBatchOperationSize,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
where TEntity : class
{
return MergeAllAsync(connection: connection,
entities: entities,
qualifiers: null,
batchSize: batchSize,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
/// <summary>
/// Merges a data entity object into an existing data in the database in an asychronous way.
/// </summary>
/// <typeparam name="TEntity">The type of the data entity object.</typeparam>
/// <param name="connection">The connection object to be used.</param>
/// <param name="entities">The list of data entity objects to be merged.</param>
/// <param name="qualifier">The field to be used during merge operation.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
public static Task<int> MergeAllAsync<TEntity>(this IDbConnection connection,
IEnumerable<TEntity> entities,
Field qualifier,
int batchSize = Constant.DefaultBatchOperationSize,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
where TEntity : class
{
return MergeAllAsync(connection: connection,
entities: entities,
qualifiers: qualifier.AsEnumerable(),
batchSize: batchSize,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
/// <summary>
/// Merges a data entity object into an existing data in the database in an asychronous way.
/// </summary>
/// <typeparam name="TEntity">The type of the data entity object.</typeparam>
/// <param name="connection">The connection object to be used.</param>
/// <param name="entities">The list of data entity objects to be merged.</param>
/// <param name="qualifiers">The list of qualifer fields to be used.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
public static Task<int> MergeAllAsync<TEntity>(this IDbConnection connection,
IEnumerable<TEntity> entities,
IEnumerable<Field> qualifiers,
int batchSize = Constant.DefaultBatchOperationSize,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
where TEntity : class
{
return MergeAllAsyncInternal(connection: connection,
entities: entities,
qualifiers: qualifiers,
batchSize: batchSize,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
/// <summary>
/// Merges a data entity object into an existing data in the database in an asychronous way.
/// </summary>
/// <typeparam name="TEntity">The type of the data entity object.</typeparam>
/// <param name="connection">The connection object to be used.</param>
/// <param name="entities">The list of data entity objects to be merged.</param>
/// <param name="qualifiers">The list of qualifer fields to be used.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
internal static Task<int> MergeAllAsyncInternal<TEntity>(this IDbConnection connection,
IEnumerable<TEntity> entities,
IEnumerable<Field> qualifiers,
int batchSize = Constant.DefaultBatchOperationSize,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
where TEntity : class
{
// Check the qualifiers
if (qualifiers?.Any() != true)
{
var primary = GetAndGuardPrimaryKey<TEntity>(connection, transaction);
qualifiers = primary.AsField().AsEnumerable();
}
// Variables needed
var setting = connection.GetDbSetting();
// Return the result
if (setting.IsUseUpsert == false)
{
return MergeAllAsyncInternalBase<TEntity>(connection: connection,
tableName: ClassMappedNameCache.Get<TEntity>(),
entities: entities,
qualifiers: qualifiers,
batchSize: batchSize,
fields: FieldCache.Get<TEntity>(),
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
else
{
return UpsertAllAsyncInternalBase<TEntity>(connection: connection,
tableName: ClassMappedNameCache.Get<TEntity>(),
entities: entities,
qualifiers: qualifiers,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
}
#endregion
#region MergeAll(TableName)
/// <summary>
/// Merges the multiple dynamic objects into the database. By default, the database fields are used unless the 'fields' argument is defined.
/// </summary>
/// <param name="connection">The connection object to be used.</param>
/// <param name="tableName">The name of the target table to be used.</param>
/// <param name="entities">The list of dynamic objects to be merged.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
public static int MergeAll(this IDbConnection connection,
string tableName,
IEnumerable<object> entities,
int batchSize = Constant.DefaultBatchOperationSize,
IEnumerable<Field> fields = null,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
{
return MergeAll(connection: connection,
tableName: tableName,
entities: entities,
qualifiers: null,
batchSize: batchSize,
fields: fields,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
/// <summary>
/// Merges the multiple dynamic objects into the database. By default, the database fields are used unless the 'fields' argument is defined.
/// </summary>
/// <param name="connection">The connection object to be used.</param>
/// <param name="tableName">The name of the target table to be used.</param>
/// <param name="entities">The list of dynamic objects to be merged.</param>
/// <param name="qualifier">The qualifier field to be used.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
public static int MergeAll(this IDbConnection connection,
string tableName,
IEnumerable<object> entities,
Field qualifier,
int batchSize = Constant.DefaultBatchOperationSize,
IEnumerable<Field> fields = null,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
{
return MergeAll(connection: connection,
tableName: tableName,
entities: entities,
qualifiers: qualifier?.AsEnumerable(),
batchSize: batchSize,
fields: fields,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
/// <summary>
/// Merges the multiple dynamic objects into the database. By default, the database fields are used unless the 'fields' argument is defined.
/// </summary>
/// <param name="connection">The connection object to be used.</param>
/// <param name="tableName">The name of the target table to be used.</param>
/// <param name="entities">The list of dynamic objects to be merged.</param>
/// <param name="qualifiers">The qualifier <see cref="Field"/> objects to be used.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
public static int MergeAll(this IDbConnection connection,
string tableName,
IEnumerable<object> entities,
IEnumerable<Field> qualifiers,
int batchSize = Constant.DefaultBatchOperationSize,
IEnumerable<Field> fields = null,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
{
return MergeAllInternal(connection: connection,
tableName: tableName,
entities: entities,
qualifiers: qualifiers,
batchSize: batchSize,
fields: fields,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
/// <summary>
/// Merges the multiple dynamic objects into the database. By default, the database fields are used unless the 'fields' argument is defined.
/// </summary>
/// <param name="connection">The connection object to be used.</param>
/// <param name="tableName">The name of the target table to be used.</param>
/// <param name="entities">The list of dynamic objects to be merged.</param>
/// <param name="qualifiers">The qualifier <see cref="Field"/> objects to be used.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
internal static int MergeAllInternal(this IDbConnection connection,
string tableName,
IEnumerable<object> entities,
IEnumerable<Field> qualifiers,
int batchSize = Constant.DefaultBatchOperationSize,
IEnumerable<Field> fields = null,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
{
var dbFields = DbFieldCache.Get(connection, tableName, transaction);
// Check the fields
if (fields?.Any() != true)
{
var first = entities?.First();
fields = first != null ? Field.Parse(first) : dbFields?.AsFields();
}
// Check the qualifiers
if (qualifiers?.Any() != true)
{
// Get the DB primary
var primary = dbFields?.FirstOrDefault(dbField => dbField.IsPrimary == true);
// Throw if there is no primary
if (primary == null)
{
throw new PrimaryFieldNotFoundException($"There is no primary found for '{tableName}'.");
}
// Set the primary as the qualifier
qualifiers = primary.AsField().AsEnumerable();
}
// Variables needed
var setting = connection.GetDbSetting();
// Return the result
if (setting.IsUseUpsert == false)
{
return MergeAllInternalBase<object>(connection: connection,
tableName: tableName,
entities: entities,
qualifiers: qualifiers,
batchSize: batchSize,
fields: fields,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
else
{
return UpsertAllInternalBase<object>(connection: connection,
tableName: tableName,
entities: entities,
qualifiers: qualifiers,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
}
#endregion
#region MergeAllAsync(TableName)
/// <summary>
/// Merges the multiple dynamic objects into the database in an asynchronous way. By default, the database fields are used unless the 'fields' argument is defined.
/// </summary>
/// <param name="connection">The connection object to be used.</param>
/// <param name="tableName">The name of the target table to be used.</param>
/// <param name="entities">The list of dynamic objects to be merged.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
public static Task<int> MergeAllAsync(this IDbConnection connection,
string tableName,
IEnumerable<object> entities,
int batchSize = Constant.DefaultBatchOperationSize,
IEnumerable<Field> fields = null,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
{
return MergeAllAsync(connection: connection,
tableName: tableName,
entities: entities,
qualifiers: null,
batchSize: batchSize,
fields: fields,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
/// <summary>
/// Merges the multiple dynamic objects into the database in an asynchronous way. By default, the database fields are used unless the 'fields' argument is defined.
/// </summary>
/// <param name="connection">The connection object to be used.</param>
/// <param name="tableName">The name of the target table to be used.</param>
/// <param name="entities">The list of dynamic objects to be merged.</param>
/// <param name="qualifier">The qualifier field to be used.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
public static Task<int> MergeAllAsync(this IDbConnection connection,
string tableName,
IEnumerable<object> entities,
Field qualifier,
int batchSize = Constant.DefaultBatchOperationSize,
IEnumerable<Field> fields = null,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
{
return MergeAllAsync(connection: connection,
tableName: tableName,
entities: entities,
qualifiers: qualifier?.AsEnumerable(),
batchSize: batchSize,
fields: fields,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
/// <summary>
/// Merges the multiple dynamic objects into the database in an asynchronous way. By default, the database fields are used unless the 'fields' argument is defined.
/// </summary>
/// <param name="connection">The connection object to be used.</param>
/// <param name="tableName">The name of the target table to be used.</param>
/// <param name="entities">The list of dynamic objects to be merged.</param>
/// <param name="qualifiers">The qualifier <see cref="Field"/> objects to be used.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
public static Task<int> MergeAllAsync(this IDbConnection connection,
string tableName,
IEnumerable<object> entities,
IEnumerable<Field> qualifiers,
int batchSize = Constant.DefaultBatchOperationSize,
IEnumerable<Field> fields = null,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
{
return MergeAllAsyncInternal(connection: connection,
tableName: tableName,
entities: entities,
qualifiers: qualifiers,
batchSize: batchSize,
fields: fields,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
/// <summary>
/// Merges the multiple dynamic objects into the database in an asynchronous way. By default, the database fields are used unless the 'fields' argument is defined.
/// </summary>
/// <param name="connection">The connection object to be used.</param>
/// <param name="tableName">The name of the target table to be used.</param>
/// <param name="entities">The list of dynamic objects to be merged.</param>
/// <param name="qualifiers">The qualifier <see cref="Field"/> objects to be used.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
internal static Task<int> MergeAllAsyncInternal(this IDbConnection connection,
string tableName,
IEnumerable<object> entities,
IEnumerable<Field> qualifiers,
int batchSize = Constant.DefaultBatchOperationSize,
IEnumerable<Field> fields = null,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
{
var dbFields = DbFieldCache.Get(connection, tableName, transaction);
// Check the fields
if (fields?.Any() != true)
{
var first = entities?.First();
fields = first != null ? Field.Parse(first) : dbFields?.AsFields();
}
// Check the qualifiers
if (qualifiers?.Any() != true)
{
// Get the DB primary
var primary = dbFields?.FirstOrDefault(dbField => dbField.IsPrimary == true);
// Throw if there is no primary
if (primary == null)
{
throw new PrimaryFieldNotFoundException($"There is no primary found for '{tableName}'.");
}
// Set the primary as the qualifier
qualifiers = primary.AsField().AsEnumerable();
}
// Variables needed
var setting = connection.GetDbSetting();
// Return the result
if (setting.IsUseUpsert == false)
{
return MergeAllAsyncInternalBase<object>(connection: connection,
tableName: tableName,
entities: entities,
qualifiers: qualifiers,
batchSize: batchSize,
fields: fields,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
else
{
return UpsertAllAsyncInternalBase<object>(connection: connection,
tableName: tableName,
entities: entities,
qualifiers: qualifiers,
hints: hints,
commandTimeout: commandTimeout,
transaction: transaction,
trace: trace,
statementBuilder: statementBuilder);
}
}
#endregion
#region MergeAllInternalBase<TEntity>
/// <summary>
/// Merges the multiple data entity or dynamic objects into the database.
/// </summary>
/// <typeparam name="TEntity">The type of the object (whether a data entity or a dynamic).</typeparam>
/// <param name="connection">The connection object to be used.</param>
/// <param name="tableName">The name of the target table to be used.</param>
/// <param name="entities">The data entity or dynamic object to be merged.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param>
/// <param name="qualifiers">The list of qualifer fields to be used.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <param name="skipIdentityCheck">True to skip the identity check.</param>
/// <returns>The number of rows affected by the execution.</returns>
internal static int MergeAllInternalBase<TEntity>(this IDbConnection connection,
string tableName,
IEnumerable<TEntity> entities,
IEnumerable<Field> qualifiers,
int batchSize,
IEnumerable<Field> fields,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null,
bool skipIdentityCheck = false)
where TEntity : class
{
// Variables needed
var dbSetting = connection.GetDbSetting();
// Guard the parameters
GuardMergeAll(entities);
// Validate the batch size
batchSize = Math.Min(batchSize, entities.Count());
// Get the function
var callback = new Func<int, MergeAllExecutionContext<TEntity>>((int batchSizeValue) =>
{
// Variables needed
var identity = (Field)null;
var dbFields = DbFieldCache.Get(connection, tableName, transaction);
var inputFields = (IEnumerable<DbField>)null;
var identityDbField = dbFields?.FirstOrDefault(f => f.IsIdentity);
// Set the identity value
if (skipIdentityCheck == false)
{
identity = IdentityCache.Get<TEntity>()?.AsField();
if (identity == null && identityDbField != null)
{
identity = FieldCache.Get<TEntity>().FirstOrDefault(field =>
string.Equals(field.Name.AsUnquoted(true, dbSetting), identityDbField.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase));
}
}
// Filter the actual properties for input fields
inputFields = dbFields?
.Where(dbField =>
fields.FirstOrDefault(field => string.Equals(field.Name.AsUnquoted(true, dbSetting), dbField.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) != null)
.AsList();
// Variables for the context
var multipleEntitiesFunc = (Action<DbCommand, IList<TEntity>>)null;
var singleEntityFunc = (Action<DbCommand, TEntity>)null;
var identitySetterFunc = (Action<TEntity, object>)null;
// Get if we have not skipped it
if (skipIdentityCheck == false && identity != null)
{
identitySetterFunc = FunctionCache.GetDataEntityPropertyValueSetterFunction<TEntity>(identity);
}
// Identity which objects to set
if (batchSizeValue <= 1)
{
singleEntityFunc = FunctionCache.GetDataEntityDbCommandParameterSetterFunction<TEntity>(
string.Concat(typeof(TEntity).FullName, ".", tableName, ".MergeAll"),
inputFields?.AsList(),
null,
dbSetting);
}
else
{
multipleEntitiesFunc = FunctionCache.GetDataEntitiesDbCommandParameterSetterFunction<TEntity>(
string.Concat(typeof(TEntity).FullName, ".", tableName, ".MergeAll"),
inputFields?.AsList(),
null,
batchSizeValue,
dbSetting);
}
// Identify the requests
var mergeAllRequest = (MergeAllRequest)null;
var mergeRequest = (MergeRequest)null;
// Create a different kind of requests
if (typeof(TEntity) == typeof(object))
{
if (batchSizeValue > 1)
{
mergeAllRequest = new MergeAllRequest(tableName,
connection,
transaction,
fields,
qualifiers,
batchSizeValue,
hints,
statementBuilder);
}
else
{
mergeRequest = new MergeRequest(tableName,
connection,
transaction,
fields,
qualifiers,
hints,
statementBuilder);
}
}
else
{
if (batchSizeValue > 1)
{
mergeAllRequest = new MergeAllRequest(typeof(TEntity),
connection,
transaction,
fields,
qualifiers,
batchSizeValue,
hints,
statementBuilder);
}
else
{
mergeRequest = new MergeRequest(typeof(TEntity),
connection,
transaction,
fields,
qualifiers,
hints,
statementBuilder);
}
}
// Return the value
return new MergeAllExecutionContext<TEntity>
{
CommandText = batchSizeValue > 1 ? CommandTextCache.GetMergeAllText(mergeAllRequest) : CommandTextCache.GetMergeText(mergeRequest),
InputFields = inputFields,
BatchSize = batchSizeValue,
SingleDataEntityParametersSetterFunc = singleEntityFunc,
MultipleDataEntitiesParametersSetterFunc = multipleEntitiesFunc,
IdentityPropertySetterFunc = identitySetterFunc
};
});
// Get the context
var context = MergeAllExecutionContextCache<TEntity>.Get(tableName, qualifiers, fields, batchSize, callback);
// Before Execution
if (trace != null)
{
var cancellableTraceLog = new CancellableTraceLog(context.CommandText, entities, null);
trace.BeforeMergeAll(cancellableTraceLog);
if (cancellableTraceLog.IsCancelled)
{
if (cancellableTraceLog.IsThrowException)
{
throw new CancelledExecutionException(context.CommandText);
}
return 0;
}
context.CommandText = (cancellableTraceLog.Statement ?? context.CommandText);
entities = (IEnumerable<TEntity>)(cancellableTraceLog.Parameter ?? entities);
}
// Before Execution Time
var beforeExecutionTime = DateTime.UtcNow;
// Execution variables
var result = 0;
// Make sure to create transaction if there is no passed one
var hasTransaction = (transaction != null);
try
{
// Ensure the connection is open
connection.EnsureOpen();
if (hasTransaction == false)
{
// Create a transaction
transaction = connection.BeginTransaction();
}
// Create the command
using (var command = (DbCommand)connection.CreateCommand(context.CommandText,
CommandType.Text, commandTimeout, transaction))
{
// Directly execute if the entities is only 1 (performance)
if (batchSize == 1)
{
// Much better to use the actual single-based setter (performance)
foreach (var entity in entities)
{
// Set the values
context.SingleDataEntityParametersSetterFunc(command, entity);
// Prepare the command
if (dbSetting.IsPreparable)
{
command.Prepare();
}
// Actual Execution
var returnValue = ObjectConverter.DbNullToNull(command.ExecuteScalar());
// Set the return value
if (returnValue != null)
{
context.IdentityPropertySetterFunc?.Invoke(entity, returnValue);
}
// Iterate the result
result++;
}
}
else
{
// Iterate the batches
foreach (var batchEntities in entities.Split(batchSize))
{
var batchItems = batchEntities.AsList();
// Break if there is no more records
if (batchItems.Count <= 0)
{
break;
}
// Check if the batch size has changed (probably the last batch on the enumerables)
if (batchItems.Count != batchSize)
{
// Get a new execution context from cache
context = MergeAllExecutionContextCache<TEntity>.Get(tableName, fields, qualifiers, batchItems.Count, callback);
// Set the command properties
command.CommandText = context.CommandText;
}
// Set the values
if (batchItems?.Count() == 1)
{
context.SingleDataEntityParametersSetterFunc(command, batchItems.First());
}
else
{
context.MultipleDataEntitiesParametersSetterFunc(command, batchItems);
}
// Prepare the command
if (dbSetting.IsPreparable)
{
command.Prepare();
}
// Actual Execution
if (context.IdentityPropertySetterFunc == null)
{
// No identity setters
result += command.ExecuteNonQuery();
}
else
{
// Set the identity back
using (var reader = command.ExecuteReader())
{
var index = 0;
do
{
if (reader.Read())
{
var value = ObjectConverter.DbNullToNull(reader.GetValue(0));
context.IdentityPropertySetterFunc.Invoke(batchItems[index], value);
result++;
}
index++;
}
while (reader.NextResult());
}
}
}
}
}
if (hasTransaction == false)
{
// Commit the transaction
transaction.Commit();
}
}
catch
{
if (hasTransaction == false)
{
// Rollback for any exception
transaction.Rollback();
}
throw;
}
finally
{
if (hasTransaction == false)
{
// Rollback and dispose the transaction
transaction.Dispose();
}
}
// After Execution
if (trace != null)
{
trace.AfterMergeAll(new TraceLog(context.CommandText, entities, result,
DateTime.UtcNow.Subtract(beforeExecutionTime)));
}
// Return the result
return result;
}
#endregion
#region UpsertAllInternalBase<TEntity>
/// <summary>
/// Upserts the multiple data entity or dynamic objects into the database.
/// </summary>
/// <typeparam name="TEntity">The type of the object (whether a data entity or a dynamic).</typeparam>
/// <param name="connection">The connection object to be used.</param>
/// <param name="tableName">The name of the target table to be used.</param>
/// <param name="entities">The data entity or dynamic object to be merged.</param>
/// <param name="qualifiers">The list of qualifer fields to be used.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
internal static int UpsertAllInternalBase<TEntity>(this IDbConnection connection,
string tableName,
IEnumerable<TEntity> entities,
IEnumerable<Field> qualifiers = null,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
where TEntity : class
{
// Variables needed
var type = entities?.First()?.GetType() ?? typeof(TEntity);
var isObjectType = typeof(TEntity) == typeof(object);
var dbFields = DbFieldCache.Get(connection, tableName, transaction);
var primary = dbFields?.FirstOrDefault(dbField => dbField.IsPrimary);
var properties = (IEnumerable<ClassProperty>)null;
var primaryKey = (ClassProperty)null;
// Get the properties
if (type.GetTypeInfo().IsGenericType == true)
{
properties = type.GetClassProperties();
}
else
{
properties = PropertyCache.Get(type);
}
// Check the qualifiers
if (qualifiers?.Any() != true)
{
// Throw if there is no primary
if (primary == null)
{
throw new PrimaryFieldNotFoundException($"There is no primary found for '{tableName}'.");
}
// Set the primary as the qualifier
qualifiers = primary.AsField().AsEnumerable();
}
// Set the primary key
primaryKey = properties?.FirstOrDefault(p =>
string.Equals(primary?.Name, p.GetMappedName(), StringComparison.OrdinalIgnoreCase));
// Before Execution
if (trace != null)
{
var cancellableTraceLog = new CancellableTraceLog("UpsertAll.Before", entities, null);
trace.BeforeMergeAll(cancellableTraceLog);
if (cancellableTraceLog.IsCancelled)
{
if (cancellableTraceLog.IsThrowException)
{
throw new CancelledExecutionException("UpsertAll.Cancelled");
}
return default(int);
}
entities = (IEnumerable<TEntity>)(cancellableTraceLog.Parameter ?? entities);
}
// Before Execution Time
var beforeExecutionTime = DateTime.UtcNow;
// Execution variables
var result = 0;
// Make sure to create transaction if there is no passed one
var hasTransaction = (transaction != null);
try
{
// Ensure to open the connection
connection.EnsureOpen();
if (hasTransaction == false)
{
// Create a transaction
transaction = connection.BeginTransaction();
}
// Iterate the entities
foreach (var entity in entities)
{
// Call the upsert
var upsertResult = connection.UpsertInternalBase<TEntity, object>(tableName,
entity,
qualifiers,
hints,
commandTimeout,
transaction,
trace,
statementBuilder);
// Iterate the result
if (ObjectConverter.DbNullToNull(upsertResult) != null)
{
result += 1;
}
}
if (hasTransaction == false)
{
// Commit the transaction
transaction.Commit();
}
}
catch
{
if (hasTransaction == false)
{
// Rollback for any exception
transaction.Rollback();
}
throw;
}
finally
{
if (hasTransaction == false)
{
// Rollback and dispose the transaction
transaction.Dispose();
}
}
// After Execution
if (trace != null)
{
trace.AfterMergeAll(new TraceLog("UpsertAll.After", entities, result,
DateTime.UtcNow.Subtract(beforeExecutionTime)));
}
// Return the result
return result;
}
#endregion
#region MergeAllAsyncInternalBase<TEntity>
/// <summary>
/// Merges the multiple data entity or dynamic objects into the database in an asynchronous way.
/// </summary>
/// <typeparam name="TEntity">The type of the object (whether a data entity or a dynamic).</typeparam>
/// <param name="connection">The connection object to be used.</param>
/// <param name="tableName">The name of the target table to be used.</param>
/// <param name="entities">The data entity or dynamic object to be merged.</param>
/// <param name="qualifiers">The list of qualifer fields to be used.</param>
/// <param name="batchSize">The batch size of the merge operation.</param>
/// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <param name="skipIdentityCheck">True to skip the identity check.</param>
/// <returns>The number of rows affected by the execution.</returns>
internal static async Task<int> MergeAllAsyncInternalBase<TEntity>(this IDbConnection connection,
string tableName,
IEnumerable<TEntity> entities,
IEnumerable<Field> qualifiers,
int batchSize,
IEnumerable<Field> fields,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null,
bool skipIdentityCheck = false)
where TEntity : class
{
// Variables needed
var dbSetting = connection.GetDbSetting();
// Guard the parameters
GuardMergeAll(entities);
// Validate the batch size
batchSize = Math.Min(batchSize, entities.Count());
var dbFields = await DbFieldCache.GetAsync(connection, tableName, transaction);
// Check the fields
if (fields?.Any() != true)
{
fields = dbFields?.AsFields();
}
// Check the qualifiers
if (qualifiers?.Any() != true)
{
var primary = dbFields?.FirstOrDefault(dbField => dbField.IsPrimary == true);
qualifiers = primary?.AsField().AsEnumerable();
}
// Get the function
var callback = new Func<int, MergeAllExecutionContext<TEntity>>((int batchSizeValue) =>
{
// Variables needed
var identity = (Field)null;
var inputFields = (IEnumerable<DbField>)null;
var identityDbField = dbFields?.FirstOrDefault(f => f.IsIdentity);
// Set the identity value
if (skipIdentityCheck == false)
{
identity = IdentityCache.Get<TEntity>()?.AsField();
if (identity == null && identityDbField != null)
{
identity = FieldCache.Get<TEntity>().FirstOrDefault(field =>
string.Equals(field.Name.AsUnquoted(true, dbSetting), identityDbField.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase));
}
}
// Filter the actual properties for input fields
inputFields = dbFields?
.Where(dbField =>
fields.FirstOrDefault(field => string.Equals(field.Name.AsUnquoted(true, dbSetting), dbField.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) != null)
.AsList();
// Variables for the context
var multipleEntitiesFunc = (Action<DbCommand, IList<TEntity>>)null;
var singleEntityFunc = (Action<DbCommand, TEntity>)null;
var identitySetterFunc = (Action<TEntity, object>)null;
// Get if we have not skipped it
if (skipIdentityCheck == false && identity != null)
{
identitySetterFunc = FunctionCache.GetDataEntityPropertyValueSetterFunction<TEntity>(identity);
}
// Identity which objects to set
if (batchSizeValue <= 1)
{
singleEntityFunc = FunctionCache.GetDataEntityDbCommandParameterSetterFunction<TEntity>(
string.Concat(typeof(TEntity).FullName, ".", tableName, ".MergeAll"),
inputFields?.AsList(),
null,
dbSetting);
}
else
{
multipleEntitiesFunc = FunctionCache.GetDataEntitiesDbCommandParameterSetterFunction<TEntity>(
string.Concat(typeof(TEntity).FullName, ".", tableName, ".MergeAll"),
inputFields?.AsList(),
null,
batchSizeValue,
dbSetting);
}
// Identify the requests
var mergeAllRequest = (MergeAllRequest)null;
var mergeRequest = (MergeRequest)null;
// Create a different kind of requests
if (typeof(TEntity) == typeof(object))
{
if (batchSizeValue > 1)
{
mergeAllRequest = new MergeAllRequest(tableName,
connection,
transaction,
fields,
qualifiers,
batchSizeValue,
hints,
statementBuilder);
}
else
{
mergeRequest = new MergeRequest(tableName,
connection,
transaction,
fields,
qualifiers,
hints,
statementBuilder);
}
}
else
{
if (batchSizeValue > 1)
{
mergeAllRequest = new MergeAllRequest(typeof(TEntity),
connection,
transaction,
fields,
qualifiers,
batchSizeValue,
hints,
statementBuilder);
}
else
{
mergeRequest = new MergeRequest(typeof(TEntity),
connection,
transaction,
fields,
qualifiers,
hints,
statementBuilder);
}
}
// Return the value
return new MergeAllExecutionContext<TEntity>
{
CommandText = batchSizeValue > 1 ? CommandTextCache.GetMergeAllText(mergeAllRequest) : CommandTextCache.GetMergeText(mergeRequest),
InputFields = inputFields,
BatchSize = batchSizeValue,
SingleDataEntityParametersSetterFunc = singleEntityFunc,
MultipleDataEntitiesParametersSetterFunc = multipleEntitiesFunc,
IdentityPropertySetterFunc = identitySetterFunc
};
});
// Get the context
var context = MergeAllExecutionContextCache<TEntity>.Get(tableName, qualifiers, fields, batchSize, callback);
// Before Execution
if (trace != null)
{
var cancellableTraceLog = new CancellableTraceLog(context.CommandText, entities, null);
trace.BeforeMergeAll(cancellableTraceLog);
if (cancellableTraceLog.IsCancelled)
{
if (cancellableTraceLog.IsThrowException)
{
throw new CancelledExecutionException(context.CommandText);
}
return 0;
}
context.CommandText = (cancellableTraceLog.Statement ?? context.CommandText);
entities = (IEnumerable<TEntity>)(cancellableTraceLog.Parameter ?? entities);
}
// Before Execution Time
var beforeExecutionTime = DateTime.UtcNow;
// Execution variables
var result = 0;
// Make sure to create transaction if there is no passed one
var hasTransaction = (transaction != null);
try
{
// Ensure the connection is open
await connection.EnsureOpenAsync();
if (hasTransaction == false)
{
// Create a transaction
transaction = connection.BeginTransaction();
}
// Create the command
using (var command = (DbCommand)connection.CreateCommand(context.CommandText,
CommandType.Text, commandTimeout, transaction))
{
// Directly execute if the entities is only 1 (performance)
if (batchSize == 1)
{
// Much better to use the actual single-based setter (performance)
foreach (var entity in entities)
{
// Set the values
context.SingleDataEntityParametersSetterFunc(command, entity);
// Prepare the command
if (dbSetting.IsPreparable)
{
command.Prepare();
}
// Actual Execution
var returnValue = ObjectConverter.DbNullToNull(await command.ExecuteScalarAsync());
// Set the return value
if (returnValue != null)
{
context.IdentityPropertySetterFunc?.Invoke(entity, returnValue);
}
// Iterate the result
result++;
}
}
else
{
// Iterate the batches
foreach (var batchEntities in entities.Split(batchSize))
{
var batchItems = batchEntities.AsList();
// Break if there is no more records
if (batchItems.Count <= 0)
{
break;
}
// Check if the batch size has changed (probably the last batch on the enumerables)
if (batchItems.Count != batchSize)
{
// Get a new execution context from cache
context = MergeAllExecutionContextCache<TEntity>.Get(tableName, fields, qualifiers, batchItems.Count, callback);
// Set the command properties
command.CommandText = context.CommandText;
}
// Set the values
if (batchItems?.Count() == 1)
{
context.SingleDataEntityParametersSetterFunc(command, batchItems.First());
}
else
{
context.MultipleDataEntitiesParametersSetterFunc(command, batchItems);
}
// Prepare the command
if (dbSetting.IsPreparable)
{
command.Prepare();
}
// Actual Execution
if (context.IdentityPropertySetterFunc == null)
{
// No identity setters
result += await command.ExecuteNonQueryAsync();
}
else
{
// Set the identity back
using (var reader = await command.ExecuteReaderAsync())
{
var index = 0;
do
{
if (await reader.ReadAsync())
{
var value = ObjectConverter.DbNullToNull(reader.GetValue(0));
context.IdentityPropertySetterFunc.Invoke(batchItems[index], value);
result++;
}
index++;
}
while (await reader.NextResultAsync());
}
}
}
}
}
if (hasTransaction == false)
{
// Commit the transaction
transaction.Commit();
}
}
catch
{
if (hasTransaction == false)
{
// Rollback for any exception
transaction.Rollback();
}
throw;
}
finally
{
if (hasTransaction == false)
{
// Rollback and dispose the transaction
transaction.Dispose();
}
}
// After Execution
if (trace != null)
{
trace.AfterMergeAll(new TraceLog(context.CommandText, entities, result,
DateTime.UtcNow.Subtract(beforeExecutionTime)));
}
// Return the result
return result;
}
#endregion
#region UpsertAllInternalBase<TEntity>
/// <summary>
/// Upserts the multiple data entity or dynamic objects into the database in an asynchronous way.
/// </summary>
/// <typeparam name="TEntity">The type of the object (whether a data entity or a dynamic).</typeparam>
/// <param name="connection">The connection object to be used.</param>
/// <param name="tableName">The name of the target table to be used.</param>
/// <param name="entities">The data entity or dynamic object to be merged.</param>
/// <param name="qualifiers">The list of qualifer fields to be used.</param>
/// <param name="hints">The table hints to be used.</param>
/// <param name="commandTimeout">The command timeout in seconds to be used.</param>
/// <param name="transaction">The transaction to be used.</param>
/// <param name="trace">The trace object to be used.</param>
/// <param name="statementBuilder">The statement builder object to be used.</param>
/// <returns>The number of rows affected by the execution.</returns>
internal static async Task<int> UpsertAllAsyncInternalBase<TEntity>(this IDbConnection connection,
string tableName,
IEnumerable<TEntity> entities,
IEnumerable<Field> qualifiers = null,
string hints = null,
int? commandTimeout = null,
IDbTransaction transaction = null,
ITrace trace = null,
IStatementBuilder statementBuilder = null)
where TEntity : class
{
// Variables needed
var type = entities?.First()?.GetType() ?? typeof(TEntity);
var isObjectType = typeof(TEntity) == typeof(object);
var dbFields = await DbFieldCache.GetAsync(connection, tableName, transaction);
var primary = dbFields?.FirstOrDefault(dbField => dbField.IsPrimary);
var properties = (IEnumerable<ClassProperty>)null;
var primaryKey = (ClassProperty)null;
// Get the properties
if (type.GetTypeInfo().IsGenericType == true)
{
properties = type.GetClassProperties();
}
else
{
properties = PropertyCache.Get(type);
}
// Check the qualifiers
if (qualifiers?.Any() != true)
{
// Throw if there is no primary
if (primary == null)
{
throw new PrimaryFieldNotFoundException($"There is no primary found for '{tableName}'.");
}
// Set the primary as the qualifier
qualifiers = primary.AsField().AsEnumerable();
}
// Set the primary key
primaryKey = properties?.FirstOrDefault(p =>
string.Equals(primary?.Name, p.GetMappedName(), StringComparison.OrdinalIgnoreCase));
// Before Execution
if (trace != null)
{
var cancellableTraceLog = new CancellableTraceLog("UpsertAll.Before", entities, null);
trace.BeforeMergeAll(cancellableTraceLog);
if (cancellableTraceLog.IsCancelled)
{
if (cancellableTraceLog.IsThrowException)
{
throw new CancelledExecutionException("UpsertAll.Cancelled");
}
return default(int);
}
entities = (IEnumerable<TEntity>)(cancellableTraceLog.Parameter ?? entities);
}
// Before Execution Time
var beforeExecutionTime = DateTime.UtcNow;
// Execution variables
var result = 0;
// Make sure to create transaction if there is no passed one
var hasTransaction = (transaction != null);
try
{
// Ensure to open the connection
await connection.EnsureOpenAsync();
if (hasTransaction == false)
{
// Create a transaction
transaction = connection.BeginTransaction();
}
// Iterate the entities
foreach (var entity in entities)
{
// Call the upsert
var upsertResult = await connection.UpsertAsyncInternalBase<TEntity, object>(tableName,
entity,
qualifiers,
hints,
commandTimeout,
transaction,
trace,
statementBuilder);
// Iterate the result
if (ObjectConverter.DbNullToNull(upsertResult) != null)
{
result += 1;
}
}
if (hasTransaction == false)
{
// Commit the transaction
transaction.Commit();
}
}
catch
{
if (hasTransaction == false)
{
// Rollback for any exception
transaction.Rollback();
}
throw;
}
finally
{
if (hasTransaction == false)
{
// Rollback and dispose the transaction
transaction.Dispose();
}
}
// After Execution
if (trace != null)
{
trace.AfterMergeAll(new TraceLog("UpsertAll.After", entities, result,
DateTime.UtcNow.Subtract(beforeExecutionTime)));
}
// Return the result
return result;
}
#endregion
#region Helpers
/// <summary>
/// Throws an exception if the entities argument is null or empty.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="entities">The enumerable list of entity objects.</param>
private static void GuardMergeAll<TEntity>(IEnumerable<TEntity> entities)
where TEntity : class
{
if (entities == null)
{
throw new NullReferenceException("The entities must not be null.");
}
if (entities.Any() == false)
{
throw new EmptyException("The entities must not be empty.");
}
}
#endregion
}
}
| 44.593819 | 196 | 0.519677 | [
"Apache-2.0"
] | davidskula/RepoDb | RepoDb.Core/RepoDb/Operations/DbConnection/MergeAll.cs | 80,806 | C# |
using System.Collections;
using System.Collections.Generic;
public class pt_ret_hero_challenge_e117 : st.net.NetBase.Pt {
public pt_ret_hero_challenge_e117()
{
Id = 0xE117;
}
public override st.net.NetBase.Pt createNew()
{
return new pt_ret_hero_challenge_e117();
}
public uint mission;
public uint hp;
public uint mp;
public byte times;
public List<st.net.NetBase.entourage> entourages = new List<st.net.NetBase.entourage>();
public override void fromBinary(byte[] binary)
{
reader = new st.net.NetBase.ByteReader(binary);
mission = reader.Read_uint();
hp = reader.Read_uint();
mp = reader.Read_uint();
times = reader.Read_byte();
ushort lenentourages = reader.Read_ushort();
entourages = new List<st.net.NetBase.entourage>();
for(int i_entourages = 0 ; i_entourages < lenentourages ; i_entourages ++)
{
st.net.NetBase.entourage listData = new st.net.NetBase.entourage();
listData.fromBinary(reader);
entourages.Add(listData);
}
}
public override byte[] toBinary()
{
writer = new st.net.NetBase.ByteWriter();
writer.write_int(mission);
writer.write_int(hp);
writer.write_int(mp);
writer.write_byte(times);
ushort lenentourages = (ushort)entourages.Count;
writer.write_short(lenentourages);
for(int i_entourages = 0 ; i_entourages < lenentourages ; i_entourages ++)
{
st.net.NetBase.entourage listData = entourages[i_entourages];
listData.toBinary(writer);
}
return writer.data;
}
}
| 27.622642 | 89 | 0.728825 | [
"BSD-3-Clause"
] | cheng219/tianyu | Assets/Protocol/pt_ret_hero_challenge_e117.cs | 1,464 | C# |
/*
dotNetRDF is free and open source software licensed under the MIT License
-----------------------------------------------------------------------------
Copyright (c) 2009-2012 dotNetRDF Project ([email protected])
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 Xunit;
using VDS.RDF.Configuration;
using VDS.RDF.Parsing;
using VDS.RDF.Storage;
using VDS.RDF.Writing.Contexts;
using VDS.RDF.Writing.Formatting;
using Xunit.Abstractions;
namespace VDS.RDF.Writing
{
public class CollectionCompressionTests
: CompressionTests
{
public CollectionCompressionTests(ITestOutputHelper output):base(output)
{
}
[Fact(Skip = "Commented out before, now fails (?)")]
public void WritingCollectionCompressionSimple7()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
INode n = g.CreateBlankNode();
INode rdfType = g.CreateUriNode("rdf:type");
g.Assert(n, rdfType, g.CreateUriNode("ex:Obj"));
g.Assert(n, rdfType, g.CreateUriNode("ex:Test"));
var collections = FindCollections(g);
Assert.Single(collections);
Assert.Single(collections.First().Value.Triples);
CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionNamedListNodes3()
{
Graph g = new Graph();
INode data1 = g.CreateBlankNode();
g.Assert(data1, g.CreateUriNode(new Uri("http://property")), g.CreateLiteralNode("test1"));
INode data2 = g.CreateBlankNode();
g.Assert(data2, g.CreateUriNode(new Uri("http://property")), g.CreateLiteralNode("test2"));
INode listEntry1 = g.CreateUriNode(new Uri("http://test/1"));
INode rdfFirst = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfListFirst));
INode rdfRest = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfListRest));
INode rdfNil = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfListNil));
g.Assert(listEntry1, rdfFirst, data1);
g.Assert(listEntry1, rdfRest, rdfNil);
INode listEntry2 = g.CreateUriNode(new Uri("http://test/2"));
g.Assert(listEntry2, rdfFirst, data2);
g.Assert(listEntry2, rdfRest, listEntry1);
INode root = g.CreateUriNode(new Uri("http://root"));
g.Assert(root, g.CreateUriNode(new Uri("http://list")), listEntry2);
NTriplesFormatter formatter = new NTriplesFormatter();
_output.WriteLine("Original Graph");
foreach (Triple t in g.Triples)
{
_output.WriteLine(t.ToString(formatter));
}
_output.WriteLine("");
var sw = new System.IO.StringWriter();
CompressingTurtleWriterContext context = new CompressingTurtleWriterContext(g, sw);
WriterHelper.FindCollections(context);
_output.WriteLine(sw.ToString());
_output.WriteLine(context.Collections.Count + " Collections Found");
_output.WriteLine("");
System.IO.StringWriter strWriter = new System.IO.StringWriter();
CompressingTurtleWriter writer = new CompressingTurtleWriter();
writer.CompressionLevel = WriterCompressionLevel.High;
writer.Save(g, strWriter);
_output.WriteLine("Compressed Turtle");
_output.WriteLine(strWriter.ToString());
_output.WriteLine("");
Graph h = new Graph();
TurtleParser parser = new TurtleParser();
StringParser.Parse(h, strWriter.ToString());
_output.WriteLine("Graph after Round Trip to Compressed Turtle");
foreach (Triple t in h.Triples)
{
_output.WriteLine(t.ToString(formatter));
}
Assert.Equal(g, h);
}
[Fact]
public void WritingCollectionCompressionCyclic()
{
var g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
g.NamespaceMap.AddNamespace("dnr", new Uri(ConfigurationLoader.ConfigurationNamespace));
INode a = g.CreateBlankNode();
INode b = g.CreateBlankNode();
INode c = g.CreateBlankNode();
var pred = g.CreateUriNode("ex:pred");
g.Assert(a, pred, b);
g.Assert(a, pred, g.CreateLiteralNode("Value for A"));
g.Assert(b, pred, c);
g.Assert(b, pred, g.CreateLiteralNode("Value for B"));
g.Assert(c, pred, a);
g.Assert(c, pred, g.CreateLiteralNode("Value for C"));
var collections = FindCollections(g);
Assert.Equal(2, collections.Count);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionCyclic2()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
g.NamespaceMap.AddNamespace("dnr", new Uri(ConfigurationLoader.ConfigurationNamespace));
INode a = g.CreateBlankNode();
INode b = g.CreateBlankNode();
INode c = g.CreateBlankNode();
INode d = g.CreateBlankNode();
INode pred = g.CreateUriNode("ex:pred");
g.Assert(d, pred, a);
g.Assert(d, pred, g.CreateLiteralNode("D"));
g.Assert(a, pred, b);
g.Assert(a, pred, g.CreateLiteralNode("A"));
g.Assert(b, pred, c);
g.Assert(b, pred, g.CreateLiteralNode("B"));
g.Assert(c, pred, a);
g.Assert(c, pred, g.CreateLiteralNode("C"));
var collections = FindCollections(g);
Assert.Equal(2, collections.Count);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionCyclic3()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
g.NamespaceMap.AddNamespace("dnr", new Uri(ConfigurationLoader.ConfigurationNamespace));
INode a = g.CreateBlankNode();
INode b = g.CreateBlankNode();
INode c = g.CreateBlankNode();
INode d = g.CreateBlankNode();
INode e = g.CreateBlankNode();
INode pred = g.CreateUriNode("ex:pred");
g.Assert(d, pred, a);
g.Assert(d, pred, g.CreateLiteralNode("D"));
g.Assert(a, pred, b);
g.Assert(a, pred, g.CreateLiteralNode("A"));
g.Assert(b, pred, c);
g.Assert(b, pred, g.CreateLiteralNode("B"));
g.Assert(c, pred, a);
g.Assert(c, pred, g.CreateLiteralNode("C"));
g.Assert(e, pred, g.CreateLiteralNode("E"));
var collections = FindCollections(g);
Assert.Equal(3, collections.Count);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionEmpty1()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
INode n = g.CreateBlankNode();
g.Assert(g.CreateUriNode("ex:subj"), g.CreateUriNode("ex:pred"), n);
var collections = FindCollections(g);
Assert.Single(collections);
Assert.Empty(collections.First().Value.Triples);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionEmpty2()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
INode rdfType = g.CreateUriNode("rdf:type");
g.Assert(g.CreateUriNode("ex:subj"), g.CreateUriNode("ex:pred"), g.CreateUriNode("rdf:nil"));
var collections = FindCollections(g);
Assert.Empty(collections);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionSimple1()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
INode n = g.CreateBlankNode();
INode rdfType = g.CreateUriNode("rdf:type");
g.Assert(g.CreateUriNode("ex:subj"), g.CreateUriNode("ex:pred"), n);
g.Assert(n, rdfType, g.CreateUriNode("ex:BlankNode"));
var collections = FindCollections(g);
Assert.Single(collections);
Assert.Single(collections.First().Value.Triples);
this.CheckCompressionRoundTrip(g);
}
private Dictionary<INode, OutputRdfCollection> FindCollections(IGraph g)
{
var sw = new System.IO.StringWriter();
var context = new CompressingTurtleWriterContext(g, sw);
_output.WriteLine(sw.ToString());
WriterHelper.FindCollections(context);
return context.Collections;
}
[Fact]
public void WritingCollectionCompressionSimple2()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
INode n = g.CreateBlankNode();
INode rdfType = g.CreateUriNode("rdf:type");
g.Assert(g.CreateUriNode("ex:subj"), g.CreateUriNode("ex:pred"), n);
g.Assert(g.CreateUriNode("ex:subj"), g.CreateUriNode("ex:pred2"), n);
g.Assert(n, rdfType, g.CreateUriNode("ex:BlankNode"));
var collections = FindCollections(g);
Assert.Empty(collections);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionSimple3()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
INode n = g.CreateBlankNode();
INode rdfType = g.CreateUriNode("rdf:type");
INode rdfFirst = g.CreateUriNode("rdf:first");
INode rdfRest = g.CreateUriNode("rdf:rest");
INode rdfNil = g.CreateUriNode("rdf:nil");
g.Assert(g.CreateUriNode("ex:subj"), g.CreateUriNode("ex:pred"), n);
g.Assert(n, rdfFirst, g.CreateLiteralNode("first"));
g.Assert(n, rdfRest, rdfNil);
var collections = FindCollections(g);
Assert.Single(collections);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionSimple4()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
INode n = g.CreateBlankNode();
INode rdfType = g.CreateUriNode("rdf:type");
INode rdfFirst = g.CreateUriNode("rdf:first");
INode rdfRest = g.CreateUriNode("rdf:rest");
INode rdfNil = g.CreateUriNode("rdf:nil");
g.Assert(n, rdfFirst, g.CreateLiteralNode("first"));
g.Assert(n, rdfRest, rdfNil);
var collections = FindCollections(g);
Assert.Empty(collections);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionSimple5()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
INode n = g.CreateBlankNode();
INode rdfType = g.CreateUriNode("rdf:type");
INode rdfFirst = g.CreateUriNode("rdf:first");
INode rdfRest = g.CreateUriNode("rdf:rest");
INode rdfNil = g.CreateUriNode("rdf:nil");
g.Assert(g.CreateUriNode("ex:subj"), g.CreateUriNode("ex:pred"), n);
g.Assert(g.CreateUriNode("ex:subj"), g.CreateUriNode("ex:pred2"), n);
g.Assert(n, rdfFirst, g.CreateLiteralNode("first"));
g.Assert(n, rdfRest, rdfNil);
var collections = FindCollections(g);
Assert.Empty(collections);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionSimple6()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
INode n = g.CreateBlankNode();
INode rdfType = g.CreateUriNode("rdf:type");
g.Assert(n, rdfType, g.CreateUriNode("ex:Obj"));
var collections = FindCollections(g);
Assert.Single(collections);
Assert.Empty(collections.First().Value.Triples);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionComplex1()
{
SparqlConnector connector = new SparqlConnector(new VDS.RDF.Query.SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql")));
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
g.NamespaceMap.AddNamespace("dnr", new Uri(ConfigurationLoader.ConfigurationNamespace));
INode n = g.CreateBlankNode();
g.Assert(g.CreateUriNode("ex:subj"), g.CreateUriNode("dnr:genericManager"), n);
ConfigurationSerializationContext sContext = new ConfigurationSerializationContext(g);
sContext.NextSubject = n;
connector.SerializeConfiguration(sContext);
var collections = FindCollections(g);
Assert.Equal(2, collections.Count);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionComplex2()
{
Graph g = new Graph();
g.LoadFromFile("resources\\complex-collections.nt");
CompressingTurtleWriterContext context = new CompressingTurtleWriterContext(g, Console.Out);
WriterHelper.FindCollections(context);
NTriplesFormatter formatter = new NTriplesFormatter();
foreach (KeyValuePair<INode, OutputRdfCollection> kvp in context.Collections)
{
_output.WriteLine("Collection Root - " + kvp.Key.ToString(formatter));
_output.WriteLine("Collection Triples (" + kvp.Value.Triples.Count + ")");
foreach (Triple t in kvp.Value.Triples)
{
_output.WriteLine(t.ToString(formatter));
}
_output.WriteLine("");
}
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionNamedListNodes()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
INode n = g.CreateUriNode("ex:list");
INode rdfType = g.CreateUriNode("rdf:type");
INode rdfFirst = g.CreateUriNode("rdf:first");
INode rdfRest = g.CreateUriNode("rdf:rest");
INode rdfNil = g.CreateUriNode("rdf:nil");
g.Assert(g.CreateUriNode("ex:subj"), g.CreateUriNode("ex:pred"), n);
g.Assert(n, rdfFirst, g.CreateLiteralNode("first"));
g.Assert(n, rdfRest, rdfNil);
var collections = FindCollections(g);
Assert.Empty(collections);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingCollectionCompressionNamedListNodes2()
{
Graph g = new Graph();
g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));
INode n = g.CreateUriNode("ex:listRoot");
INode m = g.CreateUriNode("ex:listItem");
INode rdfType = g.CreateUriNode("rdf:type");
INode rdfFirst = g.CreateUriNode("rdf:first");
INode rdfRest = g.CreateUriNode("rdf:rest");
INode rdfNil = g.CreateUriNode("rdf:nil");
g.Assert(g.CreateUriNode("ex:subj"), g.CreateUriNode("ex:pred"), n);
g.Assert(n, rdfFirst, g.CreateLiteralNode("first"));
g.Assert(n, rdfRest, m);
g.Assert(m, rdfFirst, g.CreateLiteralNode("second"));
g.Assert(m, rdfRest, rdfNil);
var collections = FindCollections(g);
Assert.Empty(collections);
this.CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingBlankNodeCollectionIssue279()
{
var g = new Graph();
INode b1 = g.CreateBlankNode("b1");
INode b2 = g.CreateBlankNode("b2");
INode b3 = g.CreateBlankNode("b3");
INode b4 = g.CreateBlankNode("b4");
INode rdfType = g.CreateUriNode("rdf:type");
INode rdfFirst = g.CreateUriNode("rdf:first");
INode rdfRest = g.CreateUriNode("rdf:rest");
INode rdfNil = g.CreateUriNode("rdf:nil");
g.Assert(b1, rdfType, b2);
g.Assert(b2, rdfFirst, b3);
g.Assert(b2, rdfRest, rdfNil);
g.Assert(b3, rdfType, b4);
FindCollections(g);
CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingBlankNodeCollection2()
{
var g = new Graph();
INode b1 = g.CreateBlankNode("b1");
INode b2 = g.CreateBlankNode("b2");
INode b3 = g.CreateBlankNode("b3");
INode b4 = g.CreateBlankNode("b4");
INode b5 = g.CreateBlankNode("b5");
INode rdfType = g.CreateUriNode("rdf:type");
INode rdfFirst = g.CreateUriNode("rdf:first");
INode rdfRest = g.CreateUriNode("rdf:rest");
INode rdfNil = g.CreateUriNode("rdf:nil");
g.Assert(b1, rdfType, b2);
g.Assert(b2, rdfFirst, b3);
g.Assert(b2, rdfRest, rdfNil);
g.Assert(b3, rdfType, b4);
g.Assert(b4, rdfType, b5);
FindCollections(g);
CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingBlankNodeCollection3()
{
var g = new Graph();
INode b1 = g.CreateBlankNode("b1");
INode b2 = g.CreateBlankNode("b2");
INode b3 = g.CreateBlankNode("b3");
INode b4 = g.CreateBlankNode("b4");
INode b5 = g.CreateBlankNode("b5");
INode rdfType = g.CreateUriNode("rdf:type");
INode rdfFirst = g.CreateUriNode("rdf:first");
INode rdfRest = g.CreateUriNode("rdf:rest");
INode rdfNil = g.CreateUriNode("rdf:nil");
g.Assert(b1, rdfType, b2);
g.Assert(b2, rdfFirst, b3);
g.Assert(b2, rdfRest, rdfNil);
g.Assert(b3, rdfType, b4);
g.Assert(b3, rdfType, b5);
FindCollections(g);
CheckCompressionRoundTrip(g);
}
[Fact]
public void WritingBlankNodeCollection4()
{
var g = new Graph();
INode b1 = g.CreateBlankNode("b1");
INode b2 = g.CreateBlankNode("b2");
INode b3 = g.CreateBlankNode("b3");
INode b4 = g.CreateBlankNode("b4");
INode b5 = g.CreateBlankNode("b5");
INode b6 = g.CreateBlankNode("b6");
INode rdfType = g.CreateUriNode("rdf:type");
INode rdfFirst = g.CreateUriNode("rdf:first");
INode rdfRest = g.CreateUriNode("rdf:rest");
INode rdfNil = g.CreateUriNode("rdf:nil");
g.Assert(b1, rdfType, b2);
g.Assert(b2, rdfFirst, b3);
g.Assert(b2, rdfRest, b4);
g.Assert(b3, rdfType, b5);
g.Assert(b4, rdfFirst, b6);
g.Assert(b4, rdfRest, rdfNil);
FindCollections(g);
CheckCompressionRoundTrip(g);
}
}
}
| 37.795455 | 139 | 0.562746 | [
"MIT"
] | BME-MIT-IET/iet-hf2021-gitgud | Testing/unittest/Writing/CollectionCompressionTests.cs | 21,619 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using HotChocolate.Configuration;
using HotChocolate.Internal;
using HotChocolate.Resolvers;
using HotChocolate.Types.Descriptors;
using HotChocolate.Types.Descriptors.Definitions;
#nullable enable
namespace HotChocolate.Types.Interceptors;
internal sealed class ResolverTypeInterceptor : TypeInterceptor
{
private readonly List<ITypeDefinition> _typeDefs = new();
private readonly List<FieldResolverConfig> _fieldResolvers;
private readonly List<(NameString, Type)> _resolverTypeList;
private readonly Dictionary<NameString, Type> _runtimeTypes;
private readonly Dictionary<string, ParameterInfo> _parameters = new();
private IDescriptorContext _context = default!;
private INamingConventions _naming = default!;
private ITypeInspector _typeInspector = default!;
private IResolverCompiler _resolverCompiler = default!;
private TypeReferenceResolver _typeReferenceResolver = default!;
private ILookup<NameString, Type> _resolverTypes = default!;
private ILookup<NameString, FieldResolverConfig> _configs = default!;
public ResolverTypeInterceptor(
List<FieldResolverConfig> fieldResolvers,
List<(NameString, Type)> resolverTypes,
Dictionary<NameString, Type> runtimeTypes)
{
_fieldResolvers = fieldResolvers;
_resolverTypeList = resolverTypes;
_runtimeTypes = runtimeTypes;
}
public override bool TriggerAggregations => true;
public override bool CanHandle(ITypeSystemObjectContext context) => true;
internal override void InitializeContext(
IDescriptorContext context,
TypeInitializer typeInitializer,
TypeRegistry typeRegistry,
TypeLookup typeLookup,
TypeReferenceResolver typeReferenceResolver)
{
_context = context;
_naming = context.Naming;
_typeInspector = context.TypeInspector;
_resolverCompiler = context.ResolverCompiler;
_typeReferenceResolver = typeReferenceResolver;
_resolverTypes = _resolverTypeList.ToLookup(t => t.Item1, t => t.Item2);
_configs = _fieldResolvers.ToLookup(t => t.Field.TypeName);
}
public override void OnAfterInitialize(
ITypeDiscoveryContext discoveryContext,
DefinitionBase? definition,
IDictionary<string, object?> contextData)
{
if (!discoveryContext.IsIntrospectionType &&
discoveryContext.Type is IHasName namedType &&
definition is ITypeDefinition typeDef &&
!typeDef.NeedsNameCompletion)
{
if (typeDef.RuntimeType == typeof(object) &&
_runtimeTypes.TryGetValue(typeDef.Name, out Type? type))
{
typeDef.RuntimeType = type;
}
typeDef.Name = namedType.Name;
_typeDefs.Add(typeDef);
}
}
public override IEnumerable<ITypeReference> RegisterMoreTypes(
IReadOnlyCollection<ITypeDiscoveryContext> discoveryContexts)
{
var context = new CompletionContext(_typeDefs);
ApplyResolver(context);
ApplySourceMembers(context);
var list = new List<TypeDependency>();
foreach (ITypeDefinition? typeDef in _typeDefs)
{
switch (typeDef)
{
case ObjectTypeDefinition otd:
TypeDependencyHelper.CollectDependencies(otd, list);
break;
case InterfaceTypeDefinition itd:
TypeDependencyHelper.CollectDependencies(itd, list);
break;
}
}
return list.Select(t => t.TypeReference);
}
public override void OnAfterCompleteName(
ITypeCompletionContext completionContext,
DefinitionBase? definition,
IDictionary<string, object?> contextData)
{
if (!completionContext.IsIntrospectionType &&
completionContext.Type is IHasName namedType &&
definition is ITypeDefinition typeDef)
{
if (typeDef.RuntimeType == typeof(object) &&
_runtimeTypes.TryGetValue(typeDef.Name, out Type? type))
{
typeDef.RuntimeType = type;
}
typeDef.Name = namedType.Name;
_typeDefs.Add(typeDef);
}
}
public override void OnAfterCompleteTypeNames()
{
var context = new CompletionContext(_typeDefs);
ApplyResolver(context);
ApplySourceMembers(context);
}
private void ApplyResolver(CompletionContext context)
{
var completed = 0;
foreach (ObjectTypeDefinition objectTypeDef in _typeDefs.OfType<ObjectTypeDefinition>())
{
if (_configs.Contains(objectTypeDef.Name))
{
foreach (FieldResolverConfig config in _configs[objectTypeDef.Name])
{
context.Resolvers[config.Field.FieldName] = config;
}
foreach (ObjectFieldDefinition field in objectTypeDef.Fields)
{
if (context.Resolvers.TryGetValue(field.Name, out FieldResolverConfig conf))
{
field.Resolvers = conf.ToFieldResolverDelegates();
TrySetRuntimeType(context, field, conf);
completed++;
}
}
context.Resolvers.Clear();
}
if (completed < objectTypeDef.Fields.Count)
{
ApplyResolverTypes(context, objectTypeDef);
}
context.Members.Clear();
}
}
private void ApplyResolverTypes(
CompletionContext context,
ObjectTypeDefinition objectTypeDef)
{
CollectResolverMembers(context, objectTypeDef.Name);
if (context.Members.Count > 0)
{
foreach (ObjectFieldDefinition field in objectTypeDef.Fields)
{
if (!field.Resolvers.HasResolvers &&
context.Members.TryGetValue(field.Name, out MemberInfo? member))
{
field.ResolverMember = member;
ObjectFieldDescriptor.From(_context, field).CreateDefinition();
field.Resolvers = _resolverCompiler.CompileResolve(
member,
objectTypeDef.RuntimeType,
resolverType: member.ReflectedType);
if (member is MethodInfo method)
{
foreach (ParameterInfo parameter in
_resolverCompiler.GetArgumentParameters(method.GetParameters()))
{
_parameters[parameter.Name!] = parameter;
}
foreach (var argument in field.Arguments)
{
if (_parameters.TryGetValue(argument.Name.Value, out var parameter))
{
argument.Parameter = parameter;
argument.RuntimeType = parameter.ParameterType;
if (_typeReferenceResolver.TryGetType(argument.Type!, out var type))
{
Type? unwrapped = Unwrap(parameter.ParameterType, type);
if (unwrapped is not null)
{
#if NET5_0_OR_GREATER
_runtimeTypes.TryAdd(type.NamedType().Name, unwrapped);
#else
if (!_runtimeTypes.ContainsKey(type.NamedType().Name))
{
_runtimeTypes.Add(type.NamedType().Name, unwrapped);
}
#endif
}
}
}
}
_parameters.Clear();
}
TrySetRuntimeTypeFromMember(context, field.Type, member);
}
}
}
}
private void ApplySourceMembers(CompletionContext context)
{
foreach (ITypeDefinition definition in
_typeDefs.Where(t => t.RuntimeType != typeof(object)))
{
context.TypesToAnalyze.Enqueue(definition);
}
while (context.TypesToAnalyze.Count > 0)
{
switch (context.TypesToAnalyze.Dequeue())
{
case ObjectTypeDefinition objectTypeDef:
ApplyObjectSourceMembers(context, objectTypeDef);
break;
case InputObjectTypeDefinition inputTypeDef:
ApplyInputSourceMembers(context, inputTypeDef);
break;
case EnumTypeDefinition enumTypeDef:
ApplyEnumSourceMembers(context, enumTypeDef);
break;
}
}
}
private void ApplyObjectSourceMembers(
CompletionContext context,
ObjectTypeDefinition objectTypeDef)
{
var initialized = false;
foreach (ObjectFieldDefinition field in objectTypeDef.Fields)
{
if (!initialized && field.Member is null)
{
CollectSourceMembers(context, objectTypeDef.RuntimeType);
initialized = true;
}
if (field.Member is null &&
context.Members.TryGetValue(field.Name, out MemberInfo? member))
{
field.Member = member;
ObjectFieldDescriptor.From(_context, field).CreateDefinition();
if (!field.Resolvers.HasResolvers)
{
field.Resolvers = _resolverCompiler.CompileResolve(
field.Member,
objectTypeDef.RuntimeType);
if (TrySetRuntimeTypeFromMember(context, field.Type, field.Member) is { } u)
{
foreach (ITypeDefinition updated in u)
{
context.TypesToAnalyze.Enqueue(updated);
}
}
}
}
}
context.Members.Clear();
}
private void ApplyInputSourceMembers(
CompletionContext context,
InputObjectTypeDefinition inputTypeDef)
{
var initialized = false;
foreach (InputFieldDefinition field in inputTypeDef.Fields)
{
if (!initialized && field.Property is null)
{
CollectSourceMembers(context, inputTypeDef.RuntimeType);
initialized = true;
}
if (field.Property is null &&
context.Members.TryGetValue(field.Name, out MemberInfo? member) &&
member is PropertyInfo property)
{
field.Property = property;
if (TrySetRuntimeTypeFromMember(context, field.Type, property) is { } upd)
{
foreach (ITypeDefinition updated in upd)
{
context.TypesToAnalyze.Enqueue(updated);
}
}
}
}
context.Members.Clear();
}
private void ApplyEnumSourceMembers(
CompletionContext context,
EnumTypeDefinition enumTypeDef)
{
var initialized = false;
foreach (EnumValueDefinition enumValue in enumTypeDef.Values)
{
if (!initialized && enumValue.Member is null)
{
foreach (object value in _typeInspector.GetEnumValues(enumTypeDef.RuntimeType))
{
NameString name = _naming.GetEnumValueName(value);
MemberInfo? member = _typeInspector.GetEnumValueMember(enumTypeDef);
context.Values.Add(name, (value, member!));
context.ValuesToName.Add(value.ToString()!, (value, member!));
}
initialized = true;
}
(object Value, MemberInfo Member) info;
if (enumValue.Member is null &&
(enumValue.BindTo is null &&
context.Values.TryGetValue(enumValue.Name, out info) ||
enumValue.BindTo is { } b &&
context.ValuesToName.TryGetValue(b, out info)))
{
enumValue.RuntimeValue = info.Value;
enumValue.Member = info.Member;
}
}
context.Values.Clear();
context.ValuesToName.Clear();
}
private void CollectResolverMembers(CompletionContext context, NameString typeName)
{
if (!_resolverTypes.Contains(typeName))
{
return;
}
foreach (Type? resolverType in _resolverTypes[typeName])
{
CollectSourceMembers(context, resolverType);
}
}
private void CollectSourceMembers(CompletionContext context, Type runtimeType)
{
foreach (MemberInfo? member in _typeInspector.GetMembers(runtimeType, false))
{
NameString name = _naming.GetMemberName(member, MemberKind.ObjectField);
context.Members[name] = member;
}
}
private void TrySetRuntimeType(
CompletionContext context,
ObjectFieldDefinition field,
FieldResolverConfig config)
{
if (config.ResultType != typeof(object) &&
field.Type is not null &&
_typeReferenceResolver.TryGetType(field.Type, out IType? type))
{
foreach (ITypeDefinition? typeDef in context.TypeDefs[type.NamedType().Name])
{
if (typeDef.RuntimeType == typeof(object))
{
typeDef.RuntimeType = Unwrap(config.ResultType, type);
}
}
}
}
private IReadOnlyCollection<ITypeDefinition>? TrySetRuntimeTypeFromMember(
CompletionContext context,
ITypeReference? typeRef,
MemberInfo member)
{
if (typeRef is not null && _typeReferenceResolver.TryGetType(typeRef, out IType? type))
{
List<ITypeDefinition>? updated = null;
Type? runtimeType = null;
foreach (ITypeDefinition? typeDef in context.TypeDefs[type.NamedType().Name])
{
if (typeDef.RuntimeType == typeof(object))
{
updated ??= new List<ITypeDefinition>();
runtimeType ??= Unwrap(_typeInspector.GetReturnType(member), type);
typeDef.RuntimeType = runtimeType;
updated.Add(typeDef);
}
}
return updated;
}
return null;
}
private Type? Unwrap(Type resultType, IType type)
=> Unwrap(_context.TypeInspector.GetType(resultType), type);
private Type? Unwrap(IExtendedType extendedType, IType type)
{
if (type.IsNonNullType())
{
return Unwrap(extendedType, type.InnerType());
}
if (type.IsListType())
{
if (extendedType.ElementType is null)
{
return null;
}
return Unwrap(extendedType.ElementType, type.InnerType());
}
return extendedType.IsNullable
? _context.TypeInspector.ChangeNullability(extendedType, false).Source
: extendedType.Source;
}
private class CompletionContext
{
public readonly Dictionary<NameString, FieldResolverConfig> Resolvers = new();
public readonly Dictionary<NameString, MemberInfo> Members = new();
public readonly Dictionary<NameString, (object, MemberInfo)> Values = new();
public readonly Dictionary<string, (object, MemberInfo)> ValuesToName = new();
public readonly Queue<ITypeDefinition> TypesToAnalyze = new();
public readonly ILookup<NameString, ITypeDefinition> TypeDefs;
public CompletionContext(List<ITypeDefinition> typeDefs)
{
TypeDefs = typeDefs.ToLookup(t => t.Name);
}
}
}
| 34.533473 | 100 | 0.563458 | [
"MIT"
] | chrisketelaar/hotchocolate | src/HotChocolate/Core/src/Types/Types/Interceptors/ResolverTypeInterceptor.cs | 16,507 | C# |
//-----------------------------------------------------------------------
// <copyright file="JsonDataWriter.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// 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>
//-----------------------------------------------------------------------
namespace TWC.OdinSerializer
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
/// <summary>
/// Writes json data to a stream that can be read by a <see cref="JsonDataReader"/>.
/// </summary>
/// <seealso cref="BaseDataWriter" />
public class JsonDataWriter : BaseDataWriter
{
private static readonly uint[] ByteToHexCharLookup = CreateByteToHexLookup();
private static readonly string NEW_LINE = Environment.NewLine;
private bool justStarted;
private bool forceNoSeparatorNextLine;
//private StringBuilder escapeStringBuilder;
//private StreamWriter writer;
private Dictionary<Type, Delegate> primitiveTypeWriters;
private Dictionary<Type, int> seenTypes = new Dictionary<Type, int>(16);
private byte[] buffer = new byte[1024 * 100];
private int bufferIndex = 0;
public JsonDataWriter() : this(null, null, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonDataWriter" /> class.
/// </summary>
/// <param name="stream">The base stream of the writer.</param>
/// <param name="context">The serialization context to use.</param>>
/// <param name="formatAsReadable">Whether the json should be packed, or formatted as human-readable.</param>
public JsonDataWriter(Stream stream, SerializationContext context, bool formatAsReadable = true) : base(stream, context)
{
this.FormatAsReadable = formatAsReadable;
this.justStarted = true;
this.EnableTypeOptimization = true;
this.primitiveTypeWriters = new Dictionary<Type, Delegate>()
{
{ typeof(char), (Action<string, char>)this.WriteChar },
{ typeof(sbyte), (Action<string, sbyte>)this.WriteSByte },
{ typeof(short), (Action<string, short>)this.WriteInt16 },
{ typeof(int), (Action<string, int>)this.WriteInt32 },
{ typeof(long), (Action<string, long>)this.WriteInt64 },
{ typeof(byte), (Action<string, byte>)this.WriteByte },
{ typeof(ushort), (Action<string, ushort>)this.WriteUInt16 },
{ typeof(uint), (Action<string, uint>)this.WriteUInt32 },
{ typeof(ulong), (Action<string, ulong>)this.WriteUInt64 },
{ typeof(decimal), (Action<string, decimal>)this.WriteDecimal },
{ typeof(bool), (Action<string, bool>)this.WriteBoolean },
{ typeof(float), (Action<string, float>)this.WriteSingle },
{ typeof(double), (Action<string, double>)this.WriteDouble },
{ typeof(Guid), (Action<string, Guid>)this.WriteGuid }
};
}
/// <summary>
/// Gets or sets a value indicating whether the json should be packed, or formatted as human-readable.
/// </summary>
/// <value>
/// <c>true</c> if the json should be formatted as human-readable; otherwise, <c>false</c>.
/// </value>
public bool FormatAsReadable;
/// <summary>
/// Whether to enable an optimization that ensures any given type name is only written once into the json stream, and thereafter kept track of by ID.
/// </summary>
public bool EnableTypeOptimization;
/// <summary>
/// Enable the "just started" flag, causing the writer to start a new "base" json object container.
/// </summary>
public void MarkJustStarted()
{
this.justStarted = true;
}
/// <summary>
/// Flushes everything that has been written so far to the writer's base stream.
/// </summary>
public override void FlushToStream()
{
if (this.bufferIndex > 0)
{
this.Stream.Write(this.buffer, 0, this.bufferIndex);
this.bufferIndex = 0;
}
base.FlushToStream();
}
/// <summary>
/// Writes the beginning of a reference node.
/// <para />
/// This call MUST eventually be followed by a corresponding call to <see cref="IDataWriter.EndNode(string)" />, with the same name.
/// </summary>
/// <param name="name">The name of the reference node.</param>
/// <param name="type">The type of the reference node. If null, no type metadata will be written.</param>
/// <param name="id">The id of the reference node. This id is acquired by calling <see cref="SerializationContext.TryRegisterInternalReference(object, out int)" />.</param>
public override void BeginReferenceNode(string name, Type type, int id)
{
this.WriteEntry(name, "{");
this.PushNode(name, id, type);
this.forceNoSeparatorNextLine = true;
this.WriteInt32(JsonConfig.ID_SIG, id);
if (type != null)
{
this.WriteTypeEntry(type);
}
}
/// <summary>
/// Begins a struct/value type node. This is essentially the same as a reference node, except it has no internal reference id.
/// <para />
/// This call MUST eventually be followed by a corresponding call to <see cref="IDataWriter.EndNode(string)" />, with the same name.
/// </summary>
/// <param name="name">The name of the struct node.</param>
/// <param name="type">The type of the struct node. If null, no type metadata will be written.</param>
public override void BeginStructNode(string name, Type type)
{
this.WriteEntry(name, "{");
this.PushNode(name, -1, type);
this.forceNoSeparatorNextLine = true;
if (type != null)
{
this.WriteTypeEntry(type);
}
}
/// <summary>
/// Ends the current node with the given name. If the current node has another name, an <see cref="InvalidOperationException" /> is thrown.
/// </summary>
/// <param name="name">The name of the node to end. This has to be the name of the current node.</param>
public override void EndNode(string name)
{
this.PopNode(name);
this.StartNewLine(true);
this.EnsureBufferSpace(1);
this.buffer[this.bufferIndex++] = (byte)'}';
}
/// <summary>
/// Begins an array node of the given length.
/// </summary>
/// <param name="length">The length of the array to come.</param>
public override void BeginArrayNode(long length)
{
this.WriteInt64(JsonConfig.REGULAR_ARRAY_LENGTH_SIG, length);
this.WriteEntry(JsonConfig.REGULAR_ARRAY_CONTENT_SIG, "[");
this.forceNoSeparatorNextLine = true;
this.PushArray();
}
/// <summary>
/// Ends the current array node, if the current node is an array node.
/// </summary>
public override void EndArrayNode()
{
this.PopArray();
this.StartNewLine(true);
this.EnsureBufferSpace(1);
this.buffer[this.bufferIndex++] = (byte)']';
}
/// <summary>
/// Writes a primitive array to the stream.
/// </summary>
/// <typeparam name="T">The element type of the primitive array. Valid element types can be determined using <see cref="FormatterUtilities.IsPrimitiveArrayType(Type)" />.</typeparam>
/// <param name="array">The primitive array to write.</param>
/// <exception cref="System.ArgumentException">Type + typeof(T).Name + is not a valid primitive array type.</exception>
/// <exception cref="System.ArgumentNullException">array</exception>
public override void WritePrimitiveArray<T>(T[] array)
{
if (FormatterUtilities.IsPrimitiveArrayType(typeof(T)) == false)
{
throw new ArgumentException("Type " + typeof(T).Name + " is not a valid primitive array type.");
}
if (array == null)
{
throw new ArgumentNullException("array");
}
Action<string, T> writer = (Action<string, T>)this.primitiveTypeWriters[typeof(T)];
this.WriteInt64(JsonConfig.PRIMITIVE_ARRAY_LENGTH_SIG, array.Length);
this.WriteEntry(JsonConfig.PRIMITIVE_ARRAY_CONTENT_SIG, "[");
this.forceNoSeparatorNextLine = true;
this.PushArray();
for (int i = 0; i < array.Length; i++)
{
writer(null, array[i]);
}
this.PopArray();
this.StartNewLine(true);
this.EnsureBufferSpace(1);
this.buffer[this.bufferIndex++] = (byte)']';
}
/// <summary>
/// Writes a <see cref="bool" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteBoolean(string name, bool value)
{
this.WriteEntry(name, value ? "true" : "false");
}
/// <summary>
/// Writes a <see cref="byte" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteByte(string name, byte value)
{
this.WriteUInt64(name, value);
}
/// <summary>
/// Writes a <see cref="char" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteChar(string name, char value)
{
this.WriteString(name, value.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Writes a <see cref="decimal" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteDecimal(string name, decimal value)
{
this.WriteEntry(name, value.ToString("G", CultureInfo.InvariantCulture));
}
/// <summary>
/// Writes a <see cref="double" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteDouble(string name, double value)
{
this.WriteEntry(name, value.ToString("R", CultureInfo.InvariantCulture));
}
/// <summary>
/// Writes an <see cref="int" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteInt32(string name, int value)
{
this.WriteInt64(name, value);
}
/// <summary>
/// Writes a <see cref="long" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteInt64(string name, long value)
{
this.WriteEntry(name, value.ToString("D", CultureInfo.InvariantCulture));
}
/// <summary>
/// Writes a null value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
public override void WriteNull(string name)
{
this.WriteEntry(name, "null");
}
/// <summary>
/// Writes an internal reference to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="id">The value to write.</param>
public override void WriteInternalReference(string name, int id)
{
this.WriteEntry(name, JsonConfig.INTERNAL_REF_SIG + ":" + id.ToString("D", CultureInfo.InvariantCulture));
}
/// <summary>
/// Writes an <see cref="sbyte" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteSByte(string name, sbyte value)
{
this.WriteInt64(name, value);
}
/// <summary>
/// Writes a <see cref="short" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteInt16(string name, short value)
{
this.WriteInt64(name, value);
}
/// <summary>
/// Writes a <see cref="float" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteSingle(string name, float value)
{
this.WriteEntry(name, value.ToString("R", CultureInfo.InvariantCulture));
}
/// <summary>
/// Writes a <see cref="string" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteString(string name, string value)
{
this.StartNewLine();
if (name != null)
{
this.EnsureBufferSpace(name.Length + value.Length + 6);
this.buffer[this.bufferIndex++] = (byte)'"';
for (int i = 0; i < name.Length; i++)
{
this.buffer[this.bufferIndex++] = (byte)name[i];
}
this.buffer[this.bufferIndex++] = (byte)'"';
this.buffer[this.bufferIndex++] = (byte)':';
if (this.FormatAsReadable)
{
this.buffer[this.bufferIndex++] = (byte)' ';
}
}
else this.EnsureBufferSpace(value.Length + 2);
this.buffer[this.bufferIndex++] = (byte)'"';
this.Buffer_WriteString_WithEscape(value);
this.buffer[this.bufferIndex++] = (byte)'"';
}
/// <summary>
/// Writes a <see cref="Guid" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteGuid(string name, Guid value)
{
this.WriteEntry(name, value.ToString("D", CultureInfo.InvariantCulture));
}
/// <summary>
/// Writes an <see cref="uint" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteUInt32(string name, uint value)
{
this.WriteUInt64(name, value);
}
/// <summary>
/// Writes an <see cref="ulong" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteUInt64(string name, ulong value)
{
this.WriteEntry(name, value.ToString("D", CultureInfo.InvariantCulture));
}
/// <summary>
/// Writes an external index reference to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="index">The value to write.</param>
public override void WriteExternalReference(string name, int index)
{
this.WriteEntry(name, JsonConfig.EXTERNAL_INDEX_REF_SIG + ":" + index.ToString("D", CultureInfo.InvariantCulture));
}
/// <summary>
/// Writes an external guid reference to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="guid">The value to write.</param>
public override void WriteExternalReference(string name, Guid guid)
{
this.WriteEntry(name, JsonConfig.EXTERNAL_GUID_REF_SIG + ":" + guid.ToString("D", CultureInfo.InvariantCulture));
}
/// <summary>
/// Writes an external string reference to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="id">The value to write.</param>
public override void WriteExternalReference(string name, string id)
{
if (id == null)
{
throw new ArgumentNullException("id");
}
this.WriteEntry(name, JsonConfig.EXTERNAL_STRING_REF_SIG + ":" + id);
}
/// <summary>
/// Writes an <see cref="ushort" /> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
public override void WriteUInt16(string name, ushort value)
{
this.WriteUInt64(name, value);
}
/// <summary>
/// Disposes all resources kept by the data writer, except the stream, which can be reused later.
/// </summary>
public override void Dispose()
{
//this.writer.Dispose();
}
/// <summary>
/// Tells the writer that a new serialization session is about to begin, and that it should clear all cached values left over from any prior serialization sessions.
/// This method is only relevant when the same writer is used to serialize several different, unrelated values.
/// </summary>
public override void PrepareNewSerializationSession()
{
base.PrepareNewSerializationSession();
this.seenTypes.Clear();
this.justStarted = true;
}
public override string GetDataDump()
{
if (!this.Stream.CanRead)
{
return "Json data stream for writing cannot be read; cannot dump data.";
}
if (!this.Stream.CanSeek)
{
return "Json data stream cannot seek; cannot dump data.";
}
var oldPosition = this.Stream.Position;
var bytes = new byte[oldPosition];
this.Stream.Position = 0;
this.Stream.Read(bytes, 0, (int)oldPosition);
this.Stream.Position = oldPosition;
return "Json: " + Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
private void WriteEntry(string name, string contents)
{
this.StartNewLine();
if (name != null)
{
this.EnsureBufferSpace(name.Length + contents.Length + 4);
this.buffer[this.bufferIndex++] = (byte)'"';
for (int i = 0; i < name.Length; i++)
{
this.buffer[this.bufferIndex++] = (byte)name[i];
}
this.buffer[this.bufferIndex++] = (byte)'"';
this.buffer[this.bufferIndex++] = (byte)':';
if (this.FormatAsReadable)
{
this.buffer[this.bufferIndex++] = (byte)' ';
}
}
else this.EnsureBufferSpace(contents.Length);
for (int i = 0; i < contents.Length; i++)
{
this.buffer[this.bufferIndex++] = (byte)contents[i];
}
}
private void WriteEntry(string name, string contents, char surroundContentsWith)
{
this.StartNewLine();
if (name != null)
{
this.EnsureBufferSpace(name.Length + contents.Length + 6);
this.buffer[this.bufferIndex++] = (byte)'"';
for (int i = 0; i < name.Length; i++)
{
this.buffer[this.bufferIndex++] = (byte)name[i];
}
this.buffer[this.bufferIndex++] = (byte)'"';
this.buffer[this.bufferIndex++] = (byte)':';
if (this.FormatAsReadable)
{
this.buffer[this.bufferIndex++] = (byte)' ';
}
}
else this.EnsureBufferSpace(contents.Length + 2);
this.buffer[this.bufferIndex++] = (byte)surroundContentsWith;
for (int i = 0; i < contents.Length; i++)
{
this.buffer[this.bufferIndex++] = (byte)contents[i];
}
this.buffer[this.bufferIndex++] = (byte)surroundContentsWith;
}
private void WriteTypeEntry(Type type)
{
int id;
if (this.EnableTypeOptimization)
{
if (this.seenTypes.TryGetValue(type, out id))
{
this.WriteInt32(JsonConfig.TYPE_SIG, id);
}
else
{
id = this.seenTypes.Count;
this.seenTypes.Add(type, id);
this.WriteString(JsonConfig.TYPE_SIG, id + "|" + this.Context.Binder.BindToName(type, this.Context.Config.DebugContext));
}
}
else
{
this.WriteString(JsonConfig.TYPE_SIG, this.Context.Binder.BindToName(type, this.Context.Config.DebugContext));
}
}
private void StartNewLine(bool noSeparator = false)
{
if (this.justStarted)
{
this.justStarted = false;
return;
}
if (noSeparator == false && this.forceNoSeparatorNextLine == false)
{
this.EnsureBufferSpace(1);
this.buffer[this.bufferIndex++] = (byte)',';
}
this.forceNoSeparatorNextLine = false;
if (this.FormatAsReadable)
{
int count = this.NodeDepth * 4;
this.EnsureBufferSpace(NEW_LINE.Length + count);
for (int i = 0; i < NEW_LINE.Length; i++)
{
this.buffer[this.bufferIndex++] = (byte)NEW_LINE[i];
}
for (int i = 0; i < count; i++)
{
this.buffer[this.bufferIndex++] = (byte)' ';
}
}
}
private void EnsureBufferSpace(int space)
{
var length = this.buffer.Length;
if (space > length)
{
throw new Exception("Insufficient buffer capacity");
}
if (this.bufferIndex + space > length)
{
this.FlushToStream();
}
}
private void Buffer_WriteString_WithEscape(string str)
{
this.EnsureBufferSpace(str.Length);
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
if (c < 0 || c > 127)
{
// We're outside the "standard" character range - so we write the character as a hexadecimal value instead
// This ensures that we don't break the Json formatting.
this.EnsureBufferSpace((str.Length - i) + 6);
this.buffer[this.bufferIndex++] = (byte)'\\';
this.buffer[this.bufferIndex++] = (byte)'u';
var byte1 = c >> 8;
var byte2 = (byte)c;
var lookup = ByteToHexCharLookup[byte1];
this.buffer[this.bufferIndex++] = (byte)lookup;
this.buffer[this.bufferIndex++] = (byte)(lookup >> 16);
lookup = ByteToHexCharLookup[byte2];
this.buffer[this.bufferIndex++] = (byte)lookup;
this.buffer[this.bufferIndex++] = (byte)(lookup >> 16);
continue;
}
this.EnsureBufferSpace(2);
// Escape any characters that need to be escaped, default to no escape
switch (c)
{
case '"':
this.buffer[this.bufferIndex++] = (byte)'\\';
this.buffer[this.bufferIndex++] = (byte)'"';
break;
case '\\':
this.buffer[this.bufferIndex++] = (byte)'\\';
this.buffer[this.bufferIndex++] = (byte)'\\';
break;
case '\a':
this.buffer[this.bufferIndex++] = (byte)'\\';
this.buffer[this.bufferIndex++] = (byte)'a';
break;
case '\b':
this.buffer[this.bufferIndex++] = (byte)'\\';
this.buffer[this.bufferIndex++] = (byte)'b';
break;
case '\f':
this.buffer[this.bufferIndex++] = (byte)'\\';
this.buffer[this.bufferIndex++] = (byte)'f';
break;
case '\n':
this.buffer[this.bufferIndex++] = (byte)'\\';
this.buffer[this.bufferIndex++] = (byte)'n';
break;
case '\r':
this.buffer[this.bufferIndex++] = (byte)'\\';
this.buffer[this.bufferIndex++] = (byte)'r';
break;
case '\t':
this.buffer[this.bufferIndex++] = (byte)'\\';
this.buffer[this.bufferIndex++] = (byte)'t';
break;
case '\0':
this.buffer[this.bufferIndex++] = (byte)'\\';
this.buffer[this.bufferIndex++] = (byte)'0';
break;
default:
this.buffer[this.bufferIndex++] = (byte)c;
break;
}
}
}
private static uint[] CreateByteToHexLookup()
{
var result = new uint[256];
for (int i = 0; i < 256; i++)
{
string s = i.ToString("x2", CultureInfo.InvariantCulture);
result[i] = ((uint)s[0]) + ((uint)s[1] << 16);
}
return result;
}
}
} | 38.367156 | 190 | 0.529109 | [
"MIT"
] | JohnMurwin/NaturalSelectionSimulation | Assets/Plugins/TileWorldCreator/Code/TileWorldCreator.OdinSerializer/Core/DataReaderWriters/Json/JsonDataWriter.cs | 28,739 | C# |
using System.Linq;
using System.Web.Mvc;
using Unity.AspNet.Mvc;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(ZPO_Projekt.UnityMvcActivator), nameof(ZPO_Projekt.UnityMvcActivator.Start))]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(ZPO_Projekt.UnityMvcActivator), nameof(ZPO_Projekt.UnityMvcActivator.Shutdown))]
namespace ZPO_Projekt
{
/// <summary>
/// Provides the bootstrapping for integrating Unity with ASP.NET MVC.
/// </summary>
public static class UnityMvcActivator
{
/// <summary>
/// Integrates Unity when the application starts.
/// </summary>
public static void Start()
{
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(UnityConfig.Container));
DependencyResolver.SetResolver(new UnityDependencyResolver(UnityConfig.Container));
// TODO: Uncomment if you want to use PerRequestLifetimeManager
// Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
/// <summary>
/// Disposes the Unity container when the application is shut down.
/// </summary>
public static void Shutdown()
{
UnityConfig.Container.Dispose();
}
}
} | 38.342105 | 139 | 0.7035 | [
"MIT"
] | mskrzypecka/ZPO_Project | ZPO_Projekt/App_Start/UnityMvcActivator.cs | 1,457 | C# |
using System.IO;
namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{
public class NoexceptSpec : ParentNode
{
public NoexceptSpec(BaseNode child) : base(NodeType.NoexceptSpec, child) { }
public override void PrintLeft(TextWriter writer)
{
writer.Write("noexcept(");
Child.Print(writer);
writer.Write(")");
}
}
}
| 23.294118 | 84 | 0.606061 | [
"MIT"
] | 0MrDarn0/Ryujinx | Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NoexceptSpec.cs | 396 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using AutoMapper.Internal;
namespace AutoMapper
{
using AutoMapper.Extensions.ExpressionMapping;
using static Expression;
internal static class ExpressionExtensions
{
public static Expression MemberAccesses(this IEnumerable<MemberInfo> members, Expression obj) =>
members.Aggregate(obj, (expression, member) => MakeMemberAccess(expression, member));
public static IEnumerable<MemberExpression> GetMembers(this Expression expression)
{
var memberExpression = expression as MemberExpression;
if(memberExpression == null)
{
return new MemberExpression[0];
}
return memberExpression.GetMembers();
}
public static IEnumerable<MemberExpression> GetMembers(this MemberExpression expression)
{
while(expression != null)
{
yield return expression;
expression = expression.Expression as MemberExpression;
}
}
public static bool IsMemberPath(this LambdaExpression exp)
{
return exp.Body.GetMembers().LastOrDefault()?.Expression == exp.Parameters.First();
}
public static Expression ReplaceParameters(this LambdaExpression exp, params Expression[] replace)
=> ExpressionFactory.ReplaceParameters(exp, replace);
public static Expression ConvertReplaceParameters(this LambdaExpression exp, params Expression[] replace)
=> ExpressionFactory.ConvertReplaceParameters(exp, replace);
public static Expression Replace(this Expression exp, Expression old, Expression replace)
=> ExpressionFactory.Replace(exp, old, replace);
public static LambdaExpression Concat(this LambdaExpression expr, LambdaExpression concat)
=> ExpressionFactory.Concat(expr, concat);
public static Expression NullCheck(this Expression expression, Type destinationType)
=> ExpressionFactory.NullCheck(expression, destinationType);
public static Expression IfNullElse(this Expression expression, Expression then, Expression @else = null)
=> ExpressionFactory.IfNullElse(expression, then, @else);
}
internal static class ExpressionHelpers
{
public static MemberExpression MemberAccesses(string members, Expression obj) =>
(MemberExpression)GetMemberPath(obj.Type, members).MemberAccesses(obj);
public static IEnumerable<MemberInfo> GetMemberPath(Type type, string fullMemberName)
{
MemberInfo property = null;
foreach (var memberName in fullMemberName.Split('.'))
{
var currentType = GetCurrentType(property, type);
yield return property = currentType.GetFieldOrProperty(memberName);
}
}
private static Type GetCurrentType(MemberInfo member, Type type)
=> member?.GetMemberType() ?? type;
}
} | 39.56962 | 113 | 0.674664 | [
"MIT"
] | hasandogu/AutoMapper.Extensions.ExpressionMapping | src/AutoMapper.Extensions.ExpressionMapping/ExpressionExtensions.cs | 3,128 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rekognition-2016-06-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Rekognition.Model
{
/// <summary>
/// The dataset used for training.
/// </summary>
public partial class TrainingData
{
private List<Asset> _assets = new List<Asset>();
/// <summary>
/// Gets and sets the property Assets.
/// <para>
/// A Sagemaker GroundTruth manifest file that contains the training images (assets).
/// </para>
/// </summary>
public List<Asset> Assets
{
get { return this._assets; }
set { this._assets = value; }
}
// Check to see if Assets property is set
internal bool IsSetAssets()
{
return this._assets != null && this._assets.Count > 0;
}
}
} | 28.877193 | 109 | 0.647023 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Rekognition/Generated/Model/TrainingData.cs | 1,646 | C# |
using System.Threading.Tasks;
namespace Octokit
{
/// <summary>
/// A client for GitHub's Enterprise Organization API
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/enterprise/orgs/">Enterprise Organization API documentation</a> for more information.
///</remarks>
public interface IEnterpriseOrganizationClient
{
/// <summary>
/// Creates an Organization on a GitHub Enterprise appliance (must be Site Admin user).
/// </summary>
/// <remarks>
/// https://developer.github.com/v3/enterprise/orgs/#create-an-organization
/// </remarks>
/// <param name="newOrganization">A <see cref="NewOrganization"/> instance describing the organization to be created</param>
/// <returns>The <see cref="Organization"/> created.</returns>
Task<Organization> Create(NewOrganization newOrganization);
}
}
| 38.875 | 142 | 0.651661 | [
"MIT"
] | 3shape/octokit.net | Octokit/Clients/Enterprise/IEnterpriseOrganizationClient.cs | 935 | C# |
// <copyright file="BrowserStackAttribute.cs" company="Automate The Planet Ltd.">
// Copyright 2021 Automate The Planet Ltd.
// 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>
// <author>Anton Angelov</author>
// <site>https://bellatrix.solutions/</site>
using System;
using System.Drawing;
using System.Reflection;
using Bellatrix.Web.Enums;
using Bellatrix.Web.Plugins.Browser;
using Bellatrix.Web.Services;
namespace Bellatrix.Web
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class BrowserStackAttribute : BrowserAttribute, IDriverOptionsAttribute
{
public BrowserStackAttribute(
BrowserType browser,
string browserVersion,
string operatingSystem,
string osVersion,
Lifecycle behavior = Lifecycle.NotSet,
bool captureVideo = false,
bool captureNetworkLogs = false,
BrowserStackConsoleLogType consoleLogType = BrowserStackConsoleLogType.Disable,
bool debug = false,
string build = null,
bool shouldAutomaticallyScrollToVisible = true)
: base(browser, behavior, shouldAutomaticallyScrollToVisible)
{
BrowserVersion = browserVersion;
OperatingSystem = operatingSystem;
OSVersion = osVersion;
Debug = debug;
Build = build;
CaptureVideo = captureVideo;
CaptureNetworkLogs = captureNetworkLogs;
ConsoleLogType = consoleLogType;
ExecutionType = ExecutionType.BrowserStack;
}
public BrowserStackAttribute(
BrowserType browser,
string browserVersion,
string operatingSystem,
string osVersion,
int width,
int height,
Lifecycle behavior = Lifecycle.NotSet,
bool captureVideo = false,
bool captureNetworkLogs = false,
BrowserStackConsoleLogType consoleLogType = BrowserStackConsoleLogType.Disable,
bool debug = false,
string build = null,
bool shouldAutomaticallyScrollToVisible = true)
: base(browser, width, height, behavior, shouldAutomaticallyScrollToVisible)
{
BrowserVersion = browserVersion;
OperatingSystem = operatingSystem;
OSVersion = osVersion;
Debug = debug;
Build = build;
CaptureVideo = captureVideo;
CaptureNetworkLogs = captureNetworkLogs;
ConsoleLogType = consoleLogType;
ExecutionType = ExecutionType.BrowserStack;
ScreenResolution = new Size(width, height).ConvertToString();
}
public BrowserStackAttribute(
BrowserType browser,
string browserVersion,
string operatingSystem,
string osVersion,
MobileWindowSize mobileWindowSize,
Lifecycle behavior = Lifecycle.NotSet,
bool captureVideo = false,
bool captureNetworkLogs = false,
BrowserStackConsoleLogType browserStackConsoleLogType = BrowserStackConsoleLogType.Disable,
bool debug = false,
string build = null,
bool shouldAutomaticallyScrollToVisible = true)
: this(browser, browserVersion, operatingSystem, osVersion, behavior, captureVideo, captureNetworkLogs, browserStackConsoleLogType, debug, build, shouldAutomaticallyScrollToVisible)
=> ScreenResolution = WindowsSizeResolver.GetWindowSize(mobileWindowSize).ConvertToString();
public BrowserStackAttribute(
BrowserType browser,
string browserVersion,
string operatingSystem,
string osVersion,
TabletWindowSize tabletWindowSize,
Lifecycle behavior = Lifecycle.NotSet,
bool captureVideo = false,
bool captureNetworkLogs = false,
BrowserStackConsoleLogType browserStackConsoleLogType = BrowserStackConsoleLogType.Disable,
bool debug = false,
string build = null)
: this(browser, browserVersion, operatingSystem, osVersion, behavior, captureVideo, captureNetworkLogs, browserStackConsoleLogType, debug, build)
=> ScreenResolution = WindowsSizeResolver.GetWindowSize(tabletWindowSize).ConvertToString();
public BrowserStackAttribute(
BrowserType browser,
string browserVersion,
string operatingSystem,
string osVersion,
DesktopWindowSize desktopWindowSize,
Lifecycle behavior = Lifecycle.NotSet,
bool captureVideo = false,
bool captureNetworkLogs = false,
BrowserStackConsoleLogType browserStackConsoleLogType = BrowserStackConsoleLogType.Disable,
bool debug = false,
string build = null,
bool shouldAutomaticallyScrollToVisible = true)
: this(browser, browserVersion, operatingSystem, osVersion, behavior, captureVideo, captureNetworkLogs, browserStackConsoleLogType, debug, build, shouldAutomaticallyScrollToVisible)
=> ScreenResolution = WindowsSizeResolver.GetWindowSize(desktopWindowSize).ConvertToString();
public bool Debug { get; }
public string Build { get; }
public string BrowserVersion { get; }
public string OperatingSystem { get; }
public string OSVersion { get; }
public bool CaptureVideo { get; }
public bool CaptureNetworkLogs { get; }
public BrowserStackConsoleLogType ConsoleLogType { get; }
public string ScreenResolution { get; set; }
public dynamic CreateOptions(MemberInfo memberInfo, Type testClassType)
{
var driverOptions = GetDriverOptionsBasedOnBrowser(testClassType);
AddAdditionalCapabilities(testClassType, driverOptions);
driverOptions.Add("browserstack.debug", Debug);
if (!string.IsNullOrEmpty(Build))
{
driverOptions.SetCapability("build", Build);
}
string browserName = Enum.GetName(typeof(BrowserType), Browser);
driverOptions.AddAdditionalCapability("browser", browserName);
driverOptions.AddAdditionalCapability("os", OperatingSystem);
driverOptions.AddAdditionalCapability("os_version", OSVersion);
driverOptions.AddAdditionalCapability("browser_version", BrowserVersion);
driverOptions.AddAdditionalCapability("resolution", ScreenResolution);
driverOptions.AddAdditionalCapability("browserstack.video", CaptureVideo);
driverOptions.AddAdditionalCapability("browserstack.networkLogs", CaptureNetworkLogs);
string consoleLogTypeText = Enum.GetName(typeof(BrowserStackConsoleLogType), ConsoleLogType).ToLower();
driverOptions.AddAdditionalCapability("browserstack.console", consoleLogTypeText);
var credentials = CloudProviderCredentialsResolver.GetCredentials();
driverOptions.AddAdditionalCapability("browserstack.user", credentials.Item1);
driverOptions.AddAdditionalCapability("browserstack.key", credentials.Item2);
return driverOptions;
}
}
} | 44.977011 | 193 | 0.672502 | [
"Apache-2.0"
] | TRabinVerisoft/BELLATRIX | src/Bellatrix.Web/plugins/execution/Attributes/BrowserStackAttribute.cs | 7,828 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PhysicsSpawner : MonoBehaviour {
public GameObject cubePrefab;
public GameObject tank;
// Use this for initialization
void CreateWall(int width, int height)
{
int halfw = width / 2;
float gap = 1.5f;
for (int row = 0; row < height; row++)
{
for (int col = -halfw; col < halfw; col++)
{
GameObject cube = GameObject.Instantiate<GameObject>(cubePrefab);
float x = col * gap;
float y = 0.5f + (row * gap);
cube.transform.position = tank.transform.TransformPoint(new Vector3(x, y, 5));
cube.GetComponent<Renderer>().material.color = Color.HSVToRGB(Random.Range(0.0f, 1.0f), 1, 0.8f);
}
}
}
void Start () {
CreateWall(10, 10);
}
// Update is called once per frame
void Update () {
}
}
| 27.611111 | 114 | 0.554326 | [
"MIT"
] | Stephen2697/OOP-2017-2018 | Unity/UnityIdioms/Assets/PhysicsSpawner.cs | 996 | C# |
namespace EA.Iws.RequestHandlers.Tests.Unit.Admin.FinancialGuarantee
{
using System;
using System.Threading.Tasks;
using Domain.FinancialGuarantee;
using FakeItEasy;
using RequestHandlers.Admin.FinancialGuarantee;
using Requests.Admin.FinancialGuarantee;
using Xunit;
public class RefuseFinancialGuaranteeHandlerTests : FinancialGuaranteeDecisionTests
{
private readonly RefuseFinancialGuaranteeHandler handler;
private readonly TestFinancialGuarantee financialGuarantee;
private readonly RefuseFinancialGuarantee refuseFinancialGuarantee =
new RefuseFinancialGuarantee(ApplicationCompletedId, FinancialGuaranteeId, FirstDate, "test");
private readonly IFinancialGuaranteeRepository repository;
public RefuseFinancialGuaranteeHandlerTests()
{
context = new TestIwsContext();
repository = A.Fake<IFinancialGuaranteeRepository>();
var financialGuaranteeCollection = new TestFinancialGuaranteeCollection(ApplicationCompletedId);
financialGuarantee = new TestFinancialGuarantee(FinancialGuaranteeId);
financialGuaranteeCollection.AddExistingFinancialGuarantee(financialGuarantee);
A.CallTo(() => repository.GetByNotificationId(ApplicationCompletedId)).Returns(financialGuaranteeCollection);
handler = new RefuseFinancialGuaranteeHandler(repository, context);
}
[Fact]
public async Task NotificationDoesNotExist_Throws()
{
await
Assert.ThrowsAsync<InvalidOperationException>(
() =>
handler.HandleAsync(new RefuseFinancialGuarantee(Guid.Empty, Guid.Empty, FirstDate, "test")));
}
[Fact]
public async Task Saves()
{
await
handler.HandleAsync(refuseFinancialGuarantee);
Assert.Equal(1, ((TestIwsContext)context).SaveChangesCount);
}
[Fact]
public async Task CallsRefuse()
{
await
handler.HandleAsync(refuseFinancialGuarantee);
Assert.True(financialGuarantee.RefuseCalled);
}
[Fact]
public async Task RefuseThrows_Propagates()
{
financialGuarantee.RejectThrows = true;
await
Assert.ThrowsAsync<InvalidOperationException>(() => handler.HandleAsync(refuseFinancialGuarantee));
}
}
}
| 35.183099 | 121 | 0.671337 | [
"Unlicense"
] | DEFRA/prsd-iws | src/EA.Iws.RequestHandlers.Tests.Unit/Admin/FinancialGuarantee/RefuseFinancialGuaranteeHandlerTests.cs | 2,500 | C# |
using System.Security.Authentication;
using ReactiveXComponent.Common;
namespace ReactiveXComponent.Configuration
{
public class ConfigurationOverrides
{
public string Host { get; set; }
public string VirtualHost { get; set; }
public string Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public WebSocketType? WebSocketType { get; set; }
public bool? SslEnabled { get; set; }
public string SslServerName { get; set; }
public string SslCertificatePath { get; set; }
public string SslCertificatePassphrase { get; set; }
public SslProtocols? SslProtocol { get; set; }
public bool? SslAllowUntrustedServerCertificate { get; set; }
}
}
| 24.181818 | 69 | 0.649123 | [
"Apache-2.0"
] | xcomponent/ReactiveXComponent.Net | ReactiveXComponent/Configuration/ConfigurationOverrides.cs | 800 | C# |
using System;
using System.IO;
using System.Runtime.CompilerServices;
namespace Datadog.Logging.Emission
{
internal struct LogSourceInfo
{
private static string s_assemblyName = null;
public string LogSourceNamePart1 { get; }
public string LogSourceNamePart2 { get; }
public int CallLineNumber { get; }
public string CallMemberName { get; }
public string CallFileName { get; }
public string AssemblyName { get; }
public LogSourceInfo(string logSourceName)
: this(logSourceNamePart1: null, logSourceNamePart2: logSourceName, callLineNumber: 0, callMemberName: null, callFileName: null, assemblyName: null)
{ }
public LogSourceInfo(string logSourceNamePart1, string logSourceNamePart2, int callLineNumber, string callMemberName, string callFileName, string assemblyName)
{
LogSourceNamePart1 = logSourceNamePart1;
LogSourceNamePart2 = logSourceNamePart2;
CallLineNumber = callLineNumber;
CallMemberName = callMemberName;
CallFileName = callFileName;
AssemblyName = assemblyName;
}
public LogSourceInfo WithCallInfo([CallerLineNumber] int callLineNumber = 0, [CallerMemberName] string callMemberName = null)
{
return new LogSourceInfo(LogSourceNamePart1, LogSourceNamePart2, callLineNumber, callMemberName, callFileName: null, AssemblyName);
}
public LogSourceInfo WithSrcFileInfo([CallerLineNumber] int callLineNumber = 0,
[CallerMemberName] string callMemberName = null,
[CallerFilePath] string callFilePath = null)
{
string callFileName = null;
if (callFilePath != null)
{
try
{
callFileName = Path.GetFileName(callFilePath);
}
catch
{
callFileName = null;
}
}
return new LogSourceInfo(LogSourceNamePart1, LogSourceNamePart2, callLineNumber, callMemberName, callFileName, AssemblyName);
}
public LogSourceInfo WithAssemblyName()
{
string assemblyName = GetAssemblyName();
return new LogSourceInfo(LogSourceNamePart1, LogSourceNamePart2, CallLineNumber, CallMemberName, CallFileName, assemblyName);
}
public LogSourceInfo WithinLogSourcesGroup(string superGroupName)
{
if (superGroupName == null)
{
return this;
}
if (LogSourceNamePart1 == null && LogSourceNamePart2 == null)
{
return WithLogSourcesName(null, superGroupName);
}
if (LogSourceNamePart1 == null && LogSourceNamePart2 != null)
{
return WithLogSourcesName(superGroupName, LogSourceNamePart2);
}
if (LogSourceNamePart1 != null && LogSourceNamePart2 == null)
{
return WithLogSourcesName(superGroupName, LogSourceNamePart1);
}
// Must be (LogSourceNamePart1 != null && LogSourceNamePart2 != null)
return WithLogSourcesName(superGroupName, DefaultFormat.LogSourceInfo.MergeNames(LogSourceNamePart1, LogSourceNamePart2));
}
public LogSourceInfo WithLogSourcesSubgroup(string subGroupName)
{
if (subGroupName == null)
{
return this;
}
if (LogSourceNamePart1 == null && LogSourceNamePart2 == null)
{
return WithLogSourcesName(null, subGroupName);
}
if (LogSourceNamePart1 == null && LogSourceNamePart2 != null)
{
return WithLogSourcesName(LogSourceNamePart2, subGroupName);
}
if (LogSourceNamePart1 != null && LogSourceNamePart2 == null)
{
return WithLogSourcesName(LogSourceNamePart1, subGroupName);
}
// Must be (LogSourceNamePart1 != null && LogSourceNamePart2 != null)
return WithLogSourcesName(DefaultFormat.LogSourceInfo.MergeNames(LogSourceNamePart1, LogSourceNamePart2), subGroupName);
}
private LogSourceInfo WithLogSourcesName(string logSourceNamePart1, string logSourceNamePart2)
{
return new LogSourceInfo(logSourceNamePart1, logSourceNamePart2, CallLineNumber, CallMemberName, CallFileName, AssemblyName);
}
private string GetAssemblyName()
{
string assemblyName = s_assemblyName;
if (assemblyName == null)
{
try
{
assemblyName = this.GetType().Assembly?.FullName;
}
catch
{
assemblyName = null;
}
s_assemblyName = assemblyName; // benign race
}
return assemblyName;
}
}
}
| 35.916084 | 167 | 0.588396 | [
"Apache-2.0"
] | DataDog/dd-trace-dotnet | shared/src/managed-src/Datadog.Logging.Emission/internal/LogSourceInfo.cs | 5,136 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Http;
namespace CadeMeuMedico
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
} | 26.73913 | 70 | 0.687805 | [
"MIT"
] | makampos/Aplicacao_mvc | CadeMeuMedico/Global.asax.cs | 617 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Collections.ObjectModel;
namespace Microsoft.Scripting.Utils {
/// <summary>
/// Caches type member lookup.
/// </summary>
/// <remarks>
/// When enumerating members (methods, properties, events) of a type (declared or inherited) Reflection enumerates all
/// runtime members of the type and its base types and caches the result.
/// When looking for a member of a specific name Reflection still enumerates all and filters out those that don't match the name.
/// That's inefficient when looking for members of multiple names one by one.
/// Instead we build a map of name to member list and then answer subsequent queries by simply looking up the dictionary.
/// </remarks>
public sealed class TypeMemberCache<T>
where T : MemberInfo {
// TODO: some memory can be saved here
// { queried-type -> immutable { member-name, members } }
private readonly ConditionalWeakTable<Type, Dictionary<string, List<T>>> _typeMembersByName =
new ConditionalWeakTable<Type, Dictionary<string, List<T>>>();
private Dictionary<string, List<T>> GetMembers(Type type) {
return _typeMembersByName.GetValue(type, t => ReflectMembers(t));
}
private readonly Func<Type, IEnumerable<T>> _reflector;
public TypeMemberCache(Func<Type, IEnumerable<T>> reflector) {
_reflector = reflector;
}
public IEnumerable<T> GetMembers(Type type, string name = null, bool inherited = false) {
var membersByName = GetMembers(type);
if (name == null) {
var allMembers = membersByName.Values.SelectMany(memberList => memberList);
if (inherited) {
return allMembers;
}
return allMembers.Where(overload => overload.DeclaringType == type);
}
if (!membersByName.TryGetValue(name, out List<T> inheritedOverloads)) {
return Enumerable.Empty<T>();
}
if (inherited) {
return new ReadOnlyCollection<T>(inheritedOverloads);
}
return inheritedOverloads.Where(overload => overload.DeclaringType == type);
}
private Dictionary<string, List<T>> ReflectMembers(Type type) {
var result = new Dictionary<string, List<T>>();
foreach (T member in _reflector(type)) {
List<T> overloads;
if (!result.TryGetValue(member.Name, out overloads)) {
result.Add(member.Name, overloads = new List<T>());
}
overloads.Add(member);
}
foreach (var list in result.Values) {
list.TrimExcess();
}
return result;
}
}
}
| 37.3125 | 133 | 0.60603 | [
"Apache-2.0"
] | ufuomaoritsemone/ironpPython1 | Src/Microsoft.Dynamic/Utils/TypeMemberCache.cs | 2,987 | 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 webcam_preview.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.7.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 39.592593 | 151 | 0.582788 | [
"MIT"
] | visioforge/.Net-SDK-s-samples | Video Capture SDK/_CodeSnippets/webcam-preview/Properties/Settings.Designer.cs | 1,071 | C# |
#if !NOT_UNITY3D
namespace Zenject
{
// For some platforms, it's desirable to be able to add dependencies to Zenject before
// Unity even starts up (eg. WSA as described here https://github.com/modesttree/Zenject/issues/118)
// In those cases you can call StaticContext.Container.BindX to add dependencies
// Anything you add there will then be injected everywhere, since all other contexts
// should be children of StaticContext
public static class StaticContext
{
static DiContainer _container;
// Useful sometimes to call from play mode tests
public static void Clear()
{
_container = null;
}
public static bool HasContainer
{
get { return _container != null; }
}
public static DiContainer Container
{
get
{
if (_container == null)
{
_container = new DiContainer();
}
return _container;
}
}
}
}
#endif
| 26.219512 | 104 | 0.573023 | [
"MIT"
] | AdJion/Zenject | UnityProject/Assets/Plugins/Zenject/Source/Install/Contexts/StaticContext.cs | 1,075 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DocumentDB.V20200601Preview.Outputs
{
[OutputType]
public sealed class TableGetPropertiesResponseOptions
{
/// <summary>
/// Specifies the Autoscale settings.
/// </summary>
public readonly Outputs.AutoscaleSettingsResponse? AutoscaleSettings;
/// <summary>
/// Value of the Cosmos DB resource throughput or autoscaleSettings. Use the ThroughputSetting resource when retrieving offer details.
/// </summary>
public readonly int? Throughput;
[OutputConstructor]
private TableGetPropertiesResponseOptions(
Outputs.AutoscaleSettingsResponse? autoscaleSettings,
int? throughput)
{
AutoscaleSettings = autoscaleSettings;
Throughput = throughput;
}
}
}
| 31.638889 | 142 | 0.682177 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DocumentDB/V20200601Preview/Outputs/TableGetPropertiesResponseOptions.cs | 1,139 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// As informações gerais sobre um assembly são controladas por
// conjunto de atributos. Altere estes valores de atributo para modificar as informações
// associadas a um assembly.
[assembly: AssemblyTitle("6ExercicioDesvioCondicional")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("6ExercicioDesvioCondicional")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Definir ComVisible como false torna os tipos neste assembly invisíveis
// para componentes COM. Caso precise acessar um tipo neste assembly de
// COM, defina o atributo ComVisible como true nesse tipo.
[assembly: ComVisible(false)]
// O GUID a seguir será destinado à ID de typelib se este projeto for exposto para COM
[assembly: Guid("1b7b68ef-639f-48d8-8a62-225e4c61b5ca")]
// As informações da versão de um assembly consistem nos quatro valores a seguir:
//
// Versão Principal
// Versão Secundária
// Número da Versão
// Revisão
//
// É possível especificar todos os valores ou usar como padrão os Números de Build e da Revisão
// usando o "*" como mostrado abaixo:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39 | 95 | 0.758143 | [
"MIT"
] | danielspositocoelho/DS-EtecAlbertEinstein-Programacao_e_Algoritmos | Condicionais/6ExercicioDesvioCondicional/Properties/AssemblyInfo.cs | 1,468 | C# |
using System;
using System.IO;
using System.Collections;
#if FEAT_IKVM
using Type = IKVM.Reflection.Type;
using IKVM.Reflection;
#else
using System.Reflection;
#endif
namespace ProtoBuf.Meta
{
/// <summary>
/// Provides protobuf serialization support for a number of types
/// </summary>
public abstract class TypeModel
{
#if WINRT || COREFX
internal TypeInfo MapType(TypeInfo type)
{
return type;
}
#endif
/// <summary>
/// Should the <c>Kind</c> be included on date/time values?
/// </summary>
protected internal virtual bool SerializeDateTimeKind() { return false; }
/// <summary>
/// Resolve a System.Type to the compiler-specific type
/// </summary>
protected internal Type MapType(System.Type type)
{
return MapType(type, true);
}
/// <summary>
/// Resolve a System.Type to the compiler-specific type
/// </summary>
protected internal virtual Type MapType(System.Type type, bool demand)
{
#if FEAT_IKVM
throw new NotImplementedException(); // this should come from RuntimeTypeModel!
#else
return type;
#endif
}
private WireType GetWireType(ProtoTypeCode code, DataFormat format, ref Type type, out int modelKey)
{
modelKey = -1;
if (Helpers.IsEnum(type))
{
modelKey = GetKey(ref type);
return WireType.Variant;
}
switch (code)
{
case ProtoTypeCode.Int64:
case ProtoTypeCode.UInt64:
return format == DataFormat.FixedSize ? WireType.Fixed64 : WireType.Variant;
case ProtoTypeCode.Int16:
case ProtoTypeCode.Int32:
case ProtoTypeCode.UInt16:
case ProtoTypeCode.UInt32:
case ProtoTypeCode.Boolean:
case ProtoTypeCode.SByte:
case ProtoTypeCode.Byte:
case ProtoTypeCode.Char:
return format == DataFormat.FixedSize ? WireType.Fixed32 : WireType.Variant;
case ProtoTypeCode.Double:
return WireType.Fixed64;
case ProtoTypeCode.Single:
return WireType.Fixed32;
case ProtoTypeCode.String:
case ProtoTypeCode.DateTime:
case ProtoTypeCode.Decimal:
case ProtoTypeCode.ByteArray:
case ProtoTypeCode.TimeSpan:
case ProtoTypeCode.Guid:
case ProtoTypeCode.Uri:
return WireType.String;
}
if ((modelKey = GetKey(ref type)) >= 0)
{
return WireType.String;
}
return WireType.None;
}
#if !FEAT_IKVM
/// <summary>
/// This is the more "complete" version of Serialize, which handles single instances of mapped types.
/// The value is written as a complete field, including field-header and (for sub-objects) a
/// length-prefix
/// In addition to that, this provides support for:
/// - basic values; individual int / string / Guid / etc
/// - IEnumerable sequences of any type handled by TrySerializeAuxiliaryType
///
/// </summary>
internal bool TrySerializeAuxiliaryType(ProtoWriter writer, Type type, DataFormat format, int tag, object value, bool isInsideList)
{
if (type == null) { type = value.GetType(); }
ProtoTypeCode typecode = Helpers.GetTypeCode(type);
int modelKey;
// note the "ref type" here normalizes against proxies
WireType wireType = GetWireType(typecode, format, ref type, out modelKey);
if (modelKey >= 0)
{ // write the header, but defer to the model
if (Helpers.IsEnum(type))
{ // no header
Serialize(modelKey, value, writer);
return true;
}
else
{
ProtoWriter.WriteFieldHeader(tag, wireType, writer);
switch (wireType)
{
case WireType.None:
throw ProtoWriter.CreateException(writer);
case WireType.StartGroup:
case WireType.String:
// needs a wrapping length etc
SubItemToken token = ProtoWriter.StartSubItem(value, writer);
Serialize(modelKey, value, writer);
ProtoWriter.EndSubItem(token, writer);
return true;
default:
Serialize(modelKey, value, writer);
return true;
}
}
}
if(wireType != WireType.None) {
ProtoWriter.WriteFieldHeader(tag, wireType, writer);
}
switch(typecode) {
case ProtoTypeCode.Int16: ProtoWriter.WriteInt16((short)value, writer); return true;
case ProtoTypeCode.Int32: ProtoWriter.WriteInt32((int)value, writer); return true;
case ProtoTypeCode.Int64: ProtoWriter.WriteInt64((long)value, writer); return true;
case ProtoTypeCode.UInt16: ProtoWriter.WriteUInt16((ushort)value, writer); return true;
case ProtoTypeCode.UInt32: ProtoWriter.WriteUInt32((uint)value, writer); return true;
case ProtoTypeCode.UInt64: ProtoWriter.WriteUInt64((ulong)value, writer); return true;
case ProtoTypeCode.Boolean: ProtoWriter.WriteBoolean((bool)value, writer); return true;
case ProtoTypeCode.SByte: ProtoWriter.WriteSByte((sbyte)value, writer); return true;
case ProtoTypeCode.Byte: ProtoWriter.WriteByte((byte)value, writer); return true;
case ProtoTypeCode.Char: ProtoWriter.WriteUInt16((ushort)(char)value, writer); return true;
case ProtoTypeCode.Double: ProtoWriter.WriteDouble((double)value, writer); return true;
case ProtoTypeCode.Single: ProtoWriter.WriteSingle((float)value, writer); return true;
case ProtoTypeCode.DateTime:
if (SerializeDateTimeKind())
BclHelpers.WriteDateTimeWithKind((DateTime)value, writer);
else
BclHelpers.WriteDateTime((DateTime)value, writer);
return true;
case ProtoTypeCode.Decimal: BclHelpers.WriteDecimal((decimal)value, writer); return true;
case ProtoTypeCode.String: ProtoWriter.WriteString((string)value, writer); return true;
case ProtoTypeCode.ByteArray: ProtoWriter.WriteBytes((byte[])value, writer); return true;
case ProtoTypeCode.TimeSpan: BclHelpers.WriteTimeSpan((TimeSpan)value, writer); return true;
case ProtoTypeCode.Guid: BclHelpers.WriteGuid((Guid)value, writer); return true;
case ProtoTypeCode.Uri: ProtoWriter.WriteString(((Uri)value).AbsoluteUri, writer); return true;
}
// by now, we should have covered all the simple cases; if we wrote a field-header, we have
// forgotten something!
Helpers.DebugAssert(wireType == WireType.None);
// now attempt to handle sequences (including arrays and lists)
IEnumerable sequence = value as IEnumerable;
if (sequence != null)
{
if (isInsideList) throw CreateNestedListsNotSupported();
foreach (object item in sequence) {
if (item == null) { throw new NullReferenceException(); }
if (!TrySerializeAuxiliaryType(writer, null, format, tag, item, true))
{
ThrowUnexpectedType(item.GetType());
}
}
return true;
}
return false;
}
private void SerializeCore(ProtoWriter writer, object value)
{
if (value == null) throw new ArgumentNullException("value");
Type type = value.GetType();
int key = GetKey(ref type);
if (key >= 0)
{
Serialize(key, value, writer);
}
else if (!TrySerializeAuxiliaryType(writer, type, DataFormat.Default, Serializer.ListItemTag, value, false))
{
ThrowUnexpectedType(type);
}
}
#endif
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream.
/// </summary>
/// <param name="value">The existing instance to be serialized (cannot be null).</param>
/// <param name="dest">The destination stream to write to.</param>
public void Serialize(Stream dest, object value)
{
Serialize(dest, value, null);
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream.
/// </summary>
/// <param name="value">The existing instance to be serialized (cannot be null).</param>
/// <param name="dest">The destination stream to write to.</param>
/// <param name="context">Additional information about this serialization operation.</param>
public void Serialize(Stream dest, object value, SerializationContext context)
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
using (ProtoWriter writer = new ProtoWriter(dest, this, context))
{
writer.SetRootObject(value);
SerializeCore(writer, value);
writer.Close();
}
#endif
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied writer.
/// </summary>
/// <param name="value">The existing instance to be serialized (cannot be null).</param>
/// <param name="dest">The destination writer to write to.</param>
public void Serialize(ProtoWriter dest, object value)
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
if (dest == null) throw new ArgumentNullException("dest");
dest.CheckDepthFlushlock();
dest.SetRootObject(value);
SerializeCore(dest, value);
dest.CheckDepthFlushlock();
ProtoWriter.Flush(dest);
#endif
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed
/// data - useful with network IO.
/// </summary>
/// <param name="type">The type being merged.</param>
/// <param name="value">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int fieldNumber)
{
int bytesRead;
return DeserializeWithLengthPrefix(source, value, type, style, fieldNumber, null, out bytesRead);
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed
/// data - useful with network IO.
/// </summary>
/// <param name="type">The type being merged.</param>
/// <param name="value">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="expectedField">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
/// <param name="resolver">Used to resolve types on a per-field basis.</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver)
{
int bytesRead;
return DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out bytesRead);
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed
/// data - useful with network IO.
/// </summary>
/// <param name="type">The type being merged.</param>
/// <param name="value">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="expectedField">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
/// <param name="resolver">Used to resolve types on a per-field basis.</param>
/// <param name="bytesRead">Returns the number of bytes consumed by this operation (includes length-prefix overheads and any skipped data).</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out int bytesRead)
{
bool haveObject;
return DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out bytesRead, out haveObject, null);
}
private object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out int bytesRead, out bool haveObject, SerializationContext context)
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
haveObject = false;
bool skip;
int len;
int tmpBytesRead;
bytesRead = 0;
if (type == null && (style != PrefixStyle.Base128 || resolver == null))
{
throw new InvalidOperationException("A type must be provided unless base-128 prefixing is being used in combination with a resolver");
}
int actualField;
do
{
bool expectPrefix = expectedField > 0 || resolver != null;
len = ProtoReader.ReadLengthPrefix(source, expectPrefix, style, out actualField, out tmpBytesRead);
if (tmpBytesRead == 0) return value;
bytesRead += tmpBytesRead;
if (len < 0) return value;
switch (style)
{
case PrefixStyle.Base128:
if (expectPrefix && expectedField == 0 && type == null && resolver != null)
{
type = resolver(actualField);
skip = type == null;
}
else { skip = expectedField != actualField; }
break;
default:
skip = false;
break;
}
if (skip)
{
if (len == int.MaxValue) throw new InvalidOperationException();
ProtoReader.Seek(source, len, null);
bytesRead += len;
}
} while (skip);
ProtoReader reader = null;
try
{
reader = ProtoReader.Create(source, this, context, len);
int key = GetKey(ref type);
if (key >= 0 && !Helpers.IsEnum(type))
{
value = Deserialize(key, value, reader);
}
else
{
if (!(TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false) || len == 0))
{
TypeModel.ThrowUnexpectedType(type); // throws
}
}
bytesRead += reader.Position;
haveObject = true;
return value;
}
finally
{
ProtoReader.Recycle(reader);
}
#endif
}
/// <summary>
/// Reads a sequence of consecutive length-prefixed items from a stream, using
/// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag
/// are directly comparable to serializing multiple items in succession
/// (use the <see cref="Serializer.ListItemTag"/> tag to emulate the implicit behavior
/// when serializing a list/array). When a tag is
/// specified, any records with different tags are silently omitted. The
/// tag is ignored. The tag is ignores for fixed-length prefixes.
/// </summary>
/// <param name="source">The binary stream containing the serialized records.</param>
/// <param name="style">The prefix style used in the data.</param>
/// <param name="expectedField">The tag of records to return (if non-positive, then no tag is
/// expected and all records are returned).</param>
/// <param name="resolver">On a field-by-field basis, the type of object to deserialize (can be null if "type" is specified). </param>
/// <param name="type">The type of object to deserialize (can be null if "resolver" is specified).</param>
/// <returns>The sequence of deserialized objects.</returns>
public System.Collections.IEnumerable DeserializeItems(System.IO.Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver)
{
return DeserializeItems(source, type, style, expectedField, resolver, null);
}
/// <summary>
/// Reads a sequence of consecutive length-prefixed items from a stream, using
/// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag
/// are directly comparable to serializing multiple items in succession
/// (use the <see cref="Serializer.ListItemTag"/> tag to emulate the implicit behavior
/// when serializing a list/array). When a tag is
/// specified, any records with different tags are silently omitted. The
/// tag is ignored. The tag is ignores for fixed-length prefixes.
/// </summary>
/// <param name="source">The binary stream containing the serialized records.</param>
/// <param name="style">The prefix style used in the data.</param>
/// <param name="expectedField">The tag of records to return (if non-positive, then no tag is
/// expected and all records are returned).</param>
/// <param name="resolver">On a field-by-field basis, the type of object to deserialize (can be null if "type" is specified). </param>
/// <param name="type">The type of object to deserialize (can be null if "resolver" is specified).</param>
/// <returns>The sequence of deserialized objects.</returns>
/// <param name="context">Additional information about this serialization operation.</param>
public System.Collections.IEnumerable DeserializeItems(System.IO.Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, SerializationContext context)
{
return new DeserializeItemsIterator(this, source, type, style, expectedField, resolver, context);
}
#if !NO_GENERICS
/// <summary>
/// Reads a sequence of consecutive length-prefixed items from a stream, using
/// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag
/// are directly comparable to serializing multiple items in succession
/// (use the <see cref="Serializer.ListItemTag"/> tag to emulate the implicit behavior
/// when serializing a list/array). When a tag is
/// specified, any records with different tags are silently omitted. The
/// tag is ignored. The tag is ignores for fixed-length prefixes.
/// </summary>
/// <typeparam name="T">The type of object to deserialize.</typeparam>
/// <param name="source">The binary stream containing the serialized records.</param>
/// <param name="style">The prefix style used in the data.</param>
/// <param name="expectedField">The tag of records to return (if non-positive, then no tag is
/// expected and all records are returned).</param>
/// <returns>The sequence of deserialized objects.</returns>
public System.Collections.Generic.IEnumerable<T> DeserializeItems<T>(Stream source, PrefixStyle style, int expectedField)
{
return DeserializeItems<T>(source, style, expectedField, null);
}
/// <summary>
/// Reads a sequence of consecutive length-prefixed items from a stream, using
/// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag
/// are directly comparable to serializing multiple items in succession
/// (use the <see cref="Serializer.ListItemTag"/> tag to emulate the implicit behavior
/// when serializing a list/array). When a tag is
/// specified, any records with different tags are silently omitted. The
/// tag is ignored. The tag is ignores for fixed-length prefixes.
/// </summary>
/// <typeparam name="T">The type of object to deserialize.</typeparam>
/// <param name="source">The binary stream containing the serialized records.</param>
/// <param name="style">The prefix style used in the data.</param>
/// <param name="expectedField">The tag of records to return (if non-positive, then no tag is
/// expected and all records are returned).</param>
/// <returns>The sequence of deserialized objects.</returns>
/// <param name="context">Additional information about this serialization operation.</param>
public System.Collections.Generic.IEnumerable<T> DeserializeItems<T>(Stream source, PrefixStyle style, int expectedField, SerializationContext context)
{
return new DeserializeItemsIterator<T>(this, source, style, expectedField, context);
}
private sealed class DeserializeItemsIterator<T> : DeserializeItemsIterator,
System.Collections.Generic.IEnumerator<T>,
System.Collections.Generic.IEnumerable<T>
{
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return this; }
public new T Current { get { return (T)base.Current; } }
void IDisposable.Dispose() { }
public DeserializeItemsIterator(TypeModel model, Stream source, PrefixStyle style, int expectedField, SerializationContext context)
: base(model, source, model.MapType(typeof(T)), style, expectedField, null, context) { }
}
#endif
private class DeserializeItemsIterator : IEnumerator, IEnumerable
{
IEnumerator IEnumerable.GetEnumerator() { return this; }
private bool haveObject;
private object current;
public bool MoveNext()
{
if (haveObject)
{
int bytesRead;
current = model.DeserializeWithLengthPrefix(source, null, type, style, expectedField, resolver, out bytesRead, out haveObject, context);
}
return haveObject;
}
void IEnumerator.Reset() { throw new NotSupportedException(); }
public object Current { get { return current; } }
private readonly Stream source;
private readonly Type type;
private readonly PrefixStyle style;
private readonly int expectedField;
private readonly Serializer.TypeResolver resolver;
private readonly TypeModel model;
private readonly SerializationContext context;
public DeserializeItemsIterator(TypeModel model, Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, SerializationContext context)
{
haveObject = true;
this.source = source;
this.type = type;
this.style = style;
this.expectedField = expectedField;
this.resolver = resolver;
this.model = model;
this.context = context;
}
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream,
/// with a length-prefix. This is useful for socket programming,
/// as DeserializeWithLengthPrefix can be used to read the single object back
/// from an ongoing stream.
/// </summary>
/// <param name="type">The type being serialized.</param>
/// <param name="value">The existing instance to be serialized (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="dest">The destination stream to write to.</param>
/// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber)
{
SerializeWithLengthPrefix(dest, value, type, style, fieldNumber, null);
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream,
/// with a length-prefix. This is useful for socket programming,
/// as DeserializeWithLengthPrefix can be used to read the single object back
/// from an ongoing stream.
/// </summary>
/// <param name="type">The type being serialized.</param>
/// <param name="value">The existing instance to be serialized (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="dest">The destination stream to write to.</param>
/// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
/// <param name="context">Additional information about this serialization operation.</param>
public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber, SerializationContext context)
{
if (type == null)
{
if(value == null) throw new ArgumentNullException("value");
type = MapType(value.GetType());
}
int key = GetKey(ref type);
using (ProtoWriter writer = new ProtoWriter(dest, this, context))
{
switch (style)
{
case PrefixStyle.None:
Serialize(key, value, writer);
break;
case PrefixStyle.Base128:
case PrefixStyle.Fixed32:
case PrefixStyle.Fixed32BigEndian:
ProtoWriter.WriteObject(value, key, writer, style, fieldNumber);
break;
default:
throw new ArgumentOutOfRangeException("style");
}
writer.Close();
}
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance (which may be null).
/// </summary>
/// <param name="type">The type (including inheritance) to consider.</param>
/// <param name="value">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
public object Deserialize(Stream source, object value, System.Type type)
{
return Deserialize(source, value, type, null);
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance (which may be null).
/// </summary>
/// <param name="type">The type (including inheritance) to consider.</param>
/// <param name="value">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
/// <param name="context">Additional information about this serialization operation.</param>
public object Deserialize(Stream source, object value, System.Type type, SerializationContext context)
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
bool autoCreate = PrepareDeserialize(value, ref type);
ProtoReader reader = null;
try
{
reader = ProtoReader.Create(source, this, context, ProtoReader.TO_EOF);
if (value != null) reader.SetRootObject(value);
object obj = DeserializeCore(reader, type, value, autoCreate);
reader.CheckFullyConsumed();
return obj;
}
finally
{
ProtoReader.Recycle(reader);
}
#endif
}
private bool PrepareDeserialize(object value, ref Type type)
{
if (type == null)
{
if (value == null)
{
throw new ArgumentNullException("type");
}
else
{
type = MapType(value.GetType());
}
}
bool autoCreate = true;
#if !NO_GENERICS
Type underlyingType = Helpers.GetUnderlyingType(type);
if (underlyingType != null)
{
type = underlyingType;
autoCreate = false;
}
#endif
return autoCreate;
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance (which may be null).
/// </summary>
/// <param name="type">The type (including inheritance) to consider.</param>
/// <param name="value">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <param name="length">The number of bytes to consume.</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
public object Deserialize(Stream source, object value, System.Type type, int length)
{
return Deserialize(source, value, type, length, null);
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance (which may be null).
/// </summary>
/// <param name="type">The type (including inheritance) to consider.</param>
/// <param name="value">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <param name="length">The number of bytes to consume (or -1 to read to the end of the stream).</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
/// <param name="context">Additional information about this serialization operation.</param>
public object Deserialize(Stream source, object value, System.Type type, int length, SerializationContext context)
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
bool autoCreate = PrepareDeserialize(value, ref type);
ProtoReader reader = null;
try
{
reader = ProtoReader.Create(source, this, context, length);
if (value != null) reader.SetRootObject(value);
object obj = DeserializeCore(reader, type, value, autoCreate);
reader.CheckFullyConsumed();
return obj;
}
finally
{
ProtoReader.Recycle(reader);
}
#endif
}
/// <summary>
/// Applies a protocol-buffer reader to an existing instance (which may be null).
/// </summary>
/// <param name="type">The type (including inheritance) to consider.</param>
/// <param name="value">The existing instance to be modified (can be null).</param>
/// <param name="source">The reader to apply to the instance (cannot be null).</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
public object Deserialize(ProtoReader source, object value, System.Type type)
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
if (source == null) throw new ArgumentNullException("source");
bool autoCreate = PrepareDeserialize(value, ref type);
if (value != null) source.SetRootObject(value);
object obj = DeserializeCore(source, type, value, autoCreate);
source.CheckFullyConsumed();
return obj;
#endif
}
#if !FEAT_IKVM
private object DeserializeCore(ProtoReader reader, Type type, object value, bool noAutoCreate)
{
int key = GetKey(ref type);
if (key >= 0 && !Helpers.IsEnum(type))
{
return Deserialize(key, value, reader);
}
// this returns true to say we actively found something, but a value is assigned either way (or throws)
TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, noAutoCreate, false);
return value;
}
#endif
#if WINRT || COREFX
private static readonly System.Reflection.TypeInfo ilist = typeof(IList).GetTypeInfo();
#else
private static readonly System.Type ilist = typeof(IList);
#endif
internal static MethodInfo ResolveListAdd(TypeModel model, Type listType, Type itemType, out bool isList)
{
#if WINRT || COREFX
TypeInfo listTypeInfo = listType.GetTypeInfo();
#else
Type listTypeInfo = listType;
#endif
isList = model.MapType(ilist).IsAssignableFrom(listTypeInfo);
Type[] types = { itemType };
MethodInfo add = Helpers.GetInstanceMethod(listTypeInfo, "Add", types);
#if !NO_GENERICS
if (add == null)
{ // fallback: look for ICollection<T>'s Add(typedObject) method
bool forceList = listTypeInfo.IsInterface &&
listTypeInfo == model.MapType(typeof(System.Collections.Generic.IEnumerable<>)).MakeGenericType(types)
#if WINRT || COREFX
.GetTypeInfo()
#endif
;
#if WINRT || COREFX
TypeInfo constuctedListType = typeof(System.Collections.Generic.ICollection<>).MakeGenericType(types).GetTypeInfo();
#else
Type constuctedListType = model.MapType(typeof(System.Collections.Generic.ICollection<>)).MakeGenericType(types);
#endif
if (forceList || constuctedListType.IsAssignableFrom(listTypeInfo))
{
add = Helpers.GetInstanceMethod(constuctedListType, "Add", types);
}
}
if (add == null)
{
#if WINRT || COREFX
foreach (Type tmpType in listTypeInfo.ImplementedInterfaces)
#else
foreach (Type interfaceType in listTypeInfo.GetInterfaces())
#endif
{
#if WINRT || COREFX
TypeInfo interfaceType = tmpType.GetTypeInfo();
#endif
if (interfaceType.Name == "IProducerConsumerCollection`1" && interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition().FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1")
{
add = Helpers.GetInstanceMethod(interfaceType, "TryAdd", types);
if (add != null) break;
}
}
}
#endif
if (add == null)
{ // fallback: look for a public list.Add(object) method
types[0] = model.MapType(typeof(object));
add = Helpers.GetInstanceMethod(listTypeInfo, "Add", types);
}
if (add == null && isList)
{ // fallback: look for IList's Add(object) method
add = Helpers.GetInstanceMethod(model.MapType(ilist), "Add", types);
}
return add;
}
internal static Type GetListItemType(TypeModel model, Type listType)
{
Helpers.DebugAssert(listType != null);
#if WINRT
TypeInfo listTypeInfo = listType.GetTypeInfo();
if (listType == typeof(string) || listType.IsArray
|| !typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(listTypeInfo)) return null;
#else
if (listType == model.MapType(typeof(string)) || listType.IsArray
|| !model.MapType(typeof(IEnumerable)).IsAssignableFrom(listType)) return null;
#endif
BasicList candidates = new BasicList();
#if WINRT
foreach (MethodInfo method in listType.GetRuntimeMethods())
#else
foreach (MethodInfo method in listType.GetMethods())
#endif
{
if (method.IsStatic || method.Name != "Add") continue;
ParameterInfo[] parameters = method.GetParameters();
Type paramType;
if (parameters.Length == 1 && !candidates.Contains(paramType = parameters[0].ParameterType))
{
candidates.Add(paramType);
}
}
string name = listType.Name;
bool isQueueStack = name != null && (name.IndexOf("Queue") >= 0 || name.IndexOf("Stack") >= 0);
#if !NO_GENERICS
if(!isQueueStack)
{
TestEnumerableListPatterns(model, candidates, listType);
#if WINRT
foreach (Type iType in listTypeInfo.ImplementedInterfaces)
{
TestEnumerableListPatterns(model, candidates, iType);
}
#else
foreach (Type iType in listType.GetInterfaces())
{
TestEnumerableListPatterns(model, candidates, iType);
}
#endif
}
#endif
#if WINRT
// more convenient GetProperty overload not supported on all platforms
foreach (PropertyInfo indexer in listType.GetRuntimeProperties())
{
if (indexer.Name != "Item" || candidates.Contains(indexer.PropertyType)) continue;
ParameterInfo[] args = indexer.GetIndexParameters();
if (args.Length != 1 || args[0].ParameterType != typeof(int)) continue;
MethodInfo getter = indexer.GetMethod;
if (getter == null || getter.IsStatic) continue;
candidates.Add(indexer.PropertyType);
}
#else
// more convenient GetProperty overload not supported on all platforms
foreach (PropertyInfo indexer in listType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (indexer.Name != "Item" || candidates.Contains(indexer.PropertyType)) continue;
ParameterInfo[] args = indexer.GetIndexParameters();
if (args.Length != 1 || args[0].ParameterType != model.MapType(typeof(int))) continue;
candidates.Add(indexer.PropertyType);
}
#endif
switch (candidates.Count)
{
case 0:
return null;
case 1:
return (Type)candidates[0];
case 2:
if (CheckDictionaryAccessors(model, (Type)candidates[0], (Type)candidates[1])) return (Type)candidates[0];
if (CheckDictionaryAccessors(model, (Type)candidates[1], (Type)candidates[0])) return (Type)candidates[1];
break;
}
return null;
}
private static void TestEnumerableListPatterns(TypeModel model, BasicList candidates, Type iType)
{
#if WINRT || COREFX
TypeInfo iTypeInfo = iType.GetTypeInfo();
if (iTypeInfo.IsGenericType)
{
Type typeDef = iTypeInfo.GetGenericTypeDefinition();
if(typeDef == typeof(System.Collections.Generic.ICollection<>) || typeDef.GetTypeInfo().FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1")
{
Type[] iTypeArgs = iTypeInfo.GenericTypeArguments;
if (!candidates.Contains(iTypeArgs[0]))
{
candidates.Add(iTypeArgs[0]);
}
}
}
#elif !NO_GENERICS
if (iType.IsGenericType)
{
Type typeDef = iType.GetGenericTypeDefinition();
if (typeDef == model.MapType(typeof(System.Collections.Generic.IEnumerable<>))
|| typeDef == model.MapType(typeof(System.Collections.Generic.ICollection<>))
|| typeDef.FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1")
{
Type[] iTypeArgs = iType.GetGenericArguments();
if (!candidates.Contains(iTypeArgs[0]))
{
candidates.Add(iTypeArgs[0]);
}
}
}
#endif
}
private static bool CheckDictionaryAccessors(TypeModel model, Type pair, Type value)
{
#if NO_GENERICS
return false;
#elif WINRT || COREFX
TypeInfo finalType = pair.GetTypeInfo();
return finalType.IsGenericType && finalType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>)
&& finalType.GenericTypeArguments[1] == value;
#else
return pair.IsGenericType && pair.GetGenericTypeDefinition() == model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>))
&& pair.GetGenericArguments()[1] == value;
#endif
}
#if !FEAT_IKVM
private bool TryDeserializeList(TypeModel model, ProtoReader reader, DataFormat format, int tag, Type listType, Type itemType, ref object value)
{
bool isList;
MethodInfo addMethod = TypeModel.ResolveListAdd(model, listType, itemType, out isList);
if (addMethod == null) throw new NotSupportedException("Unknown list variant: " + listType.FullName);
bool found = false;
object nextItem = null;
IList list = value as IList;
object[] args = isList ? null : new object[1];
BasicList arraySurrogate = listType.IsArray ? new BasicList() : null;
while (TryDeserializeAuxiliaryType(reader, format, tag, itemType, ref nextItem, true, true, true, true))
{
found = true;
if (value == null && arraySurrogate == null)
{
value = CreateListInstance(listType, itemType);
list = value as IList;
}
if (list != null)
{
list.Add(nextItem);
}
else if (arraySurrogate != null)
{
arraySurrogate.Add(nextItem);
}
else
{
args[0] = nextItem;
addMethod.Invoke(value, args);
}
nextItem = null;
}
if (arraySurrogate != null)
{
Array newArray;
if (value != null)
{
if (arraySurrogate.Count == 0)
{ // we'll stay with what we had, thanks
}
else
{
Array existing = (Array)value;
newArray = Array.CreateInstance(itemType, existing.Length + arraySurrogate.Count);
Array.Copy(existing, newArray, existing.Length);
arraySurrogate.CopyTo(newArray, existing.Length);
value = newArray;
}
}
else
{
newArray = Array.CreateInstance(itemType, arraySurrogate.Count);
arraySurrogate.CopyTo(newArray, 0);
value = newArray;
}
}
return found;
}
private static object CreateListInstance(Type listType, Type itemType)
{
Type concreteListType = listType;
if (listType.IsArray)
{
return Array.CreateInstance(itemType, 0);
}
#if WINRT || COREFX
TypeInfo listTypeInfo = listType.GetTypeInfo();
if (!listTypeInfo.IsClass || listTypeInfo.IsAbstract ||
Helpers.GetConstructor(listTypeInfo, Helpers.EmptyTypes, true) == null)
#else
if (!listType.IsClass || listType.IsAbstract ||
Helpers.GetConstructor(listType, Helpers.EmptyTypes, true) == null)
#endif
{
string fullName;
bool handled = false;
#if WINRT || COREFX
if (listTypeInfo.IsInterface &&
#else
if (listType.IsInterface &&
#endif
(fullName = listType.FullName) != null && fullName.IndexOf("Dictionary") >= 0) // have to try to be frugal here...
{
#if !NO_GENERICS
#if WINRT || COREFX
TypeInfo finalType = listType.GetTypeInfo();
if (finalType.IsGenericType && finalType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>))
{
Type[] genericTypes = listType.GenericTypeArguments;
concreteListType = typeof(System.Collections.Generic.Dictionary<,>).MakeGenericType(genericTypes);
handled = true;
}
#else
if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>))
{
Type[] genericTypes = listType.GetGenericArguments();
concreteListType = typeof(System.Collections.Generic.Dictionary<,>).MakeGenericType(genericTypes);
handled = true;
}
#endif
#endif
#if !SILVERLIGHT && !WINRT && !PORTABLE && ! COREFX
if (!handled && listType == typeof(IDictionary))
{
concreteListType = typeof(Hashtable);
handled = true;
}
#endif
}
#if !NO_GENERICS
if (!handled)
{
concreteListType = typeof(System.Collections.Generic.List<>).MakeGenericType(itemType);
handled = true;
}
#endif
#if !SILVERLIGHT && !WINRT && !PORTABLE && ! COREFX
if (!handled)
{
concreteListType = typeof(ArrayList);
handled = true;
}
#endif
}
return Activator.CreateInstance(concreteListType);
}
/// <summary>
/// This is the more "complete" version of Deserialize, which handles single instances of mapped types.
/// The value is read as a complete field, including field-header and (for sub-objects) a
/// length-prefix..kmc
///
/// In addition to that, this provides support for:
/// - basic values; individual int / string / Guid / etc
/// - IList sets of any type handled by TryDeserializeAuxiliaryType
/// </summary>
internal bool TryDeserializeAuxiliaryType(ProtoReader reader, DataFormat format, int tag, Type type, ref object value, bool skipOtherFields, bool asListItem, bool autoCreate, bool insideList)
{
if (type == null) throw new ArgumentNullException("type");
Type itemType = null;
ProtoTypeCode typecode = Helpers.GetTypeCode(type);
int modelKey;
WireType wiretype = GetWireType(typecode, format, ref type, out modelKey);
bool found = false;
if (wiretype == WireType.None)
{
itemType = GetListItemType(this, type);
if (itemType == null && type.IsArray && type.GetArrayRank() == 1 && type != typeof(byte[]))
{
itemType = type.GetElementType();
}
if (itemType != null)
{
if (insideList) throw TypeModel.CreateNestedListsNotSupported();
found = TryDeserializeList(this, reader, format, tag, type, itemType, ref value);
if (!found && autoCreate)
{
value = CreateListInstance(type, itemType);
}
return found;
}
// otherwise, not a happy bunny...
ThrowUnexpectedType(type);
}
// to treat correctly, should read all values
while (true)
{
// for convenience (re complex exit conditions), additional exit test here:
// if we've got the value, are only looking for one, and we aren't a list - then exit
if (found && asListItem) break;
// read the next item
int fieldNumber = reader.ReadFieldHeader();
if (fieldNumber <= 0) break;
if (fieldNumber != tag)
{
if (skipOtherFields)
{
reader.SkipField();
continue;
}
throw ProtoReader.AddErrorData(new InvalidOperationException(
"Expected field " + tag.ToString() + ", but found " + fieldNumber.ToString()), reader);
}
found = true;
reader.Hint(wiretype); // handle signed data etc
if (modelKey >= 0)
{
switch (wiretype)
{
case WireType.String:
case WireType.StartGroup:
SubItemToken token = ProtoReader.StartSubItem(reader);
value = Deserialize(modelKey, value, reader);
ProtoReader.EndSubItem(token, reader);
continue;
default:
value = Deserialize(modelKey, value, reader);
continue;
}
}
switch (typecode)
{
case ProtoTypeCode.Int16: value = reader.ReadInt16(); continue;
case ProtoTypeCode.Int32: value = reader.ReadInt32(); continue;
case ProtoTypeCode.Int64: value = reader.ReadInt64(); continue;
case ProtoTypeCode.UInt16: value = reader.ReadUInt16(); continue;
case ProtoTypeCode.UInt32: value = reader.ReadUInt32(); continue;
case ProtoTypeCode.UInt64: value = reader.ReadUInt64(); continue;
case ProtoTypeCode.Boolean: value = reader.ReadBoolean(); continue;
case ProtoTypeCode.SByte: value = reader.ReadSByte(); continue;
case ProtoTypeCode.Byte: value = reader.ReadByte(); continue;
case ProtoTypeCode.Char: value = (char)reader.ReadUInt16(); continue;
case ProtoTypeCode.Double: value = reader.ReadDouble(); continue;
case ProtoTypeCode.Single: value = reader.ReadSingle(); continue;
case ProtoTypeCode.DateTime: value = BclHelpers.ReadDateTime(reader); continue;
case ProtoTypeCode.Decimal: value = BclHelpers.ReadDecimal(reader); continue;
case ProtoTypeCode.String: value = reader.ReadString(); continue;
case ProtoTypeCode.ByteArray: value = ProtoReader.AppendBytes((byte[])value, reader); continue;
case ProtoTypeCode.TimeSpan: value = BclHelpers.ReadTimeSpan(reader); continue;
case ProtoTypeCode.Guid: value = BclHelpers.ReadGuid(reader); continue;
case ProtoTypeCode.Uri: value = new Uri(reader.ReadString()); continue;
}
}
if (!found && !asListItem && autoCreate)
{
if (type != typeof(string))
{
value = Activator.CreateInstance(type);
}
}
return found;
}
#endif
#if !NO_RUNTIME
/// <summary>
/// Creates a new runtime model, to which the caller
/// can add support for a range of types. A model
/// can be used "as is", or can be compiled for
/// optimal performance.
/// </summary>
public static RuntimeTypeModel Create()
{
return new RuntimeTypeModel(false);
}
#endif
/// <summary>
/// Applies common proxy scenarios, resolving the actual type to consider
/// </summary>
protected internal static Type ResolveProxies(Type type)
{
if (type == null) return null;
#if !NO_GENERICS
if (type.IsGenericParameter) return null;
// Nullable<T>
Type tmp = Helpers.GetUnderlyingType(type);
if (tmp != null) return tmp;
#endif
#if !(WINRT || CF)
// EF POCO
string fullName = type.FullName;
if (fullName != null && fullName.StartsWith("System.Data.Entity.DynamicProxies."))
{
#if COREFX
return type.GetTypeInfo().BaseType;
#else
return type.BaseType;
#endif
}
// NHibernate
Type[] interfaces = type.GetInterfaces();
for(int i = 0 ; i < interfaces.Length ; i++)
{
switch(interfaces[i].FullName)
{
case "NHibernate.Proxy.INHibernateProxy":
case "NHibernate.Proxy.DynamicProxy.IProxy":
case "NHibernate.Intercept.IFieldInterceptorAccessor":
#if COREFX
return type.GetTypeInfo().BaseType;
#else
return type.BaseType;
#endif
}
}
#endif
return null;
}
/// <summary>
/// Indicates whether the supplied type is explicitly modelled by the model
/// </summary>
public bool IsDefined(Type type)
{
return GetKey(ref type) >= 0;
}
/// <summary>
/// Provides the key that represents a given type in the current model.
/// The type is also normalized for proxies at the same time.
/// </summary>
protected internal int GetKey(ref Type type)
{
if (type == null) return -1;
int key = GetKeyImpl(type);
if (key < 0)
{
Type normalized = ResolveProxies(type);
if (normalized != null) {
type = normalized; // hence ref
key = GetKeyImpl(type);
}
}
return key;
}
/// <summary>
/// Provides the key that represents a given type in the current model.
/// </summary>
protected abstract int GetKeyImpl(Type type);
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream.
/// </summary>
/// <param name="key">Represents the type (including inheritance) to consider.</param>
/// <param name="value">The existing instance to be serialized (cannot be null).</param>
/// <param name="dest">The destination stream to write to.</param>
protected internal abstract void Serialize(int key, object value, ProtoWriter dest);
/// <summary>
/// Applies a protocol-buffer stream to an existing instance (which may be null).
/// </summary>
/// <param name="key">Represents the type (including inheritance) to consider.</param>
/// <param name="value">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
protected internal abstract object Deserialize(int key, object value, ProtoReader source);
//internal ProtoSerializer Create(IProtoSerializer head)
//{
// return new RuntimeSerializer(head, this);
//}
//internal ProtoSerializer Compile
/// <summary>
/// Indicates the type of callback to be used
/// </summary>
protected internal enum CallbackType
{
/// <summary>
/// Invoked before an object is serialized
/// </summary>
BeforeSerialize,
/// <summary>
/// Invoked after an object is serialized
/// </summary>
AfterSerialize,
/// <summary>
/// Invoked before an object is deserialized (or when a new instance is created)
/// </summary>
BeforeDeserialize,
/// <summary>
/// Invoked after an object is deserialized
/// </summary>
AfterDeserialize
}
/// <summary>
/// Create a deep clone of the supplied instance; any sub-items are also cloned.
/// </summary>
public object DeepClone(object value)
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
if (value == null) return null;
Type type = value.GetType();
int key = GetKey(ref type);
if (key >= 0 && !Helpers.IsEnum(type))
{
using (MemoryStream ms = new MemoryStream())
{
using(ProtoWriter writer = new ProtoWriter(ms, this, null))
{
writer.SetRootObject(value);
Serialize(key, value, writer);
writer.Close();
}
ms.Position = 0;
ProtoReader reader = null;
try
{
reader = ProtoReader.Create(ms, this, null, ProtoReader.TO_EOF);
return Deserialize(key, null, reader);
}
finally
{
ProtoReader.Recycle(reader);
}
}
}
int modelKey;
if (type == typeof(byte[])) {
byte[] orig = (byte[])value, clone = new byte[orig.Length];
Helpers.BlockCopy(orig, 0, clone, 0, orig.Length);
return clone;
}
else if (GetWireType(Helpers.GetTypeCode(type), DataFormat.Default, ref type, out modelKey) != WireType.None && modelKey < 0)
{ // immutable; just return the original value
return value;
}
using (MemoryStream ms = new MemoryStream())
{
using (ProtoWriter writer = new ProtoWriter(ms, this, null))
{
if (!TrySerializeAuxiliaryType(writer, type, DataFormat.Default, Serializer.ListItemTag, value, false)) ThrowUnexpectedType(type);
writer.Close();
}
ms.Position = 0;
ProtoReader reader = null;
try
{
reader = ProtoReader.Create(ms, this, null, ProtoReader.TO_EOF);
value = null; // start from scratch!
TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false);
return value;
}
finally
{
ProtoReader.Recycle(reader);
}
}
#endif
}
/// <summary>
/// Indicates that while an inheritance tree exists, the exact type encountered was not
/// specified in that hierarchy and cannot be processed.
/// </summary>
protected internal static void ThrowUnexpectedSubtype(Type expected, Type actual)
{
if (expected != TypeModel.ResolveProxies(actual))
{
throw new InvalidOperationException("Unexpected sub-type: " + actual.FullName);
}
}
/// <summary>
/// Indicates that the given type was not expected, and cannot be processed.
/// </summary>
protected internal static void ThrowUnexpectedType(Type type)
{
string fullName = type == null ? "(unknown)" : type.FullName;
#if !NO_GENERICS && !WINRT
if (type != null)
{
Type baseType = type
#if COREFX
.GetTypeInfo()
#endif
.BaseType;
if (baseType != null && baseType
#if COREFX
.GetTypeInfo()
#endif
.IsGenericType && baseType.GetGenericTypeDefinition().Name == "GeneratedMessage`2")
{
throw new InvalidOperationException(
"Are you mixing protobuf-net and protobuf-csharp-port? See http://stackoverflow.com/q/11564914; type: " + fullName);
}
}
#endif
throw new InvalidOperationException("Type is not expected, and no contract can be inferred: " + fullName);
}
internal static Exception CreateNestedListsNotSupported()
{
return new NotSupportedException("Nested or jagged lists and arrays are not supported");
}
/// <summary>
/// Indicates that the given type cannot be constructed; it may still be possible to
/// deserialize into existing instances.
/// </summary>
public static void ThrowCannotCreateInstance(Type type)
{
throw new ProtoException("No parameterless constructor found for " + (type == null ? "(null)" : type.Name));
}
internal static string SerializeType(TypeModel model, System.Type type)
{
if (model != null)
{
TypeFormatEventHandler handler = model.DynamicTypeFormatting;
if (handler != null)
{
TypeFormatEventArgs args = new TypeFormatEventArgs(type);
handler(model, args);
if (!Helpers.IsNullOrEmpty(args.FormattedName)) return args.FormattedName;
}
}
return type.AssemblyQualifiedName;
}
internal static System.Type DeserializeType(TypeModel model, string value)
{
if (model != null)
{
TypeFormatEventHandler handler = model.DynamicTypeFormatting;
if (handler != null)
{
TypeFormatEventArgs args = new TypeFormatEventArgs(value);
handler(model, args);
if (args.Type != null) return args.Type;
}
}
return System.Type.GetType(value);
}
/// <summary>
/// Returns true if the type supplied is either a recognised contract type,
/// or a *list* of a recognised contract type.
/// </summary>
/// <remarks>Note that primitives always return false, even though the engine
/// will, if forced, try to serialize such</remarks>
/// <returns>True if this type is recognised as a serializable entity, else false</returns>
public bool CanSerializeContractType(Type type)
{
return CanSerialize(type, false, true, true);
}
/// <summary>
/// Returns true if the type supplied is a basic type with inbuilt handling,
/// a recognised contract type, or a *list* of a basic / contract type.
/// </summary>
public bool CanSerialize(Type type)
{
return CanSerialize(type, true, true, true);
}
/// <summary>
/// Returns true if the type supplied is a basic type with inbuilt handling,
/// or a *list* of a basic type with inbuilt handling
/// </summary>
public bool CanSerializeBasicType(Type type)
{
return CanSerialize(type, true, false, true);
}
private bool CanSerialize(Type type, bool allowBasic, bool allowContract, bool allowLists)
{
if (type == null) throw new ArgumentNullException("type");
Type tmp = Helpers.GetUnderlyingType(type);
if (tmp != null) type = tmp;
// is it a basic type?
ProtoTypeCode typeCode = Helpers.GetTypeCode(type);
switch(typeCode)
{
case ProtoTypeCode.Empty:
case ProtoTypeCode.Unknown:
break;
default:
return allowBasic; // well-known basic type
}
int modelKey = GetKey(ref type);
if (modelKey >= 0) return allowContract; // known contract type
// is it a list?
if (allowLists)
{
Type itemType = null;
if (type.IsArray)
{ // note we don't need to exclude byte[], as that is handled by GetTypeCode already
if (type.GetArrayRank() == 1) itemType = type.GetElementType();
}
else
{
itemType = GetListItemType(this, type);
}
if (itemType != null) return CanSerialize(itemType, allowBasic, allowContract, false);
}
return false;
}
/// <summary>
/// Suggest a .proto definition for the given type
/// </summary>
/// <param name="type">The type to generate a .proto definition for, or <c>null</c> to generate a .proto that represents the entire model</param>
/// <returns>The .proto definition as a string</returns>
public virtual string GetSchema(Type type)
{
throw new NotSupportedException();
}
/// <summary>
/// Used to provide custom services for writing and parsing type names when using dynamic types. Both parsing and formatting
/// are provided on a single API as it is essential that both are mapped identically at all times.
/// </summary>
public event TypeFormatEventHandler DynamicTypeFormatting;
#if PLAT_BINARYFORMATTER && !(WINRT || PHONE8 || COREFX)
/// <summary>
/// Creates a new IFormatter that uses protocol-buffer [de]serialization.
/// </summary>
/// <returns>A new IFormatter to be used during [de]serialization.</returns>
/// <param name="type">The type of object to be [de]deserialized by the formatter.</param>
public System.Runtime.Serialization.IFormatter CreateFormatter(Type type)
{
return new Formatter(this, type);
}
internal sealed class Formatter : System.Runtime.Serialization.IFormatter
{
private readonly TypeModel model;
private readonly Type type;
internal Formatter(TypeModel model, Type type)
{
if (model == null) throw new ArgumentNullException("model");
if (type == null) throw new ArgumentNullException("type");
this.model = model;
this.type = type;
}
private System.Runtime.Serialization.SerializationBinder binder;
public System.Runtime.Serialization.SerializationBinder Binder
{
get { return binder; }
set { binder = value; }
}
private System.Runtime.Serialization.StreamingContext context;
public System.Runtime.Serialization.StreamingContext Context
{
get { return context; }
set { context = value; }
}
public object Deserialize(Stream source)
{
#if FEAT_IKVM
throw new NotSupportedException();
#else
return model.Deserialize(source, null, type, -1, Context);
#endif
}
public void Serialize(Stream destination, object graph)
{
model.Serialize(destination, graph, Context);
}
private System.Runtime.Serialization.ISurrogateSelector surrogateSelector;
public System.Runtime.Serialization.ISurrogateSelector SurrogateSelector
{
get { return surrogateSelector; }
set { surrogateSelector = value; }
}
}
#endif
#if DEBUG // this is used by some unit tests only, to ensure no buffering when buffering is disabled
private bool forwardsOnly;
/// <summary>
/// If true, buffering of nested objects is disabled
/// </summary>
public bool ForwardsOnly
{
get { return forwardsOnly; }
set { forwardsOnly = value; }
}
#endif
internal virtual Type GetType(string fullName, Assembly context)
{
#if FEAT_IKVM
throw new NotImplementedException();
#else
return ResolveKnownType(fullName, this, context);
#endif
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
internal static Type ResolveKnownType(string name, TypeModel model, Assembly assembly)
{
if (Helpers.IsNullOrEmpty(name)) return null;
try
{
#if FEAT_IKVM
// looks like a NullReferenceException, but this should call into RuntimeTypeModel's version
Type type = model == null ? null : model.GetType(name, assembly);
#else
Type type = Type.GetType(name);
#endif
if (type != null) return type;
}
catch { }
try
{
int i = name.IndexOf(',');
string fullName = (i > 0 ? name.Substring(0, i) : name).Trim();
#if !(WINRT || FEAT_IKVM || COREFX)
if (assembly == null) assembly = Assembly.GetCallingAssembly();
#endif
Type type = assembly == null ? null : assembly.GetType(fullName);
if (type != null) return type;
}
catch { }
return null;
}
}
}
| 44.906949 | 232 | 0.563192 | [
"Apache-2.0"
] | inquick/rxzp | Assets/protobuf-net/Meta/TypeModel.cs | 74,323 | C# |
using Cosmos.Business.Extensions.Holiday.Core;
using Cosmos.I18N.Countries;
namespace Cosmos.Business.Extensions.Holiday.Definitions.Europe.Andorra.Commemoration
{
/// <summary>
/// Escaldes–Engordany Annual Festival
/// </summary>
public class EscaldesEngordanyAnnualFestival : BaseFixedHolidayFunc
{
/// <inheritdoc />
public override Country Country { get; } = Country.Andorra;
/// <inheritdoc />
public override Country BelongsToCountry { get; } = Country.Andorra;
/// <inheritdoc />
public override string Name { get; } = "Escaldes-Engordany";
/// <inheritdoc />
public override HolidayType HolidayType { get; set; } = HolidayType.Commemoration;
/// <inheritdoc />
public override (int Month, int Day)? FromDate { get; set; } = (7, 25);
/// <inheritdoc />
public override (int Month, int Day)? ToDate { get; set; } = (7, 26);
/// <inheritdoc />
public override string I18NIdentityCode { get; } = "i18n_holiday_ad_escaldes_engordany";
}
} | 33.90625 | 96 | 0.634101 | [
"Apache-2.0"
] | cosmos-open/Holiday | src/Cosmos.Business.Extensions.Holiday/Cosmos/Business/Extensions/Holiday/Definitions/Europe/Andorra/Commemoration/EscaldesEngordanyAnnualFestival.cs | 1,087 | C# |
namespace Machete.X12Schema.V5010
{
using X12;
public interface L2330E_837P :
X12Layout
{
Segment<NM1> FacilityLocation { get; }
SegmentList<REF> SecondaryIdentification { get; }
}
} | 18 | 57 | 0.606838 | [
"Apache-2.0"
] | AreebaAroosh/Machete | src/Machete.X12Schema/Generated/V5010/Layouts/L2330E_837P.cs | 236 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace FishSpinDays.Data.Migrations
{
public partial class AddDateAndLikeToComments : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "CreationDate",
table: "Comments",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
migrationBuilder.AddColumn<int>(
name: "Likes",
table: "Comments",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "UnLikes",
table: "Comments",
nullable: false,
defaultValue: 0);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "CreationDate",
table: "Comments");
migrationBuilder.DropColumn(
name: "Likes",
table: "Comments");
migrationBuilder.DropColumn(
name: "UnLikes",
table: "Comments");
}
}
}
| 29.044444 | 91 | 0.525631 | [
"MIT"
] | hrimar/MyFirstOwnWebProject-FishSpinDays | FishSpinDays/FishSpinDays.Data/Migrations/20180820185219_AddDateAndLikeToComments.cs | 1,309 | C# |
using System;
namespace Spring.Core
{
public class BeforePostConstruct : Attribute
{
}
} | 12.75 | 48 | 0.676471 | [
"MIT"
] | Mu-L/Tank | Assets/Spring/Core/BeforePostConstruct.cs | 104 | 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.HtmlToPdf
{
using System;
using System.IO;
using System.Text;
public class HtmlToPdfOptions
{
private const string DefaultStyleSheet = "defaults/default-css.css";
/// <summary>
/// Specify a user style sheet, to load with every page.
/// </summary>
public string UserStyleSheet { get; set; }
/// <summary>
/// The option to put a outline into the pdf (default put a default outline into the pdf).
/// </summary>
public OutlineOption OutlineOption { get; set; } = OutlineOption.DefaultOutline;
/// <summary>
/// Set the default text encoding, for input
/// </summary>
public string Encoding { get; set; } = "utf-8";
/// <summary>
/// Be less verbose if true.
/// </summary>
public bool IsQuiet { get; set; } = true;
/// <summary>
/// Whether read command line arguments from stdin or not (default read command line arguments from stdin).
/// </summary>
public bool IsReadArgsFromStdin { get; set; } = true;
/// <summary>
/// Whether output the stream to stdout or not (default output the stream to stdout).
/// </summary>
public bool IsOutputToStdout { get; set; } = true;
/// <summary>
/// The base path or base url.
/// </summary>
public string BasePath { get; set; }
/// <summary>
/// The header html path for pdf.
/// </summary>
public string HeaderHtmlPath { get; set; }
/// <summary>
/// The footer html path for pdf.
/// </summary>
public string FooterHtmlPath { get; set; }
/// <summary>
/// Specify how to handle pages that fail to load: abort, ignore or skip(default abort)
/// </summary>
public string LoadErrorHandling { get; set; } = "skip";
/// <summary>
/// When convert pdf failed, we will retry twice, the default interval value is 5 seconds.
/// </summary>
public TimeSpan[] RetryIntervals { get; set; } = new[] { TimeSpan.FromSeconds(5) };
/// <summary>
/// The max degree of parallelism to convert pdf.
/// </summary>
public int MaxDegreeOfParallelism { get; set; } = 8;
/// <summary>
/// Gets or sets the path and file name of the pdf executable.
/// </summary>
public string FilePath { get; set; }
/// <summary>
/// Additional arguments.
/// </summary>
public string AdditionalArguments { get; set; }
/// <summary>
/// Get the string of the html to pdf options.
/// </summary>
/// <returns>The configuration of html to pdf options.</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
// here to show the options http://wkhtmltopdf.org/usage/wkhtmltopdf.txt
// why set javascript delay to 3000? https://github.com/wkhtmltopdf/wkhtmltopdf/issues/2054
sb.Append(" --javascript-delay 3000");
sb.Append(IsQuiet ? " -q" : string.Empty);
sb.Append(OutlineOption == OutlineOption.WkDefaultOutline ? " --outline" : " --no-outline");
if (!string.IsNullOrEmpty(Encoding))
{
sb.Append(" --encoding ").Append(Encoding);
}
if (string.IsNullOrEmpty(UserStyleSheet))
{
if (File.Exists(DefaultStyleSheet))
{
sb.Append(" --user-style-sheet \"").Append(DefaultStyleSheet).Append("\"");
}
}
else
{
sb.Append(" --user-style-sheet \"").Append(UserStyleSheet).Append("\"");
}
if (!string.IsNullOrEmpty(HeaderHtmlPath))
{
sb.Append(" --header-html \"").Append(HeaderHtmlPath).Append("\"");
}
if (!string.IsNullOrEmpty(FooterHtmlPath))
{
sb.Append(" --footer-html \"").Append(FooterHtmlPath).Append("\"");
}
if (!string.IsNullOrEmpty(LoadErrorHandling))
{
sb.Append(" --load-error-handling ").Append(LoadErrorHandling);
}
if (IsReadArgsFromStdin)
{
sb.Append(" --read-args-from-stdin");
}
if (!string.IsNullOrEmpty(AdditionalArguments))
{
sb.Append(" ").Append(AdditionalArguments);
}
return sb.ToString();
}
}
}
| 36.014493 | 116 | 0.52495 | [
"MIT"
] | Algorithman/docfx | src/Microsoft.DocAsCode.HtmlToPdf/HtmlToPdfOptions.cs | 4,835 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Workday.Payroll
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Submunicipality_Information_DataType : INotifyPropertyChanged
{
private string address_Component_NameField;
private string typeField;
private string valueField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string Address_Component_Name
{
get
{
return this.address_Component_NameField;
}
set
{
this.address_Component_NameField = value;
this.RaisePropertyChanged("Address_Component_Name");
}
}
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string Type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
this.RaisePropertyChanged("Type");
}
}
[XmlText]
public string Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
this.RaisePropertyChanged("Value");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 20.675325 | 136 | 0.728015 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.Payroll/Submunicipality_Information_DataType.cs | 1,592 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Assignment01 {
public partial class Site_Mobile {
/// <summary>
/// HeadContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder HeadContent;
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// FeaturedContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder FeaturedContent;
/// <summary>
/// MainContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder MainContent;
}
}
| 34 | 87 | 0.524321 | [
"MIT"
] | luizerico/Comp229-2016-Assignment-01 | Assignment01/Assignment01/Site.Mobile.Master.designer.cs | 1,768 | C# |
using System;
using System.Xml.Serialization;
namespace AllInOne.Logic
{
[Serializable]
public class LangItem
{
[XmlAttribute]
public string name;
[XmlText]
public string value;
}
}
| 12.3125 | 31 | 0.725888 | [
"Apache-2.0"
] | MrIkso/AllInOne | Logic/LangItem.cs | 199 | C# |
using System;
using System.Linq;
namespace P4MaximalSum
{
class MaximalSum
{
static void Main(string[] args)
{
int[] matrixSizes = Console.ReadLine().Split(' ', options: StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse).ToArray();
int[,] matrix = new int[matrixSizes[0], matrixSizes[1]];
int maxSum = int.MinValue;
int currentRow = -1;
int currentCol = -1;
for (int row = 0; row < matrix.GetLength(0); row++)
{
int[] fillMatrixRow = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
for (int col = 0; col < matrix.GetLength(1); col++)
{
matrix[row, col] = fillMatrixRow[col];
}
}
for (int row = 0; row < matrix.GetLength(0) - 2; row++)
{
for (int col = 0; col < matrix.GetLength(1) - 2; col++)
{
int currentSum = (matrix[row, col] + matrix[row, col + 1] + matrix[row, col + 2])
+ (matrix[row + 1, col] + matrix[row + 1, col + 1] + matrix[row + 1, col + 2])
+ (matrix[row + 2, col] + matrix[row + 2, col + 1] + matrix[row + 2, col + 2]);
if (currentSum > maxSum)
{
maxSum = currentSum;
currentRow = row;
currentCol = col;
}
}
}
Console.WriteLine($"Sum = {maxSum}");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (j < 2)
{
Console.Write($"{matrix[currentRow + i, currentCol + j]} ");
}
else
{
Console.Write($"{matrix[currentRow + i, currentCol + j]}");
}
}
Console.WriteLine();
}
}
}
}
| 30.957143 | 135 | 0.399631 | [
"MIT"
] | teodortenchev/C-Sharp-Advanced-Coursework | C# Advanced/MultidimensionalArraysExercises/P4MaximalSum/MaximalSum.cs | 2,169 | C# |
namespace TechTalk.SpecFlow.Generator.Generation
{
public class GeneratorConstants
{
public const string DEFAULT_NAMESPACE = "SpecFlowTests";
public const string TEST_NAME_FORMAT = "{0}";
public const string SCENARIO_INITIALIZE_NAME = "ScenarioInitialize";
public const string SCENARIO_START_NAME = "ScenarioStartAsync";
public const string SCENARIO_CLEANUP_NAME = "ScenarioCleanupAsync";
public const string TEST_INITIALIZE_NAME = "TestInitializeAsync";
public const string TEST_CLEANUP_NAME = "TestTearDownAsync";
public const string TESTCLASS_INITIALIZE_NAME = "FeatureSetupAsync";
public const string TESTCLASS_CLEANUP_NAME = "FeatureTearDownAsync";
public const string BACKGROUND_NAME = "FeatureBackgroundAsync";
public const string TESTRUNNER_FIELD = "testRunner";
public const string SPECFLOW_NAMESPACE = "TechTalk.SpecFlow";
public const string SCENARIO_OUTLINE_EXAMPLE_TAGS_PARAMETER = "exampleTags";
public const string SCENARIO_TAGS_VARIABLE_NAME = "tagsOfScenario";
public const string SCENARIO_ARGUMENTS_VARIABLE_NAME = "argumentsOfScenario";
public const string FEATURE_TAGS_VARIABLE_NAME = "featureTags";
}
} | 57.454545 | 85 | 0.747627 | [
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | NorekZ/SpecFlow | TechTalk.SpecFlow.Generator/Generation/GeneratorConstants.cs | 1,266 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using GRA.Domain.Model;
using GRA.Domain.Model.Filters;
namespace GRA.Domain.Repository
{
public interface IEventRepository : IRepository<Event>
{
Task<int> CountAsync(EventFilter filter);
Task<ICollection<Event>> PageAsync(EventFilter filter);
Task<List<Event>> GetByChallengeIdAsync(int challengeId);
Task<List<Event>> GetByChallengeGroupIdAsync(int challengeGroupId);
Task<bool> LocationInUse(int siteId, int locationId);
Task DetachRelatedTrigger(int triggerId);
Task<ICollection<Event>> GetRelatedEventsForTriggerAsync(int triggerId);
Task DetachRelatedChallenge(int userId, int challengeId);
Task DetachRelatedChallengeGroup(int userId, int challengeGroupId);
Task<ICollection<DataWithCount<Event>>> GetCommunityExperienceAttendanceAsync(
ReportCriterion criterion);
Task<IEnumerable<int>> GetUserFavoriteEvents(int userId,
IEnumerable<int> eventIds = null);
Task UpdateUserFavoritesAsync(int authUserId, int userId,
IEnumerable<int> favoritesToAdd, IEnumerable<int> favoritesToRemove);
Task<IEnumerable<int>> ValidateEventIdsAsync(int siteId,
IEnumerable<int> eventIds);
Task<ICollection<Event>> GetEventListAsync(EventFilter filter);
}
}
| 46.133333 | 86 | 0.730491 | [
"MIT"
] | MCLD/greatreadingadventure | src/GRA.Domain.Repository/IEventRepository.cs | 1,386 | C# |
using System;
namespace Anvil.Unity.DOTS.Data
{
/// <summary>
/// Helper methods when working with <see cref="VirtualData{TKey,TInstance}"/>
/// These make it more clear what is happening when operating on <see cref="VirtualData{TKey,TInstance}"/> instances
/// in a job.
/// </summary>
public static class VirtualDataExtensions
{
/// <summary>
/// Writes result data to the <see cref="VDResultsDestination{TResult}"/> on a
/// <see cref="IVirtualDataInstance{TResult}"/>
/// </summary>
/// <param name="instance">The instance to correspond the result to</param>
/// <param name="result">The result data to write</param>
/// <param name="updater">The <see cref="VDUpdater{TKey,TInstance}"/> the instance was from.</param>
/// <typeparam name="TKey">The type of key for the instance.</typeparam>
/// <typeparam name="TInstance">The type of the instance struct.</typeparam>
/// <typeparam name="TResult">The type of the result struct</typeparam>
public static void Resolve<TKey, TInstance, TResult>(this TInstance instance, ref TResult result, ref VDUpdater<TKey, TInstance> updater)
where TKey : struct, IEquatable<TKey>
where TInstance : struct, IKeyedData<TKey>, IVirtualDataInstance<TResult>
where TResult : struct
{
VDResultsWriter<TResult> resultsWriter = instance.ResultsDestination.AsResultsWriter();
resultsWriter.Add(ref result, updater.LaneIndex);
updater.Resolve();
}
/// <inheritdoc cref="Resolve{TKey,TInstance,TResult}"/>
public static void Resolve<TKey, TInstance, TResult>(this TInstance instance, TResult result, ref VDUpdater<TKey, TInstance> updater)
where TKey : struct, IEquatable<TKey>
where TInstance : struct, IKeyedData<TKey>, IVirtualDataInstance<TResult>
where TResult : struct
{
Resolve(instance, ref result, ref updater);
}
/// <summary>
/// Consistency helper function to correspond to <see cref="Resolve{TKey,TInstance,TResult}(TInstance,ref TResult,ref Anvil.Unity.DOTS.Data.VDUpdater{TKey,TInstance})"/>
/// when there is no result to write.
/// Allows for the code to look the same in the jobs and checks safeties when ENABLE_UNITY_COLLECTIONS_CHECKS is enabled.
/// </summary>
/// <param name="instance">The instance to operate on</param>
/// <param name="updater">The <see cref="VDUpdater{TKey,TInstance}"/> the instance was from.</param>
/// <typeparam name="TKey">The type of key for the instance.</typeparam>
/// <typeparam name="TInstance">The type of the instance struct.</typeparam>
public static void Resolve<TKey, TInstance>(this TInstance instance, ref VDUpdater<TKey, TInstance> updater)
where TKey : struct, IEquatable<TKey>
where TInstance : struct, IKeyedData<TKey>
{
updater.Resolve();
}
/// <summary>
/// Companion to <see cref="Resolve{TKey,TInstance,TResult}(TInstance,ref TResult,ref Anvil.Unity.DOTS.Data.VDUpdater{TKey,TInstance})"/>
/// where the instance is not ready to write it's result and should be updated again the next frame.
/// </summary>
/// <param name="instance">The instance to update again next frame</param>
/// <param name="updater">The <see cref="VDUpdater{TKey,TInstance}"/> the instance was from.</param>
/// <typeparam name="TKey">The type of key for the instance.</typeparam>
/// <typeparam name="TInstance">The type of the instance struct.</typeparam>
public static void ContinueOn<TKey, TInstance>(this TInstance instance, ref VDUpdater<TKey, TInstance> updater)
where TKey : struct, IEquatable<TKey>
where TInstance : struct, IKeyedData<TKey>
{
updater.Continue(ref instance);
}
}
}
| 55.178082 | 177 | 0.64573 | [
"MIT"
] | decline-cookies/anvil-ecs-dots-core | Scripts/Runtime/Data/VirtualData/VirtualDataExtensions.cs | 4,028 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
namespace ForecastTool
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
} | 25.52381 | 62 | 0.705224 | [
"MIT"
] | raisaurabh777/ForecastingTool | ForecastTool/ForecastTool/Global.asax.cs | 538 | C# |
namespace DLLInjection {
using System;
[AttributeUsage(AttributeTargets.Assembly)]
public class AssemblyInjectedAttribute : Attribute {
}
public abstract class ShouldBeInjectedAttribute : Attribute {
}
}
| 15.666667 | 65 | 0.714894 | [
"MIT"
] | m1stm4o/Helloworld | Assets/DLLInjection/Scripts/InjectionAttributes.cs | 237 | C# |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
using System.Collections.ObjectModel;
namespace Pixytech.Desktop.Presentation.DataVisualization.Charting
{
/// <summary>
/// Represents a series in a chart.
/// </summary>
public interface ISeries : IRequireSeriesHost
{
/// <summary>
/// Gets a list of the legend items associated with the object.
/// </summary>
ObservableCollection<object> LegendItems { get; }
}
} | 31.75 | 72 | 0.680315 | [
"Apache-2.0"
] | Pixytech/Frameworks | Pixytech.Desktop.Presentation/DataVisualization/Charting/Series/ISeries.cs | 637 | C# |
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
public class SelectOtherWhenSelected : global::UnityEngine.MonoBehaviour, global::UnityEngine.EventSystems.ISelectHandler, global::UnityEngine.EventSystems.IEventSystemHandler
{
public void Select(global::UnityEngine.GameObject go)
{
global::UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject(go ?? base.gameObject);
}
public void OnSelect(global::UnityEngine.EventSystems.BaseEventData eventData)
{
base.StartCoroutine(this.Select());
}
public global::System.Collections.IEnumerator Select()
{
yield return null;
this.Select(this.target);
yield break;
}
public global::UnityEngine.GameObject target;
}
| 27.222222 | 175 | 0.8 | [
"CC0-1.0"
] | FreyaFreed/mordheim | Assembly-CSharp/SelectOtherWhenSelected.cs | 737 | 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 apigateway-2015-07-09.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.APIGateway.Model
{
/// <summary>
/// Represents an authorization layer for methods. If enabled on a method, API Gateway
/// will activate the authorizer when a client calls the method.
///
/// <div class="seeAlso"> <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html">Use
/// Lambda Function as Authorizer</a> <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html">Use
/// Cognito User Pool as Authorizer</a> </div>
/// </summary>
public partial class Authorizer
{
private string _authorizerCredentials;
private int? _authorizerResultTtlInSeconds;
private string _authorizerUri;
private string _authType;
private string _id;
private string _identitySource;
private string _identityValidationExpression;
private string _name;
private List<string> _providerarNs = new List<string>();
private AuthorizerType _type;
/// <summary>
/// Gets and sets the property AuthorizerCredentials.
/// <para>
/// Specifies the required credentials as an IAM role for API Gateway to invoke the authorizer.
/// To specify an IAM role for API Gateway to assume, use the role's Amazon Resource Name
/// (ARN). To use resource-based permissions on the Lambda function, specify null.
/// </para>
/// </summary>
public string AuthorizerCredentials
{
get { return this._authorizerCredentials; }
set { this._authorizerCredentials = value; }
}
// Check to see if AuthorizerCredentials property is set
internal bool IsSetAuthorizerCredentials()
{
return this._authorizerCredentials != null;
}
/// <summary>
/// Gets and sets the property AuthorizerResultTtlInSeconds.
/// <para>
/// The TTL in seconds of cached authorizer results. If it equals 0, authorization caching
/// is disabled. If it is greater than 0, API Gateway will cache authorizer responses.
/// If this field is not set, the default value is 300. The maximum value is 3600, or
/// 1 hour.
/// </para>
/// </summary>
public int AuthorizerResultTtlInSeconds
{
get { return this._authorizerResultTtlInSeconds.GetValueOrDefault(); }
set { this._authorizerResultTtlInSeconds = value; }
}
// Check to see if AuthorizerResultTtlInSeconds property is set
internal bool IsSetAuthorizerResultTtlInSeconds()
{
return this._authorizerResultTtlInSeconds.HasValue;
}
/// <summary>
/// Gets and sets the property AuthorizerUri.
/// <para>
/// Specifies the authorizer's Uniform Resource Identifier (URI). For <code>TOKEN</code>
/// or <code>REQUEST</code> authorizers, this must be a well-formed Lambda function URI,
/// for example, <code>arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:{account_id}:function:{lambda_function_name}/invocations</code>.
/// In general, the URI has this form <code>arn:aws:apigateway:{region}:lambda:path/{service_api}</code>,
/// where <code>{region}</code> is the same as the region hosting the Lambda function,
/// <code>path</code> indicates that the remaining substring in the URI should be treated
/// as the path to the resource, including the initial <code>/</code>. For Lambda functions,
/// this is usually of the form <code>/2015-03-31/functions/[FunctionARN]/invocations</code>.
/// </para>
/// </summary>
public string AuthorizerUri
{
get { return this._authorizerUri; }
set { this._authorizerUri = value; }
}
// Check to see if AuthorizerUri property is set
internal bool IsSetAuthorizerUri()
{
return this._authorizerUri != null;
}
/// <summary>
/// Gets and sets the property AuthType.
/// <para>
/// Optional customer-defined field, used in OpenAPI imports and exports without functional
/// impact.
/// </para>
/// </summary>
public string AuthType
{
get { return this._authType; }
set { this._authType = value; }
}
// Check to see if AuthType property is set
internal bool IsSetAuthType()
{
return this._authType != null;
}
/// <summary>
/// Gets and sets the property Id.
/// <para>
/// The identifier for the authorizer resource.
/// </para>
/// </summary>
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property IdentitySource.
/// <para>
/// The identity source for which authorization is requested. <ul><li>For a <code>TOKEN</code>
/// or <code>COGNITO_USER_POOLS</code> authorizer, this is required and specifies the
/// request header mapping expression for the custom header holding the authorization
/// token submitted by the client. For example, if the token header name is <code>Auth</code>,
/// the header mapping expression is <code>method.request.header.Auth</code>.</li><li>For
/// the <code>REQUEST</code> authorizer, this is required when authorization caching is
/// enabled. The value is a comma-separated string of one or more mapping expressions
/// of the specified request parameters. For example, if an <code>Auth</code> header,
/// a <code>Name</code> query string parameter are defined as identity sources, this value
/// is <code>method.request.header.Auth, method.request.querystring.Name</code>. These
/// parameters will be used to derive the authorization caching key and to perform runtime
/// validation of the <code>REQUEST</code> authorizer by verifying all of the identity-related
/// request parameters are present, not null and non-empty. Only when this is true does
/// the authorizer invoke the authorizer Lambda function, otherwise, it returns a 401
/// Unauthorized response without calling the Lambda function. The valid value is a string
/// of comma-separated mapping expressions of the specified request parameters. When the
/// authorization caching is not enabled, this property is optional.</li></ul>
/// </para>
/// </summary>
public string IdentitySource
{
get { return this._identitySource; }
set { this._identitySource = value; }
}
// Check to see if IdentitySource property is set
internal bool IsSetIdentitySource()
{
return this._identitySource != null;
}
/// <summary>
/// Gets and sets the property IdentityValidationExpression.
/// <para>
/// A validation expression for the incoming identity token. For <code>TOKEN</code> authorizers,
/// this value is a regular expression. For <code>COGNITO_USER_POOLS</code> authorizers,
/// API Gateway will match the <code>aud</code> field of the incoming token from the client
/// against the specified regular expression. It will invoke the authorizer's Lambda function
/// when there is a match. Otherwise, it will return a 401 Unauthorized response without
/// calling the Lambda function. The validation expression does not apply to the <code>REQUEST</code>
/// authorizer.
/// </para>
/// </summary>
public string IdentityValidationExpression
{
get { return this._identityValidationExpression; }
set { this._identityValidationExpression = value; }
}
// Check to see if IdentityValidationExpression property is set
internal bool IsSetIdentityValidationExpression()
{
return this._identityValidationExpression != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// [Required] The name of the authorizer.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property ProviderARNs.
/// <para>
/// A list of the Amazon Cognito user pool ARNs for the <code>COGNITO_USER_POOLS</code>
/// authorizer. Each element is of this format: <code>arn:aws:cognito-idp:{region}:{account_id}:userpool/{user_pool_id}</code>.
/// For a <code>TOKEN</code> or <code>REQUEST</code> authorizer, this is not defined.
///
/// </para>
/// </summary>
public List<string> ProviderARNs
{
get { return this._providerarNs; }
set { this._providerarNs = value; }
}
// Check to see if ProviderARNs property is set
internal bool IsSetProviderARNs()
{
return this._providerarNs != null && this._providerarNs.Count > 0;
}
/// <summary>
/// Gets and sets the property Type.
/// <para>
/// The authorizer type. Valid values are <code>TOKEN</code> for a Lambda function using
/// a single authorization token submitted in a custom header, <code>REQUEST</code> for
/// a Lambda function using incoming request parameters, and <code>COGNITO_USER_POOLS</code>
/// for using an Amazon Cognito user pool.
/// </para>
/// </summary>
public AuthorizerType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
}
} | 41.448905 | 182 | 0.620146 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/APIGateway/Generated/Model/Authorizer.cs | 11,357 | C# |
using System;
using System.Windows.Forms;
namespace Calculator
{
static class Program
{
/// <summary>
/// アプリケーションのメイン エントリ ポイントです。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 21.45 | 66 | 0.536131 | [
"MIT"
] | soundofhorizon/LearnC | LearnC-GUI/WindowsFormsApp1/Calculator/Program.cs | 477 | 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 TodoApi.Data;
namespace TodoApi.Migrations
{
[DbContext(typeof(TodoContext))]
[Migration("20210209183836_test")]
partial class test
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityColumns()
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.2");
modelBuilder.Entity("TodoApi.Models.TodoItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<DateTime?>("DueDate")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<int>("PriorityLevel")
.HasColumnType("int");
b.Property<bool>("finished")
.HasColumnType("bit");
b.Property<DateTime?>("finishedOn")
.HasColumnType("datetime2");
b.HasKey("Id");
b.ToTable("TodoItems");
});
#pragma warning restore 612, 618
}
}
}
| 32.328125 | 75 | 0.517158 | [
"MIT"
] | bjornvandewalle/todo-api | Migrations/20210209183836_test.Designer.cs | 2,071 | C# |
using System;
namespace Svelto.ECS
{
public interface IDisposingEngine: IDisposable
{
bool isDisposing { set; }
}
} | 15.111111 | 50 | 0.654412 | [
"MIT"
] | Ujinjinjin/Svelto.ECS | Svelto.ECS/Core/IDisposingEngine.cs | 136 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Baseline;
using Baseline.Dates;
using Lamar;
using Microsoft.Extensions.Hosting;
namespace Jasper.Tracking
{
public class TrackedSession : ITrackedSession
{
private readonly Cache<Guid, EnvelopeHistory> _envelopes
= new Cache<Guid, EnvelopeHistory>(id => new EnvelopeHistory(id));
private readonly IList<ITrackedCondition> _conditions = new List<ITrackedCondition>();
private readonly IList<Exception> _exceptions = new List<Exception>();
private readonly TaskCompletionSource<TrackingStatus> _source;
private readonly Stopwatch _stopwatch = new Stopwatch();
private readonly IHost _primaryHost;
private TrackingStatus _status = TrackingStatus.Active;
private readonly IList<MessageTrackingLogger> _otherHosts = new List<MessageTrackingLogger>();
private readonly MessageTrackingLogger _primaryLogger;
public TrackedSession(IHost host)
{
_primaryHost = host;
_source = new TaskCompletionSource<TrackingStatus>();
_primaryLogger = host?.GetTrackingLogger();
}
public void WatchOther(IHost host)
{
_otherHosts.Add(host.GetTrackingLogger());
}
public TimeSpan Timeout { get; set; } = 5.Seconds();
public bool AssertNoExceptions { get; set; } = true;
public Func<IMessageContext, Task> Execution { get; set; } = c => Task.CompletedTask;
public void AssertNoExceptionsWereThrown()
{
if (_exceptions.ToArray().Any()) throw new AggregateException(_exceptions);
}
public void AssertNotTimedOut()
{
if (Status == TrackingStatus.TimedOut)
{
var message = $"This {nameof(TrackedSession)} timed out before all activity completed.\nActivity detected:\n{AllRecordsInOrder().Select(x => x.ToString()).Join("\n")}";
if (_conditions.Any())
{
message += $"\nConditions:\n{_conditions.Select(x => $"{x} ({x.IsCompleted()})").Join("\n")}";
}
throw new TimeoutException(message);
}
}
public TrackingStatus Status
{
get => _status;
private set
{
_status = value;
_source.TrySetResult(value);
if (value == TrackingStatus.Completed) _stopwatch.Stop();
}
}
public bool AlwaysTrackExternalTransports { get; set; } = false;
public T FindSingleTrackedMessageOfType<T>()
{
return AllRecordsInOrder()
.Select(x => x.Envelope.Message)
.OfType<T>()
.Distinct()
.Single();
}
public IEnumerable<object> UniqueMessages()
{
return _envelopes.Select(x => x.Message);
}
public IEnumerable<object> UniqueMessages(EventType eventType)
{
return _envelopes
.Where(x => x.Has(eventType))
.Select(x => x.MessageFor(eventType));
}
public T FindSingleTrackedMessageOfType<T>(EventType eventType)
{
return AllRecordsInOrder()
.Where(x => x.EventType == eventType)
.Select(x => x.Envelope.Message)
.OfType<T>()
.Distinct()
.Single();
}
public EnvelopeRecord[] FindEnvelopesWithMessageType<T>(EventType eventType)
{
return _envelopes
.SelectMany(x => x.Records)
.Where(x => x.EventType == eventType)
.Where(x => x.Envelope.Message is T)
.ToArray();
}
public EnvelopeRecord[] FindEnvelopesWithMessageType<T>()
{
return _envelopes
.SelectMany(x => x.Records)
.Where(x => x.Envelope.Message is T)
.ToArray();
}
public EnvelopeRecord[] AllRecordsInOrder()
{
return _envelopes.SelectMany(x => x.Records).OrderBy(x => x.SessionTime).ToArray();
}
public bool HasNoRecordsOfAnyKind()
{
return !_envelopes.Any();
}
public EnvelopeRecord[] AllRecordsInOrder(EventType eventType)
{
return _envelopes
.SelectMany(x => x.Records)
.Where(x => x.EventType == eventType)
.OrderBy(x => x.SessionTime)
.ToArray();
}
private void setActiveSession(TrackedSession session)
{
_primaryLogger.ActiveSession = session;
foreach (var logger in _otherHosts)
{
logger.ActiveSession = session;
}
}
public async Task ExecuteAndTrack()
{
setActiveSession(this);
_stopwatch.Start();
try
{
using (var scope = _primaryHost.Services.As<IContainer>().GetNestedContainer())
{
var context = scope.GetInstance<IMessageContext>();
await Execution(context);
}
}
catch (Exception)
{
cleanUp();
throw;
}
startTimeoutTracking();
await _source.Task;
cleanUp();
if (AssertNoExceptions) AssertNoExceptionsWereThrown();
AssertNotTimedOut();
}
public Task Track()
{
_stopwatch.Start();
startTimeoutTracking();
return _source.Task;
}
private void cleanUp()
{
setActiveSession(null);
_stopwatch.Stop();
}
private void startTimeoutTracking()
{
#pragma warning disable 4014
Task.Factory.StartNew(async () =>
#pragma warning restore 4014
{
await Task.Delay(Timeout);
Status = TrackingStatus.TimedOut;
});
}
public void Record(EventType eventType, Envelope envelope, string serviceName, int uniqueNodeId,
Exception ex = null)
{
var history = _envelopes[envelope.Id];
var record = new EnvelopeRecord(eventType, envelope, _stopwatch.ElapsedMilliseconds, ex)
{
ServiceName = serviceName,
UniqueNodeId = uniqueNodeId
};
if (AlwaysTrackExternalTransports || _otherHosts.Any())
{
history.RecordCrossApplication(record);
}
else
{
history.RecordLocally(record);
}
foreach (var condition in _conditions)
{
condition.Record(record);
}
if (ex != null) _exceptions.Add(ex);
if (IsCompleted()) Status = TrackingStatus.Completed;
}
public bool IsCompleted()
{
if (!_envelopes.All(x => x.IsComplete())) return false;
return !_conditions.Any() || _conditions.All(x => x.IsCompleted());
}
public void LogException(Exception exception, string serviceName)
{
_exceptions.Add(exception);
}
public void AddCondition(ITrackedCondition condition)
{
_conditions.Add(condition);
}
}
}
| 27.974453 | 184 | 0.538421 | [
"MIT"
] | ejsmith/jasper | src/Jasper/Tracking/TrackedSession.cs | 7,665 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Skoruba.IdentityServer4.Admin.BusinessLogic.Dtos.Configuration
{
public class ApiScopeDto
{
public ApiScopeDto()
{
UserClaims = new List<string>();
}
public bool ShowInDiscoveryDocument { get; set; } = true;
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
public bool Required { get; set; }
public bool Emphasize { get; set; }
public List<string> UserClaims { get; set; }
public string UserClaimsItems { get; set; }
public bool Enabled { get; set; } = true;
public List<ApiScopePropertyDto> ApiScopeProperties { get; set; }
}
} | 21.694444 | 72 | 0.690141 | [
"MIT"
] | 861191244/IdentityServer4.Admin | src/Skoruba.IdentityServer4.Admin.BusinessLogic/Dtos/Configuration/ApiScopeDto.cs | 783 | C# |
using System;
using System.IO;
using GoldenLlama.Cnc.Test;
namespace CNCTestBoard
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Generating G-Code test!");
var tester = new BackAndForthRateTester
{
FeedRateInitial = 40.0,
FeedRateIncrement = 1,
StepDown = 0.025, //0.6mm
TestDistance = 3,
MaterialThickness = 0.39,
MaxIterations = 30,
RapidRate = 30,
SpindleSpeed = 20000,
PauseTimeIncrement = 0,
PauseTimeInitial = 0,
};
string operations = tester.GenerateTest();
string targetFilePath = Path.Combine(Environment.CurrentDirectory,
"Generated Tests",
"BackAndForthRateTester.nc");
var fileInfo = new FileInfo(targetFilePath);
if (!fileInfo.Directory.Exists) {
fileInfo.Directory.Create();
}
using (var output = new StreamWriter(fileInfo.OpenWrite()))
{
output.WriteLine(operations);
}
Console.WriteLine(operations);
}
}
}
| 29.911111 | 81 | 0.481426 | [
"MIT"
] | Kynreuten/CNCTestBoard | Program.cs | 1,348 | C# |
using UnityEngine;
public class LookAtCamera:MonoBehaviour{
public Camera lookAtCamera;
public bool lookOnlyOnAwake;
public void Start() {
if(lookAtCamera == null){
lookAtCamera = Camera.main;
}
if(lookOnlyOnAwake){
LookCamera();
}
}
public void Update() {
if(!lookOnlyOnAwake){
LookCamera();
}
}
public void LookCamera() {
transform.LookAt(lookAtCamera.transform);
}
} | 18.28 | 46 | 0.617068 | [
"Apache-2.0"
] | BeatBender/ConoctiumGold | Assets/CustomAssets/3D Particles/Scripts/LookAtCamera.cs | 457 | C# |
#region Header
//
// Copyright 2003-2021 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
#endregion // Header
using System;
namespace RevitLookup.Snoop.Data
{
/// <summary>
/// Snoop.Data class to hold and format an Angle value.
/// </summary>
public class Angle : Data
{
protected double m_val;
public
Angle(string label, double val)
: base(label)
{
m_val = val;
}
public override string
StrValue()
{
// convert from radians to degrees so we can read it
// TBD: probably need an API to format in current dispaly units
double degAng = GeomUtils.RadiansToDegrees(m_val);
return degAng.ToString();
}
}
}
| 30.333333 | 73 | 0.680708 | [
"MIT"
] | BobbyCJones/RevitLookup | CS/Snoop/Data/Angle.cs | 1,638 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
using System.Linq;
public class SettingsMenu : MonoBehaviour
{
public AudioMixer audioMixer;
public Dropdown resolutionDropdown;
Resolution[] resolutions;
void Start()
{
resolutions = Screen.resolutions.Select(resolution => new Resolution { width = resolution.width, height = resolution.height }).Distinct().ToArray();
resolutionDropdown.ClearOptions(); // Clear list of resolutions initially.
List<string> options = new List<string>();
int currentResolutionIndex = 0;
for (int i = 0; i < resolutions.Length; i++) // Loop through resolutions, format to strings, add them to options list.
{
string option = resolutions[i].width + " x " + resolutions[i].height;
options.Add(option);
if (resolutions[i].width == Screen.currentResolution.width && // Check the current resolution of the users system,
resolutions[i].height == Screen.currentResolution.height) // and default to that setting in the options menu on start.
{
currentResolutionIndex = i;
}
}
resolutionDropdown.AddOptions(options);
resolutionDropdown.value = currentResolutionIndex;
resolutionDropdown.RefreshShownValue();
}
public void SetResolution (int resolutionIndex)
{
Resolution resolution = resolutions[resolutionIndex];
Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
}
// Method for changing volume in menu using slider.
public void SetVolume (float volume)
{
audioMixer.SetFloat("volume", volume);
}
public void SetMusicVolume (float volume)
{
audioMixer.SetFloat("musicVolume", volume);
}
// Method for changing the Graphics quality preset via dropdown menu.
public void SetQuality (int qualityIndex)
{
QualitySettings.SetQualityLevel(qualityIndex);
}
// Method for changing to fullscreen mode using toggle in menu
// TODO: This might change to a dropdown to include Windowed and Borderless mode.
public void SetFullScreen (bool isFullscreen)
{
Screen.fullScreen = isFullscreen;
}
}
| 32.736111 | 156 | 0.670344 | [
"MIT"
] | DannyT115/FYP-2020-2021 | VR_Simulation/Assets/Project/Scripts/SettingsMenu.cs | 2,359 | C# |
using Ametista.Core.Entity;
using Ametista.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Ametista.Infrastructure.Persistence.Repository
{
public class GemstoneWriteOnlyRepository : IWriteOnlyRepository<Gemstone>
{
private readonly WriteDbContext context;
public GemstoneWriteOnlyRepository(WriteDbContext context)
{
this.context = context ?? throw new ArgumentNullException(nameof(context));
}
public async Task<bool> Add(Gemstone entity)
{
context.Gemstones.Add(entity);
return await context.SaveChangesAsync() > 0;
}
public async Task<bool> Delete(Gemstone entity)
{
context.Gemstones.Remove(entity);
return await context.SaveChangesAsync() > 0;
}
public async Task<Gemstone> Find(Guid id)
{
return await context.Gemstones.FindAsync(id);
}
public async Task<bool> Update(Gemstone entity)
{
context.Gemstones.Update(entity);
return await context.SaveChangesAsync() > 0;
}
}
}
| 26.108696 | 87 | 0.6403 | [
"MIT"
] | ivanpaulovich/cqrs-clean-eventual-consistency | src/Ametista.Infrastructure/Persistence/Repository/GemstoneWriteOnlyRepository.cs | 1,203 | C# |
using System;
using System.Threading.Tasks;
using NUnit.Framework;
using Shouldly;
using Statiq.Testing;
namespace Statiq.Common.Tests.Config
{
[TestFixture]
public class ConfigExtensionsFixture : BaseFixture
{
public class GetValueAsyncTests : ConfigExtensionsFixture
{
[Test]
public async Task ReturnsDefaultTaskForNullIntConfig()
{
// Given, When
Task<int> task = ((Config<int>)null).GetValueAsync(null, null);
// Then
(await task).ShouldBe(default);
}
[Test]
public async Task ReturnsDefaultTaskForNullObjectConfig()
{
// Given, When
Task<object> task = ((Config<object>)null).GetValueAsync(null, null);
// Then
(await task).ShouldBe(default);
}
[Test]
public async Task ConvertsValue()
{
// Given
TestExecutionContext context = new TestExecutionContext();
Config<object> config = "10";
// When
int result = await config.GetValueAsync<int>(null, context);
// Then
result.ShouldBe(10);
}
[Test]
public async Task ThrowsIfNoConversion()
{
// Given
TestExecutionContext context = new TestExecutionContext();
Config<object> config = "abc";
// When, Then
await Should.ThrowAsync<InvalidOperationException>(async () => await config.GetValueAsync<int>(null, context));
}
}
public class TryGetValueAsyncTests : ConfigExtensionsFixture
{
[Test]
public async Task ConvertsValue()
{
// Given
TestExecutionContext context = new TestExecutionContext();
Config<object> config = "10";
// When
int result = await config.TryGetValueAsync<int>(null, context);
// Then
result.ShouldBe(10);
}
[Test]
public async Task ReturnsDefaultValueIfNoConversion()
{
// Given
TestExecutionContext context = new TestExecutionContext();
Config<object> config = "abc";
// When
int result = await config.TryGetValueAsync<int>(null, context);
// Then
result.ShouldBe(default);
}
}
public class EnsureNonNullTests : ConfigExtensionsFixture
{
[Test]
public void ThrowsForNullConfig()
{
// Given
Config<object> config = null;
// When, Then
Should.Throw<ArgumentNullException>(() => config.EnsureNonNull());
}
[Test]
public void DoesNotThrowForNonNullConfig()
{
// Given
Config<object> config = Common.Config.FromValue(true);
// When, Then
Should.NotThrow(() => config.EnsureNonNull());
}
}
public class EnsureNonDocumentTests : ConfigExtensionsFixture
{
[Test]
public void ThrowsForNullConfig()
{
// Given
Config<object> config = null;
// When, Then
Should.Throw<ArgumentNullException>(() => config.EnsureNonDocument());
}
[Test]
public void ThrowsForDocumentConfig()
{
// Given
Config<object> config = Common.Config.FromDocument(_ => true);
// When, Then
Should.Throw<ArgumentException>(() => config.EnsureNonDocument());
}
[Test]
public void DoesNotThrowForNonDocumentConfig()
{
// Given
Config<object> config = Common.Config.FromContext(_ => true);
// When, Then
Should.NotThrow(() => config.EnsureNonDocument());
}
}
}
}
| 29.189189 | 127 | 0.488194 | [
"MIT"
] | JimBobSquarePants/Statiq.Framework | tests/core/Statiq.Common.Tests/Config/ConfigExtensionsFixture.cs | 4,322 | 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("Compression CS sample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)]
| 34.733333 | 84 | 0.742802 | [
"MIT"
] | Ranin26/msdn-code-gallery-microsoft | Official Windows Platform Sample/Windows 8 app samples/[C#]-Windows 8 app samples/C#/Windows 8 app samples/Compression sample (Windows 8)/C#/Properties/AssemblyInfo.cs | 1,042 | C# |
using System;
using System.IO;
namespace EditorTexto
{
class Program
{
static void Main(string[] args)
{
Menu();
}
static void Menu()
{
Console.Clear();
Console.WriteLine("O que vamos fazer hoje? :)");
Console.WriteLine("1 - Abrir arquivo");
Console.WriteLine("2 - Criar novo arquivo");
Console.WriteLine("0 - Sair :(");
short opcao = short.Parse(Console.ReadLine());
switch (opcao)
{
case 0: System.Environment.Exit(0); break;
case 1: Abrir(); break;
case 2: Editar(); break;
default: Menu(); break;
}
}
static void Abrir()
{
Console.Clear();
Console.WriteLine("Por favor, digite o caminho do caminho.");
string path = Console.ReadLine();
if ((File.Exists(path)))
{
using (var file = new StreamReader(path))
{
string texto = file.ReadToEnd();
Console.Clear();
Console.WriteLine(texto);
}
Console.WriteLine("");
Console.WriteLine("Pressione qualquer tecla para voltar ao menu inicial.");
Console.ReadLine();
Menu();
}
else
{
Console.WriteLine("O arquivo não foi encontrado");
Console.WriteLine("Pressione qualquer tecla para voltar ao menu inicial.");
Console.ReadLine();
Menu();
}
}
static void Editar()
{
Console.Clear();
Console.WriteLine("Digite seu texto aqui. :) (Esc para sair)");
Console.WriteLine("-------------------------");
string texto = "";
do
{
texto += Console.ReadLine();
texto += Environment.NewLine;
}
while (Console.ReadKey().Key != ConsoleKey.Escape);
Salvar(texto);
}
static void Salvar(string texto)
{
Console.Clear();
Console.WriteLine("Por favor, digite o caminho para salvar o caminho.");
string path = Console.ReadLine();
using (var file = new StreamWriter(path))
{
file.Write(texto);
}
Console.Clear();
Console.WriteLine("Arquivo salvo com sucesso!");
Console.WriteLine($"Caminho: {path}");
Console.WriteLine("Pressione qualquer tecla para voltar ao menu inicial.");
Console.ReadLine();
Menu();
}
}
}
| 30.166667 | 92 | 0.445787 | [
"MIT"
] | NatanAmurim/EditorTexto | Program.cs | 2,899 | C# |
using System;
using System.Linq;
using Commerce.Services;
namespace Commerce.Models;
public record Cart(CartItem[] Items) {
public string SubTotal => "$350,97";
public string Tax => "$15,75";
public string Total => "$405,29";
}
| 19.5 | 38 | 0.705128 | [
"Apache-2.0"
] | AndreAbrantes/uno.extensions | samples/Commerce/Commerce.Shared/Models/Cart.cs | 236 | C# |
// using System.Collections;
// using System.Collections.Generic;
// using UnityEngine;
// using UnityEngine.Tilemaps;
// public class HighlighterMouseTile : MonoBehaviour
// {
// public Tilemap highlightMap;
// // public Tilemap tilemap;
// public TileBase highlightTile;
// void Start()
// {
// Vector3Int previousTileCoordinate = Vector3Int.zero;
// }
// void Update()
// {
// //set the previously highlighted tile back to null
// if(previousTileCoordinate != null)
// {
// highlightMap.SetTile(previousTileCoordinate, null);
// }
// //We need to highlight the tile on mousover. First get the curent position
// Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// Vector3Int tileCoordinate = highlightMap.WorldToCell(mouseWorldPos);
// //store the current position for the next frame
// previousTileCoordinate = tileCoordinate;
// //set the current tile to the highlighted version
// highlightMap.SetTile(tileCoordinate, highlightTile);
// }
// //This line outside the Update
// // public TileBase highlightTile;
// // void Update() {
// // Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// // Vector3Int tileCoordinate = highlightMap.WorldToCell(mouseWorldPos);
// // if(tileCoordinate != previousTileCoordinate ){
// // highlightMap.SetTile(previousTileCoordinate, null);
// // highlightMap.SetTile(tileCoordinate,highlightTile);
// // previousTileCoordinate = tileCoordinate;
// // }
// // Start is called before the first frame update
// // Update is called once per frame
// }
| 32.392857 | 88 | 0.632304 | [
"MIT"
] | aafishman/ACID | Assets/HighlighterMouseTile.cs | 1,816 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Xml;
using System.Globalization;
using System.IO;
using DigitalPlatform;
using DigitalPlatform.Xml;
using DigitalPlatform.OPAC.Server;
using DigitalPlatform.OPAC.Web;
// using DigitalPlatform.CirculationClient;
using DigitalPlatform.LibraryClient;
public partial class UserInfo : MyWebPage
{
//OpacApplication app = null;
//SessionInfo sessioninfo = null;
#if NO
protected override void InitializeCulture()
{
WebUtil.InitLang(this);
base.InitializeCulture();
}
#endif
protected void Page_Init(object sender, EventArgs e)
{
if (WebUtil.PrepareEnvironment(this,
ref app,
ref sessioninfo) == false)
return;
this.TitleBarControl1.CurrentColumn = DigitalPlatform.OPAC.Web.TitleColumn.Browse;
this.TitleBarControl1.LibraryCodeChanged += new LibraryCodeChangedEventHandler(TitleBarControl1_LibraryCodeChanged);
this.TitleBarControl1.LibraryCodeChanged -= new LibraryCodeChangedEventHandler(TitleBarControl1_LibraryCodeChanged);
this.BrowseSearchResultControl1.DefaultFormatName = "详细";
this.BrowseSearchResultControl1.Visible = true;
}
void TitleBarControl1_LibraryCodeChanged(object sender, LibraryCodeChangedEventArgs e)
{
this.BrowseSearchResultControl1.ResetAllItemsControlPager();
}
protected void Page_Load(object sender, EventArgs e)
{
if (WebUtil.PrepareEnvironment(this,
ref app,
ref sessioninfo) == false)
return;
// 是否登录?
if (sessioninfo.UserID == "")
{
sessioninfo.UserID = "public";
sessioninfo.IsReader = false;
}
string strError = "";
int nRet = 0;
#if NO
SessionInfo temp_sessioninfo = new SessionInfo(app);
temp_sessioninfo.UserID = app.ManagerUserName;
temp_sessioninfo.Password = app.ManagerPassword;
temp_sessioninfo.IsReader = false;
#endif
LibraryChannel channel = app.GetChannel();
try
{
bool bHintDisplayName = false; // []暗示为显示名
string strDisplayName = this.Request["displayName"];
string strBarcode = this.Request["barcode"];
string strEncyptBarcode = Request.QueryString["encrypt_barcode"];
string strText = "";
// 如果为加密的条码形态
if (String.IsNullOrEmpty(strEncyptBarcode) == false)
{
strBarcode = OpacApplication.DecryptPassword(strEncyptBarcode);
if (strBarcode == null)
{
strError = "encrypt_barcode参数值格式错误";
goto ERROR1;
}
bHintDisplayName = true;
goto SEARCH_COMMENT;
}
{
if (String.IsNullOrEmpty(strDisplayName) == false)
{
if (strDisplayName.IndexOfAny(new char[] { '[', ']' }) != -1)
bHintDisplayName = true;
strDisplayName = strDisplayName.Replace("[", "").Trim();
strDisplayName = strDisplayName.Replace("]", "").Trim();
}
nRet = 0;
string strReaderXml = "";
string strOutputReaderPath = "";
if (String.IsNullOrEmpty(strDisplayName) == false)
{
byte[] timestamp = null;
string[] results = null;
long lRet = // temp_sessioninfo.Channel.
channel.GetReaderInfo(
null,
"@displayName:" + strDisplayName,
"xml",
out results,
out strOutputReaderPath,
out timestamp,
out strError);
if (lRet == -1)
goto ERROR1;
if (lRet == 0 && bHintDisplayName == true)
{
strBarcode = "";
goto SEARCH_COMMENT;
}
strReaderXml = results[0];
// CONTINUE1:
if (nRet == 0)
strBarcode = strDisplayName;
}
// SEARCH_BARCODE:
if (nRet == 0 && String.IsNullOrEmpty(strBarcode) == false)
{
strReaderXml = "";
byte[] timestamp = null;
string[] results = null;
long lRet = // temp_sessioninfo.Channel.
channel.GetReaderInfo(
null,
strBarcode,
"xml",
out results,
out strOutputReaderPath,
out timestamp,
out strError);
if (lRet == -1)
goto ERROR1;
if (lRet == 0)
{
goto SEARCH_COMMENT;
}
strReaderXml = results[0];
}
if (nRet == 0)
{
/*
strError = "读者显示名或者证条码号 '" + strDisplayName + "' 不存在";
goto ERROR1;
* */
if (String.IsNullOrEmpty(strBarcode) == true)
strBarcode = strDisplayName;
goto SEARCH_COMMENT;
}
XmlDocument readerdom = null;
nRet = OpacApplication.LoadToDom(strReaderXml,
out readerdom,
out strError);
if (nRet == -1)
{
strError = "装载读者记录 '" + strOutputReaderPath + "' 进入XML DOM时发生错误: " + strError;
goto ERROR1;
}
strDisplayName = DomUtil.GetElementText(readerdom.DocumentElement,
"displayName");
strBarcode = DomUtil.GetElementInnerXml(readerdom.DocumentElement,
"barcode");
}
SEARCH_COMMENT:
strText = strDisplayName;
if (String.IsNullOrEmpty(strText) == true)
strText = strBarcode;
this.Label_name.Text = strText;
string strRecipient = "";
/*
if (String.IsNullOrEmpty(strDisplayName) == false)
{
if (strDisplayName.IndexOf("[") == -1)
strRecipient = "[" + strDisplayName + "]";
else
strRecipient = strDisplayName;
if (String.IsNullOrEmpty(strEncyptBarcode) == false)
strRecipient += " encrypt_barcode:" + strEncyptBarcode;
}
else
strRecipient = strBarcode;
* */
strRecipient = BoxesInfo.BuildOneAddress(strDisplayName, strBarcode);
string strSendMessageUrl = "./message.aspx?recipient=" + HttpUtility.UrlEncode(strRecipient);
this.Button_sendMessage.OnClientClick = "window.open('" + strSendMessageUrl + "','_blank'); return cancelClick();";
LoginState loginstate = GlobalUtil.GetLoginState(this.Page);
if (loginstate == LoginState.NotLogin || loginstate == LoginState.Public)
this.Button_sendMessage.Enabled = false;
this.BrowseSearchResultControl1.Title = strText + " 所发表的书评";
if (String.IsNullOrEmpty(strEncyptBarcode) == false)
this.Image_photo.ImageUrl = "./getphoto.aspx?encrypt_barcode=" + HttpUtility.UrlEncode(strEncyptBarcode) + "&displayName=" + HttpUtility.UrlEncode(strDisplayName);
else
this.Image_photo.ImageUrl = "./getphoto.aspx?barcode=" + HttpUtility.UrlEncode(strBarcode);
this.Image_photo.Width = 128;
this.Image_photo.Height = 128;
if (this.IsPostBack == false)
{
string strXml = "";
if (String.IsNullOrEmpty(strDisplayName) == false
&& String.IsNullOrEmpty(strBarcode) == false)
{
// 创建评注记录XML检索式
// 用作者和作者显示名共同限定检索
nRet = ItemSearchControl.BuildCommentQueryXml(
app,
strDisplayName,
strBarcode,
"<全部>",
15000, // app.SearchMaxResultCount
true,
out strXml,
out strError);
if (nRet == -1)
goto ERROR1;
}
else if (String.IsNullOrEmpty(strBarcode) == false)
{
// 创建XML检索式
nRet = ItemSearchControl.BuildQueryXml(
this.app,
"comment",
strBarcode,
"<全部>",
"作者",
"exact",
15000, // app.SearchMaxResultCount
true,
out strXml,
out strError);
if (nRet == -1)
goto ERROR1;
}
else if (String.IsNullOrEmpty(strDisplayName) == false)
{
// 创建XML检索式
nRet = ItemSearchControl.BuildQueryXml(
this.app,
"comment",
strDisplayName,
"<全部>",
"作者显示名",
"exact",
15000, // app.SearchMaxResultCount
true,
out strXml,
out strError);
if (nRet == -1)
goto ERROR1;
}
else
{
strError = "strBarcode和strDisplayName均为空,无法进行检索";
goto ERROR1;
}
string strResultSetName = "opac_userinfo";
// sessioninfo.Channel.
channel.Idle += new IdleEventHandler(channel_Idle);
try
{
long lRet = //sessioninfo.Channel.
channel.Search(
null,
strXml,
strResultSetName,
"", // strOutputStyle
out strError);
if (lRet == -1)
goto ERROR1;
// not found
if (lRet == 0)
{
this.BrowseSearchResultControl1.Title = strText + " 没有发表过任何书评";
}
else
{
this.BrowseSearchResultControl1.ResultSetName = strResultSetName;
this.BrowseSearchResultControl1.ResultCount = (int)lRet;
this.BrowseSearchResultControl1.StartIndex = 0;
}
return;
}
finally
{
//sessioninfo.Channel.
channel.Idle -= new IdleEventHandler(channel_Idle);
}
}
return;
ERROR1:
Response.Write(HttpUtility.HtmlEncode(strError));
Response.End();
}
finally
{
#if NO
temp_sessioninfo.CloseSession();
#endif
app.ReturnChannel(channel);
}
}
void channel_Idle(object sender, IdleEventArgs e)
{
bool bConnected = this.Response.IsClientConnected;
if (bConnected == false)
{
LibraryChannel channel = (LibraryChannel)sender;
channel.Abort();
}
// e.bDoEvents = false;
}
protected void Button_sendMessage_Click(object sender, EventArgs e)
{
}
} | 34.218837 | 179 | 0.470736 | [
"Apache-2.0"
] | DigitalPlatform/dp2 | dp2OPAC/UserInfo.aspx.cs | 12,613 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Aws.WafV2.Inputs
{
public sealed class WebAclRuleStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeaderGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the query header to inspect. This setting must be provided as lower case characters.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
public WebAclRuleStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeaderGetArgs()
{
}
}
}
| 35.5 | 156 | 0.726977 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Inputs/WebAclRuleStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeaderGetArgs.cs | 923 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CSASPNETCurrentOnlineUserList
{
public partial class CheckUserOnlinePage
{
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
}
}
| 28.444444 | 84 | 0.486979 | [
"MIT"
] | Ranin26/msdn-code-gallery-microsoft | OneCodeTeam/Get online users in ASP.NET (CSASPNETCurrentOnlineUserList) 2/[C#]-Get online users in ASP.NET (CSASPNETCurrentOnlineUserList)/C#/CSASPNETCurrentOnlineUserList/CheckUserOnlinePage.aspx.designer.cs | 770 | C# |
/**
* CCTask
*
* Copyright 2012 Konrad Kruczyński <[email protected]>
*
* 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;
namespace CCTask.Compilers
{
public interface ICompiler
{
bool Compile(string source, string output, string flags, Func<IEnumerable<string>, string, bool> sourceHasChanged);
}
}
| 38.805556 | 117 | 0.763064 | [
"MIT"
] | UPBIoT/renode-iot | lib/cctask/CCTask/Compilers/ICompiler.cs | 1,398 | 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("Myrtille.Web")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Myrtille")]
[assembly: AssemblyCopyright("Copyright © 2014-2018 Cedric Coste")]
[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("3d5900ae-111a-45be-96b3-d9e4606ca793")]
// 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("2.3.1.0")]
[assembly: AssemblyFileVersion("2.3.1.0")]
| 39.027778 | 85 | 0.730249 | [
"Apache-2.0"
] | 0xh4di/myrtille | Myrtille.Web/Properties/AssemblyInfo.cs | 1,408 | C# |
using System;
using System.Globalization;
using System.Windows.Data;
namespace ProductManager.WPF.Presentation.Converters
{
public class StringFormatConverter : IValueConverter
{
private static readonly StringFormatConverter defaultInstance = new StringFormatConverter();
public static StringFormatConverter Default { get { return defaultInstance; } }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string format = parameter as string ?? "{0}";
return string.Format(culture, format, value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
| 29.555556 | 103 | 0.689223 | [
"ECL-2.0",
"Apache-2.0"
] | 6bee/ntieref | samples/ProductManager/ProductManager.WPF/ProductManager.WPF.Presentation/Converters/StringFormatConverter.cs | 800 | C# |
namespace Core3.Recoverability.Delayed.CustomPolicies
{
using System;
using NServiceBus.Management.Retries;
using NServiceBus.Unicast.Transport;
class ExceptionPolicy
{
ExceptionPolicy()
{
SecondLevelRetries.RetryPolicy = MyCustomRetryPolicy;
}
#region DelayedRetriesCustomExceptionPolicyHandler
TimeSpan MyCustomRetryPolicy(TransportMessage transportMessage)
{
if (ExceptionType(transportMessage) == typeof(MyBusinessException).FullName)
{
// Do not retry for MyBusinessException
return TimeSpan.MinValue;
}
if (NumberOfRetries(transportMessage) >= 3)
{
return TimeSpan.MinValue;
}
return TimeSpan.FromSeconds(5);
}
static int NumberOfRetries(TransportMessage transportMessage)
{
var headers = transportMessage.Headers;
if (headers.TryGetValue(NServiceBus.Headers.Retries, out var value))
{
return int.Parse(value);
}
return 0;
}
static string ExceptionType(TransportMessage transportMessage)
{
var headers = transportMessage.Headers;
return headers["NServiceBus.ExceptionInfo.ExceptionType"];
}
#endregion
}
class MyBusinessException :
Exception
{
}
} | 27.125 | 89 | 0.571429 | [
"Apache-2.0"
] | foz1284/docs.particular.net | Snippets/Core/Core_3/Recoverability/Delayed/CustomPolicies/ExceptionPolicy.cs | 1,466 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Panda.Examples.Shooter
{
// Manages the AI vision.
public class AIVision : MonoBehaviour
{
public float fieldOfView = 90.0f; // Object within this angle are seen.
public float closeFieldDistance = 1.0f; // Objects below this distance is always seen.
public List<Collider> colliders = new List<Collider>();
public List<GameObject> visibles = new List<GameObject>();
public Unit shooter;
public float lastBulletSeenTime;
void OnTriggerEnter( Collider other )
{
var triggerType = other.GetComponent<TriggerType>();
if( triggerType != null && triggerType.collidesWithVision && !colliders.Contains(other) )
{
colliders.Add(other);
colliders.RemoveAll((c) => c == null);
}
}
void OnTriggerExit(Collider other)
{
if (colliders.Contains(other))
{
colliders.Remove(other);
colliders.RemoveAll((c) => c == null);
}
}
void UpdateVisibility()
{
visibles.Clear();
foreach( var c in colliders)
{
if (c == null)
continue;
var go = c.attachedRigidbody != null ? c.attachedRigidbody.gameObject: null;
bool isVisible = false;
if (go != null)
{
float angle = Vector3.Angle(this.transform.forward, go.transform.position - this.transform.position);
bool isInClosedField = Vector3.Distance(go.transform.position, this.transform.position) <= closeFieldDistance;
bool isInFieldOfView = Mathf.Abs(angle) <= fieldOfView * 0.5f;
isVisible = isInClosedField || (isInFieldOfView && HasLoS( go.gameObject ));
}
if (isVisible && !visibles.Contains(go))
{
var bullet = go.GetComponent<Bullet>();
if ( bullet != null)
{
var attacker = bullet.shooter != null? bullet.shooter.GetComponent<Unit>(): null;
if( attacker != null && attacker.team != shooter.team)
lastBulletSeenTime = Time.time;
}
visibles.Add(go);
}
}
}
bool HasLoS( GameObject target ) // Line of sight test.
{
bool has = false;
var targetDirection = (target.transform.position - this.transform.position).normalized;
Ray ray = new Ray(this.transform.position, targetDirection);
var hits = Physics.RaycastAll(ray, float.PositiveInfinity);
float minD = float.PositiveInfinity;
GameObject closest = null;
foreach( var h in hits)
{
var ct = h.collider.GetComponent<TriggerType>();
if (ct == null || !ct.collidesWithVision)
continue;
float d = Vector3.Distance(h.point, this.transform.position);
var o = h.collider.attachedRigidbody != null ? h.collider.attachedRigidbody.gameObject : h.collider.gameObject;
if ( d <= minD && o != this.gameObject)
{
minD = d;
closest = o;
}
}
has = closest == target;
return has;
}
// Use this for initialization
void Start()
{
lastBulletSeenTime = float.NegativeInfinity;
}
// Update is called once per frame
void Update()
{
UpdateVisibility();
}
}
}
| 31.395349 | 131 | 0.494568 | [
"MIT"
] | auxeon/katana-utility-ai | Assets/PandaBehaviour/Examples/03_Shooter/Assets/AIVision.cs | 4,052 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace MedicalClinic.Models.AccountViewModels
{
public class LoginViewModel
{
[Required(ErrorMessage = "Wymagany adres e-mail.")]
[EmailAddress(ErrorMessage = "Podano nieprawidłowy adres e-mail.")]
public string Email { get; set; }
[Required(ErrorMessage = "Wymagane hasło.")]
[DataType(DataType.Password)]
[Display(Name = "Hasło")]
public string Password { get; set; }
[Display(Name = "Zapamiętaj mnie")]
public bool RememberMe { get; set; }
}
}
| 28.333333 | 75 | 0.667647 | [
"MIT"
] | kulisdominik/MedicalClinic | MedicalClinic/Models/AccountViewModels/LoginViewModel.cs | 686 | C# |
using System;
using System.Collections.Generic;
using JustAssembly.Core.DiffItems;
namespace JustAssembly.Core.Comparers
{
abstract class BaseDiffComparer<T> where T : class
{
public IEnumerable<IDiffItem> GetMultipleDifferences(IEnumerable<T> oldElements, IEnumerable<T> newElements)
{
List<T> oldElementsSorted = new List<T>(oldElements);
oldElementsSorted.Sort(CompareElements);
List<T> newElementsSorted = new List<T>(newElements);
newElementsSorted.Sort(CompareElements);
int oldIndex;
int newIndex;
List<IDiffItem> result = new List<IDiffItem>();
for (oldIndex = 0, newIndex = 0; oldIndex < oldElementsSorted.Count && newIndex < newElementsSorted.Count; )
{
T oldElement = oldElementsSorted[oldIndex];
T newElement = newElementsSorted[newIndex];
int compareResult = CompareElements(oldElement, newElement);
if (compareResult < 0)
{
oldIndex++;
if (IsAPIElement(oldElement))
{
result.Add(GetMissingDiffItem(oldElement));
}
}
else if (compareResult > 0)
{
newIndex++;
if (IsAPIElement(newElement))
{
IDiffItem newItem = GetNewDiffItem(newElement);
if (newItem != null)
{
result.Add(newItem);
}
}
}
else
{
oldIndex++;
newIndex++;
if (IsAPIElement(oldElement) || IsAPIElement(newElement))
{
IDiffItem diffResult = this.GenerateDiffItem(oldElement, newElement);
if (diffResult != null)
{
result.Add(diffResult);
}
}
}
}
for (; oldIndex < oldElementsSorted.Count; oldIndex++)
{
if (IsAPIElement(oldElementsSorted[oldIndex]))
{
result.Add(GetMissingDiffItem(oldElementsSorted[oldIndex]));
}
}
for (; newIndex < newElementsSorted.Count; newIndex++)
{
if (IsAPIElement(newElementsSorted[newIndex]))
{
IDiffItem newItem = GetNewDiffItem(newElementsSorted[newIndex]);
if (newItem != null)
{
result.Add(newItem);
}
}
}
return result;
}
protected abstract IDiffItem GetMissingDiffItem(T element);
protected abstract IDiffItem GenerateDiffItem(T oldElement, T newElement);
protected abstract IDiffItem GetNewDiffItem(T element);
protected abstract bool IsAPIElement(T element);
protected abstract int CompareElements(T x, T y);
}
}
| 33.306122 | 120 | 0.481618 | [
"Apache-2.0"
] | Acidburn0zzz/JustAssembly | Core/JustAssembly.Core/Comparers/BaseDiffComparer.cs | 3,266 | C# |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
//using System.Security.Cryptography;
namespace System
{
internal static class Marvin
{
/// <summary>
/// Convenience method to compute a Marvin hash and collapse it into a 32-bit hash.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int ComputeHash32(ReadOnlySpan<byte> data, ulong seed)
{
long hash64 = ComputeHash(data, seed);
return ((int)(hash64 >> 32)) ^ (int)hash64;
}
/// <summary>
/// Computes a 64-hash using the Marvin algorithm.
/// </summary>
public static long ComputeHash(ReadOnlySpan<byte> data, ulong seed)
{
uint p0 = (uint)seed;
uint p1 = (uint)(seed >> 32);
if (data.Length >= sizeof(uint))
{
ReadOnlySpan<uint> uData = MemoryMarshal.Cast<byte, uint>(data);
for (int i = 0; i < uData.Length; i++)
{
p0 += uData[i];
Block(ref p0, ref p1);
}
// byteOffset = data.Length - data.Length % 4
// is equivalent to clearing last 2 bits of length
// Using it directly gives a perf hit for short strings making it at least 5% or more slower.
int byteOffset = data.Length & (~3);
data = data.Slice(byteOffset);
}
switch (data.Length)
{
case 0:
p0 += 0x80u;
break;
case 1:
p0 += 0x8000u | data[0];
break;
case 2:
p0 += 0x800000u | MemoryMarshal.Cast<byte, ushort>(data)[0];
break;
case 3:
p0 += 0x80000000u | (((uint)data[2]) << 16) | (uint)(MemoryMarshal.Cast<byte, ushort>(data)[0]);
break;
default:
Debug.Fail("Should not get here.");
break;
}
Block(ref p0, ref p1);
Block(ref p0, ref p1);
return (((long)p1) << 32) | p0;
}
/// <summary>
/// Compute a Marvin hash and collapse it into a 32-bit hash.
/// </summary>
public static int ComputeHash32(ref byte data, uint count, uint p0, uint p1)
{
// Control flow of this method generally flows top-to-bottom, trying to
// minimize the number of branches taken for large (>= 8 bytes, 4 chars) inputs.
// If small inputs (< 8 bytes, 4 chars) are given, this jumps to a "small inputs"
// handler at the end of the method.
if (count < 8)
{
// We can't run the main loop, but we might still have 4 or more bytes available to us.
// If so, jump to the 4 .. 7 bytes logic immediately after the main loop.
if (count >= 4)
{
goto Between4And7BytesRemain;
}
else
{
goto InputTooSmallToEnterMainLoop;
}
}
// Main loop - read 8 bytes at a time.
// The block function is unrolled 2x in this loop.
uint loopCount = count / 8;
Debug.Assert(loopCount > 0, "Shouldn't reach this code path for small inputs.");
do
{
// Most x86 processors have two dispatch ports for reads, so we can read 2x 32-bit
// values in parallel. We opt for this instead of a single 64-bit read since the
// typical use case for Marvin32 is computing String hash codes, and the particular
// layout of String instances means the starting data is never 8-byte aligned when
// running in a 64-bit process.
p0 += Unsafe.ReadUnaligned<uint>(ref data);
uint nextUInt32 = Unsafe.ReadUnaligned<uint>(ref Unsafe.AddByteOffset(ref data, (IntPtr)4));
// One block round for each of the 32-bit integers we just read, 2x rounds total.
Block(ref p0, ref p1);
p0 += nextUInt32;
Block(ref p0, ref p1);
// Bump the data reference pointer and decrement the loop count.
// Decrementing by 1 every time and comparing against zero allows the JIT to produce
// better codegen compared to a standard 'for' loop with an incrementing counter.
// Requires https://github.com/dotnet/runtime/issues/6794 to be addressed first
// before we can realize the full benefits of this.
data = ref Unsafe.AddByteOffset(ref data, (IntPtr)8);
} while (--loopCount > 0);
// n.b. We've not been updating the original 'count' parameter, so its actual value is
// still the original data length. However, we can still rely on its least significant
// 3 bits to tell us how much data remains (0 .. 7 bytes) after the loop above is
// completed.
if ((count & 0b_0100) == 0)
{
goto DoFinalPartialRead;
}
Between4And7BytesRemain:
// If after finishing the main loop we still have 4 or more leftover bytes, or if we had
// 4 .. 7 bytes to begin with and couldn't enter the loop in the first place, we need to
// consume 4 bytes immediately and send them through one round of the block function.
Debug.Assert(count >= 4, "Only should've gotten here if the original count was >= 4.");
p0 += Unsafe.ReadUnaligned<uint>(ref data);
Block(ref p0, ref p1);
DoFinalPartialRead:
// Finally, we have 0 .. 3 bytes leftover. Since we know the original data length was at
// least 4 bytes (smaller lengths are handled at the end of this routine), we can safely
// read the 4 bytes at the end of the buffer without reading past the beginning of the
// original buffer. This necessarily means the data we're about to read will overlap with
// some data we've already processed, but we can handle that below.
Debug.Assert(count >= 4, "Only should've gotten here if the original count was >= 4.");
// Read the last 4 bytes of the buffer.
uint partialResult = Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref Unsafe.AddByteOffset(ref data, (IntPtr)((uint)count & 7)), -4));
// The 'partialResult' local above contains any data we have yet to read, plus some number
// of bytes which we've already read from the buffer. An example of this is given below
// for little-endian architectures. In this table, AA BB CC are the bytes which we still
// need to consume, and ## are bytes which we want to throw away since we've already
// consumed them as part of a previous read.
//
// (partialResult contains) (we want it to contain)
// count mod 4 = 0 -> [ ## ## ## ## | ] -> 0x####_#### -> 0x0000_0080
// count mod 4 = 1 -> [ ## ## ## ## | AA ] -> 0xAA##_#### -> 0x0000_80AA
// count mod 4 = 2 -> [ ## ## ## ## | AA BB ] -> 0xBBAA_#### -> 0x0080_BBAA
// count mod 4 = 3 -> [ ## ## ## ## | AA BB CC ] -> 0xCCBB_AA## -> 0x80CC_BBAA
count = ~count << 3;
if (BitConverter.IsLittleEndian)
{
partialResult >>= 8; // make some room for the 0x80 byte
partialResult |= 0x8000_0000u; // put the 0x80 byte at the beginning
partialResult >>= (int)count & 0x1F; // shift out all previously consumed bytes
}
else
{
partialResult <<= 8; // make some room for the 0x80 byte
partialResult |= 0x80u; // put the 0x80 byte at the end
partialResult <<= (int)count & 0x1F; // shift out all previously consumed bytes
}
DoFinalRoundsAndReturn:
// Now that we've computed the final partial result, merge it in and run two rounds of
// the block function to finish out the Marvin algorithm.
p0 += partialResult;
Block(ref p0, ref p1);
Block(ref p0, ref p1);
return (int)(p1 ^ p0);
InputTooSmallToEnterMainLoop:
// We had only 0 .. 3 bytes to begin with, so we can't perform any 32-bit reads.
// This means that we're going to be building up the final result right away and
// will only ever run two rounds total of the block function. Let's initialize
// the partial result to "no data".
if (BitConverter.IsLittleEndian)
{
partialResult = 0x80u;
}
else
{
partialResult = 0x80000000u;
}
if ((count & 0b_0001) != 0)
{
// If the buffer is 1 or 3 bytes in length, let's read a single byte now
// and merge it into our partial result. This will result in partialResult
// having one of the two values below, where AA BB CC are the buffer bytes.
//
// (little-endian / big-endian)
// [ AA ] -> 0x0000_80AA / 0xAA80_0000
// [ AA BB CC ] -> 0x0000_80CC / 0xCC80_0000
partialResult = Unsafe.AddByteOffset(ref data, (IntPtr)((uint)count & 2));
if (BitConverter.IsLittleEndian)
{
partialResult |= 0x8000;
}
else
{
partialResult <<= 24;
partialResult |= 0x800000u;
}
}
if ((count & 0b_0010) != 0)
{
// If the buffer is 2 or 3 bytes in length, let's read a single ushort now
// and merge it into the partial result. This will result in partialResult
// having one of the two values below, where AA BB CC are the buffer bytes.
//
// (little-endian / big-endian)
// [ AA BB ] -> 0x0080_BBAA / 0xAABB_8000
// [ AA BB CC ] -> 0x80CC_BBAA / 0xAABB_CC80 (carried over from above)
if (BitConverter.IsLittleEndian)
{
partialResult <<= 16;
partialResult |= (uint)Unsafe.ReadUnaligned<ushort>(ref data);
}
else
{
partialResult |= (uint)Unsafe.ReadUnaligned<ushort>(ref data);
partialResult = _rotl(partialResult, 16);
}
}
// Everything is consumed! Go perform the final rounds and return.
goto DoFinalRoundsAndReturn;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Block(ref uint rp0, ref uint rp1)
{
uint p0 = rp0;
uint p1 = rp1;
p1 ^= p0;
p0 = _rotl(p0, 20);
p0 += p1;
p1 = _rotl(p1, 9);
p1 ^= p0;
p0 = _rotl(p0, 27);
p0 += p1;
p1 = _rotl(p1, 19);
rp0 = p0;
rp1 = p1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static uint _rotl(uint value, int shift)
{
// This is expected to be optimized into a single rol (or ror with negated shift value) instruction
return (value << shift) | (value >> (32 - shift));
}
//public static ulong DefaultSeed { get; } = GenerateSeed();
//private static ulong GenerateSeed()
//{
// using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
// {
// var bytes = new byte[sizeof(ulong)];
// rng.GetBytes(bytes);
// return BitConverter.ToUInt64(bytes, 0);
// }
//}
}
}
| 37.601881 | 143 | 0.551313 | [
"BSD-3-Clause"
] | AnErrupTion/MOSA-Project | Source/Mosa.Korlib/System/Marvin.cs | 11,997 | C# |
// This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using NetExtender.Types.Dictionaries.Interfaces;
namespace NetExtender.Types.Immutable.Dictionaries.Interfaces
{
public interface IImmutableMultiDictionary<TKey, TValue> : IReadOnlyMultiDictionary<TKey, TValue>, IImmutableDictionary<TKey, TValue>, IImmutableDictionary<TKey, ImmutableHashSet<TValue>>
{
public new IEnumerator<KeyValuePair<TKey, ImmutableHashSet<TValue>>> GetEnumerator();
/// <summary>
/// Gets an empty dictionary with equivalent ordering and key/value comparison rules.
/// </summary>
public new IImmutableMultiDictionary<TKey, TValue> Clear();
/// <summary>
/// Adds the specified key and value to the dictionary.
/// </summary>
/// <param name="key">The key of the entry to add.</param>
/// <param name="value">The value of the entry to add.</param>
/// <returns>The new dictionary containing the additional key-value pair.</returns>
/// <exception cref="ArgumentException">Thrown when the given key already exists in the dictionary but has a different value.</exception>
/// <remarks>
/// If the given key-value pair are already in the dictionary, the existing instance is returned.
/// </remarks>
public new IImmutableMultiDictionary<TKey, TValue> Add(TKey key, TValue value);
/// <summary>
/// Adds the specified key and value to the dictionary.
/// </summary>
/// <param name="key">The key of the entry to add.</param>
/// <param name="value">The value of the entry to add.</param>
/// <returns>The new dictionary containing the additional key-value pair.</returns>
/// <exception cref="ArgumentException">Thrown when the given key already exists in the dictionary but has a different value.</exception>
/// <remarks>
/// If the given key-value pair are already in the dictionary, the existing instance is returned.
/// </remarks>
public new IImmutableMultiDictionary<TKey, TValue> Add(TKey key, ImmutableHashSet<TValue> value);
/// <summary>
/// Adds the specified key-value pairs to the dictionary.
/// </summary>
/// <param name="pairs">The pairs.</param>
/// <returns>The new dictionary containing the additional key-value pairs.</returns>
/// <exception cref="ArgumentException">Thrown when one of the given keys already exists in the dictionary but has a different value.</exception>
public new IImmutableMultiDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs);
/// <summary>
/// Adds the specified key-value pairs to the dictionary.
/// </summary>
/// <param name="pairs">The pairs.</param>
/// <returns>The new dictionary containing the additional key-value pairs.</returns>
/// <exception cref="ArgumentException">Thrown when one of the given keys already exists in the dictionary but has a different value.</exception>
public new IImmutableMultiDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, ImmutableHashSet<TValue>>> pairs);
/// <summary>
/// Sets the specified key and value to the dictionary, possibly overwriting an existing value for the given key.
/// </summary>
/// <param name="key">The key of the entry to add.</param>
/// <param name="value">The value of the entry to add.</param>
/// <returns>The new dictionary containing the additional key-value pair.</returns>
/// <remarks>
/// If the given key-value pair are already in the dictionary, the existing instance is returned.
/// If the key already exists but with a different value, a new instance with the overwritten value will be returned.
/// </remarks>
public new IImmutableMultiDictionary<TKey, TValue> SetItem(TKey key, TValue value);
/// <summary>
/// Sets the specified key and value to the dictionary, possibly overwriting an existing value for the given key.
/// </summary>
/// <param name="key">The key of the entry to add.</param>
/// <param name="value">The value of the entry to add.</param>
/// <returns>The new dictionary containing the additional key-value pair.</returns>
/// <remarks>
/// If the given key-value pair are already in the dictionary, the existing instance is returned.
/// If the key already exists but with a different value, a new instance with the overwritten value will be returned.
/// </remarks>
public new IImmutableMultiDictionary<TKey, TValue> SetItem(TKey key, ImmutableHashSet<TValue> value);
/// <summary>
/// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary.
/// </summary>
/// <param name="items">The key=value pairs to set on the dictionary. Any keys that conflict with existing keys will overwrite the previous values.</param>
/// <returns>An immutable dictionary.</returns>
public new IImmutableMultiDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items);
/// <summary>
/// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary.
/// </summary>
/// <param name="items">The key=value pairs to set on the dictionary. Any keys that conflict with existing keys will overwrite the previous values.</param>
/// <returns>An immutable dictionary.</returns>
public new IImmutableMultiDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, ImmutableHashSet<TValue>>> items);
/// <summary>
/// Removes the specified keys from the dictionary with their associated values.
/// </summary>
/// <param name="keys">The keys to remove.</param>
/// <returns>A new dictionary with those keys removed; or this instance if those keys are not in the dictionary.</returns>
public new IImmutableMultiDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys);
/// <summary>
/// Removes the specified key from the dictionary with its associated value.
/// </summary>
/// <param name="key">The key to remove.</param>
/// <returns>A new dictionary with the matching entry removed; or this instance if the key is not in the dictionary.</returns>
public new IImmutableMultiDictionary<TKey, TValue> Remove(TKey key);
/// <summary>
/// Removes the specified key from the dictionary with its associated value.
/// </summary>
/// <param name="key">The key to remove.</param>
/// <param name="value"></param>
/// <returns>A new dictionary with the matching entry removed; or this instance if the key is not in the dictionary.</returns>
public IImmutableMultiDictionary<TKey, TValue> Remove(TKey key, TValue value);
/// <summary>
/// Removes the specified key from the dictionary with its associated value.
/// </summary>
/// <param name="key">The key to remove.</param>
/// <param name="value"></param>
/// <returns>A new dictionary with the matching entry removed; or this instance if the key is not in the dictionary.</returns>
public IImmutableMultiDictionary<TKey, TValue> Remove(TKey key, ImmutableHashSet<TValue> value);
/// <summary>
/// Searches the dictionary for a given key and returns the equal key it finds, if any.
/// </summary>
/// <param name="equalKey">The key to search for.</param>
/// <param name="actualKey">The key from the dictionary that the search found, or <paramref name="equalKey"/> if the search yielded no match.</param>
/// <returns>A value indicating whether the search was successful.</returns>
/// <remarks>
/// This can be useful when you want to reuse a previously stored reference instead of
/// a newly constructed one (so that more sharing of references can occur) or to look up
/// the canonical value, or a value that has more complete data than the value you currently have,
/// although their comparer functions indicate they are equal.
/// </remarks>
public new Boolean TryGetKey(TKey equalKey, out TKey actualKey);
}
} | 61.725352 | 191 | 0.666857 | [
"MIT"
] | Rain0Ash/NetExtender | NetExtender.Core/Types/Immutable/Dictionaries/Interfaces/IImmutableMultiDictionary.cs | 8,765 | C# |
namespace LaunchProgramActivity.Design
{
using System.Activities.Presentation.Metadata;
/// <summary>
/// Designer Metadata registration support
/// </summary>
public sealed class MyActivityLibraryMetadata2 : IRegisterMetadata
{
#region Public Methods
/// <summary>
/// Registers metadata
/// </summary>
public static void RegisterAll()
{
var builder = new AttributeTableBuilder();
MyActivityDesigner2.RegisterMetadata(builder);
// TODO: Other activities can be added here
MetadataStore.AddAttributeTable(builder.CreateTable());
}
/// <summary>
/// Registers metadata
/// </summary>
public void Register()
{
RegisterAll();
}
#endregion
}
} | 24.171429 | 70 | 0.578014 | [
"MIT"
] | Caduar/RobotsForEveryone | CustomActivitiesExamples/LaunchProgram/C#/Launch.Design/MyActivityLibraryMetadata.cs | 848 | C# |
using UIKit;
namespace StickyHeaderDemo
{
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");
}
}
}
| 21.125 | 82 | 0.704142 | [
"MIT"
] | szysz3/xamarin-ios-stickyheader | StickyHeader/Main.cs | 340 | C# |
using System;
using NetOffice;
namespace NetOffice.OfficeApi.Enums
{
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff863128.aspx </remarks>
[SupportByVersionAttribute("Office", 12,14,15,16)]
[EntityTypeAttribute(EntityType.IsEnum)]
public enum XlDataLabelPosition
{
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// </summary>
/// <remarks>-4108</remarks>
[SupportByVersionAttribute("Office", 12,14,15,16)]
xlLabelPositionCenter = -4108,
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// </summary>
/// <remarks>0</remarks>
[SupportByVersionAttribute("Office", 12,14,15,16)]
xlLabelPositionAbove = 0,
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersionAttribute("Office", 12,14,15,16)]
xlLabelPositionBelow = 1,
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// </summary>
/// <remarks>-4131</remarks>
[SupportByVersionAttribute("Office", 12,14,15,16)]
xlLabelPositionLeft = -4131,
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// </summary>
/// <remarks>-4152</remarks>
[SupportByVersionAttribute("Office", 12,14,15,16)]
xlLabelPositionRight = -4152,
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersionAttribute("Office", 12,14,15,16)]
xlLabelPositionOutsideEnd = 2,
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// </summary>
/// <remarks>3</remarks>
[SupportByVersionAttribute("Office", 12,14,15,16)]
xlLabelPositionInsideEnd = 3,
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// </summary>
/// <remarks>4</remarks>
[SupportByVersionAttribute("Office", 12,14,15,16)]
xlLabelPositionInsideBase = 4,
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// </summary>
/// <remarks>5</remarks>
[SupportByVersionAttribute("Office", 12,14,15,16)]
xlLabelPositionBestFit = 5,
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// </summary>
/// <remarks>6</remarks>
[SupportByVersionAttribute("Office", 12,14,15,16)]
xlLabelPositionMixed = 6,
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// </summary>
/// <remarks>7</remarks>
[SupportByVersionAttribute("Office", 12,14,15,16)]
xlLabelPositionCustom = 7
}
} | 28.477778 | 119 | 0.639095 | [
"MIT"
] | Engineerumair/NetOffice | Source/Office/Enums/XlDataLabelPosition.cs | 2,563 | C# |
namespace Craftsman.Builders.Tests.UnitTests
{
using Craftsman.Exceptions;
using Craftsman.Helpers;
using Craftsman.Models;
using System.IO;
using System.IO.Abstractions;
using System.Text;
public class CurrentUserServiceTestBuilder
{
public static void CreateTests(string solutionDirectory, string projectBaseName, IFileSystem fileSystem)
{
var classPath = ClassPathHelper.UnitTestWrapperTestsClassPath(solutionDirectory, $"CurrentUserServiceTests.cs", projectBaseName);
var fileText = WriteTestFileText(solutionDirectory, classPath, projectBaseName);
Utilities.CreateFile(classPath, fileText, fileSystem);
}
private static string WriteTestFileText(string solutionDirectory, ClassPath classPath, string projectBaseName)
{
var servicesClassPath = ClassPathHelper.WebApiServicesClassPath(solutionDirectory, "", projectBaseName);
return @$"namespace {classPath.ClassNamespace};
using {servicesClassPath.ClassNamespace};
using System.Security.Claims;
using Bogus;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using NUnit.Framework;
public class {Path.GetFileNameWithoutExtension(classPath.FullClassPath)}
{{
[Test]
public void returns_user_in_context_if_present()
{{
var name = new Faker().Person.UserName;
var id = new ClaimsIdentity();
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, name));
var context = new DefaultHttpContext().HttpContext;
context.User = new ClaimsPrincipal(id);
var sub = Substitute.For<IHttpContextAccessor>();
sub.HttpContext.Returns(context);
var currentUserService = new CurrentUserService(sub);
currentUserService.UserId.Should().Be(name);
}}
[Test]
public void returns_null_if_user_is_not_present()
{{
var context = new DefaultHttpContext().HttpContext;
var sub = Substitute.For<IHttpContextAccessor>();
sub.HttpContext.Returns(context);
var currentUserService = new CurrentUserService(sub);
currentUserService.UserId.Should().BeNullOrEmpty();
}}
}}";
}
}
} | 32.911765 | 141 | 0.703753 | [
"MIT"
] | RolandTa/craftsman | Craftsman/Builders/Tests/UnitTests/CurrentUserServiceTestBuilder.cs | 2,240 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;
using System.Data.SQLite;
using System.IO;
using System.Globalization;
using Autodesk.Revit.UI;
namespace Metamorphosis
{
internal class SnapshotMaker
{
private Document _doc;
private Dictionary<int, Parameter> _paramDict = new Dictionary<int, Parameter>();
private Dictionary<string, int> _valueDict = new Dictionary<string, int>();
private Dictionary<string, string> _headerDict = new Dictionary<string, string>();
private string _filename;
private string _dbFilename;
private int _valueId = 0;
private List<Level> _allLevels;
private Utilities.Settings.LogLevel _logLevel = Utilities.Settings.LogLevel.Basic;
#region Constructor
internal SnapshotMaker(Document doc, string filename)
{
_doc = doc;
_filename = filename;
_dbFilename = _filename;
// see: http://system.data.sqlite.org/index.html/info/bbdda6eae2
if (_filename.StartsWith(@"\\")) _dbFilename = @"\\" + _dbFilename;
_logLevel = Utilities.Settings.GetLogLevel();
}
#endregion
#region Accessor
internal TimeSpan Duration { get; private set; }
#endregion
#region PublicMethods
internal void Export()
{
// make the sqlite database
createDatabase();
// populate
exportParameterData();
//_doc.Application.WriteJournalComment("Export Completed. Releasing hold on database file.", false);
// release the hold on the database
//https://stackoverflow.com/questions/8511901/system-data-sqlite-close-not-releasing-database-file
GC.Collect();
GC.WaitForPendingFinalizers();
}
#endregion
#region PrivateMethods
private void createDatabase()
{
_doc.Application.WriteJournalComment("Creating database: " + _filename, false);
if (File.Exists(_filename)) File.Delete(_filename); // we have to replace the contents anyway
// ran into a case where the path didn't exist. make it happen.
string folder = Path.GetDirectoryName(_filename);
if (Directory.Exists(folder) == false) Directory.CreateDirectory(folder);
//create the SQLite database file.
SQLiteConnection.CreateFile(_filename);
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + _dbFilename + ";Version=3;"))
{
conn.Open();
// create the table structure from the sql instructions.
string[] lines = Utilities.DataUtility.ReadSQLScript("Metamorphosis.databaseFormat.txt");
foreach (string sql in lines)
{
SQLiteCommand command = new SQLiteCommand(sql, conn);
command.ExecuteNonQuery();
}
}
}
private void exportParameterData()
{
//_doc.Application.WriteJournalComment("Retrieving Data...", false);
DateTime start = DateTime.Now;
// retrieve all of the instance elements, and process them.
//FilteredElementCollector coll = new FilteredElementCollector(_doc, _doc.ActiveView.Id); //get only the object visible in the active view. Not working with Link Model!
FilteredElementCollector coll = new FilteredElementCollector(_doc);
coll.WhereElementIsNotElementType();
Dictionary<ElementId, Element> typeElementsUsed = new Dictionary<ElementId, Element>();
IList<Element> instances = coll.ToElements().Where(e => e.Category != null).ToList();
foreach ( var elem in instances)
{
if (elem.Category == null) continue; // don't do it!
// see if the current element has a type element, and make sure we're getting that.
ElementId typeId = elem.GetTypeId();
if (typeId != ElementId.InvalidElementId)
{
if (typeElementsUsed.ContainsKey(typeId) == false)
{
Element typeElem = _doc.GetElement(typeId);
if ((typeElem.Category != null))
{
typeElementsUsed.Add(typeId, typeElem); // only add if it's a typeElement with Category
}
}
}
}
string msg = (DateTime.Now - start) + ": " + instances.Count + " instances and " + typeElementsUsed.Count + " types.";
//_doc.Application.WriteJournalComment(msg, false);
System.Diagnostics.Debug.WriteLine(msg);
// go through all of the type elements and instances and capture the parameter ids
_headerDict["SchemaVersion"] = "1.0";
_headerDict["Model"] = Utilities.RevitUtils.GetModelPath(_doc);
_headerDict["ExportVersion"] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
_headerDict["ExportDate"] = DateTime.Now.ToString();
_headerDict["ExportDateTicks"] = DateTime.Now.Ticks.ToString();
_headerDict["ExportingUser"] = Environment.UserDomainName + "\\" + Environment.UserName;
_headerDict["MachineName"] = Environment.MachineName;
updateHeaderTable();
updateParameterDictionary(typeElementsUsed.Values.ToList());
log((DateTime.Now - start) + ": Parameter Dictionary Updated for Types");
updateParameterDictionary(instances);
log((DateTime.Now - start) + ": Parameter Dictionary Updated for Instances");
updateIdTable(typeElementsUsed.Values.ToList(), true);
log((DateTime.Now - start) + ": Id Table Updated for Types");
updateIdTable(instances, false);
log((DateTime.Now - start) + ": Id Table Updated for Instances");
//updateAttributeTable();
//log((DateTime.Now - start) + ": Attribute Table Updated for All");
//updateEntityAttributeValues(typeElementsUsed.Values.ToList());
//log((DateTime.Now - start) + ": Att/Values Table Updated for Types");
//updateEntityAttributeValues(instances);
//log((DateTime.Now - start) + ": Att/Values Table Updated for Instances");
//updateValueTable();
//log((DateTime.Now - start) + ": Value Table Updated for All");
updateGeometryTable(instances);
log((DateTime.Now - start) + ": Geometry Table Updated for Types");
Duration = DateTime.Now - start;
log("Total Time: " + Duration.TotalMinutes + " minutes");
}
private void log(string msg)
{
//_doc.Application.WriteJournalComment(msg, false);
System.Diagnostics.Debug.WriteLine(msg);
}
private string GetElementTypeFamilyAndName(Document doc, Element typeEle)
{
string result = "";
try
{
ElementType eleType = typeEle as ElementType;
result += $"{eleType.FamilyName} : {typeEle.Name}";
}
catch
{
ElementType et = doc.GetElement(typeEle.GetTypeId()) as ElementType;
result += $"{typeEle.Name} : {et.Name}";
}
return result;
}
private string GetInstaceFamilyAndName(Document doc, Element typeEle)
{
string result = "";
try
{
ElementType et = doc.GetElement(typeEle.GetTypeId()) as ElementType;
result += $"{et.FamilyName} : {typeEle.Name}";
}
catch
{
}
return result;
}
private void updateIdTable(IList<Element> elements, bool isTypes)
{
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + _dbFilename + ";Version=3;"))
{
string errorElements = "";
conn.Open();
using (var transaction = conn.BeginTransaction())
{
foreach (Element e in elements)
{
Category c = e.Category;
string familyAndName = ""; //get element Name
if (isTypes)
{
familyAndName = GetElementTypeFamilyAndName(_doc, e);
}
else
{
familyAndName = GetInstaceFamilyAndName(_doc, e);
}
if (c == null)
{
FamilySymbol fs = e as FamilySymbol;
if (fs != null)
{
c = fs.Family.FamilyCategory;
}
}
string catName = (c != null) ? c.Name : "(none)";
if (catName.Contains("'")) catName = catName.Replace("'", "''");
if (familyAndName.Contains("'")) familyAndName = familyAndName.Replace("'", "''");
var cmd = conn.CreateCommand();
try
{
cmd.CommandText = String.Format("INSERT INTO _objects_id (id,external_id,category,family_name,isType) VALUES({0},'{1}','{2}','{3}',{4})", e.Id.IntegerValue, e.UniqueId, catName, familyAndName, (isTypes) ? 1 : 0);
cmd.ExecuteNonQuery();
}
catch
{
errorElements += $"{e.Name} : {e.Id} \n";
}
}
transaction.Commit();
if (isTypes)
{
TaskDialog.Show("Type Error", errorElements);
}
else
{
TaskDialog.Show("Instance Error", errorElements);
}
}
}
}
private void updateHeaderTable()
{
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + _dbFilename + ";Version=3;"))
{
conn.Open();
using (var transaction = conn.BeginTransaction())
{
foreach (var pair in _headerDict)
{
var cmd = conn.CreateCommand();
cmd.CommandText = String.Format("INSERT INTO _objects_header (keyword,value) VALUES('{0}','{1}')", pair.Key,pair.Value);
cmd.ExecuteNonQuery();
}
transaction.Commit();
}
}
}
private void updateAttributeTable()
{
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + _dbFilename + ";Version=3;"))
{
conn.Open();
using (var transaction = conn.BeginTransaction())
{
foreach (var pair in _paramDict)
{
string name = pair.Value.Definition.Name;
if (name.Contains("'")) name = name.Replace("'", "''");
var cmd = conn.CreateCommand();
cmd.CommandText = String.Format("INSERT INTO _objects_attr (id,name,category,data_type) VALUES({0},'{1}','{2}',{3})", pair.Value.Id.IntegerValue, name, LabelUtils.GetLabelFor(pair.Value.Definition.ParameterGroup), (int)pair.Value.Definition.ParameterGroup);
cmd.ExecuteNonQuery();
}
transaction.Commit();
}
}
}
private void updateValueTable()
{
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + _dbFilename + ";Version=3;"))
{
conn.Open();
using (var transaction = conn.BeginTransaction())
{
foreach (var pair in _valueDict)
{
string val = pair.Key;
if (val.Contains("'")) val = val.Replace("'", "''"); // need to escape single quotes.
var cmd = conn.CreateCommand();
cmd.CommandText = String.Format("INSERT INTO _objects_val (id,value) VALUES({0},'{1}')", pair.Value, val);
cmd.ExecuteNonQuery();
}
transaction.Commit();
}
}
}
private void updateEntityAttributeValues(IList<Element> elems)
{
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + _dbFilename + ";Version=3;"))
{
conn.Open();
using (var transaction = conn.BeginTransaction())
{
foreach (Element e in elems)
{
IList<Parameter> parms = Utilities.RevitUtils.GetParameters(e);
foreach (var p in parms)
{
if (p.Definition == null) continue; // don't want that!
//Quick and Dirty - will need to call different stuff for each thing
string val = null;
switch (p.StorageType)
{
case StorageType.String:
val = p.AsString();
break;
default:
val = p.AsValueString();
break;
}
if (val == null) val = "(n/a)";
if (_valueDict.ContainsKey(val) == false)
{
_valueId++;
_valueDict.Add(val, _valueId);
}
var cmd = conn.CreateCommand();
cmd.CommandText = String.Format("INSERT INTO _objects_eav (entity_id,attribute_id,value_id) VALUES({0},{1},{2})", e.Id.IntegerValue, p.Id.IntegerValue, _valueDict[val]);
cmd.ExecuteNonQuery();
}
}
transaction.Commit();
}
}
}
private void updateParameterDictionary(IList<Element> elems)
{
foreach( Element e in elems)
{
IList<Parameter> parms = Utilities.RevitUtils.GetParameters(e);
foreach( Parameter p in parms )
{
if (p.Definition == null) continue; // ignore!
if (_paramDict.ContainsKey(p.Id.IntegerValue) == false) _paramDict.Add(p.Id.IntegerValue, p);
}
}
}
private void updateGeometryTable(IList<Element> elements)
{
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + _dbFilename + ";Version=3;"))
{
conn.Open();
using (var transaction = conn.BeginTransaction())
{
foreach (Element e in elements)
{
BoundingBoxXYZ box = e.get_BoundingBox(null);
Location loc = e.Location;
if ((loc == null) && (box == null)) continue; // nothing to see here.
String bbMin = String.Empty;
String bbMax = String.Empty;
string lp = String.Empty;
string lp2 = String.Empty;
float rotation = -1.0f;
if (box != null)
{
bbMin = Utilities.RevitUtils.SerializePoint(box.Min);
bbMax = Utilities.RevitUtils.SerializePoint(box.Max);
}
XYZ p1 = null;
if (loc != null)
{
LocationPoint pt = loc as LocationPoint;
if (pt != null)
{
try
{
// noted a time where with a group it didn't work.
XYZ pt1 = pt.Point;
// special cases.
if ((e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Columns) ||
(e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralColumns))
{
// in this case, get the Z value from the
var offset = e.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM);
if ((e.LevelId != ElementId.InvalidElementId) && (offset != null))
{
Level levPt1 = lookupLevel(e, pt1);
double newZ = levPt1.Elevation + offset.AsDouble();
pt1 = new XYZ(pt1.X, pt1.Y, newZ);
}
}
lp = Utilities.RevitUtils.SerializePoint(pt1);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error: " + e.Name + ": " + e.GetType().Name + ": " + ex.Message);
}
try
{
if (e is FamilyInstance)
{
if ((e as FamilyInstance).CanRotate)
{
rotation = (float)pt.Rotation;
}
}
}
catch { // swallow. Some just don't like it...
}
}
else
{
LocationCurve crv = loc as LocationCurve;
if (crv != null)
{
if (crv.Curve.IsBound)
{
p1 = crv.Curve.GetEndPoint(0);
XYZ p2 = crv.Curve.GetEndPoint(1);
lp = Utilities.RevitUtils.SerializePoint(p1);
lp2 = Utilities.RevitUtils.SerializePoint(p2);
}
}
else
{
if (box == null)
{
// ok, special case one: Grid
if (e is Grid)
{
Grid g = e as Grid;
p1 = g.Curve.GetEndPoint(0);
XYZ p2 = g.Curve.GetEndPoint(1);
lp = Utilities.RevitUtils.SerializePoint(p1);
lp2 = Utilities.RevitUtils.SerializePoint(p2);
}
else
{
continue; // not sure what this is???
}
}
}
}
}
// retrieve the level
Level lev = lookupLevel(e, p1);
string levName = String.Empty;
if (lev != null) levName = lev.Name;
var cmd = conn.CreateCommand();
cmd.CommandText = String.Format("INSERT INTO _objects_geom (id,BoundingBoxMin,BoundingBoxMax,Location,Location2,Level,Rotation) VALUES({0},'{1}','{2}','{3}','{4}','{5}',{6})", e.Id.IntegerValue, bbMin, bbMax, lp, lp2, escapeQuote(levName), rotation.ToString(CultureInfo.InvariantCulture));
if (_logLevel == Utilities.Settings.LogLevel.Verbose) _doc.Application.WriteJournalComment(cmd.CommandText,false);
cmd.ExecuteNonQuery();
}
transaction.Commit();
}
}
}
private Level lookupLevel(Element e, XYZ pt)
{
// given the Element, figure out the level if possible.
if (e.LevelId != ElementId.InvalidElementId) return e.Document.GetElement(e.LevelId) as Level;
// otherwise, let's see if we can get it from the location point.
if (pt == null) return null; // we don't know.
if (_allLevels == null)
{
FilteredElementCollector coll = new FilteredElementCollector(_doc);
coll.OfClass(typeof(Level));
_allLevels = coll.Cast<Level>().ToList();
}
// we want the next level down from the z value...
Level lev = Utilities.RevitUtils.GetNextLevelDown(pt, _allLevels);
return lev;
}
private string escapeQuote(string input)
{
return input.Replace("'", "''");
}
#endregion
}
}
| 40.165217 | 313 | 0.443949 | [
"MIT"
] | giobel/MetamorphosisDesktop | src/RevitFingerPrint/SnapshotMaker.cs | 23,097 | C# |
using GoogleTranslate.Common.Models;
namespace GoogleTranslate.Common;
/// <summary>
/// Converting url for google translate
/// </summary>
public interface IConvertHtml
{
/// <summary>
/// Converting html to another format, because Google translate begin translate html tags
/// </summary>
/// <param name="content">Content in html format</param>
ConvertResult Convert(string content);
/// <summary>
/// Unconverted text to clean string
/// </summary>
/// <param name="dirtyContent">Content with special tags</param>
/// <param name="groups">Information what change by group of elements</param>
/// <param name="tags">Information what tags need change</param>
string UnConvert(string dirtyContent, Dictionary<int, string> groups,Dictionary<int, string> tags);
} | 35.434783 | 103 | 0.699387 | [
"Apache-2.0"
] | dmitry575/GoogleTranslate | src/Common/IConvertHtml.cs | 817 | C# |
using System.Reflection;
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("13. Stateless")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("13. Stateless")]
[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("7ba84ef8-b124-4737-9d05-e96b45e5460a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.638889 | 84 | 0.741697 | [
"MIT"
] | pirocorp/CSharp-Fundamentals | 14. Strings and Text Processing - Exercises/13. Stateless/Properties/AssemblyInfo.cs | 1,358 | C# |
using AutoPoco.Configuration;
using AutoPoco.KCL.DataSources;
namespace AutoPoco.KCL.Conventions
{
public class RandomNullableDateTimeConvention : ITypePropertyConvention
{
#region ITypePropertyConvention Members
public void Apply(ITypePropertyConventionContext context)
{
context.SetSource<RandomNullableDateTimeDataSource>();
}
public void SpecifyRequirements(ITypeMemberConventionRequirements requirements)
{
requirements.Type(c => c == typeof(System.Nullable<System.DateTime>));
}
#endregion
}
} | 24 | 81 | 0.797348 | [
"MIT"
] | KCL5South/KCLAutoPoco | AutoPoco.KCL/Conventions/RandomNullableDateTimeConvention.cs | 528 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Yandex.Inputs
{
public sealed class GetComputeInstanceSchedulingPolicyInputArgs : Pulumi.ResourceArgs
{
/// <summary>
/// (Optional) Specifies if the instance is preemptible. Defaults to false.
/// </summary>
[Input("preemptible")]
public Input<bool>? Preemptible { get; set; }
public GetComputeInstanceSchedulingPolicyInputArgs()
{
}
}
}
| 28.807692 | 89 | 0.682243 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-yandex | sdk/dotnet/Inputs/GetComputeInstanceSchedulingPolicyArgs.cs | 749 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel;
#pragma warning disable CA1001
namespace CommunityToolkit.Common.Deferred;
/// <summary>
/// <see cref="EventArgs"/> which can retrieve a <see cref="EventDeferral"/> in order to process data asynchronously before an <see cref="EventHandler"/> completes and returns to the calling control.
/// </summary>
public class DeferredEventArgs : EventArgs
{
/// <summary>
/// Gets a new <see cref="DeferredEventArgs"/> to use in cases where no <see cref="EventArgs"/> wish to be provided.
/// </summary>
public static new DeferredEventArgs Empty => new();
private readonly object _eventDeferralLock = new();
private EventDeferral? _eventDeferral;
/// <summary>
/// Returns an <see cref="EventDeferral"/> which can be completed when deferred event is ready to continue.
/// </summary>
/// <returns><see cref="EventDeferral"/> instance.</returns>
public EventDeferral GetDeferral()
{
lock (_eventDeferralLock)
{
return _eventDeferral ??= new EventDeferral();
}
}
/// <summary>
/// DO NOT USE - This is a support method used by <see cref="EventHandlerExtensions"/>. It is public only for
/// additional usage within extensions for the UWP based TypedEventHandler extensions.
/// </summary>
/// <returns>Internal EventDeferral reference</returns>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This is an internal only method to be used by EventHandler extension classes, public callers should call GetDeferral() instead.")]
public EventDeferral? GetCurrentDeferralAndReset()
{
lock (_eventDeferralLock)
{
EventDeferral? eventDeferral = _eventDeferral;
_eventDeferral = null;
return eventDeferral;
}
}
}
| 35.655172 | 199 | 0.686654 | [
"MIT"
] | Avid29/dotnet | CommunityToolkit.Common/Deferred/DeferredEventArgs.cs | 2,068 | C# |
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
//옵션 중 사운드 관련 옵션 관리
namespace Kupa
{
public class Option_Sound : MonoBehaviourUI
{
//엔진에서 마우스로 끌어서 참조하는 부분을 최소화. 스크립트에서 대부분 처리하도록
[SerializeField] private Transform masterObject;
[SerializeField] private Transform bgmObject;
[SerializeField] private Transform sfxObject;
[SerializeField] private Transform voiceObject;
private TMP_Text masterText;
private TMP_Text bgmText;
private TMP_Text sfxText;
private TMP_Text voiceText;
private Button masterButtonDown;
private Button bgmButtonDown;
private Button sfxButtonDown;
private Button voiceButtonDown;
private Button masterButtonUp;
private Button bgmButtonUp;
private Button sfxButtonUp;
private Button voiceButtonUp;
private Slider masterSlider;
private Slider bgmSlider;
private Slider sfxSlider;
private Slider voiceSlider;
private int master; //전체 볼륨
private int bgm; //배경음
private int sfx; //효과음
private int voice; //대사
private OptionCanvas optionCanvas;
private void Awake()
{
InitOptionItem(masterObject, out masterText, out masterButtonDown, out masterButtonUp, out masterSlider, OnClickMasterDown, OnClickMasterUp, OnValueChangedMaster);
InitOptionItem(bgmObject, out bgmText, out bgmButtonDown, out bgmButtonUp, out bgmSlider, OnClickBGMDown, OnClickBGMUp, OnValueChangedBGM);
InitOptionItem(sfxObject, out sfxText, out sfxButtonDown, out sfxButtonUp, out sfxSlider, OnClickSFXDown, OnClickSFXUp, OnValueChangedSFX);
InitOptionItem(voiceObject, out voiceText, out voiceButtonDown, out voiceButtonUp, out voiceSlider, OnClickVoiceDown, OnClickVoiceUp, OnValueChangedVoice);
optionCanvas = GetComponentInParent<OptionCanvas>(); //옵션 내 공용 버튼을 위함. (적용, 닫기 버튼)
}
protected override void OnEnable()
{
base.OnEnable();
master = PreferenceData.MasterVolume;
bgm = PreferenceData.BgmVolume;
sfx = PreferenceData.SfxVolume;
voice = PreferenceData.VoiceVolume;
UpdateMaster();
UpdateBGM();
UpdateSFX();
UpdateVoice();
optionCanvas.SetApplyOnClickListener(false);
optionCanvas.SetCloseOnClickListener(true, Close);
}
// public void OnClickApply()
// {
// }
protected override void Close()
{
UIManager.Self.OpenCanvasOption(false);
}
private void OnClickMasterDown()
{
if (--master < 0) master = 0;
PreferenceData.MasterVolume = master;
UpdateMaster();
}
private void OnClickMasterUp()
{
if (100 < ++master) master = 100;
PreferenceData.MasterVolume = master;
UpdateMaster();
}
private void OnClickBGMDown()
{
if (--bgm < 0) bgm = 0;
PreferenceData.BgmVolume = bgm;
UpdateBGM();
}
private void OnClickBGMUp()
{
if (100 < ++bgm) bgm = 100;
PreferenceData.BgmVolume = bgm;
UpdateBGM();
}
private void OnClickSFXDown()
{
if (--sfx < 0) sfx = 0;
PreferenceData.SfxVolume = sfx;
UpdateSFX();
}
private void OnClickSFXUp()
{
if (100 < ++sfx) sfx = 100;
PreferenceData.SfxVolume = sfx;
UpdateSFX();
}
private void OnClickVoiceDown()
{
if (--voice < 0) voice = 0;
PreferenceData.VoiceVolume = voice;
UpdateVoice();
}
private void OnClickVoiceUp()
{
if (100 < ++voice) voice = 100;
PreferenceData.VoiceVolume = voice;
UpdateVoice();
}
private void OnValueChangedMaster(float volume)
{
PreferenceData.MasterVolume = master = Mathf.RoundToInt(volume);
UpdateMaster();
}
private void OnValueChangedBGM(float volume)
{
PreferenceData.BgmVolume = bgm = Mathf.RoundToInt(volume);
UpdateBGM();
}
private void OnValueChangedSFX(float volume)
{
PreferenceData.SfxVolume = sfx = Mathf.RoundToInt(volume);
UpdateSFX();
}
private void OnValueChangedVoice(float volume)
{
PreferenceData.VoiceVolume = voice = Mathf.RoundToInt(volume);
UpdateVoice();
}
private void UpdateMaster()
{
masterSlider.value = master;
masterText.text = master.ToString();
}
private void UpdateBGM()
{
bgmSlider.value = bgm;
bgmText.text = bgm.ToString();
}
private void UpdateSFX()
{
sfxSlider.value = sfx;
sfxText.text = sfx.ToString();
}
private void UpdateVoice()
{
voiceSlider.value = voice;
voiceText.text = voice.ToString();
}
private void InitOptionItem(Transform itemObj, out TMP_Text valueText, out Button DownBtn, out Button UpBtn, out Slider slider, UnityAction OnClickDownListener, UnityAction OnClickUpListener, UnityAction<float> OnValueChangedListener)
{
valueText = itemObj.Find("TMP_Value").GetComponent<TMP_Text>();
DownBtn = itemObj.Find("Btn_Down").GetComponent<Button>();
UpBtn = itemObj.Find("Btn_Up").GetComponent<Button>();
slider = itemObj.Find("Slider").GetComponent<Slider>();
DownBtn.onClick.AddListener(OnClickDownListener);
UpBtn.onClick.AddListener(OnClickUpListener);
slider.onValueChanged.AddListener(OnValueChangedListener);
}
}
} | 33.308108 | 242 | 0.588121 | [
"MIT"
] | jab724/Kupa3DRPG | Kupa3DRPG_SRC/Assets/01. Scripts/Option/Option_Sound.cs | 6,314 | C# |
using AElf.Contracts.Parliament;
using AElf.Kernel.SmartContract.Application;
using AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.FreeFeeTransactions;
using AElf.Types;
namespace AElf.Kernel.SmartContract.ExecutionPluginForProposal
{
public class ParliamentContractChargeFeeStrategy : IChargeFeeStrategy
{
private readonly ISmartContractAddressService _smartContractAddressService;
public ParliamentContractChargeFeeStrategy(ISmartContractAddressService smartContractAddressService)
{
_smartContractAddressService = smartContractAddressService;
}
public Address ContractAddress =>
_smartContractAddressService.GetAddressByContractName(ParliamentSmartContractAddressNameProvider.Name);
public string MethodName =>
nameof(ParliamentContractContainer.ParliamentContractStub.ApproveMultiProposals);
public bool IsFree(Transaction transaction)
{
return true;
}
}
} | 36.142857 | 115 | 0.761858 | [
"MIT"
] | booggzen/AElf | src/AElf.Kernel.SmartContract.ExecutionPluginForProposal/ParliamentContractChargeFeeStrategy.cs | 1,012 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Dummy implementations of non-portable interop methods that just throw PlatformNotSupportedException
using System.Reflection;
using System.Runtime.InteropServices.ComTypes;
namespace System.Runtime.InteropServices
{
public static partial class Marshal
{
public static int GetHRForException(Exception e)
{
return (e != null) ? e.HResult : 0;
}
public static int AddRef(IntPtr pUnk)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool AreComObjectsAvailableForCleanup() => false;
public static IntPtr CreateAggregatedObject(IntPtr pOuter, object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static Object BindToMoniker(String monikerName)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void CleanupUnusedObjectsInCurrentContext()
{
return;
}
public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object CreateWrapperOfType(object o, Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int FinalReleaseComObject(object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static IntPtr GetComInterfaceForObject(object o, Type T)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static IntPtr GetComInterfaceForObject(object o, Type T, CustomQueryInterfaceMode mode)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static IntPtr GetComInterfaceForObject<T, TInterface>(T o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetComObjectData(object obj, object key)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static IntPtr GetHINSTANCE(Module m)
{
if (m == null)
{
throw new ArgumentNullException(nameof(m));
}
return (IntPtr) (-1);
}
public static IntPtr GetIUnknownForObject(object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void GetNativeVariantForObject(object obj, IntPtr pDstNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static Object GetTypedObjectForIUnknown(IntPtr pUnk, Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetObjectForIUnknown(IntPtr pUnk)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetObjectForNativeVariant(IntPtr pSrcNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int GetStartComSlot(Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int GetEndComSlot(Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static Type GetTypeFromCLSID(Guid clsid)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static string GetTypeInfoName(ITypeInfo typeInfo)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetUniqueObjectForIUnknown(IntPtr unknown)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool IsComObject(object o)
{
if (o == null)
{
throw new ArgumentNullException(nameof(o));
}
return false;
}
public static bool IsTypeVisibleFromCom(Type t)
{
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}
return false;
}
public static int QueryInterface(IntPtr pUnk, ref Guid iid, out IntPtr ppv)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int Release(IntPtr pUnk)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int ReleaseComObject(object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool SetComObjectData(object obj, object key, object data)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
}
public class DispatchWrapper
{
public DispatchWrapper(object obj)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public object WrappedObject => throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static class ComEventsHelper
{
public static void Combine(object rcw, Guid iid, int dispid, Delegate d)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static Delegate Remove(object rcw, Guid iid, int dispid, Delegate d)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
}
}
| 33.362445 | 115 | 0.661126 | [
"MIT"
] | AlexejLiebenthal/coreclr | src/System.Private.CoreLib/src/System/Runtime/InteropServices/NonPortable.cs | 7,640 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using PostgreKeyRotation.Models;
using Refit;
using System.Threading.Tasks;
namespace PostgreKeyRotation.IntegrationTests
{
public interface IPostgreKeyRotationService
{
[Get("/postgresql/")]
Task<PostgreSQLConnectResult> GetResultAsync();
}
}
| 21.875 | 55 | 0.737143 | [
"MIT"
] | GreatHonda/aks-postgre-keyrotation | PostgreKeyRotation/PostgreKeyRotation.IntegrationTests/IPostgreKeyRotationService.cs | 352 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using Bam.Net.Data;
namespace Bam.Net.Services.DataReplication.Data.Dao
{
public class SaveOperationCollection: DaoCollection<SaveOperationColumns, SaveOperation>
{
public SaveOperationCollection(){}
public SaveOperationCollection(Database db, DataTable table, Bam.Net.Data.Dao dao = null, string rc = null) : base(db, table, dao, rc) { }
public SaveOperationCollection(DataTable table, Bam.Net.Data.Dao dao = null, string rc = null) : base(table, dao, rc) { }
public SaveOperationCollection(Query<SaveOperationColumns, SaveOperation> q, Bam.Net.Data.Dao dao = null, string rc = null) : base(q, dao, rc) { }
public SaveOperationCollection(Database db, Query<SaveOperationColumns, SaveOperation> q, bool load) : base(db, q, load) { }
public SaveOperationCollection(Query<SaveOperationColumns, SaveOperation> q, bool load) : base(q, load) { }
}
} | 51.684211 | 148 | 0.755601 | [
"MIT"
] | BryanApellanes/bam.net.shared | Services/DataReplication/Data/Generated_Dao/SaveOperationCollection.cs | 982 | C# |
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RedFolder.Blog.Markdown.Transformers
{
public interface ITransformer
{
string TransformMarkdown(JObject meta, string markdown);
}
}
| 20.533333 | 64 | 0.762987 | [
"MIT"
] | Red-Folder/red-folder.com | src/Red-Folder.Blog.Markdown/Transformers/ITransformer.cs | 310 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Internal.Messages.Core.Models.Domain;
using Internal.Messages.Core.Models.ResourceParameters;
using Internal.Messages.Repository.Data;
using Internal.Messages.Repository.Repositories;
using Internal.Messages.TestUtilities;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
namespace Internal.Messages.UnitTests.Repositories
{
[TestFixture]
public class UserRepositoryTests
{
public static IEnumerable<TestCaseData> NormalSearchTestCases
{
get
{
yield return new TestCaseData(new UsersResourceParameters
{
Email = "[email protected]",
FirstName = null,
LastName = null,
SearchQuery = null
});
yield return new TestCaseData(new UsersResourceParameters
{
Email = null,
FirstName = "test1",
LastName = null,
SearchQuery = null
});
yield return new TestCaseData(new UsersResourceParameters
{
Email = null,
FirstName = null,
LastName = "user1",
SearchQuery = null
});
yield return new TestCaseData(new UsersResourceParameters
{
Email = null,
FirstName = null,
LastName = null,
SearchQuery = "test1"
});
yield return new TestCaseData(new UsersResourceParameters
{
Email = "[email protected]",
FirstName = null,
LastName = null,
SearchQuery = null
});
yield return new TestCaseData(new UsersResourceParameters
{
Email = null,
FirstName = "Test1",
LastName = null,
SearchQuery = null
});
yield return new TestCaseData(new UsersResourceParameters
{
Email = null,
FirstName = null,
LastName = "User1",
SearchQuery = null
});
yield return new TestCaseData(new UsersResourceParameters
{
Email = null,
FirstName = null,
LastName = null,
SearchQuery = "Test1"
});
}
}
public static IEnumerable<TestCaseData> NotFoundSearchTestCases
{
get
{
yield return new TestCaseData(new UsersResourceParameters
{
Email = "NotFound",
FirstName = null,
LastName = null,
SearchQuery = null
});
yield return new TestCaseData(new UsersResourceParameters
{
Email = null,
FirstName = "NotFound",
LastName = null,
SearchQuery = null
});
yield return new TestCaseData(new UsersResourceParameters
{
Email = null,
FirstName = null,
LastName = "NotFound",
SearchQuery = null
});
yield return new TestCaseData(new UsersResourceParameters
{
Email = null,
FirstName = null,
LastName = null,
SearchQuery = "NotFound"
});
}
}
[SetUp]
public void Setup()
{
}
[Test]
public void GetUsersAsync_NullParameters_ReturnsArgumentNullException()
{
// Arrange
var options = DatabaseUtilities.GetTestDbConextOptions<InternalMessagesContext>();
using (var context = new InternalMessagesContext(options))
{
context.Database.OpenConnection();
context.Database.EnsureCreated();
var usersRepository = new UsersRepository(context, MapperUtilities.GetTestMapper());
// Assert
Assert.ThrowsAsync<ArgumentNullException>(async () => await usersRepository.GetUsersAsync(null));
}
}
[Test]
public async Task GetUsersAsync_AllPropertiesNull_ReturnsAllUsers()
{
// Arrange
var options = DatabaseUtilities.GetTestDbConextOptions<InternalMessagesContext>();
var user1 = new User()
{
Email = "[email protected]",
FirstName = "Test1",
LastName = "User1"
};
var user2 = new User()
{
Email = "[email protected]",
FirstName = "Test2",
LastName = "User2"
};
using (var context = new InternalMessagesContext(options))
{
context.Database.OpenConnection();
context.Database.EnsureCreated();
// Add a user because we need a UserId foreign key for the Users
var usersRepository = new UsersRepository(context, MapperUtilities.GetTestMapper());
await usersRepository.CreateAsync(user1);
await usersRepository.CreateAsync(user2);
}
using (var context = new InternalMessagesContext(options))
{
var usersRepository = new UsersRepository(context, MapperUtilities.GetTestMapper());
// Act
var parameters = new UsersResourceParameters
{
Email = null,
FirstName = null,
LastName = null,
SearchQuery = null
};
// Get Users with null properties for parameters
var results = await usersRepository.GetUsersAsync(parameters);
// Assert
Assert.AreEqual(results.Count(), 2);
Assert.IsTrue(results.FirstOrDefault(x => x.Email == user1.Email) != null);
Assert.IsTrue(results.FirstOrDefault(x => x.Email == user2.Email) != null);
}
}
[TestCaseSource(nameof(NormalSearchTestCases))]
public async Task GetUsersAsync_Search_ReturnsUser(UsersResourceParameters usersResourceParameters)
{
// Arrange
var options = DatabaseUtilities.GetTestDbConextOptions<InternalMessagesContext>();
var user1 = new User()
{
Email = "[email protected]",
FirstName = "Test1",
LastName = "User1"
};
var user2 = new User()
{
Email = "[email protected]",
FirstName = "Test2",
LastName = "User2"
};
using (var context = new InternalMessagesContext(options))
{
context.Database.OpenConnection();
context.Database.EnsureCreated();
// Add a user because we need a UserId foreign key for the Users
var usersRepository = new UsersRepository(context, MapperUtilities.GetTestMapper());
await usersRepository.CreateAsync(user1);
await usersRepository.CreateAsync(user2);
}
using (var context = new InternalMessagesContext(options))
{
var usersRepository = new UsersRepository(context, MapperUtilities.GetTestMapper());
// Act
var results = await usersRepository.GetUsersAsync(usersResourceParameters);
// Assert
Assert.AreEqual(results.Count(), 1);
Assert.IsTrue(results.FirstOrDefault(x => x.Email == user1.Email) != null);
}
}
[TestCaseSource(nameof(NotFoundSearchTestCases))]
public async Task GetUsersAsync_SearchQueryDoesntExist_ReturnsNull(UsersResourceParameters usersResourceParameters)
{
// Arrange
var options = DatabaseUtilities.GetTestDbConextOptions<InternalMessagesContext>();
var user1 = new User()
{
Email = "[email protected]",
FirstName = "Test1",
LastName = "User1"
};
var user2 = new User()
{
Email = "[email protected]",
FirstName = "Test2",
LastName = "User2"
};
using (var context = new InternalMessagesContext(options))
{
context.Database.OpenConnection();
context.Database.EnsureCreated();
// Add a user because we need a UserId foreign key for the Users
var usersRepository = new UsersRepository(context, MapperUtilities.GetTestMapper());
await usersRepository.CreateAsync(user1);
await usersRepository.CreateAsync(user2);
}
using (var context = new InternalMessagesContext(options))
{
var usersRepository = new UsersRepository(context, MapperUtilities.GetTestMapper());
// Act
var results = await usersRepository.GetUsersAsync(usersResourceParameters);
// Assert
Assert.AreEqual(results.Count(), 0);
}
}
}
}
| 35.241993 | 123 | 0.50409 | [
"MIT"
] | DustinChristians/internal-messages-domain | Internal.Messages/Tests/Internal.Messages.UnitTests/Repositories/UserRepositoryTests.cs | 9,903 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
namespace NCop.Core.Runtime
{
public interface IRuntimeSettings
{
IEnumerable<Type> Types { get; }
IEnumerable<Assembly> Assemblies { get; }
}
}
| 19.076923 | 49 | 0.689516 | [
"MIT"
] | sagifogel/NCop | NCop.Core/Runtime/IRuntimeSettings.cs | 250 | C# |
using System;
using System.Collections.Generic;
using FubuCore;
using FubuMVC.Core.Behaviors.Conditional;
using FubuMVC.Core.Registration.Diagnostics;
using FubuMVC.Core.Registration.Nodes;
using FubuMVC.Core.Registration.ObjectGraph;
using FubuMVC.Core.Runtime.Conditionals;
using FubuMVC.Core.Security;
using NUnit.Framework;
using System.Linq;
using FubuTestingSupport;
using Rhino.Mocks;
namespace FubuMVC.Tests.Registration.Diagnostics
{
[TestFixture]
public class BehaviorNodeTracingMechanicsTester
{
private ITracedModel theTracedNode;
private AuthorizationNode theNode;
[SetUp]
public void SetUp()
{
theNode = new AuthorizationNode();
theTracedNode = theNode.As<ITracedModel>();
}
[Test]
public void just_after_being_created_there_should_be_a_Created_event()
{
theTracedNode.StagedEvents.Single().ShouldBeOfType<Created>();
}
[Test]
public void trace_with_a_string_creates_a_new_trace_event()
{
theTracedNode.Trace("some text");
theTracedNode.StagedEvents.Last().ShouldBeOfType<Traced>()
.Text.ShouldEqual("some text");
}
[Test]
public void recording_events_removes_the_events_from_the_node_and_calls_back()
{
var list = new List<NodeEvent>();
theTracedNode.RecordEvents(list.Add);
list.Single().ShouldBeOfType<Created>();
theTracedNode.StagedEvents.Any().ShouldBeFalse();
theTracedNode.Trace("something");
theTracedNode.RecordEvents(list.Add);
list.Last().ShouldBeOfType<Traced>().Text.ShouldEqual("something");
}
[Test]
public void add_condition_with_description()
{
theNode.Condition(() => true, "wacky");
theTracedNode.StagedEvents.Last().ShouldBeOfType<ConditionAdded>()
.Description.ShouldEqual("wacky");
}
[Test]
public void add_condition_by_function_against_service()
{
theNode.ConditionByService<Something>(x => true);
theTracedNode.StagedEvents.Last().ShouldBeOfType<ConditionAdded>()
.Description.ShouldEqual("By Service: Func<Something, bool>");
}
[Test]
public void add_condition_by_function_against_model()
{
theNode.ConditionByModel<Something>(x => true);
theTracedNode.StagedEvents.Last().ShouldBeOfType<ConditionAdded>()
.Description.ShouldEqual("By Model: Func<Something, bool>");
}
[Test]
public void add_condition_by_type()
{
theNode.Condition<SomethingCondition>();
theTracedNode.StagedEvents.Last().ShouldBeOfType<ConditionAdded>()
.Type.ShouldEqual(typeof (SomethingCondition));
}
[Test]
public void the_remove_method_puts_a_node_removed_event_on_the_chain()
{
var chain = new BehaviorChain();
chain.AddToEnd(new SimpleNode());
var nodeToBeRemoved = new SimpleNode();
chain.AddToEnd(nodeToBeRemoved);
chain.AddToEnd(new SimpleNode());
chain.AddToEnd(new SimpleNode());
nodeToBeRemoved.Remove();
chain.As<ITracedModel>().StagedEvents.Last()
.ShouldEqual(new NodeRemoved(nodeToBeRemoved));
}
[Test]
public void the_replace_method_puts_a_node_replaced_event_on_the_chain()
{
var original = new SimpleNode();
var newNode = new SimpleNode();
var chain = new BehaviorChain();
chain.AddToEnd(original);
original.ReplaceWith(newNode);
chain.As<ITracedModel>().StagedEvents.Last()
.ShouldEqual(new NodeReplaced(original, newNode));
}
public class SomethingCondition : IConditional
{
public bool ShouldExecute()
{
throw new NotImplementedException();
}
}
public class Something{}
public class SimpleNode : BehaviorNode
{
public override BehaviorCategory Category
{
get { throw new NotImplementedException(); }
}
protected override ObjectDef buildObjectDef()
{
throw new NotImplementedException();
}
}
}
} | 30.152866 | 87 | 0.583861 | [
"Apache-2.0"
] | DovetailSoftware/fubumvc | src/FubuMVC.Tests/Registration/Diagnostics/BehaviorNodeTracingMechanicsTester.cs | 4,734 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Content.Server.GameObjects.EntitySystems.DoAfter;
using Content.Shared.Audio;
using Content.Shared.GameObjects.Components.Interactable;
using Content.Shared.GameObjects.EntitySystems;
using Content.Shared.GameObjects.EntitySystems.ActionBlocker;
using Robust.Server.GameObjects.EntitySystems;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Interactable
{
public interface IToolComponent
{
ToolQuality Qualities { get; set; }
}
[RegisterComponent]
[ComponentReference(typeof(IToolComponent))]
public class ToolComponent : SharedToolComponent, IToolComponent
{
protected ToolQuality _qualities = ToolQuality.None;
[ViewVariables]
public override ToolQuality Qualities
{
get => _qualities;
set
{
_qualities = value;
Dirty();
}
}
/// <summary>
/// For tool interactions that have a delay before action this will modify the rate, time to wait is divided by this value
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public float SpeedModifier { get; set; } = 1;
public string UseSound { get; set; }
public string UseSoundCollection { get; set; }
public void AddQuality(ToolQuality quality)
{
_qualities |= quality;
Dirty();
}
public void RemoveQuality(ToolQuality quality)
{
_qualities &= ~quality;
Dirty();
}
public bool HasQuality(ToolQuality quality)
{
return _qualities.HasFlag(quality);
}
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataReadWriteFunction(
"qualities",
new List<ToolQuality>(),
qualities => qualities.ForEach(AddQuality),
() =>
{
var qualities = new List<ToolQuality>();
foreach (ToolQuality quality in Enum.GetValues(typeof(ToolQuality)))
{
if ((_qualities & quality) != 0)
{
qualities.Add(quality);
}
}
return qualities;
});
serializer.DataField(this, mod => SpeedModifier, "speed", 1);
serializer.DataField(this, use => UseSound, "useSound", string.Empty);
serializer.DataField(this, collection => UseSoundCollection, "useSoundCollection", string.Empty);
}
public virtual async Task<bool> UseTool(IEntity user, IEntity target, float doAfterDelay, ToolQuality toolQualityNeeded, Func<bool> doAfterCheck = null)
{
if (!HasQuality(toolQualityNeeded) || !ActionBlockerSystem.CanInteract(user))
return false;
if (doAfterDelay > 0f)
{
var doAfterSystem = EntitySystem.Get<DoAfterSystem>();
var doAfterArgs = new DoAfterEventArgs(user, doAfterDelay / SpeedModifier, default, target)
{
ExtraCheck = doAfterCheck,
BreakOnDamage = false, // TODO: Change this to true once breathing is fixed.
BreakOnStun = true,
BreakOnTargetMove = true,
BreakOnUserMove = true,
NeedHand = true,
};
var result = await doAfterSystem.DoAfter(doAfterArgs);
if (result == DoAfterStatus.Cancelled)
return false;
}
PlayUseSound();
return true;
}
protected void PlaySoundCollection(string name, float volume=-5f)
{
var file = AudioHelpers.GetRandomFileFromSoundCollection(name);
EntitySystem.Get<AudioSystem>()
.PlayFromEntity(file, Owner, AudioHelpers.WithVariation(0.15f).WithVolume(volume));
}
public void PlayUseSound(float volume=-5f)
{
if (string.IsNullOrEmpty(UseSoundCollection))
{
if (!string.IsNullOrEmpty(UseSound))
{
EntitySystem.Get<AudioSystem>()
.PlayFromEntity(UseSound, Owner, AudioHelpers.WithVariation(0.15f).WithVolume(volume));
}
}
else
{
PlaySoundCollection(UseSoundCollection, volume);
}
}
}
}
| 32.939597 | 160 | 0.569071 | [
"MIT"
] | LetterN/space-station-14 | Content.Server/GameObjects/Components/Interactable/ToolComponent.cs | 4,908 | 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 ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the ImportInstance operation.
/// Creates an import instance task using metadata from the specified disk image. <code>ImportInstance</code>
/// only supports single-volume VMs. To import multi-volume VMs, use <a>ImportImage</a>.
/// For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/CommandLineReference/ec2-cli-vmimport-export.html">Importing
/// a Virtual Machine Using the Amazon EC2 CLI</a>.
///
///
/// <para>
/// For information about the import manifest referenced by this API action, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html">VM
/// Import Manifest</a>.
/// </para>
/// </summary>
public partial class ImportInstanceRequest : AmazonEC2Request
{
private string _description;
private List<DiskImage> _diskImages = new List<DiskImage>();
private ImportInstanceLaunchSpecification _launchSpecification;
private PlatformValues _platform;
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// A description for the instance being imported.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property DiskImages.
/// <para>
/// The disk image.
/// </para>
/// </summary>
public List<DiskImage> DiskImages
{
get { return this._diskImages; }
set { this._diskImages = value; }
}
// Check to see if DiskImages property is set
internal bool IsSetDiskImages()
{
return this._diskImages != null && this._diskImages.Count > 0;
}
/// <summary>
/// Gets and sets the property LaunchSpecification.
/// <para>
/// The launch specification.
/// </para>
/// </summary>
public ImportInstanceLaunchSpecification LaunchSpecification
{
get { return this._launchSpecification; }
set { this._launchSpecification = value; }
}
// Check to see if LaunchSpecification property is set
internal bool IsSetLaunchSpecification()
{
return this._launchSpecification != null;
}
/// <summary>
/// Gets and sets the property Platform.
/// <para>
/// The instance operating system.
/// </para>
/// </summary>
public PlatformValues Platform
{
get { return this._platform; }
set { this._platform = value; }
}
// Check to see if Platform property is set
internal bool IsSetPlatform()
{
return this._platform != null;
}
}
} | 32.691057 | 165 | 0.611788 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/ImportInstanceRequest.cs | 4,021 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OCM.API.Common.Model.Extended
{
public class GeocodingResult
{
public int AddressInfoID { get; set; }
public bool ResultsAvailable { get; set; }
public string Service { get; set; }
public double? Latitude { get; set; }
public double? Longitude { get; set; }
public string QueryURL { get; set; }
public string ExtendedData { get; set; }
public string Address { get; set; }
public string Attribution { get; set; }
}
}
| 27.347826 | 50 | 0.6407 | [
"MIT"
] | cybersol795/ocm-system | API/OCM.Net/OCM.API.Model/Extended/GeocodingResult.cs | 631 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public class AcceptAsync
{
private readonly ITestOutputHelper _log;
public AcceptAsync(ITestOutputHelper output)
{
_log = TestLogging.GetInstance();
}
public void OnAcceptCompleted(object sender, SocketAsyncEventArgs args)
{
_log.WriteLine("OnAcceptCompleted event handler");
EventWaitHandle handle = (EventWaitHandle)args.UserToken;
handle.Set();
}
public void OnConnectCompleted(object sender, SocketAsyncEventArgs args)
{
_log.WriteLine("OnConnectCompleted event handler");
EventWaitHandle handle = (EventWaitHandle)args.UserToken;
handle.Set();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[Trait("IPv4", "true")]
public void AcceptAsync_IpV4_Success()
{
Assert.True(Capability.IPv4Support());
AutoResetEvent completed = new AutoResetEvent(false);
AutoResetEvent completedClient = new AutoResetEvent(false);
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = sock.BindToAnonymousPort(IPAddress.Loopback);
sock.Listen(1);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed += OnAcceptCompleted;
args.UserToken = completed;
Assert.True(sock.AcceptAsync(args));
_log.WriteLine("IPv4 Server: Waiting for clients.");
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs();
argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port);
argsClient.Completed += OnConnectCompleted;
argsClient.UserToken = completedClient;
client.ConnectAsync(argsClient);
_log.WriteLine("IPv4 Client: Connecting.");
Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection");
Assert.Equal<SocketError>(SocketError.Success, args.SocketError);
Assert.NotNull(args.AcceptSocket);
Assert.True(args.AcceptSocket.Connected, "IPv4 Accept Socket was not connected");
Assert.NotNull(args.AcceptSocket.RemoteEndPoint);
Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint);
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[Trait("IPv6", "true")]
public void AcceptAsync_IPv6_Success()
{
Assert.True(Capability.IPv6Support());
AutoResetEvent completed = new AutoResetEvent(false);
AutoResetEvent completedClient = new AutoResetEvent(false);
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
int port = sock.BindToAnonymousPort(IPAddress.IPv6Loopback);
sock.Listen(1);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed += OnAcceptCompleted;
args.UserToken = completed;
Assert.True(sock.AcceptAsync(args));
_log.WriteLine("IPv6 Server: Waiting for clients.");
using (Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs();
argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, port);
argsClient.Completed += OnConnectCompleted;
argsClient.UserToken = completedClient;
client.ConnectAsync(argsClient);
_log.WriteLine("IPv6 Client: Connecting.");
Assert.True(completed.WaitOne(5000), "IPv6: Timed out while waiting for connection");
Assert.Equal<SocketError>(SocketError.Success, args.SocketError);
Assert.NotNull(args.AcceptSocket);
Assert.True(args.AcceptSocket.Connected, "IPv6 Accept Socket was not connected");
Assert.NotNull(args.AcceptSocket.RemoteEndPoint);
Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint);
}
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(2)]
[InlineData(5)]
public async Task AcceptAsync_ConcurrentAcceptsBeforeConnects_Success(int numberAccepts)
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(numberAccepts);
var clients = new Socket[numberAccepts];
var servers = new Task<Socket>[numberAccepts];
try
{
for (int i = 0; i < numberAccepts; i++)
{
clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
servers[i] = listener.AcceptAsync();
}
foreach (Socket client in clients)
{
client.Connect(listener.LocalEndPoint);
}
await Task.WhenAll(servers);
Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status));
Assert.All(servers, s => Assert.NotNull(s.Result));
Assert.All(servers, s => Assert.True(s.Result.Connected));
}
finally
{
foreach (Socket client in clients)
{
client?.Dispose();
}
foreach (Task<Socket> server in servers)
{
if (server?.Status == TaskStatus.RanToCompletion)
{
server.Result.Dispose();
}
}
}
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(2)]
[InlineData(5)]
public async Task AcceptAsync_ConcurrentAcceptsAfterConnects_Success(int numberAccepts)
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(numberAccepts);
var clients = new Socket[numberAccepts];
var clientConnects = new Task[numberAccepts];
var servers = new Task<Socket>[numberAccepts];
try
{
for (int i = 0; i < numberAccepts; i++)
{
clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientConnects[i] = clients[i].ConnectAsync(listener.LocalEndPoint);
}
for (int i = 0; i < numberAccepts; i++)
{
servers[i] = listener.AcceptAsync();
}
await Task.WhenAll(clientConnects);
Assert.All(clientConnects, c => Assert.Equal(TaskStatus.RanToCompletion, c.Status));
await Task.WhenAll(servers);
Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status));
Assert.All(servers, s => Assert.NotNull(s.Result));
Assert.All(servers, s => Assert.True(s.Result.Connected));
}
finally
{
foreach (Socket client in clients)
{
client?.Dispose();
}
foreach (Task<Socket> server in servers)
{
if (server?.Status == TaskStatus.RanToCompletion)
{
server.Result.Dispose();
}
}
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Unix platforms don't yet support receiving data with AcceptAsync.
public void AcceptAsync_WithReceiveBuffer_Success()
{
Assert.True(Capability.IPv4Support());
AutoResetEvent accepted = new AutoResetEvent(false);
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = server.BindToAnonymousPort(IPAddress.Loopback);
server.Listen(1);
const int acceptBufferOverheadSize = 288; // see https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.acceptasync(v=vs.110).aspx
const int acceptBufferDataSize = 256;
const int acceptBufferSize = acceptBufferOverheadSize + acceptBufferDataSize;
byte[] sendBuffer = new byte[acceptBufferDataSize];
new Random().NextBytes(sendBuffer);
SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs();
acceptArgs.Completed += OnAcceptCompleted;
acceptArgs.UserToken = accepted;
acceptArgs.SetBuffer(new byte[acceptBufferSize], 0, acceptBufferSize);
Assert.True(server.AcceptAsync(acceptArgs));
_log.WriteLine("IPv4 Server: Waiting for clients.");
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
client.Connect(IPAddress.Loopback, port);
client.Send(sendBuffer);
client.Shutdown(SocketShutdown.Both);
}
Assert.True(
accepted.WaitOne(TestSettings.PassingTestTimeout), "Test completed in alotted time");
Assert.Equal(
SocketError.Success, acceptArgs.SocketError);
Assert.Equal(
acceptBufferDataSize, acceptArgs.BytesTransferred);
Assert.Equal(
new ArraySegment<byte>(sendBuffer),
new ArraySegment<byte>(acceptArgs.Buffer, 0, acceptArgs.BytesTransferred));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Unix platforms don't yet support receiving data with AcceptAsync.
public void AcceptAsync_WithTooSmallReceiveBuffer_Failure()
{
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = server.BindToAnonymousPort(IPAddress.Loopback);
server.Listen(1);
SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs();
acceptArgs.Completed += OnAcceptCompleted;
acceptArgs.UserToken = new ManualResetEvent(false);
byte[] buffer = new byte[1];
acceptArgs.SetBuffer(buffer, 0, buffer.Length);
AssertExtensions.Throws<ArgumentException>(null, () => server.AcceptAsync(acceptArgs));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[ActiveIssue(17209, TestPlatforms.AnyUnix)]
public void AcceptAsync_WithTargetSocket_Success()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = listener.BindToAnonymousPort(IPAddress.Loopback);
listener.Listen(1);
Task<Socket> acceptTask = listener.AcceptAsync(server);
client.Connect(IPAddress.Loopback, port);
Assert.Same(server, acceptTask.Result);
}
}
[ActiveIssue(17209, TestPlatforms.AnyUnix)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(false)]
[InlineData(true)]
public void AcceptAsync_WithTargetSocket_ReuseAfterDisconnect_Success(bool reuseSocket)
{
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var saea = new SocketAsyncEventArgs())
{
int port = listener.BindToAnonymousPort(IPAddress.Loopback);
listener.Listen(1);
var are = new AutoResetEvent(false);
saea.Completed += delegate { are.Set(); };
saea.AcceptSocket = server;
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.True(listener.AcceptAsync(saea));
client.Connect(IPAddress.Loopback, port);
are.WaitOne();
Assert.Same(server, saea.AcceptSocket);
Assert.True(server.Connected);
}
server.Disconnect(reuseSocket);
Assert.False(server.Connected);
if (reuseSocket)
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.True(listener.AcceptAsync(saea));
client.Connect(IPAddress.Loopback, port);
are.WaitOne();
Assert.Same(server, saea.AcceptSocket);
Assert.True(server.Connected);
}
}
else
{
if (listener.AcceptAsync(saea))
{
are.WaitOne();
}
Assert.Equal(SocketError.InvalidArgument, saea.SocketError);
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[ActiveIssue(17209, TestPlatforms.AnyUnix)]
public void AcceptAsync_WithAlreadyBoundTargetSocket_Failed()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = listener.BindToAnonymousPort(IPAddress.Loopback);
listener.Listen(1);
server.BindToAnonymousPort(IPAddress.Loopback);
Assert.Throws<InvalidOperationException>(() => { listener.AcceptAsync(server); });
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix platforms don't yet support receiving data with AcceptAsync.
public void AcceptAsync_WithReceiveBuffer_Failure()
{
//
// Unix platforms don't yet support receiving data with AcceptAsync.
//
Assert.True(Capability.IPv4Support());
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = server.BindToAnonymousPort(IPAddress.Loopback);
server.Listen(1);
SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs();
acceptArgs.Completed += OnAcceptCompleted;
acceptArgs.UserToken = new ManualResetEvent(false);
byte[] buffer = new byte[1024];
acceptArgs.SetBuffer(buffer, 0, buffer.Length);
Assert.Throws<PlatformNotSupportedException>(() => server.AcceptAsync(acceptArgs));
}
}
}
}
| 42.004866 | 158 | 0.559893 | [
"MIT"
] | cydhaselton/cfx-android | src/System.Net.Sockets/tests/FunctionalTests/AcceptAsync.cs | 17,264 | C# |
using System.Numerics;
using Esprima.Ast;
namespace Esprima
{
public enum TokenType
{
BooleanLiteral,
EOF,
Identifier,
Keyword,
NullLiteral,
NumericLiteral,
Punctuator,
StringLiteral,
RegularExpression,
Template,
BigIntLiteral
};
public class Token
{
public TokenType Type;
public string? Literal;
public int Start; // Range[0]
public int End; // Range[1]
public int LineNumber;
public int LineStart;
public Location Location;
// For NumericLiteral
public bool Octal;
public char? NotEscapeSequenceHead;
// For templates
public bool Head;
public bool Tail;
public string? RawTemplate;
public bool BooleanValue;
public double NumericValue;
public object? Value;
public RegexValue? RegexValue;
public BigInteger? BigIntValue;
public void Clear()
{
Type = TokenType.BooleanLiteral;
Literal = null;
Start = 0;
End = 0;
LineNumber = 0;
LineStart = 0;
Location = default;
Octal = false;
Head = false;
Tail = false;
RawTemplate = null;
BooleanValue = false;
NumericValue = 0;
Value = null;
RegexValue = null;
BigIntValue = null;
}
}
}
| 22 | 44 | 0.521739 | [
"BSD-3-Clause"
] | dungjk/esprima-dotnet | src/Esprima/Token.cs | 1,520 | C# |
using AutoMapper;
using supermarketapi.Domain.Models;
using supermarketapi.Domain.Models.Queries;
using supermarketapi.Extensions;
using supermarketapi.Resources;
namespace supermarketapi.Mapping
{
public class ModelToResourceProfile : Profile
{
public ModelToResourceProfile()
{
CreateMap<Category, CategoryResource>();
CreateMap<Product, ProductResource>();
//CreateMap<Product, ProductResource>()
// .ForMember(src => src.UnitOfMeasurement,
// opt => opt.MapFrom(src => src.UnitOfMeasurement.ToDescriptionString()));
CreateMap<QueryResult<Product>, QueryResultResource<Product>>();
}
}
} | 29.958333 | 101 | 0.659249 | [
"MIT"
] | ricardocosta21/deliveryAPI | Mapping/ModelToResourceProfile.cs | 719 | C# |
using FestivalManager.Entities.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FestivalManager.Entities.Sets
{
public abstract class Set : ISet
{
private List<IPerformer> performers = new List<IPerformer>();
private List<ISong> songs = new List<ISong>();
protected Set(string name)
{
Name = name;
}
public string Name { get; }
public virtual TimeSpan MaxDuration { get; }
public TimeSpan ActualDuration => TimeSpan.FromTicks(Songs.Sum(s => s.Duration.Ticks));
public IReadOnlyCollection<IPerformer> Performers
{
get => performers;
}
public IReadOnlyCollection<ISong> Songs
{
get => songs;
}
public void AddPerformer(IPerformer performer)
{
performers.Add(performer);
}
public void AddSong(ISong song)
{
if (song.Duration + ActualDuration > MaxDuration)
{
throw new InvalidOperationException("Song is over the set limit!");
}
songs.Add(song);
}
public bool CanPerform()
{
if (Songs.Count >= 1 && Performers.Count >= 1 && Performers.All(p => p.Instruments.Any(i => i.IsBroken == false)))
{
return true;
}
else
{
return false;
}
}
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine(string.Join(", ", this.Performers));
foreach (var song in this.Songs)
{
sb.AppendLine($"-- {song}");
}
var result = sb.ToString();
return result;
}
}
}
| 23.987179 | 126 | 0.519508 | [
"MIT"
] | sevgin0954/SoftUni-Projects | C# OOP Advanced/Exam - 22 April 2018/FestivalManager/Entities/Sets/Set.cs | 1,873 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AimScale : MonoBehaviour {
public float minSize = 0.05f;
public float maxSize = 1f;
public float shrinkSpd = 0.5f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(transform.localScale.x > minSize) {
transform.localScale = new Vector3(transform.localScale.x - shrinkSpd * Time.deltaTime, transform.localScale.y, transform.localScale.z);
}else{
transform.localScale = new Vector3(maxSize, transform.localScale.y, transform.localScale.z);
}
}
}
| 27.333333 | 148 | 0.690549 | [
"MIT"
] | Ashment/TetrisFall | Assets/Scripts/AimScale.cs | 658 | C# |
using LibGit2Sharp;
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization.Formatters;
using System.Text.RegularExpressions;
namespace PRFinder
{
class Program
{
static readonly Regex IsMergePRCommit = new Regex(@"^Merge pull request #(\d+) from");
static readonly Regex IsSquashedPRCommit = new Regex(@"\(#(\d+)\)$");
const string RepoPRUrl = @"https://www.github.com/dotnet/roslyn";
static int Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += (sender, e) => Console.Error.WriteLine($"Error: {e.ToString()}");
if (args.Length != 4)
{
Console.Error.WriteLine($"ERROR: Expected 4 arguments but got {args.Length}");
return 1;
}
if (args[0] != "-prev" || args[2] != "-curr")
{
Console.Error.WriteLine("ERROR: Invalid arguments. Invoke `prfinder -prev {sha} -curr {sha}`");
return 1;
}
var previousCommitSha = args[1];
var currentCommitSha = args[3];
using (var repo = new Repository(Environment.CurrentDirectory))
{
var currentCommit = repo.Lookup<Commit>(currentCommitSha);
var previousCommit = repo.Lookup<Commit>(previousCommitSha);
if (currentCommit is null || previousCommit is null)
{
Console.WriteLine($"Couldn't find commit {(currentCommit is null ? currentCommitSha : previousCommitSha)}");
Console.WriteLine("Fetching and trying again...");
// it doesn't please me to do this, but libgit2sharp doesn't support ssh easily
Process.Start("git", "fetch --all").WaitForExit();
Console.WriteLine("--- end of git output ---");
Console.WriteLine();
currentCommit = repo.Lookup<Commit>(currentCommitSha);
previousCommit = repo.Lookup<Commit>(previousCommitSha);
}
// Get commit history starting at the current commit and ending at the previous commit
var commitLog = repo.Commits.QueryBy(
new CommitFilter
{
IncludeReachableFrom = currentCommit,
ExcludeReachableFrom = previousCommit
});
Console.WriteLine($@"Changes since [{previousCommitSha}]({RepoPRUrl}/commit/{previousCommitSha})");
foreach (var commit in commitLog)
{
// Exclude auto-merges
if (commit.Author.Name == "dotnet-automerge-bot")
{
continue;
}
var match = IsMergePRCommit.Match(commit.MessageShort);
if (!match.Success)
{
match = IsSquashedPRCommit.Match(commit.MessageShort);
}
if (!match.Success)
{
continue;
}
var prNumber = match.Groups[1].Value;
var prLink = $@"- [{commit.MessageShort}]({RepoPRUrl}/pull/{prNumber})";
Console.WriteLine(prLink);
}
}
return 0;
}
}
}
| 36.354167 | 128 | 0.511175 | [
"Apache-2.0"
] | RikkiGibson/roslyn-tools | src/RoslynInsertionTool/PRFinder/Program.cs | 3,492 | C# |
/*Write a program that reads the coefficients a, b and c of a quadratic
* equation ax2 + bx + c = 0 and solves it (prints its real roots).*/
using System;
using System.Globalization;
using System.Threading;
class QuadraticEquation
{
static void Main()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Console.Write("a = ");
double a = double.Parse(Console.ReadLine());
Console.Write("b = ");
double b = double.Parse(Console.ReadLine());
Console.Write("c = ");
double c = double.Parse(Console.ReadLine());
double d = ((b * b) - (4 * a * c)); //diskriminant
double x1 = ((-b - Math.Sqrt(d)) / (2 * a)); //formula for square roots
double x2 = ((-b + Math.Sqrt(d)) / (2 * a));
if (d < 0)
{
Console.WriteLine("no real roots");
}
else if (x1 == x2) //one root
{
Console.WriteLine("x1 = x2 = " + x1);
}
else // two roots
{
Console.WriteLine("x1 = " + x1);
Console.WriteLine("x2 = " + x2);
}
}
}
| 28.75 | 79 | 0.517391 | [
"MIT"
] | mimiem/CSharp-Part1 | ConsoleInputOutput/QuadraticEquation/QuadraticEquation.cs | 1,152 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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 ("Spin2Win.Android")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("Spin2Win.Android")]
[assembly: AssemblyCopyright ("Copyright © 2013")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
[assembly: ComVisible (false)]
// 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")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission (Android.Manifest.Permission.Internet)]
[assembly: UsesPermission (Android.Manifest.Permission.WriteExternalStorage)]
| 36.914286 | 84 | 0.748452 | [
"MIT"
] | Samples-Playgrounds/Samples.Xamarin.Forms | diverse/forum-samples/beta-users/Spin2Win/Spin2Win.Android/Properties/AssemblyInfo.cs | 1,295 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FirstAid_Step12 : BasicStep
{
public GameObject mouthTrigger;
public void Start()
{
mouthTrigger.SetActive(false);
}
void Update()
{
if (this.IsActivated && LiamInteraction.instance.mouth.isHolding)
{
this.Complete();
}
}
// Start after the activation of the step
public override void Enter()
{
mouthTrigger.SetActive(true);
}
// Start before the completion of the step
public override void Exit()
{
mouthTrigger.SetActive(false);
}
}
| 19.205882 | 73 | 0.624809 | [
"MIT"
] | y3lousso/UQAC_Int3D_VR | Assets/Scripts/FirstAids/Steps/FirstAid_Step12.cs | 655 | C# |
namespace Affecto.AuditTrail.Interfaces.Model
{
public interface IAuditTrailTextFilterParameter
{
AuditTrailTextFilterOperator FilterOperator { get; set; }
string FilterValue { get; set; }
}
} | 27.625 | 65 | 0.710407 | [
"MIT"
] | affecto/dotnet-AuditTrailService | AuditTrail.Interfaces/Model/IAuditTrailTextFilterParameter.cs | 223 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX.Direct3D11;
using SharpDX;
using System.Diagnostics;
namespace Capture.Hook.DX11
{
public class DXImage : Component
{
Device _device;
DeviceContext _deviceContext;
Texture2D _tex;
ShaderResourceView _texSRV;
int _texWidth, _texHeight;
bool _initialised = false;
public int Width
{
get
{
return _texWidth;
}
}
public int Height
{
get
{
return _texHeight;
}
}
public Device Device
{
get { return _device; }
}
public DXImage(Device device, DeviceContext deviceContext): base("DXImage")
{
_device = device;
_deviceContext = deviceContext;
_tex = null;
_texSRV = null;
_texWidth = 0;
_texHeight = 0;
}
public bool Initialise(System.Drawing.Bitmap bitmap)
{
RemoveAndDispose(ref _tex);
RemoveAndDispose(ref _texSRV);
//Debug.Assert(bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb);
System.Drawing.Imaging.BitmapData bmData;
_texWidth = bitmap.Width;
_texHeight = bitmap.Height;
bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, _texWidth, _texHeight), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
try
{
Texture2DDescription texDesc = new Texture2DDescription();
texDesc.Width = _texWidth;
texDesc.Height = _texHeight;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
texDesc.SampleDescription.Count = 1;
texDesc.SampleDescription.Quality = 0;
texDesc.Usage = ResourceUsage.Immutable;
texDesc.BindFlags = BindFlags.ShaderResource;
texDesc.CpuAccessFlags = CpuAccessFlags.None;
texDesc.OptionFlags = ResourceOptionFlags.None;
SharpDX.DataBox data;
data.DataPointer = bmData.Scan0;
data.RowPitch = bmData.Stride;// _texWidth * 4;
data.SlicePitch = 0;
_tex = ToDispose(new Texture2D(_device, texDesc, new[] { data }));
if (_tex == null)
return false;
ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription();
srvDesc.Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
srvDesc.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D;
srvDesc.Texture2D.MipLevels = 1;
srvDesc.Texture2D.MostDetailedMip = 0;
_texSRV = ToDispose(new ShaderResourceView(_device, _tex, srvDesc));
if (_texSRV == null)
return false;
}
finally
{
bitmap.UnlockBits(bmData);
}
_initialised = true;
return true;
}
public ShaderResourceView GetSRV()
{
Debug.Assert(_initialised);
return _texSRV;
}
}
}
| 30.736842 | 195 | 0.549658 | [
"MIT"
] | Dwedit/NvidiaOptimusFixer | Capture/Hook/DX11/DXImage.cs | 3,506 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using Android.App;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("tinyrowgame.Droid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) Johan Karlsson")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 36.428571 | 82 | 0.745098 | [
"MIT"
] | matst80/TinyRowGame | src/xamarin-client/Droid/Properties/AssemblyInfo.cs | 1,022 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.