context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// ReSharper disable All
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using Frapid.Configuration;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.DbPolicy;
using Frapid.Framework.Extensions;
using Npgsql;
using Frapid.NPoco;
using Serilog;
namespace Frapid.Config.DataAccess
{
/// <summary>
/// Provides simplified data access features to perform SCRUD operation on the database table "config.filters".
/// </summary>
public class Filter : DbAccess, IFilterRepository
{
/// <summary>
/// The schema of this table. Returns literal "config".
/// </summary>
public override string _ObjectNamespace => "config";
/// <summary>
/// The schema unqualified name of this table. Returns literal "filters".
/// </summary>
public override string _ObjectName => "filters";
/// <summary>
/// Login id of application user accessing this table.
/// </summary>
public long _LoginId { get; set; }
/// <summary>
/// User id of application user accessing this table.
/// </summary>
public int _UserId { get; set; }
/// <summary>
/// The name of the database on which queries are being executed to.
/// </summary>
public string _Catalog { get; set; }
/// <summary>
/// Performs SQL count on the table "config.filters".
/// </summary>
/// <returns>Returns the number of rows of the table "config.filters".</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long Count()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"Filter\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT COUNT(*) FROM config.filters;";
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "config.filters" to return all instances of the "Filter" class.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "Filter" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.Filter> GetAll()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"Filter\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.filters ORDER BY filter_id;";
return Factory.Get<Frapid.Config.Entities.Filter>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "config.filters" to return all instances of the "Filter" class to export.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "Filter" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<dynamic> Export()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"Filter\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.filters ORDER BY filter_id;";
return Factory.Get<dynamic>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "config.filters" with a where filter on the column "filter_id" to return a single instance of the "Filter" class.
/// </summary>
/// <param name="filterId">The column "filter_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped instance of "Filter" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Config.Entities.Filter Get(long filterId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get entity \"Filter\" filtered by \"FilterId\" with value {FilterId} was denied to the user with Login ID {_LoginId}", filterId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.filters WHERE filter_id=@0;";
return Factory.Get<Frapid.Config.Entities.Filter>(this._Catalog, sql, filterId).FirstOrDefault();
}
/// <summary>
/// Gets the first record of the table "config.filters".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "Filter" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Config.Entities.Filter GetFirst()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the first record of entity \"Filter\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.filters ORDER BY filter_id LIMIT 1;";
return Factory.Get<Frapid.Config.Entities.Filter>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Gets the previous record of the table "config.filters" sorted by filterId.
/// </summary>
/// <param name="filterId">The column "filter_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "Filter" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Config.Entities.Filter GetPrevious(long filterId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the previous entity of \"Filter\" by \"FilterId\" with value {FilterId} was denied to the user with Login ID {_LoginId}", filterId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.filters WHERE filter_id < @0 ORDER BY filter_id DESC LIMIT 1;";
return Factory.Get<Frapid.Config.Entities.Filter>(this._Catalog, sql, filterId).FirstOrDefault();
}
/// <summary>
/// Gets the next record of the table "config.filters" sorted by filterId.
/// </summary>
/// <param name="filterId">The column "filter_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "Filter" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Config.Entities.Filter GetNext(long filterId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the next entity of \"Filter\" by \"FilterId\" with value {FilterId} was denied to the user with Login ID {_LoginId}", filterId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.filters WHERE filter_id > @0 ORDER BY filter_id LIMIT 1;";
return Factory.Get<Frapid.Config.Entities.Filter>(this._Catalog, sql, filterId).FirstOrDefault();
}
/// <summary>
/// Gets the last record of the table "config.filters".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "Filter" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Config.Entities.Filter GetLast()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the last record of entity \"Filter\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.filters ORDER BY filter_id DESC LIMIT 1;";
return Factory.Get<Frapid.Config.Entities.Filter>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Executes a select query on the table "config.filters" with a where filter on the column "filter_id" to return a multiple instances of the "Filter" class.
/// </summary>
/// <param name="filterIds">Array of column "filter_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped collection of "Filter" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.Filter> Get(long[] filterIds)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to entity \"Filter\" was denied to the user with Login ID {LoginId}. filterIds: {filterIds}.", this._LoginId, filterIds);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.filters WHERE filter_id IN (@0);";
return Factory.Get<Frapid.Config.Entities.Filter>(this._Catalog, sql, filterIds);
}
/// <summary>
/// Custom fields are user defined form elements for config.filters.
/// </summary>
/// <returns>Returns an enumerable custom field collection for the table config.filters</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to get custom fields for entity \"Filter\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
string sql;
if (string.IsNullOrWhiteSpace(resourceId))
{
sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='config.filters' ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql);
}
sql = "SELECT * from config.get_custom_field_definition('config.filters'::text, @0::text) ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId);
}
/// <summary>
/// Displayfields provide a minimal name/value context for data binding the row collection of config.filters.
/// </summary>
/// <returns>Returns an enumerable name and value collection for the table config.filters</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>();
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return displayFields;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to get display field for entity \"Filter\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT filter_id AS key, filter_name as value FROM config.filters;";
using (NpgsqlCommand command = new NpgsqlCommand(sql))
{
using (DataTable table = DbOperation.GetDataTable(this._Catalog, command))
{
if (table?.Rows == null || table.Rows.Count == 0)
{
return displayFields;
}
foreach (DataRow row in table.Rows)
{
if (row != null)
{
DisplayField displayField = new DisplayField
{
Key = row["key"].ToString(),
Value = row["value"].ToString()
};
displayFields.Add(displayField);
}
}
}
}
return displayFields;
}
/// <summary>
/// Inserts or updates the instance of Filter class on the database table "config.filters".
/// </summary>
/// <param name="filter">The instance of "Filter" class to insert or update.</param>
/// <param name="customFields">The custom field collection.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public object AddOrEdit(dynamic filter, List<Frapid.DataAccess.Models.CustomField> customFields)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
filter.audit_user_id = this._UserId;
filter.audit_ts = System.DateTime.UtcNow;
object primaryKeyValue = filter.filter_id;
if (Cast.To<long>(primaryKeyValue) > 0)
{
this.Update(filter, Cast.To<long>(primaryKeyValue));
}
else
{
primaryKeyValue = this.Add(filter);
}
string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" +
"SELECT custom_field_setup_id " +
"FROM config.custom_field_setup " +
"WHERE form_name=config.get_custom_field_form_name('config.filters')" +
");";
Factory.NonQuery(this._Catalog, sql);
if (customFields == null)
{
return primaryKeyValue;
}
foreach (var field in customFields)
{
sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " +
"SELECT config.get_custom_field_setup_id_by_table_name('config.filters', @0::character varying(100)), " +
"@1, @2;";
Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value);
}
return primaryKeyValue;
}
/// <summary>
/// Inserts the instance of Filter class on the database table "config.filters".
/// </summary>
/// <param name="filter">The instance of "Filter" class to insert.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public object Add(dynamic filter)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to add entity \"Filter\" was denied to the user with Login ID {LoginId}. {Filter}", this._LoginId, filter);
throw new UnauthorizedException("Access is denied.");
}
}
return Factory.Insert(this._Catalog, filter, "config.filters", "filter_id");
}
/// <summary>
/// Inserts or updates multiple instances of Filter class on the database table "config.filters";
/// </summary>
/// <param name="filters">List of "Filter" class to import.</param>
/// <returns></returns>
public List<object> BulkImport(List<ExpandoObject> filters)
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to import entity \"Filter\" was denied to the user with Login ID {LoginId}. {filters}", this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
var result = new List<object>();
int line = 0;
try
{
using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName))
{
using (ITransaction transaction = db.GetTransaction())
{
foreach (dynamic filter in filters)
{
line++;
filter.audit_user_id = this._UserId;
filter.audit_ts = System.DateTime.UtcNow;
object primaryKeyValue = filter.filter_id;
if (Cast.To<long>(primaryKeyValue) > 0)
{
result.Add(filter.filter_id);
db.Update("config.filters", "filter_id", filter, filter.filter_id);
}
else
{
result.Add(db.Insert("config.filters", "filter_id", filter));
}
}
transaction.Complete();
}
return result;
}
}
catch (NpgsqlException ex)
{
string errorMessage = $"Error on line {line} ";
if (ex.Code.StartsWith("P"))
{
errorMessage += Factory.GetDbErrorResource(ex);
throw new DataAccessException(errorMessage, ex);
}
errorMessage += ex.Message;
throw new DataAccessException(errorMessage, ex);
}
catch (System.Exception ex)
{
string errorMessage = $"Error on line {line} ";
throw new DataAccessException(errorMessage, ex);
}
}
/// <summary>
/// Updates the row of the table "config.filters" with an instance of "Filter" class against the primary key value.
/// </summary>
/// <param name="filter">The instance of "Filter" class to update.</param>
/// <param name="filterId">The value of the column "filter_id" which will be updated.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Update(dynamic filter, long filterId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to edit entity \"Filter\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {Filter}", filterId, this._LoginId, filter);
throw new UnauthorizedException("Access is denied.");
}
}
Factory.Update(this._Catalog, filter, filterId, "config.filters", "filter_id");
}
/// <summary>
/// Deletes the row of the table "config.filters" against the primary key value.
/// </summary>
/// <param name="filterId">The value of the column "filter_id" which will be deleted.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Delete(long filterId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to delete entity \"Filter\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", filterId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "DELETE FROM config.filters WHERE filter_id=@0;";
Factory.NonQuery(this._Catalog, sql, filterId);
}
/// <summary>
/// Performs a select statement on table "config.filters" producing a paginated result of 10.
/// </summary>
/// <returns>Returns the first page of collection of "Filter" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.Filter> GetPaginatedResult()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the first page of the entity \"Filter\" was denied to the user with Login ID {LoginId}.", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.filters ORDER BY filter_id LIMIT 10 OFFSET 0;";
return Factory.Get<Frapid.Config.Entities.Filter>(this._Catalog, sql);
}
/// <summary>
/// Performs a select statement on table "config.filters" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result.</param>
/// <returns>Returns collection of "Filter" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.Filter> GetPaginatedResult(long pageNumber)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the entity \"Filter\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
const string sql = "SELECT * FROM config.filters ORDER BY filter_id LIMIT 10 OFFSET @0;";
return Factory.Get<Frapid.Config.Entities.Filter>(this._Catalog, sql, offset);
}
public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName)
{
const string sql = "SELECT * FROM config.filters WHERE object_name='config.filters' AND lower(filter_name)=lower(@0);";
return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList();
}
/// <summary>
/// Performs a filtered count on table "config.filters".
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns number of rows of "Filter" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"Filter\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.filters WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.Filter(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "config.filters" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns collection of "Filter" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.Filter> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"Filter\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM config.filters WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.Filter(), filters);
sql.OrderBy("filter_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Config.Entities.Filter>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered count on table "config.filters".
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns number of rows of "Filter" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountFiltered(string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"Filter\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.filters WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.Filter(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "config.filters" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns collection of "Filter" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.Filter> GetFiltered(long pageNumber, string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"Filter\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM config.filters WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.Filter(), filters);
sql.OrderBy("filter_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Config.Entities.Filter>(this._Catalog, sql);
}
/// <summary>
/// Deletes the row of the table "config.filters" against the supplied filter name.
/// </summary>
/// <param name="filterName">The value of the column "filter_name" which will be deleted.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Delete(string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to delete entity \"Filter\" with Filter Name {FilterName} was denied to the user with Login ID {LoginId}.", filterName, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "DELETE FROM config.filters WHERE filter_name=@0;";
Factory.NonQuery(this._Catalog, sql, filterName);
}
public void RecreateFilters(string objectName, string filterName, List<Frapid.Config.Entities.Filter> filters)
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to add entity \"Filter\" was denied to the user with Login ID {LoginId}. {filters}", this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName))
{
using (ITransaction transaction = db.GetTransaction())
{
var toDelete = this.GetWhere(1, new List<Frapid.DataAccess.Models.Filter>
{
new Frapid.DataAccess.Models.Filter { ColumnName = "object_name", FilterCondition = (int) FilterCondition.IsEqualTo, FilterValue = objectName },
new Frapid.DataAccess.Models.Filter { ColumnName = "filter_name", FilterCondition = (int) FilterCondition.IsEqualTo, FilterValue = filterName }
});
foreach (var filter in toDelete)
{
db.Delete(filter);
}
foreach (var filter in filters)
{
filter.AuditUserId = this._UserId;
filter.AuditTs = System.DateTime.UtcNow;
db.Insert(filter);
}
transaction.Complete();
}
}
}
public void MakeDefault(string objectName, string filterName)
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.CreateFilter, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to create default filter '{FilterName}' for {ObjectName} was denied to the user with Login ID {LoginId}.", filterName, objectName, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "UPDATE config.filters SET is_default=true WHERE object_name=@0 AND filter_name=@1;";
Factory.NonQuery(this._Catalog, sql, objectName, filterName);
}
public void RemoveDefault(string objectName)
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.DeleteFilter, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to remove default filter for {ObjectName} was denied to the user with Login ID {LoginId}.", objectName, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "UPDATE config.filters SET is_default=false WHERE object_name=@0;";
Factory.NonQuery(this._Catalog, sql, objectName);
}
}
}
| |
<?cs def:AutoEscape(v) ?>Inside macro which *should* be auto escaped
Argument: <?cs var:v ?>
Local var: <?cs var:Title ?>
End macro<?cs /def ?>
-- Parse successfully <....>
-- Test with relevant CS commands --
var: <?cs var:Title ?>
uvar: <?cs uvar:Title ?>
alt: <?cs alt:Title ?>Not me<?cs /alt ?>
<?cs set: myvar="<script>alert(1);</script>" ?>
Var created using 'set' command: <?cs var: myvar ?>
lvar: <?cs lvar: csvar ?>
evar: <?cs evar: csvar ?>
<?cs # Could not set this in .hdf, get parsing error ?>
<?cs set: "Names.<evilname>" = 1 ?>
<?cs each: x = Names ?>
name: <?cs name: x ?>
<?cs /each ?>
include:
<?cs include: "test_include.cs" ?>
<?cs set: includefile="test_include.cs" ?>
linclude:
<?cs linclude: includefile ?>
Call macro:<?cs call:AutoEscape(Title) ?>
-- Test with explicit escaping functions, which should take precedence --
<?cs escape: "js" ?>
Inside cs escape: "js" : <?cs var:Title ?>
<?cs /escape ?>
<?cs escape: "none" ?>
Inside cs escape: "none" : <?cs var:Title ?>
<?cs /escape ?>
<?cs def:test_explicit_escape() ?>
<script>
var x = "<?cs var: Title ?>"
var htmlX = <?cs escape:"html" ?>"<?cs var:Title ?>"<?cs /escape ?>
var noneX = <?cs escape:"none" ?>"<?cs var:Title ?>"<?cs /escape ?>
var xagain = "<?cs var: Title ?>"
</script>
<?cs /def ?>
<?cs call:test_explicit_escape() ?>
<script>
include inside escape html:
var htmlX = <?cs escape: "html" ?><?cs include: "test_include.cs" ?><?cs /escape ?>
var X = "<?cs var: Title ?>"
include inside escape none:
var noneX = <?cs escape: "none" ?><?cs include: "test_include.cs" ?><?cs /escape ?>
var xagain = "<?cs var: Title ?>"
</script>
--- Test all possible auto escaping cases ---
HTML body: <?cs var:Title ?>
HTML attr: <input type=text name="<?cs var:BlahJs ?>" >
Unquoted attr: <input value=<?cs var:BlahJs ?> >
Unquoted attr with spaces: <input value=<?cs var:SpaceAttr ?>>
Unquoted attr with ctrl chars: <input value=<?cs var:CtrlAttr ?>>
<?cs set: BadName = "ab!#cs" ?>
Bad HTML tag name: <<?cs var: BadName ?> value=x >
Bad HTML attr name: <input <?cs var: BadName ?> value=x >
<?cs set: GoodName = "ab-cs" ?>
Good HTML tag name: <<?cs var: GoodName ?> value=x >
Good HTML attr name: <input <?cs var: GoodName ?> value=x >
JS attr: <input name=x onclick="alert('<?cs var:BlahJs ?>')">
Unquoted JS inside quoted attr: <input name=x onclick="alert(<?cs var:BlahJs ?>)">
Quoted JS inside unquoted attr: <input name=x onclick=alert('<?cs var:BlahJs ?>')>
Unquoted JS inside unquoted attr: <input name=x onclick=alert(<?cs var:BlahJs ?>)>
Quoted JS with spaces in unquoted attr: <input onclick=alert('<?cs var:SpaceAttr ?>')>
Quoted JS with ctrl chars in unquoted attr: <input onclick=alert('<?cs var:CtrlAttr ?>')>
<?cs set: JsNumber=10 ?>
Valid unquoted JS attr: <input name=x onclick=alert(<?cs var:JsNumber ?>)>
Valid unquoted JS in quoted attr: <input name=x onclick="alert(<?cs var:JsNumber ?>)">
<?cs set: JsNumber2="true" ?>
Valid JS boolean literal: <input name=x onclick=alert(<?cs var:JsNumber2 ?>)>
<?cs set: JsNumber3="0x45" ?>
Valid JS numeric literal: <input name=x onclick=alert(<?cs var:JsNumber3 ?>)>
<?cs set: JsNumber4="45.2345" ?>
Valid JS numeric literal: <input name=x onclick=alert(<?cs var:JsNumber4 ?>)>
<?cs set: JsNumber5="trueer" ?>
Invalid JS boolean literal: <input name=x onclick=alert(<?cs var:JsNumber5 ?>)>
<?cs set: JsNumber6="12.er" ?>
Invalid JS numeric literal: <input name=x onclick=alert(<?cs var:JsNumber6 ?>)>
URI attr: <a href="http://a.com?q=<?cs var:Title ?>">link </a>
Unquoted URI attr: <a href=http://a.com?q=<?cs var:BlahJs ?>>link </a>
<?cs set: GoodUrl="http://www.google.com" ?>
GoodUrl in URI attr: <a href="<?cs var:GoodUrl ?>">link </a>
<?cs set: GoodUrlCaps="HTTP://WWW.GOOGLE.COM" ?>
GoodUrlCaps in URI attr: <a href="<?cs var:GoodUrlCaps ?>">link </a>
GoodUrl in unquoted URI attr: <a href=<?cs var:GoodUrl ?>>link </a>
<?cs set: RelativeUrl="logo.gif" ?>
RelativeUrl in URI attr: <a href="<?cs var:RelativeUrl ?>">link </a>
<?cs set: AbsUrl="/logo.gif" ?>
AbsUrl in URI attr: <a href="<?cs var:AbsUrl ?>">link </a>
<?cs set: AbsUrl2="www.google.com" ?>
AbsUrl2 in URI attr: <a href="<?cs var:AbsUrl2 ?>">link </a>
<?cs set: BadUrl="javascript:alert(1)" ?>
BadUrl in URI attr: <a href="<?cs var:BadUrl ?>">link </a>
BadUrl in unquoted URI attr: <a href=<?cs var:BadUrl ?>>link </a>
<?cs # TODO(mugdha): This test fails currently, the parser never sees
# the close tag.
-- Test passing variables to htmlparser --
set: TagName = "script"
Tag name:
<uvar: TagName>var q="var:BlahJs"</uvar: TagName>
?>
Unquoted attr value as uvar:
<a href=<?cs uvar: GoodUrl ?> onclick="alert('<?cs var: BlahJs ?>')">
Unquoted attr value as var:
<a href=<?cs var:BadUrl ?> onclick="alert('<?cs var: BlahJs ?>')">
Unquoted attr value as var that is not modified:
<a href=<?cs var:GoodUrl ?> onclick="alert('<?cs var: BlahJs ?>')">
Quoted attr value as uvar:
<a href="<?cs uvar: GoodUrl ?>" onclick="alert('<?cs var: BlahJs ?>')">
Quoted attr value as var:
<a href="<?cs var:BadUrl ?>" onclick="alert('<?cs var: BlahJs ?>')">
Unquoted attr value pair:
<?cs set: Attr = "name=button" ?>
<input <?cs uvar:Attr ?> onclick="alert('<?cs var: BlahJs ?>')">
attr name as var:<?cs set: AttrName = "href" ?>
<a <?cs var: AttrName ?>="<?cs var: BadUrl ?>" onclick="alert('<?cs var: BlahJs ?>')">
Unquoted attr value as lvar:
<a href=<?cs lvar:GoodUrl ?> onclick="alert('<?cs var: BlahJs ?>')">
name:
<a href=<?cs name:GoodUrl ?> onclick="alert('<?cs var: BlahJs ?>')">
Number as var:
<a name=<?cs var:Numbers.hdf9 ?> onclick="alert('<?cs var: BlahJs ?>')">
Number as lvar:
<a name=<?cs lvar:Numbers.hdf9 ?> onclick="alert('<?cs var: BlahJs ?>')">
A kludgy way to validate that variable outside tag is not parsed:
<?cs set: ScriptTag = "<script>" ?>
<?cs uvar: ScriptTag ?>
var q="<?cs var:BlahJs ?>"
<?cs set: EndScriptTag = "</script>" ?>
<?cs uvar: EndScriptTag ?>
-- Test Style --
<?cs set: StyleVar="2px \x123 <>()' solid #ddd;" ?>
In style attr "<?cs uvar:StyleVar ?>": <input name=x style="border: <?cs var:StyleVar ?>">
In unquoted style attr: <input name=x style=border:<?cs var:StyleVar ?>>
<?cs set: GoodStyleVar=" 95%" ?>
Valid style attr "<?cs uvar:GoodStyleVar ?>": <input name=x style="font-size:<?cs var:GoodStyleVar ?>">
Valid unquoted style attr: <input name=x style=font-size:<?cs var:GoodStyleVar ?>>
<?cs set: BadJs='" alert(1);' ?>
Inside javascript:
<script>
var unquoted = <?cs var:BadJs ?>
<?cs set: ScriptNumber = 10 ?>
var unquoted_num = <?cs var:ScriptNumber ?>
<?cs set: ScriptBool = "false" ?>
var unquoted_bool = <?cs var:ScriptBool ?>
<?cs set: BadNumber = "0x45ye" ?>
var bad_number = <?cs var:BadNumber ?>
var quoted = "<?cs var: BadJs ?>"
</script>
Inside style tag:
<style>
<?cs set: color=' #110022' ?>
div.paddedRadioOption {
/* Valid style property: "<?cs uvar: color ?>" */ color: <?cs var: color ?>;
}
<?cs set: badbody="body {background-image: url(javascript:alert(1));}" ?>
/* Invalid style body: "<?cs uvar: badbody ?>" */ <?cs var:badbody ?>
/* Non ascii: "<?cs uvar: NonAscii ?>" */ font-family: <?cs var: NonAscii ?>
</style>
-- End of tests --
| |
// AllOlympics.cs (c) 2004 Kari Laitinen
// http://www.naturalprogramming.com
// 2004-11-14 File created.
// 2004-11-14 Last modification.
// A solution to Exercise 11-17.
using System ;
class Olympics
{
char olympics_type ;
int olympic_year ;
string olympic_city ;
string olympic_country ;
public Olympics( char given_olympics_type,
int given_olympic_year,
string given_olympic_city,
string given_olympic_country )
{
olympics_type = given_olympics_type ;
olympic_year = given_olympic_year ;
olympic_city = given_olympic_city ;
olympic_country = given_olympic_country ;
}
public int get_year()
{
return olympic_year ;
}
public string get_olympic_city()
{
return olympic_city ;
}
public string get_olympic_country()
{
return olympic_country ;
}
public bool these_are_summer_games()
{
return ( olympics_type == 's' ) ;
}
public bool these_are_winter_games()
{
return ( olympics_type == 'w' ) ;
}
public void print_olympics_data()
{
string olympics_type_to_print ;
if ( olympics_type == 's' )
{
olympics_type_to_print = "Summer" ;
}
else
{
olympics_type_to_print = "Winter" ;
}
Console.Write( "\n In " + olympic_year + ", "
+ olympics_type_to_print
+ " Olympic Games were held in " + olympic_city
+ ", " + olympic_country ) ;
}
}
class OlympicsDataFinder
{
static Olympics[] olympics_table = new Olympics[ 200 ] ;
static void search_olympics_of_certain_year()
{
Console.Write("\n Give a year by using four digits: " ) ;
int given_year = Convert.ToInt32( Console.ReadLine() ) ;
int olympics_index = 0 ;
bool olympics_data_was_found = false ;
bool table_search_ready = false ;
while ( table_search_ready == false )
{
if ( olympics_table[ olympics_index ] == null )
{
table_search_ready = true ;
}
else if ( olympics_table[ olympics_index ].get_year()
== given_year )
{
olympics_table[ olympics_index ].print_olympics_data() ;
olympics_data_was_found = true ;
}
olympics_index ++ ;
}
if ( olympics_data_was_found == false )
{
Console.Write( "\n Sorry, no Olympic Games were held in "
+ given_year + ".\n" ) ;
}
}
static void search_olympics_held_in_a_certain_country()
{
Console.Write("\n Give the name of a country: " ) ;
string given_country = Console.ReadLine() ;
Console.Write( "\n Olympic Games held in \"" + given_country
+ "\" are the following: \n" ) ;
int olympics_index = 0 ;
bool olympics_data_was_found = false ;
bool table_search_ready = false ;
while ( table_search_ready == false )
{
if ( olympics_table[ olympics_index ] == null )
{
table_search_ready = true ;
}
else if (( olympics_table[ olympics_index ].get_olympic_country()
.ToLower().IndexOf( given_country.ToLower() ) != -1 ) )
{
olympics_table[ olympics_index ].print_olympics_data() ;
olympics_data_was_found = true ;
}
olympics_index ++ ;
}
if ( olympics_data_was_found == false )
{
Console.Write( "\n Sorry, no Olympic Games were held in "
+ "a country named \"" + given_country + "\".\n" ) ;
}
}
static void search_olympics_held_in_a_certain_city()
{
Console.Write("\n Give the name of a city: " ) ;
string given_city = Console.ReadLine() ;
Console.Write( "\n Olympic Games held in \"" + given_city
+ "\" are the following: \n" ) ;
int olympics_index = 0 ;
bool olympics_data_was_found = false ;
bool table_search_ready = false ;
while ( table_search_ready == false )
{
if ( olympics_table[ olympics_index ] == null )
{
table_search_ready = true ;
}
else if (( olympics_table[ olympics_index ].get_olympic_city()
.ToLower().IndexOf( given_city.ToLower() ) != -1 ) )
{
olympics_table[ olympics_index ].print_olympics_data() ;
olympics_data_was_found = true ;
}
olympics_index ++ ;
}
if ( olympics_data_was_found == false )
{
Console.Write( "\n Sorry, no Olympic Games were held in "
+ "a city named \"" + given_city + "\".\n" ) ;
}
}
static void list_all_summer_games()
{
Console.Write( "\n The Olympic Summer Games are the following: \n" ) ;
int olympics_index = 0 ;
while ( olympics_table[ olympics_index ] != null )
{
if ( olympics_table[ olympics_index ].these_are_summer_games() )
{
olympics_table[ olympics_index ].print_olympics_data() ;
}
olympics_index ++ ;
}
}
static void list_all_winter_games()
{
Console.Write( "\n The Olympic Winter Games are the following: \n" ) ;
int olympics_index = 0 ;
while ( olympics_table[ olympics_index ] != null )
{
if ( olympics_table[ olympics_index ].these_are_winter_games() )
{
olympics_table[ olympics_index ].print_olympics_data() ;
}
olympics_index ++ ;
}
}
static void Main()
{
olympics_table[ 0 ] = new Olympics( 's', 1896, "Athens", "Greece" ) ;
olympics_table[ 1 ] = new Olympics( 's', 1900, "Paris", "France" ) ;
olympics_table[ 2 ] = new Olympics( 's', 1904, "St. Louis", "U.S.A." );
olympics_table[ 3 ] = new Olympics( 's', 1906, "Athens", "Greece" ) ;
olympics_table[ 4 ] = new Olympics( 's', 1908, "London", "Great Britain");
olympics_table[ 5 ] = new Olympics( 's', 1912, "Stockholm","Sweden" ) ;
olympics_table[ 6 ] = new Olympics( 's', 1920, "Antwerp", "Belgium" ) ;
olympics_table[ 7 ] = new Olympics( 's', 1924, "Paris", "France" ) ;
olympics_table[ 8 ] = new Olympics( 's', 1928, "Amsterdam","Netherlands");
olympics_table[ 9 ] = new Olympics( 's', 1932, "Los Angeles", "U.S.A.");
olympics_table[ 10 ] = new Olympics( 's', 1936, "Berlin", "Germany" ) ;
olympics_table[ 11 ] = new Olympics( 's', 1948, "London","Great Britain");
olympics_table[ 12 ] = new Olympics( 's', 1952, "Helsinki","Finland" ) ;
olympics_table[ 13 ] = new Olympics( 's', 1956, "Melbourne","Australia" ) ;
olympics_table[ 14 ] = new Olympics( 's', 1960, "Rome", "Italy" ) ;
olympics_table[ 15 ] = new Olympics( 's', 1964, "Tokyo", "Japan" ) ;
olympics_table[ 16 ] = new Olympics( 's', 1968, "Mexico City","Mexico" ) ;
olympics_table[ 17 ] = new Olympics( 's', 1972, "Munich", "West Germany");
olympics_table[ 18 ] = new Olympics( 's', 1976, "Montreal", "Canada" ) ;
olympics_table[ 19 ] = new Olympics( 's', 1980, "Moscow", "Soviet Union");
olympics_table[ 20 ] = new Olympics( 's', 1984, "Los Angeles","U.S.A.");
olympics_table[ 21 ] = new Olympics( 's', 1988, "Seoul", "South Korea");
olympics_table[ 22 ] = new Olympics( 's', 1992, "Barcelona","Spain" ) ;
olympics_table[ 23 ] = new Olympics( 's', 1996, "Atlanta", "U.S.A." );
olympics_table[ 24 ] = new Olympics( 's', 2000, "Sydney", "Australia" ) ;
olympics_table[ 25 ] = new Olympics( 's', 2004, "Athens", "Greece" ) ;
olympics_table[ 26 ] = new Olympics( 's', 2008, "Beijing", "China" ) ;
// New summer Olympics data should be added to the end of the table.
olympics_table[ 27 ] = new Olympics( 'w', 1924, "Chamonix", "France") ;
olympics_table[ 28 ] = new Olympics( 'w', 1928, "St.Moritz",
"Switzerland");
olympics_table[ 29 ] = new Olympics( 'w', 1932, "Lake Placid", "U.S.A.");
olympics_table[ 30 ] = new Olympics( 'w', 1936, "Garmisch-Partenkirchen",
"Germany" ) ;
olympics_table[ 31 ] = new Olympics( 'w', 1948, "St.Moritz",
"Switzerland");
olympics_table[ 32 ] = new Olympics( 'w', 1952, "Oslo", "Norway" ) ;
olympics_table[ 33 ] = new Olympics( 'w',1956, "Cortina d'Ampezzo",
"Italy" );
olympics_table[ 34 ] = new Olympics( 'w', 1960, "Squaw Valley","U.S.A." );
olympics_table[ 35 ] = new Olympics( 'w', 1964, "Innsbruck", "Austria" ) ;
olympics_table[ 36 ] = new Olympics( 'w', 1968, "Grenoble", "France" );
olympics_table[ 37 ] = new Olympics( 'w', 1972, "Sapporo", "Japan");
olympics_table[ 38 ] = new Olympics( 'w', 1976, "Innsbruck","Austria" ) ;
olympics_table[ 39 ] = new Olympics( 'w', 1980, "Lake Placid","U.S.A.");
olympics_table[ 40 ] = new Olympics( 'w', 1984, "Sarajevo", "Yugoslavia");
olympics_table[ 41 ] = new Olympics( 'w', 1988, "Calgary", "Canada");
olympics_table[ 42 ] = new Olympics( 'w', 1992, "Albertville","France" );
olympics_table[ 43 ] = new Olympics( 'w', 1994, "Lillehammer","Norway" );
olympics_table[ 44 ] = new Olympics( 'w', 1998, "Nagano", "Japan" ) ;
olympics_table[ 45 ] = new Olympics( 'w', 2002, "Salt Lake City",
"U.S.A." ) ;
olympics_table[ 46 ] = new Olympics( 'w', 2006, "Turin", "Italy" ) ;
olympics_table[ 47 ] = new Olympics( 'w', 2010, "Vancouver","Canada" ) ;
// The "end" of olympics data in olympics_table is here detected
// in the same way as in program Planets.cs, i.e., an array element
// contains a null when it does not reference an object.
Console.Write("\n This program can tell where the Winter Olympic "
+ "\n Games were held in a given year. Give a year"
+ "\n by using four digits: " ) ;
string user_selection = "????" ;
while ( user_selection[ 0 ] != '6' )
{
Console.Write( "\n\n Select according to the following menu: \n"
+ "\n 1 Search Olympics of certain year "
+ "\n 2 Search Olympics held in a certain country "
+ "\n 3 Search Olympics held in a certain city "
+ "\n 4 List all Summer Games "
+ "\n 5 List all Winter Games "
+ "\n 6 Exit the program \n\n " ) ;
user_selection = Console.ReadLine() ;
if ( user_selection[ 0 ] == '1' )
{
search_olympics_of_certain_year() ;
}
else if ( user_selection[ 0 ] == '2' )
{
search_olympics_held_in_a_certain_country() ;
}
else if ( user_selection[ 0 ] == '3' )
{
search_olympics_held_in_a_certain_city() ;
}
else if ( user_selection[ 0 ] == '4' )
{
list_all_summer_games() ;
}
else if ( user_selection[ 0 ] == '5' )
{
list_all_winter_games() ;
}
}
}
}
| |
// 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.Reflection;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.Versioning;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace System.Runtime.Loader
{
public abstract class AssemblyLoadContext
{
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool CanUseAppPathAssemblyLoadContextInCurrentDomain();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, int iAssemblyArrayLen, IntPtr ptrSymbols, int iSymbolArrayLen, ObjectHandleOnStack retAssembly);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalSetProfileRoot(string directoryPath);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext);
protected AssemblyLoadContext()
{
// Initialize the ALC representing non-TPA LoadContext
InitializeLoadContext(false);
}
internal AssemblyLoadContext(bool fRepresentsTPALoadContext)
{
// Initialize the ALC representing TPA LoadContext
InitializeLoadContext(fRepresentsTPALoadContext);
}
private void InitializeLoadContext(bool fRepresentsTPALoadContext)
{
// Initialize the VM side of AssemblyLoadContext if not already done.
GCHandle gchALC = GCHandle.Alloc(this);
IntPtr ptrALC = GCHandle.ToIntPtr(gchALC);
m_pNativeAssemblyLoadContext = InitializeAssemblyLoadContext(ptrALC, fRepresentsTPALoadContext);
// Initialize event handlers to be null by default
Resolving = null;
Unloading = null;
// Since unloading an AssemblyLoadContext is not yet implemented, this is a temporary solution to raise the
// Unloading event on process exit. Register for the current AppDomain's ProcessExit event, and the handler will in
// turn raise the Unloading event.
AppContext.Unloading += OnAppContextUnloading;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly);
public static Assembly[] GetLoadedAssemblies()
{
return AppDomain.CurrentDomain.GetAssemblies(false);
}
// These are helpers that can be used by AssemblyLoadContext derivations.
// They are used to load assemblies in DefaultContext.
public Assembly LoadFromAssemblyPath(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException(nameof(assemblyPath));
}
if (PathInternal.IsPartiallyQualified(assemblyPath))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(assemblyPath));
}
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, null, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
public Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath)
{
if (nativeImagePath == null)
{
throw new ArgumentNullException(nameof(nativeImagePath));
}
if (PathInternal.IsPartiallyQualified(nativeImagePath))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(nativeImagePath));
}
if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(assemblyPath));
}
// Basic validation has succeeded - lets try to load the NI image.
// Ask LoadFile to load the specified assembly in the DefaultContext
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, nativeImagePath, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
public Assembly LoadFromStream(Stream assembly)
{
return LoadFromStream(assembly, null);
}
public Assembly LoadFromStream(Stream assembly, Stream assemblySymbols)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (assembly.Length <= 0)
{
throw new BadImageFormatException(SR.BadImageFormat_BadILFormat);
}
int iAssemblyStreamLength = (int)assembly.Length;
int iSymbolLength = 0;
// Allocate the byte[] to hold the assembly
byte[] arrAssembly = new byte[iAssemblyStreamLength];
// Copy the assembly to the byte array
assembly.Read(arrAssembly, 0, iAssemblyStreamLength);
// Get the symbol stream in byte[] if provided
byte[] arrSymbols = null;
if (assemblySymbols != null)
{
iSymbolLength = (int)assemblySymbols.Length;
arrSymbols = new byte[iSymbolLength];
assemblySymbols.Read(arrSymbols, 0, iSymbolLength);
}
RuntimeAssembly loadedAssembly = null;
unsafe
{
fixed (byte* ptrAssembly = arrAssembly, ptrSymbols = arrSymbols)
{
LoadFromStream(m_pNativeAssemblyLoadContext, new IntPtr(ptrAssembly), iAssemblyStreamLength, new IntPtr(ptrSymbols), iSymbolLength, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
}
}
return loadedAssembly;
}
// Custom AssemblyLoadContext implementations can override this
// method to perform custom processing and use one of the protected
// helpers above to load the assembly.
protected abstract Assembly Load(AssemblyName assemblyName);
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static Assembly Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
return context.ResolveUsingLoad(assemblyName);
}
// This method is invoked by the VM to resolve an assembly reference using the Resolving event
// after trying assembly resolution via Load override and TPA load context without success.
private static Assembly ResolveUsingResolvingEvent(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
// Invoke the AssemblyResolve event callbacks if wired up
return context.ResolveUsingEvent(assemblyName);
}
private Assembly GetFirstResolvedAssembly(AssemblyName assemblyName)
{
Assembly resolvedAssembly = null;
Func<AssemblyLoadContext, AssemblyName, Assembly> assemblyResolveHandler = Resolving;
if (assemblyResolveHandler != null)
{
// Loop through the event subscribers and return the first non-null Assembly instance
Delegate[] arrSubscribers = assemblyResolveHandler.GetInvocationList();
for (int i = 0; i < arrSubscribers.Length; i++)
{
resolvedAssembly = ((Func<AssemblyLoadContext, AssemblyName, Assembly>)arrSubscribers[i])(this, assemblyName);
if (resolvedAssembly != null)
{
break;
}
}
}
return resolvedAssembly;
}
private Assembly ValidateAssemblyNameWithSimpleName(Assembly assembly, string requestedSimpleName)
{
// Get the name of the loaded assembly
string loadedSimpleName = null;
// Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly
// which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder),
// we need to check for RuntimeAssembly.
RuntimeAssembly rtLoadedAssembly = assembly as RuntimeAssembly;
if (rtLoadedAssembly != null)
{
loadedSimpleName = rtLoadedAssembly.GetSimpleName();
}
// The simple names should match at the very least
if (String.IsNullOrEmpty(loadedSimpleName) || (!requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase)))
throw new InvalidOperationException(SR.Argument_CustomAssemblyLoadContextRequestedNameMismatch);
return assembly;
}
private Assembly ResolveUsingLoad(AssemblyName assemblyName)
{
string simpleName = assemblyName.Name;
Assembly assembly = Load(assemblyName);
if (assembly != null)
{
assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName);
}
return assembly;
}
private Assembly ResolveUsingEvent(AssemblyName assemblyName)
{
string simpleName = assemblyName.Name;
// Invoke the AssemblyResolve event callbacks if wired up
Assembly assembly = GetFirstResolvedAssembly(assemblyName);
if (assembly != null)
{
assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName);
}
// Since attempt to resolve the assembly via Resolving event is the last option,
// throw an exception if we do not find any assembly.
if (assembly == null)
{
throw new FileNotFoundException(SR.IO_FileLoad, simpleName);
}
return assembly;
}
public Assembly LoadFromAssemblyName(AssemblyName assemblyName)
{
// Attempt to load the assembly, using the same ordering as static load, in the current load context.
Assembly loadedAssembly = Assembly.Load(assemblyName, m_pNativeAssemblyLoadContext);
return loadedAssembly;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr InternalLoadUnmanagedDllFromPath(string unmanagedDllPath);
// This method provides a way for overriders of LoadUnmanagedDll() to load an unmanaged DLL from a specific path in a
// platform-independent way. The DLL is loaded with default load flags.
protected IntPtr LoadUnmanagedDllFromPath(string unmanagedDllPath)
{
if (unmanagedDllPath == null)
{
throw new ArgumentNullException(nameof(unmanagedDllPath));
}
if (unmanagedDllPath.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(unmanagedDllPath));
}
if (PathInternal.IsPartiallyQualified(unmanagedDllPath))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(unmanagedDllPath));
}
return InternalLoadUnmanagedDllFromPath(unmanagedDllPath);
}
// Custom AssemblyLoadContext implementations can override this
// method to perform the load of unmanaged native dll
// This function needs to return the HMODULE of the dll it loads
protected virtual IntPtr LoadUnmanagedDll(String unmanagedDllName)
{
//defer to default coreclr policy of loading unmanaged dll
return IntPtr.Zero;
}
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static IntPtr ResolveUnmanagedDll(String unmanagedDllName, IntPtr gchManagedAssemblyLoadContext)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
return context.LoadUnmanagedDll(unmanagedDllName);
}
public static AssemblyLoadContext Default
{
get
{
if (s_DefaultAssemblyLoadContext == null)
{
// Try to initialize the default assembly load context with apppath one if we are allowed to
if (AssemblyLoadContext.CanUseAppPathAssemblyLoadContextInCurrentDomain())
{
// Synchronize access to initializing Default ALC
lock (s_initLock)
{
if (s_DefaultAssemblyLoadContext == null)
{
s_DefaultAssemblyLoadContext = new AppPathAssemblyLoadContext();
}
}
}
}
return s_DefaultAssemblyLoadContext;
}
}
// Helper to return AssemblyName corresponding to the path of an IL assembly
public static AssemblyName GetAssemblyName(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException(nameof(assemblyPath));
}
return AssemblyName.GetAssemblyName(assemblyPath);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr GetLoadContextForAssembly(RuntimeAssembly assembly);
// Returns the load context in which the specified assembly has been loaded
public static AssemblyLoadContext GetLoadContext(Assembly assembly)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
AssemblyLoadContext loadContextForAssembly = null;
RuntimeAssembly rtAsm = assembly as RuntimeAssembly;
// We only support looking up load context for runtime assemblies.
if (rtAsm != null)
{
IntPtr ptrAssemblyLoadContext = GetLoadContextForAssembly(rtAsm);
if (ptrAssemblyLoadContext == IntPtr.Zero)
{
// If the load context is returned null, then the assembly was bound using the TPA binder
// and we shall return reference to the active "Default" binder - which could be the TPA binder
// or an overridden CLRPrivBinderAssemblyLoadContext instance.
loadContextForAssembly = AssemblyLoadContext.Default;
}
else
{
loadContextForAssembly = (AssemblyLoadContext)(GCHandle.FromIntPtr(ptrAssemblyLoadContext).Target);
}
}
return loadContextForAssembly;
}
// Set the root directory path for profile optimization.
public void SetProfileOptimizationRoot(string directoryPath)
{
InternalSetProfileRoot(directoryPath);
}
// Start profile optimization for the specified profile name.
public void StartProfileOptimization(string profile)
{
InternalStartProfile(profile, m_pNativeAssemblyLoadContext);
}
private void OnAppContextUnloading(object sender, EventArgs e)
{
var unloading = Unloading;
if (unloading != null)
{
unloading(this);
}
}
public event Func<AssemblyLoadContext, AssemblyName, Assembly> Resolving;
public event Action<AssemblyLoadContext> Unloading;
// Contains the reference to VM's representation of the AssemblyLoadContext
private IntPtr m_pNativeAssemblyLoadContext;
// Each AppDomain contains the reference to its AssemblyLoadContext instance, if one is
// specified by the host. By having the field as a static, we are
// making it an AppDomain-wide field.
private static volatile AssemblyLoadContext s_DefaultAssemblyLoadContext;
// Synchronization primitive for controlling initialization of Default load context
private static readonly object s_initLock = new Object();
// Occurs when an Assembly is loaded
public static event AssemblyLoadEventHandler AssemblyLoad
{
add { AppDomain.CurrentDomain.AssemblyLoad += value; }
remove { AppDomain.CurrentDomain.AssemblyLoad -= value; }
}
// Occurs when resolution of type fails
public static event ResolveEventHandler TypeResolve
{
add { AppDomain.CurrentDomain.TypeResolve += value; }
remove { AppDomain.CurrentDomain.TypeResolve -= value; }
}
// Occurs when resolution of resource fails
public static event ResolveEventHandler ResourceResolve
{
add { AppDomain.CurrentDomain.ResourceResolve += value; }
remove { AppDomain.CurrentDomain.ResourceResolve -= value; }
}
// Occurs when resolution of assembly fails
// This event is fired after resolve events of AssemblyLoadContext fails
public static event ResolveEventHandler AssemblyResolve
{
add { AppDomain.CurrentDomain.AssemblyResolve += value; }
remove { AppDomain.CurrentDomain.AssemblyResolve -= value; }
}
}
internal class AppPathAssemblyLoadContext : AssemblyLoadContext
{
internal AppPathAssemblyLoadContext() : base(true)
{
}
protected override Assembly Load(AssemblyName assemblyName)
{
// We were loading an assembly into TPA ALC that was not found on TPA list. As a result we are here.
// Returning null will result in the AssemblyResolve event subscribers to be invoked to help resolve the assembly.
return null;
}
}
internal class IndividualAssemblyLoadContext : AssemblyLoadContext
{
internal IndividualAssemblyLoadContext() : base(false)
{
}
protected override Assembly Load(AssemblyName assemblyName)
{
return null;
}
}
}
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.ui.core.scroll
{
/// <summary>
/// <para>This class represents a scroll able pane. This means that this widget
/// may contain content which is bigger than the available (inner)
/// dimensions of this widget. The widget also offer methods to control
/// the scrolling position. It can only have exactly one child.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.core.scroll.ScrollPane", OmitOptionalParameters = true, Export = false)]
public partial class ScrollPane : qx.ui.core.Widget
{
#region Events
/// <summary>
/// <para>Fired on scroll animation end invoked by ‘scroll*’ methods.</para>
/// </summary>
public event Action<qx.eventx.type.Event> OnScrollAnimationEnd;
/// <summary>
/// Fired on change of the property <see cref="ScrollX"/>.
/// </summary>
public event Action<qx.eventx.type.Data> OnScrollX;
/// <summary>
/// Fired on change of the property <see cref="ScrollY"/>.
/// </summary>
public event Action<qx.eventx.type.Data> OnScrollY;
/// <summary>
/// <para>Fired on resize of both the container or the content.</para>
/// </summary>
public event Action<qx.eventx.type.Event> OnUpdate;
#endregion Events
#region Properties
/// <summary>
/// <para>The horizontal scroll position</para>
/// </summary>
[JsProperty(Name = "scrollX", NativeField = true)]
public object ScrollX { get; set; }
/// <summary>
/// <para>The vertical scroll position</para>
/// </summary>
[JsProperty(Name = "scrollY", NativeField = true)]
public object ScrollY { get; set; }
#endregion Properties
#region Methods
public ScrollPane() { throw new NotImplementedException(); }
/// <summary>
/// <para>Configures the content of the scroll pane. Replaces any existing child
/// with the newly given one.</para>
/// </summary>
/// <param name="widget">The content widget of the pane</param>
[JsMethod(Name = "add")]
public void Add(qx.ui.core.Widget widget = null) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns an array containing the current content.</para>
/// </summary>
/// <returns>The content array</returns>
[JsMethod(Name = "getChildren")]
public object GetChildren() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the top offset of the end of the given item in relation to the
/// inner height of this widget.</para>
/// </summary>
/// <param name="item">Item to query</param>
/// <returns>Top offset</returns>
[JsMethod(Name = "getItemBottom")]
public double GetItemBottom(qx.ui.core.Widget item) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the left offset of the given item in relation to the
/// inner width of this widget.</para>
/// </summary>
/// <param name="item">Item to query</param>
/// <returns>Top offset</returns>
[JsMethod(Name = "getItemLeft")]
public double GetItemLeft(qx.ui.core.Widget item) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the left offset of the end of the given item in relation to the
/// inner width of this widget.</para>
/// </summary>
/// <param name="item">Item to query</param>
/// <returns>Right offset</returns>
[JsMethod(Name = "getItemRight")]
public double GetItemRight(qx.ui.core.Widget item) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the top offset of the given item in relation to the
/// inner height of this widget.</para>
/// </summary>
/// <param name="item">Item to query</param>
/// <returns>Top offset</returns>
[JsMethod(Name = "getItemTop")]
public double GetItemTop(qx.ui.core.Widget item) { throw new NotImplementedException(); }
/// <summary>
/// <para>The maximum horizontal scroll position.</para>
/// </summary>
/// <returns>Maximum horizontal scroll position.</returns>
[JsMethod(Name = "getScrollMaxX")]
public double GetScrollMaxX() { throw new NotImplementedException(); }
/// <summary>
/// <para>The maximum vertical scroll position.</para>
/// </summary>
/// <returns>Maximum vertical scroll position.</returns>
[JsMethod(Name = "getScrollMaxY")]
public double GetScrollMaxY() { throw new NotImplementedException(); }
/// <summary>
/// <para>The size (identical with the preferred size) of the content.</para>
/// </summary>
/// <returns>Size of the content (keys: width and height)</returns>
[JsMethod(Name = "getScrollSize")]
public object GetScrollSize() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property scrollX.</para>
/// </summary>
[JsMethod(Name = "getScrollX")]
public object GetScrollX() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property scrollY.</para>
/// </summary>
[JsMethod(Name = "getScrollY")]
public object GetScrollY() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property scrollX
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property scrollX.</param>
[JsMethod(Name = "initScrollX")]
public void InitScrollX(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property scrollY
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property scrollY.</param>
[JsMethod(Name = "initScrollY")]
public void InitScrollY(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Removes the given widget from the content. The pane is empty
/// afterwards as only one child is supported by the pane.</para>
/// </summary>
/// <param name="widget">The content widget of the pane</param>
[JsMethod(Name = "remove")]
public void Remove(qx.ui.core.Widget widget = null) { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property scrollX.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetScrollX")]
public void ResetScrollX() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property scrollY.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetScrollY")]
public void ResetScrollY() { throw new NotImplementedException(); }
/// <summary>
/// <para>Scrolls the element’s content horizontally by the given amount.</para>
/// </summary>
/// <param name="x">Amount to scroll</param>
/// <param name="duration">The time in milliseconds the scroll to should take.</param>
[JsMethod(Name = "scrollByX")]
public void ScrollByX(double x = 0, double? duration = null) { throw new NotImplementedException(); }
/// <summary>
/// <para>Scrolls the element’s content vertically by the given amount.</para>
/// </summary>
/// <param name="y">Amount to scroll</param>
/// <param name="duration">The time in milliseconds the scroll to should take.</param>
[JsMethod(Name = "scrollByY")]
public void ScrollByY(double y = 0, double? duration = null) { throw new NotImplementedException(); }
/// <summary>
/// <para>Scrolls the element’s content to the given left coordinate</para>
/// </summary>
/// <param name="value">The vertical position to scroll to.</param>
/// <param name="duration">The time in milliseconds the scroll to should take.</param>
[JsMethod(Name = "scrollToX")]
public void ScrollToX(double value, double duration) { throw new NotImplementedException(); }
/// <summary>
/// <para>Scrolls the element’s content to the given top coordinate</para>
/// </summary>
/// <param name="value">The horizontal position to scroll to.</param>
/// <param name="duration">The time in milliseconds the scroll to should take.</param>
[JsMethod(Name = "scrollToY")]
public void ScrollToY(double value, double duration) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property scrollX.</para>
/// </summary>
/// <param name="value">New value for property scrollX.</param>
[JsMethod(Name = "setScrollX")]
public void SetScrollX(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property scrollY.</para>
/// </summary>
/// <param name="value">New value for property scrollY.</param>
[JsMethod(Name = "setScrollY")]
public void SetScrollY(object value) { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.UnitTests;
using Xunit;
namespace Microsoft.ApiDesignGuidelines.Analyzers.UnitTests
{
public class DoNotRaiseExceptionsInUnexpectedLocationsTests : DiagnosticAnalyzerTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer();
}
#region Property and Event Tests
[Fact]
public void CSharpPropertyNoDiagnostics()
{
var code = @"
using System;
public class C
{
public int PropWithNoException { get { return 10; } set { } }
public int PropWithSetterException { get { return 10; } set { throw new NotSupportedException(); } }
public int PropWithAllowedException { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
public int this[int x] { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
}
class NonPublic
{
public int PropWithException { get { throw new Exception(); } set { throw new NotSupportedException(); } }
}
";
VerifyCSharp(code);
}
[Fact]
public void BasicPropertyNoDiagnostics()
{
var code = @"
Imports System
Public Class C
Public Property PropWithNoException As Integer
Get
Return 10
End Get
Set
End Set
End Property
Public Property PropWithSetterException As Integer
Get
Return 10
End Get
Set
Throw New NotSupportedException()
End Set
End Property
Public Property PropWithAllowedException As Integer
Get
Throw New NotSupportedException()
End Get
Set
Throw New NotSupportedException()
End Set
End Property
Default Public Property Item(x As Integer) As Integer
Get
Throw New NotSupportedException()
End Get
Set
Throw New NotSupportedException()
End Set
End Property
End Class
Class NonPublic
Public Property PropWithInvalidException As Integer
Get
Throw New Exception() 'Doesn't fire because it's not visible outside assembly
End Get
Set
End Set
End Property
End Class
";
VerifyBasic(code);
}
[Fact]
public void CSharpPropertyWithInvalidExceptions()
{
var code = @"
using System;
public class C
{
public int Prop1 { get { throw new Exception(); } set { throw new NotSupportedException(); } }
public int this[int x] { get { throw new Exception(); } set { throw new NotSupportedException(); } }
public event EventHandler Event1 { add { throw new Exception(); } remove { throw new Exception(); } }
}
";
VerifyCSharp(code,
GetCSharpPropertyResultAt(6, 30, "get_Prop1", "Exception"),
GetCSharpPropertyResultAt(7, 36, "get_Item", "Exception"),
GetCSharpAllowedExceptionsResultAt(8, 46, "add_Event1", "Exception"),
GetCSharpAllowedExceptionsResultAt(8, 80, "remove_Event1", "Exception"));
}
[Fact]
public void BasicPropertyWithInvalidExceptions()
{
var code = @"
Imports System
Public Class C
Public Property Prop1 As Integer
Get
Throw New Exception()
End Get
Set
Throw New NotSupportedException()
End Set
End Property
Default Public Property Item(x As Integer) As Integer
Get
Throw New Exception()
End Get
Set
Throw New NotSupportedException()
End Set
End Property
Public Custom Event Event1 As EventHandler
AddHandler(ByVal value As EventHandler)
Throw New Exception()
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Throw New Exception()
End RemoveHandler
' RaiseEvent accessors are considered private and we won't flag this exception.
RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
Throw New Exception()
End RaiseEvent
End Event
End Class
";
VerifyBasic(code,
GetBasicPropertyResultAt(7, 12, "get_Prop1", "Exception"),
GetBasicPropertyResultAt(15, 12, "get_Item", "Exception"),
GetBasicAllowedExceptionsResultAt(24, 13, "add_Event1", "Exception"),
GetBasicAllowedExceptionsResultAt(28, 13, "remove_Event1", "Exception"));
}
#endregion
#region Equals, GetHashCode, Dispose and ToString Tests
[Fact]
public void CSharpEqualsAndGetHashCodeWithExceptions()
{
var code = @"
using System;
public class C
{
public override bool Equals(object obj)
{
throw new Exception();
}
public override int GetHashCode()
{
throw new ArgumentException("");
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "Equals", "Exception"),
GetCSharpNoExceptionsResultAt(12, 9, "GetHashCode", "ArgumentException"));
}
[Fact]
public void BasicEqualsAndGetHashCodeWithExceptions()
{
var code = @"
Imports System
Public Class C
Public Overrides Function Equals(obj As Object) As Boolean
Throw New Exception()
End Function
Public Overrides Function GetHashCode() As Integer
Throw New ArgumentException("")
End Function
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(6, 9, "Equals", "Exception"),
GetBasicNoExceptionsResultAt(9, 9, "GetHashCode", "ArgumentException"));
}
[Fact]
public void CSharpEqualsAndGetHashCodeNoDiagnostics()
{
var code = @"
using System;
public class C
{
public new bool Equals(object obj)
{
throw new Exception();
}
public new int GetHashCode()
{
throw new ArgumentException("");
}
}
";
VerifyCSharp(code);
}
[Fact]
public void BasicEqualsAndGetHashCodeNoDiagnostics()
{
var code = @"
Imports System
Public Class C
Public Shadows Function Equals(obj As Object) As Boolean
Throw New Exception()
End Function
Public Shadows Function GetHashCode() As Integer
Throw New ArgumentException("")
End Function
End Class
";
VerifyBasic(code);
}
[Fact]
public void CSharpIEquatableEqualsWithExceptions()
{
var code = @"
using System;
public class C : IEquatable<C>
{
public bool Equals(C obj)
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "Equals", "Exception"));
}
[Fact]
public void BasicIEquatableEqualsExceptions()
{
var code = @"
Imports System
Public Class C
Implements IEquatable(Of C)
Public Function Equals(obj As C) As Boolean Implements IEquatable(Of C).Equals
Throw New Exception()
End Function
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(7, 9, "Equals", "Exception"));
}
[Fact]
public void CSharpIHashCodeProviderGetHashCode()
{
var code = @"
using System;
using System.Collections;
public class C : IHashCodeProvider
{
public int GetHashCode(object obj)
{
throw new Exception();
}
}
public class D : IHashCodeProvider
{
public int GetHashCode(object obj)
{
throw new ArgumentException(""obj""); // this is fine.
}
}
";
VerifyCSharp(code,
GetCSharpAllowedExceptionsResultAt(8, 9, "GetHashCode", "Exception"));
}
[Fact]
public void BasicIHashCodeProviderGetHashCode()
{
var code = @"
Imports System
Imports System.Collections
Public Class C
Implements IHashCodeProvider
Public Function GetHashCode(obj As Object) As Integer Implements IHashCodeProvider.GetHashCode
Throw New Exception()
End Function
End Class
Public Class D
Implements IHashCodeProvider
Public Function GetHashCode(obj As Object) As Integer Implements IHashCodeProvider.GetHashCode
Throw New ArgumentException() ' This is fine.
End Function
End Class
";
VerifyBasic(code,
GetBasicAllowedExceptionsResultAt(7, 9, "GetHashCode", "Exception"));
}
[Fact]
public void CSharpIEqualityComparer()
{
var code = @"
using System;
using System.Collections.Generic;
public class C : IEqualityComparer<C>
{
public bool Equals(C obj1, C obj2)
{
throw new Exception();
}
public int GetHashCode(C obj)
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "Equals", "Exception"),
GetCSharpAllowedExceptionsResultAt(12, 9, "GetHashCode", "Exception"));
}
[Fact]
public void BasicIEqualityComparer()
{
var code = @"
Imports System
Imports System.Collections.Generic
Public Class C
Implements IEqualityComparer(Of C)
Public Function Equals(obj1 As C, obj2 As C) As Boolean Implements IEqualityComparer(Of C).Equals
Throw New Exception()
End Function
Public Function GetHashCode(obj As C) As Integer Implements IEqualityComparer(Of C).GetHashCode
Throw New Exception()
End Function
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(7, 9, "Equals", "Exception"),
GetBasicAllowedExceptionsResultAt(10, 9, "GetHashCode", "Exception"));
}
[Fact]
public void CSharpIDisposable()
{
var code = @"
using System;
public class C : IDisposable
{
public void Dispose()
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "Dispose", "Exception"));
}
[Fact]
public void BasicIDisposable()
{
var code = @"
Imports System
Public Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Throw New Exception()
End Sub
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(7, 9, "Dispose", "Exception"));
}
[Fact]
public void CSharpToStringWithExceptions()
{
var code = @"
using System;
public class C
{
public override string ToString()
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "ToString", "Exception"));
}
[Fact]
public void BasicToStringWithExceptions()
{
var code = @"
Imports System
Public Class C
Public Overrides Function ToString() As String
Throw New Exception()
End Function
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(6, 9, "ToString", "Exception"));
}
#endregion
#region Constructor and Destructor tests
[Fact]
public void CSharpStaticConstructorWithExceptions()
{
var code = @"
using System;
class NonPublic
{
static NonPublic()
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, ".cctor", "Exception"));
}
[Fact]
public void BasicStaticConstructorWithExceptions()
{
var code = @"
Imports System
Class NonPublic
Shared Sub New()
Throw New Exception()
End Sub
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(6, 9, ".cctor", "Exception"));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")]
public void CSharpFinalizerWithExceptions()
{
var code = @"
using System;
class NonPublic
{
~NonPublic()
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "Finalize", "Exception"));
}
[Fact]
public void BasicFinalizerWithExceptions()
{
var code = @"
Imports System
Class NonPublic
Protected Overrides Sub Finalize()
Throw New Exception()
End Sub
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(6, 9, "Finalize", "Exception"));
}
#endregion
#region Operator tests
[Fact]
public void CSharpEqualityOperatorWithExceptions()
{
var code = @"
using System;
public class C
{
public static C operator ==(C c1, C c2)
{
throw new Exception();
}
public static C operator !=(C c1, C c2)
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "op_Equality", "Exception"),
GetCSharpNoExceptionsResultAt(12, 9, "op_Inequality", "Exception"));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")]
public void BasicEqualityOperatorWithExceptions()
{
var code = @"
Imports System
Public Class C
Public Shared Operator =(c1 As C, c2 As C) As C
Throw New Exception()
End Operator
Public Shared Operator <>(c1 As C, c2 As C) As C
Throw New Exception()
End Operator
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(6, 9, "op_Equality", "Exception"),
GetBasicNoExceptionsResultAt(9, 9, "op_Inequality", "Exception"));
}
[Fact]
public void CSharpImplicitOperatorWithExceptions()
{
var code = @"
using System;
public class C
{
public static implicit operator int(C c1)
{
throw new Exception();
}
public static explicit operator double(C c1)
{
throw new Exception(); // This is fine.
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "op_Implicit", "Exception"));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")]
public void BasicImplicitOperatorWithExceptions()
{
var code = @"
Imports System
Public Class C
Public Shared Widening Operator CType(x As Integer) As C
Throw New Exception()
End Operator
Public Shared Narrowing Operator CType(x As Double) As C
Throw New Exception()
End Operator
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(6, 9, "op_Implicit", "Exception"));
}
#endregion
private DiagnosticResult GetCSharpPropertyResultAt(int line, int column, string methodName, string exceptionName)
{
return GetCSharpResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.PropertyGetterRule, methodName, exceptionName);
}
private DiagnosticResult GetCSharpAllowedExceptionsResultAt(int line, int column, string methodName, string exceptionName)
{
return GetCSharpResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.HasAllowedExceptionsRule, methodName, exceptionName);
}
private DiagnosticResult GetCSharpNoExceptionsResultAt(int line, int column, string methodName, string exceptionName)
{
return GetCSharpResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.NoAllowedExceptionsRule, methodName, exceptionName);
}
private DiagnosticResult GetBasicPropertyResultAt(int line, int column, string methodName, string exceptionName)
{
return GetBasicResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.PropertyGetterRule, methodName, exceptionName);
}
private DiagnosticResult GetBasicAllowedExceptionsResultAt(int line, int column, string methodName, string exceptionName)
{
return GetBasicResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.HasAllowedExceptionsRule, methodName, exceptionName);
}
private DiagnosticResult GetBasicNoExceptionsResultAt(int line, int column, string methodName, string exceptionName)
{
return GetBasicResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.NoAllowedExceptionsRule, methodName, exceptionName);
}
}
}
| |
using UnityEngine;
using System.Collections;
// relies on: http://forum.unity3d.com/threads/12031-create-random-colors?p=84625&viewfull=1#post84625
public class ColorPicker : MonoBehaviour
{
public bool useDefinedPosition = false;
public int positionLeft = 0;
public int positionTop = 0;
// the solid texture which everything is compared against
public Texture2D colorPicker;
// the picker being displayed
private Texture2D displayPicker;
// the color that has been chosen
public Color setColor;
private Color lastSetColor;
public bool useDefinedSize = false;
public int textureWidth = 360;
public int textureHeight = 120;
private float saturationSlider = 0.0F;
private Texture2D saturationTexture;
private Texture2D styleTexture;
public bool showPicker = false;
void Awake()
{
if (!useDefinedPosition)
{
positionLeft = (Screen.width / 2) - (textureWidth / 2);
positionTop = (Screen.height / 2) - (textureHeight / 2);
}
// if a default color picker texture hasn't been assigned, make one dynamically
if (!colorPicker)
{
colorPicker = new Texture2D(textureWidth, textureHeight, TextureFormat.ARGB32, false);
ColorHSV hsvColor;
for (int i = 0; i < textureWidth; i++)
{
for (int j = 0; j < textureHeight; j++)
{
hsvColor = new ColorHSV((float)i, (1.0f / j) * textureHeight, 1.0f);
colorPicker.SetPixel(i, j, hsvColor.ToColor());
}
}
}
colorPicker.Apply();
displayPicker = colorPicker;
if (!useDefinedSize)
{
textureWidth = colorPicker.width;
textureHeight = colorPicker.height;
}
float v = 0.0F;
float diff = 1.0f / textureHeight;
saturationTexture = new Texture2D(20, textureHeight);
for (int i = 0; i < saturationTexture.width; i++)
{
for (int j = 0; j < saturationTexture.height; j++)
{
saturationTexture.SetPixel(i, j, new Color(v, v, v));
v += diff;
}
v = 0.0F;
}
saturationTexture.Apply();
// small color picker box texture
styleTexture = new Texture2D(1, 1);
styleTexture.SetPixel(0, 0, setColor);
}
void OnGUI()
{
if (!showPicker) return;
GUI.Box(new Rect(positionLeft - 3, positionTop - 3, textureWidth + 60, textureHeight + 60), "");
if (GUI.RepeatButton(new Rect(positionLeft, positionTop, textureWidth, textureHeight), displayPicker))
{
int a = (int)Input.mousePosition.x;
int b = Screen.height - (int)Input.mousePosition.y;
setColor = displayPicker.GetPixel(a - positionLeft, -(b - positionTop));
lastSetColor = setColor;
}
saturationSlider = GUI.VerticalSlider(new Rect(positionLeft + textureWidth + 3, positionTop, 10, textureHeight), saturationSlider, 1, -1);
setColor = lastSetColor + new Color(saturationSlider, saturationSlider, saturationSlider);
Camera.main.gameObject.SendMessage("SetBlimpColor", setColor, SendMessageOptions.DontRequireReceiver);
GUI.Box(new Rect(positionLeft + textureWidth + 20, positionTop, 20, textureHeight), saturationTexture);
if (GUI.Button(new Rect(positionLeft + textureWidth - 60, positionTop + textureHeight + 10, 60, 25), "Apply"))
{
setColor = styleTexture.GetPixel(0, 0);
// hide picker
showPicker = false;
}
// color display
GUIStyle style = new GUIStyle();
styleTexture.SetPixel(0, 0, setColor);
styleTexture.Apply();
style.normal.background = styleTexture;
GUI.Box(new Rect(positionLeft + textureWidth + 10, positionTop + textureHeight + 10, 30, 30), new GUIContent(""), style);
}
}
class ColorHSV : System.Object
{
float h= 0.0f;
float s = 0.0f;
float v= 0.0f;
float a= 0.0f;
/**
* Construct without alpha (which defaults to 1)
*/
public ColorHSV(float h, float s, float v)
{
this.h = h;
this.s = s;
this.v = v;
this.a = 1.0f;
}
/**
* Construct with alpha
*/
public ColorHSV(float h, float s, float v, float a)
{
this.h = h;
this.s = s;
this.v = v;
this.a = a;
}
/**
* Create from an RGBA color object
*/
public ColorHSV(Color color)
{
float min = Mathf.Min(Mathf.Min(color.r, color.g), color.b);
float max = Mathf.Max(Mathf.Max(color.r, color.g), color.b);
float delta = max - min;
// value is our max color
this.v = max;
// saturation is percent of max
if(!Mathf.Approximately(max, 0))
this.s = delta / max;
else
{
// all colors are zero, no saturation and hue is undefined
this.s = 0;
this.h = -1;
return;
}
// grayscale image if min and max are the same
if(Mathf.Approximately(min, max))
{
this.v = max;
this.s = 0;
this.h = -1;
return;
}
// hue depends which color is max (this creates a rainbow effect)
if( color.r == max )
this.h = ( color.g - color.b ) / delta; // between yellow & magenta
else if( color.g == max )
this.h = 2 + ( color.b - color.r ) / delta; // between cyan & yellow
else
this.h = 4 + ( color.r - color.g ) / delta; // between magenta & cyan
// turn hue into 0-360 degrees
this.h *= 60;
if(this.h < 0 )
this.h += 360;
}
/**
* Return an RGBA color object
*/
public Color ToColor()
{
// no saturation, we can return the value across the board (grayscale)
if(this.s == 0 )
return new Color(this.v, this.v, this.v, this.a);
// which chunk of the rainbow are we in?
float sector = this.h / 60;
// split across the decimal (ie 3.87 into 3 and 0.87)
int i = (int)Mathf.Floor(sector);
float f = sector - i;
float v = this.v;
float p = v * ( 1 - s );
float q = v * ( 1 - s * f );
float t = v * ( 1 - s * ( 1 - f ) );
// build our rgb color
Color color = new Color(0, 0, 0, this.a);
switch(i)
{
case 0:
color.r = v;
color.g = t;
color.b = p;
break;
case 1:
color.r = q;
color.g = v;
color.b = p;
break;
case 2:
color.r = p;
color.g = v;
color.b = t;
break;
case 3:
color.r = p;
color.g = q;
color.b = v;
break;
case 4:
color.r = t;
color.g = p;
color.b = v;
break;
default:
color.r = v;
color.g = p;
color.b = q;
break;
}
return color;
}
/**
* Format nicely
*/
public override string ToString()
{
return string.Format("h: {0:0.00}, s: {1:0.00}, v: {2:0.00}, a: {3:0.00}", h, s, v, a);
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using FileHelpers;
namespace FileHelpersSamples
{
/// <summary>
/// Run the engine in Async mode to speed
/// the processing times of the file up.
/// </summary>
public class frmEasySampleAsync : frmFather
{
private TextBox txtClass;
private Button cmdRun;
private Label label2;
private Label label1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox txtOut;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
public frmEasySampleAsync()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing) {
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources =
new System.ComponentModel.ComponentResourceManager(typeof (frmEasySampleAsync));
this.txtClass = new System.Windows.Forms.TextBox();
this.cmdRun = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.txtOut = new System.Windows.Forms.TextBox();
((System.ComponentModel.ISupportInitialize) (this.pictureBox3)).BeginInit();
this.SuspendLayout();
//
// pictureBox3
//
this.pictureBox3.Location = new System.Drawing.Point(576, 8);
//
// txtClass
//
this.txtClass.Font = new System.Drawing.Font("Courier New",
8.25F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.txtClass.Location = new System.Drawing.Point(8, 288);
this.txtClass.Multiline = true;
this.txtClass.Name = "txtClass";
this.txtClass.ReadOnly = true;
this.txtClass.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtClass.Size = new System.Drawing.Size(328, 160);
this.txtClass.TabIndex = 0;
this.txtClass.Text = resources.GetString("txtClass.Text");
this.txtClass.WordWrap = false;
//
// cmdRun
//
this.cmdRun.BackColor = System.Drawing.Color.FromArgb(((int) (((byte) (0)))),
((int) (((byte) (0)))),
((int) (((byte) (110)))));
this.cmdRun.Font = new System.Drawing.Font("Tahoma",
9.75F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.cmdRun.ForeColor = System.Drawing.Color.White;
this.cmdRun.Location = new System.Drawing.Point(336, 8);
this.cmdRun.Name = "cmdRun";
this.cmdRun.Size = new System.Drawing.Size(152, 32);
this.cmdRun.TabIndex = 0;
this.cmdRun.Text = "RUN >>";
this.cmdRun.UseVisualStyleBackColor = false;
this.cmdRun.Click += new System.EventHandler(this.cmdRun_Click);
//
// label2
//
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Font = new System.Drawing.Font("Tahoma",
9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.label2.ForeColor = System.Drawing.Color.White;
this.label2.Location = new System.Drawing.Point(8, 272);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(216, 16);
this.label2.TabIndex = 7;
this.label2.Text = "Code of the Mapping Class";
//
// label1
//
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = new System.Drawing.Font("Tahoma",
9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.label1.ForeColor = System.Drawing.Color.White;
this.label1.Location = new System.Drawing.Point(344, 272);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(216, 16);
this.label1.TabIndex = 8;
this.label1.Text = "Console Output";
//
// label4
//
this.label4.BackColor = System.Drawing.Color.Transparent;
this.label4.Font = new System.Drawing.Font("Tahoma",
9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.label4.ForeColor = System.Drawing.Color.White;
this.label4.Location = new System.Drawing.Point(8, 64);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(152, 16);
this.label4.TabIndex = 10;
this.label4.Text = "Code to Read the File";
//
// textBox1
//
this.textBox1.Font = new System.Drawing.Font("Courier New",
8.25F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.textBox1.Location = new System.Drawing.Point(8, 80);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(656, 184);
this.textBox1.TabIndex = 11;
this.textBox1.Text = resources.GetString("textBox1.Text");
this.textBox1.WordWrap = false;
//
// txtOut
//
this.txtOut.Font = new System.Drawing.Font("Courier New",
8.25F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.txtOut.Location = new System.Drawing.Point(344, 288);
this.txtOut.Multiline = true;
this.txtOut.Name = "txtOut";
this.txtOut.ReadOnly = true;
this.txtOut.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtOut.Size = new System.Drawing.Size(328, 160);
this.txtOut.TabIndex = 12;
this.txtOut.WordWrap = false;
//
// frmEasySampleAsync
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(680, 480);
this.Controls.Add(this.txtOut);
this.Controls.Add(this.label4);
this.Controls.Add(this.label1);
this.Controls.Add(this.label2);
this.Controls.Add(this.cmdRun);
this.Controls.Add(this.txtClass);
this.Controls.Add(this.textBox1);
this.Name = "frmEasySampleAsync";
this.Text = "FileHelpers - Easy Example";
this.Controls.SetChildIndex(this.textBox1, 0);
this.Controls.SetChildIndex(this.pictureBox3, 0);
this.Controls.SetChildIndex(this.txtClass, 0);
this.Controls.SetChildIndex(this.cmdRun, 0);
this.Controls.SetChildIndex(this.label2, 0);
this.Controls.SetChildIndex(this.label1, 0);
this.Controls.SetChildIndex(this.label4, 0);
this.Controls.SetChildIndex(this.txtOut, 0);
((System.ComponentModel.ISupportInitialize) (this.pictureBox3)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// Run the Async engine with a vertical bar file
/// </summary>
private void cmdRun_Click(object sender, EventArgs e)
{
txtOut.Text = string.Empty;
var engine = new FileHelperAsyncEngine<CustomersVerticalBar>();
engine.BeginReadString(TestData.mCustomersTest);
// The Async engines are IEnumerable
foreach (CustomersVerticalBar cust in engine) {
// your code here
txtOut.Text += cust.CustomerID + " - " + cust.ContactTitle + Environment.NewLine;
}
engine.Close();
}
}
}
| |
using UnityEngine;
using UnityEngine.Serialization;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(SgtRing))]
public class SgtRing_Editor : SgtEditor<SgtRing>
{
protected override void OnInspector()
{
var updateMaterial = false;
var updateModels = false;
DrawDefault("Color", ref updateMaterial);
BeginError(Any(t => t.Brightness < 0.0f));
DrawDefault("Brightness", ref updateMaterial);
EndError();
DrawDefault("RenderQueue", ref updateMaterial);
DrawDefault("RenderQueueOffset", ref updateMaterial);
Separator();
BeginError(Any(t => t.MainTex == null));
DrawDefault("MainTex", ref updateMaterial);
EndError();
BeginError(Any(t => t.Segments < 1));
DrawDefault("Segments", ref updateModels, ref updateModels);
EndError();
BeginError(Any(t => t.Mesh == null));
DrawDefault("Mesh", ref updateModels);
EndError();
Separator();
DrawDefault("Detail", ref updateMaterial);
if (Any(t => t.Detail == true))
{
BeginIndent();
BeginError(Any(t => t.DetailTex == null));
DrawDefault("DetailTex", ref updateMaterial);
EndError();
BeginError(Any(t => t.DetailScaleX < 0.0f));
DrawDefault("DetailScaleX", ref updateMaterial);
EndError();
BeginError(Any(t => t.DetailScaleY < 1));
DrawDefault("DetailScaleY", ref updateMaterial);
EndError();
DrawDefault("DetailOffset", ref updateMaterial);
DrawDefault("DetailSpeed", ref updateMaterial);
DrawDefault("DetailTwist", ref updateMaterial);
BeginError(Any(t => t.DetailTwistBias < 1.0f));
DrawDefault("DetailTwistBias", ref updateMaterial);
EndError();
EndIndent();
}
Separator();
DrawDefault("Fade", ref updateMaterial);
if (Any(t => t.Fade == true))
{
BeginIndent();
BeginError(Any(t => t.FadeTex == null));
DrawDefault("FadeTex", ref updateMaterial);
EndError();
BeginError(Any(t => t.FadeDistance <= 0.0f));
DrawDefault("FadeDistance", ref updateMaterial);
EndError();
EndIndent();
}
Separator();
DrawDefault("Lit", ref updateMaterial);
if (Any(t => t.Lit == true))
{
BeginIndent();
BeginError(Any(t => t.LightingTex == null));
DrawDefault("LightingTex", ref updateMaterial);
EndError();
DrawDefault("Scattering", ref updateMaterial);
if (Any(t => t.Scattering == true))
{
BeginIndent();
BeginError(Any(t => t.ScatteringMie <= 0.0f));
DrawDefault("ScatteringMie", ref updateMaterial);
EndError();
DrawDefault("ScatteringStrength"); // Updated in LateUpdate
EndIndent();
}
BeginError(Any(t => t.Lights != null && (t.Lights.Count == 0 || t.Lights.Exists(l => l == null))));
DrawDefault("Lights", ref updateMaterial);
EndError();
BeginError(Any(t => t.Shadows != null && t.Shadows.Exists(s => s == null)));
DrawDefault("Shadows", ref updateMaterial);
EndError();
EndIndent();
}
if (Any(t => t.Mesh == null && t.GetComponent<SgtRingMesh>() == null))
{
Separator();
if (Button("Add Mesh") == true)
{
Each(t => SgtHelper.GetOrAddComponent<SgtRingMesh>(t.gameObject));
}
}
if (Any(t => t.Fade == true && t.FadeTex == null && t.GetComponent<SgtRingFade>() == null))
{
Separator();
if (Button("Add Fade") == true)
{
Each(t => SgtHelper.GetOrAddComponent<SgtRingFade>(t.gameObject));
}
}
if (Any(t => t.Lit == true && t.LightingTex == null && t.GetComponent<SgtRingLighting>() == null))
{
Separator();
if (Button("Add Lighting") == true)
{
Each(t => SgtHelper.GetOrAddComponent<SgtRingLighting>(t.gameObject));
}
}
if (updateMaterial == true) DirtyEach(t => t.UpdateMaterial());
if (updateModels == true) DirtyEach(t => t.UpdateModels ());
}
}
#endif
[ExecuteInEditMode]
[AddComponentMenu(SgtHelper.ComponentMenuPrefix + "Ring")]
public class SgtRing : MonoBehaviour
{
// All currently active and enabled rings
public static List<SgtRing> AllRings = new List<SgtRing>();
[Tooltip("The color tint")]
public Color Color = Color.white;
[Tooltip("The Color.rgb values are multiplied by this")]
public float Brightness = 1.0f;
[Tooltip("The render queue group for this ring")]
public SgtRenderQueue RenderQueue = SgtRenderQueue.Transparent;
[Tooltip("The render queue offset for this ring")]
public int RenderQueueOffset;
[Tooltip("The texture applied to the ring (left side = inside, right side = outside)")]
public Texture MainTex;
[Tooltip("The mesh applied to each ring model")]
public Mesh Mesh;
[Tooltip("The amount of segments this ring is split into")]
[FormerlySerializedAs("SegmentCount")]
public int Segments = 8;
[Tooltip("Should the ring have a detail texture?")]
public bool Detail;
[Tooltip("The detail texture applied to the ring")]
public Texture DetailTex;
[Tooltip("The detail texture horizontal tiling")]
public float DetailScaleX = 1.0f;
[Tooltip("The detail texture vertical tiling")]
public int DetailScaleY = 1;
[Tooltip("The UV offset of the detail texture")]
public Vector2 DetailOffset;
[Tooltip("The scroll speed of the detail texture UV offset")]
public Vector2 DetailSpeed;
[Tooltip("The amount the detail texture is twisted around the ring")]
public float DetailTwist;
[Tooltip("The amount the twisting is pushed to the outer edge")]
public float DetailTwistBias = 1.0f;
[Tooltip("Fade out as the camera approaches?")]
public bool Fade;
[Tooltip("The lookup table used to calculate the fade")]
public Texture FadeTex;
[Tooltip("The distance the fading begins from in world space")]
public float FadeDistance = 1.0f;
[Tooltip("Should light scatter through the rings?")]
public bool Scattering;
[Tooltip("The sharpness of the front scattered light")]
public float ScatteringMie = 8.0f;
[Tooltip("The scattering brightness multiplier")]
public float ScatteringStrength = 25.0f;
[Tooltip("Does this receive light?")]
public bool Lit;
[Tooltip("The lookup table used to calculate the lighting")]
public Texture LightingTex;
[Tooltip("The lights shining on this ring (max = 1 light, 2 scatter)")]
public List<Light> Lights;
[Tooltip("The shadows casting on this ring (max = 2)")]
public List<SgtShadow> Shadows;
// The models used to render the full ring
[FormerlySerializedAs("Segments")]
public List<SgtRingModel> Models;
// The material applied to all models
[System.NonSerialized]
public Material Material;
[SerializeField]
private bool startCalled;
[System.NonSerialized]
private bool updateMaterialCalled;
[System.NonSerialized]
private bool updateModelsCalled;
protected virtual string ShaderName
{
get
{
return SgtHelper.ShaderNamePrefix + "Ring";
}
}
public virtual void UpdateMainTex()
{
if (Material != null)
{
Material.SetTexture("_MainTex", MainTex);
}
}
public virtual void UpdateFadeTex()
{
if (Material != null)
{
Material.SetTexture("_FadeTex", FadeTex);
}
}
public virtual void UpdateLightingTex()
{
if (Material != null)
{
Material.SetTexture("_LightingTex", LightingTex);
}
}
[ContextMenu("Update Material")]
public virtual void UpdateMaterial()
{
updateMaterialCalled = true;
if (Material == null)
{
Material = SgtHelper.CreateTempMaterial("Ring (Generated)", ShaderName);
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.SetMaterial(Material);
}
}
}
}
var color = SgtHelper.Brighten(Color, Brightness);
var renderQueue = (int)RenderQueue + RenderQueueOffset;
Material.renderQueue = renderQueue;
Material.SetColor("_Color", color);
Material.SetTexture("_MainTex", MainTex);
if (Detail == true)
{
SgtHelper.EnableKeyword("SGT_B", Material); // Detail
Material.SetTexture("_DetailTex", DetailTex);
Material.SetVector("_DetailScale", new Vector2(DetailScaleX, DetailScaleY));
Material.SetFloat("_DetailTwist", DetailTwist);
Material.SetFloat("_DetailTwistBias", DetailTwistBias);
}
else
{
SgtHelper.DisableKeyword("SGT_B", Material); // Detail
}
if (Fade == true)
{
SgtHelper.EnableKeyword("SGT_C", Material); // Fade
Material.SetTexture("_FadeTex", FadeTex);
Material.SetFloat("_FadeDistanceRecip", SgtHelper.Reciprocal(FadeDistance));
}
else
{
SgtHelper.DisableKeyword("SGT_C", Material); // Fade
}
if (Lit == true)
{
Material.SetTexture("_LightingTex", LightingTex);
}
if (Scattering == true)
{
SgtHelper.EnableKeyword("SGT_A", Material); // Scattering
Material.SetFloat("_ScatteringMie", ScatteringMie * ScatteringMie);
}
else
{
SgtHelper.DisableKeyword("SGT_A", Material); // Scattering
}
UpdateMaterialNonSerialized();
}
[ContextMenu("Update Mesh")]
public void UpdateMesh()
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.SetMesh(Mesh);
}
}
}
}
[ContextMenu("Update Models")]
public void UpdateModels()
{
updateModelsCalled = true;
var angleStep = SgtHelper.Divide(360.0f, Segments);
for (var i = 0; i < Segments; i++)
{
var model = GetOrAddModel(i);
var angle = angleStep * i;
var rotation = Quaternion.Euler(0.0f, angle, 0.0f);
model.SetMesh(Mesh);
model.SetMaterial(Material);
model.SetRotation(rotation);
}
// Remove any excess
if (Models != null)
{
var min = Mathf.Max(0, Segments);
for (var i = Models.Count - 1; i >= min; i--)
{
SgtRingModel.Pool(Models[i]);
Models.RemoveAt(i);
}
}
}
public static SgtRing CreateRing(int layer = 0, Transform parent = null)
{
return CreateRing(layer, parent, Vector3.zero, Quaternion.identity, Vector3.one);
}
public static SgtRing CreateRing(int layer, Transform parent, Vector3 localPosition, Quaternion localRotation, Vector3 localScale)
{
var gameObject = SgtHelper.CreateGameObject("Ring", layer, parent, localPosition, localRotation, localScale);
var ring = gameObject.AddComponent<SgtRing>();
return ring;
}
#if UNITY_EDITOR
[MenuItem(SgtHelper.GameObjectMenuPrefix + "Ring", false, 10)]
public static void CreateRingMenuItem()
{
var parent = SgtHelper.GetSelectedParent();
var ring = CreateRing(parent != null ? parent.gameObject.layer : 0, parent);
SgtHelper.SelectAndPing(ring);
}
#endif
protected virtual void OnEnable()
{
AllRings.Add(this);
Camera.onPreRender += CameraPreRender;
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.gameObject.SetActive(true);
}
}
}
if (startCalled == true)
{
CheckUpdateCalls();
}
}
protected virtual void Start()
{
if (startCalled == false)
{
startCalled = true;
CheckUpdateCalls();
}
}
protected virtual void LateUpdate()
{
// The lights and shadows may have moved, so write them
if (Material != null)
{
SgtHelper.SetTempMaterial(Material);
SgtHelper.WriteLights(Lit, Lights, 2, transform.position, null, null, SgtHelper.Brighten(Color, Brightness), ScatteringStrength);
SgtHelper.WriteShadows(Shadows, 2);
if (Detail == true)
{
if (Application.isPlaying == true)
{
DetailOffset += DetailSpeed * Time.deltaTime;
}
Material.SetVector("_DetailOffset", DetailOffset);
}
}
}
protected virtual void OnDisable()
{
AllRings.Remove(this);
Camera.onPreRender -= CameraPreRender;
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.gameObject.SetActive(false);
}
}
}
}
protected virtual void OnDestroy()
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
SgtRingModel.MarkForDestruction(Models[i]);
}
}
SgtHelper.Destroy(Material);
}
private void UpdateMaterialNonSerialized()
{
SgtHelper.SetTempMaterial(Material);
SgtHelper.WriteShadowsNonSerialized(Shadows, 2);
}
private void CameraPreRender(Camera camera)
{
if (Material != null)
{
UpdateMaterialNonSerialized();
}
}
private SgtRingModel GetOrAddModel(int index)
{
var model = default(SgtRingModel);
if (Models == null)
{
Models = new List<SgtRingModel>();
}
if (index < Models.Count)
{
model = Models[index];
if (model == null)
{
model = SgtRingModel.Create(this);
Models[index] = model;
}
}
else
{
model = SgtRingModel.Create(this);
Models.Add(model);
}
return model;
}
private void CheckUpdateCalls()
{
if (updateMaterialCalled == false)
{
UpdateMaterial();
}
if (updateModelsCalled == false)
{
UpdateModels();
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Stratus
{
/// <summary>
/// Common interpolation algorithms
/// </summary>
public enum StratusEase
{
/// <summary>
/// Linear interpolation
/// </summary>
Linear,
QuadraticIn,
QuadraticInOut,
QuadraticOut,
CubicIn,
CubicOut,
CubicInOut,
ExponentialIn,
ExponentialOut,
ExponentialInOut,
SineIn,
SineOut,
SineInOut,
ElasticIn,
ElasticOut,
ElasticInOut,
Smoothstep
}
/// <summary>
/// Provides methods for common interpolation algorithms,
/// and common interpolation functions
/// </summary>
public static class StratusEasing
{
//--------------------------------------------------------------------------------------------/
// Declarations
//--------------------------------------------------------------------------------------------/
/// <summary>
/// The easing function to be used
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public delegate float EaseFunction(float t);
/// <summary>
/// An abstract interpolator for all supported easing types
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class Interpolator<T>
{
public System.Action<T> setter;
public EaseFunction function;
public T difference { get; private set; }
public T initialValue;
public T finalValue;
public Interpolator(T initialValue, T finalValue, EaseFunction function)
{
this.initialValue = initialValue;
this.finalValue = finalValue;
this.difference = ComputeDifference();
}
public abstract T ComputeDifference();
public abstract T ComputeCurrentValue(float t);
}
//--------------------------------------------------------------------------------------------/
// Properties
//--------------------------------------------------------------------------------------------/
private static Dictionary<StratusEase, EaseFunction> easingFunctions { get; set; } = new Dictionary<StratusEase, EaseFunction>();
public static float tMinimum { get; } = 0f;
public static float tMax { get; } = 1f;
private static Dictionary<float, Dictionary<float, float>> exponentCache { get; set; } = new Dictionary<float, Dictionary<float, float>>();
//--------------------------------------------------------------------------------------------/
// CTOR
//--------------------------------------------------------------------------------------------/
static StratusEasing()
{
easingFunctions.Add(StratusEase.Linear, Linear);
easingFunctions.Add(StratusEase.CubicIn, CubicIn);
easingFunctions.Add(StratusEase.CubicInOut, CubicInOut);
easingFunctions.Add(StratusEase.CubicOut, CubicOut);
easingFunctions.Add(StratusEase.QuadraticIn, QuadIn);
easingFunctions.Add(StratusEase.QuadraticOut, QuadOut);
easingFunctions.Add(StratusEase.QuadraticInOut, QuadInOut);
easingFunctions.Add(StratusEase.ExponentialIn, ExponentialIn);
easingFunctions.Add(StratusEase.ExponentialOut, ExponentialOut);
easingFunctions.Add(StratusEase.ExponentialInOut, ExponentialInOut);
easingFunctions.Add(StratusEase.ElasticIn, ElasticIn);
easingFunctions.Add(StratusEase.ElasticOut, ElasticOut);
easingFunctions.Add(StratusEase.ElasticInOut, ElasticInOut);
easingFunctions.Add(StratusEase.SineIn, SineIn);
easingFunctions.Add(StratusEase.SineOut, SineOut);
easingFunctions.Add(StratusEase.SineInOut, SineInOut);
easingFunctions.Add(StratusEase.Smoothstep, Smoothstep);
}
//--------------------------------------------------------------------------------------------/
// Ease Functions
//--------------------------------------------------------------------------------------------/
// Many of these were found on this repository, by Fonserbc
// https://gist.github.com/Fonserbc/3d31a25e87fdaa541ddf
// Linear
public static float Linear(float t)
{
return t;
}
// - Powers
// General Power
public static float PowerIn(float t, float exponent)
{
return Power(t, exponent);
}
public static float PowerOut(float t, float exponent)
{
return 1f - Power(1 - t, exponent);
}
public static float PowerInOut(float t, float exponent)
{
if (t < 0.5f)
return PowerIn(t * 2, exponent) / 2;
return PowerOut(t * 2 - 1, exponent) / 2 + 0.5f;
}
// Quadratic
public static float QuadIn(float t)
{
return t * t;
}
public static float QuadOut(float t)
{
return t * (2f - t);
}
public static float QuadInOut(float t)
{
if ((t *= 2f) < 1f)
return 0.5f * t * t;
return -0.5f * ((t -= 1f) * (t - 2f) - 1f);
}
// Cubic
public static float CubicIn(float t)
{
return t * t * t;
}
public static float CubicOut(float t)
{
return 1f + ((t -= 1f) * t * t);
}
public static float CubicInOut(float t)
{
if ((t *= 2f) < 1f)
return 0.5f * t * t * t;
return 0.5f * ((t -= 2f) * t * t + 2f);
}
// Sine
public static float SineIn(float t)
{
return 1f - Mathf.Cos(t * Mathf.PI / 2f);
}
public static float SineOut(float t)
{
return Mathf.Sin(t * Mathf.PI / 2f);
}
public static float SineInOut(float t)
{
return 0.5f * (1f - Mathf.Cos(Mathf.PI * t));
}
// Exponential
public static float ExponentialIn(float t)
{
return t == 0f ? 0f : Power(1024f, t - 1f);
}
public static float ExponentialOut(float t)
{
return t == 1f ? 1f : 1f - Power(2f, -10f * t);
}
public static float ExponentialInOut(float t)
{
if (t == 0f) return 0f;
if (t == 1f) return 1f;
if ((t *= 2f) < 1f) return 0.5f * Power(1024f, t - 1f);
return 0.5f * (-Power(2f, -10f * (t - 1f)) + 2f);
}
// Elastic
public static float ElasticIn(float t)
{
if (t == 0) return 0;
if (t == 1) return 1;
return -Power(2f, 10f * (t -= 1f)) * Mathf.Sin((t - 0.1f) * (2f * Mathf.PI) / 0.4f);
}
public static float ElasticOut(float t)
{
if (t == 0) return 0;
if (t == 1) return 1;
return Power(2f, -10f * t) * Mathf.Sin((t - 0.1f) * (2f * Mathf.PI) / 0.4f) + 1f;
}
public static float ElasticInOut(float t)
{
if ((t *= 2f) < 1f) return -0.5f * Mathf.Pow(2f, 10f * (t -= 1f)) * Mathf.Sin((t - 0.1f) * (2f * Mathf.PI) / 0.4f);
return Power(2f, -10f * (t -= 1f)) * Mathf.Sin((t - 0.1f) * (2f * Mathf.PI) / 0.4f) * 0.5f + 1f;
}
// Smoothstep
public static float Smoothstep(float t)
{
return t * t * (3 - 2 * t);
}
//--------------------------------------------------------------------------------------------/
// Functions: Calculate t
//--------------------------------------------------------------------------------------------/
/// <summary>
/// Recalculates the given t value based on the ease selected
/// </summary>
/// <param name="t"></param>
/// <param name="ease"></param>
/// <returns></returns>
public static float Calculate(StratusEase ease, float t) => easingFunctions[ease](t);
/// <summary>
/// Returns the function used for this ease
/// </summary>
/// <param name="ease"></param>
/// <returns></returns>
public static EaseFunction ToFunction(this StratusEase ease)
{
switch (ease)
{
case StratusEase.Linear:
return Linear;
case StratusEase.QuadraticIn:
return QuadIn;
case StratusEase.QuadraticInOut:
return QuadInOut;
case StratusEase.QuadraticOut:
return QuadOut;
case StratusEase.CubicIn:
return CubicIn;
case StratusEase.CubicOut:
return CubicOut;
case StratusEase.CubicInOut:
return CubicInOut;
case StratusEase.ElasticIn:
return ElasticIn;
case StratusEase.ElasticOut:
return ElasticOut;
case StratusEase.ElasticInOut:
return ElasticInOut;
case StratusEase.ExponentialIn:
return ExponentialIn;
case StratusEase.ExponentialOut:
return ExponentialOut;
case StratusEase.ExponentialInOut:
return ExponentialInOut;
case StratusEase.SineIn:
return SineIn;
case StratusEase.SineOut:
return SineOut;
case StratusEase.SineInOut:
return SineInOut;
case StratusEase.Smoothstep:
return Smoothstep;
}
throw new System.Exception($"No function found for the ease {ease}");
}
public static float Evaluate(this StratusEase ease, float t) => easingFunctions[ease](t);
/// <summary>
/// Returns the specified number raised to a specified power
/// </summary>
/// <param name="value"></param>
/// <param name="exponent"></param>
/// <returns></returns>
public static float Power(float value, float exponent)
{
if (!exponentCache.ContainsKey(value))
{
exponentCache.Add(value, new Dictionary<float, float>());
}
if (!exponentCache[value].ContainsKey(exponent))
{
exponentCache[value].Add(exponent, Mathf.Pow(value, exponent));
}
return exponentCache[value][exponent];
}
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_15_4_4_12 : EcmaTest
{
[Fact]
[Trait("Category", "15.4.4.12")]
public void ArrayPrototypeSpliceFromIsTheResultOfTostringActualstartKInAnArray()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/15.4.4.12-9-a-1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void ArrayPrototypeSpliceWillSpliceAnArrayEvenWhenArrayPrototypeHasIndex0SetToReadOnlyAndFrompresentLessThanActualdeletecountStep9CIi()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/15.4.4.12-9-c-ii-1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsPositiveUseMinStartLengthIfDeletecountIsPositiveUseMinDeletecountLengthStart()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.1_T1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsPositiveUseMinStartLengthIfDeletecountIsPositiveUseMinDeletecountLengthStart2()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.1_T2.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsPositiveUseMinStartLengthIfDeletecountIsPositiveUseMinDeletecountLengthStart3()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.1_T3.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsPositiveUseMinStartLengthIfDeletecountIsPositiveUseMinDeletecountLengthStart4()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.1_T4.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsPositiveUseMinStartLengthIfDeletecountIsPositiveUseMinDeletecountLengthStart5()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.1_T5.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsPositiveUseMinStartLengthIfDeletecountIsPositiveUseMinDeletecountLengthStart6()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.1_T6.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsNegativeUseMaxStartLength0IfDeletecountIsNegativeUse0()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.2_T1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsNegativeUseMaxStartLength0IfDeletecountIsNegativeUse02()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.2_T2.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsNegativeUseMaxStartLength0IfDeletecountIsNegativeUse03()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.2_T3.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsNegativeUseMaxStartLength0IfDeletecountIsNegativeUse04()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.2_T4.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsNegativeUseMaxStartLength0IfDeletecountIsNegativeUse05()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.2_T5.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsPositiveUseMinStartLengthIfDeletecountIsNegativeUse0()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.3_T1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsPositiveUseMinStartLengthIfDeletecountIsNegativeUse02()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.3_T2.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsPositiveUseMinStartLengthIfDeletecountIsNegativeUse03()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.3_T3.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsPositiveUseMinStartLengthIfDeletecountIsNegativeUse04()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.3_T4.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsPositiveUseMinStartLengthIfDeletecountIsNegativeUse05()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.3_T5.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsNegativeUseMaxStartLength0IfDeletecountIsPositiveUseMinDeletecountLengthStart()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.4_T1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsNegativeUseMaxStartLength0IfDeletecountIsPositiveUseMinDeletecountLengthStart2()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.4_T2.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsNegativeUseMaxStartLength0IfDeletecountIsPositiveUseMinDeletecountLengthStart3()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.4_T3.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsNegativeUseMaxStartLength0IfDeletecountIsPositiveUseMinDeletecountLengthStart4()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.4_T4.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsNegativeUseMaxStartLength0IfDeletecountIsPositiveUseMinDeletecountLengthStart5()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.4_T5.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void IfStartIsNegativeUseMaxStartLength0IfDeletecountIsPositiveUseMinDeletecountLengthStart6()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.4_T6.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void SpliceWithUndefinedArguments()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.5_T1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void SpliceWithUndefinedArguments2()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A1.5_T2.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void OperatorUseTointegerFromStart()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2.1_T1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void OperatorUseTointegerFromStart2()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2.1_T2.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void OperatorUseTointegerFromStart3()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2.1_T3.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void OperatorUseTointegerFromStart4()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2.1_T4.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void OperatorUseTointegerFromStart5()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2.1_T5.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void OperatorUseTointegerFromDeletecount()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2.2_T1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void OperatorUseTointegerFromDeletecount2()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2.2_T2.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void OperatorUseTointegerFromDeletecount3()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2.2_T3.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void OperatorUseTointegerFromDeletecount4()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2.2_T4.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void OperatorUseTointegerFromDeletecount5()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2.2_T5.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void TheSpliceFunctionIsIntentionallyGenericItDoesNotRequireThatItsThisValueBeAnArrayObject()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2_T1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void TheSpliceFunctionIsIntentionallyGenericItDoesNotRequireThatItsThisValueBeAnArrayObject2()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2_T2.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void TheSpliceFunctionIsIntentionallyGenericItDoesNotRequireThatItsThisValueBeAnArrayObject3()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2_T3.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void TheSpliceFunctionIsIntentionallyGenericItDoesNotRequireThatItsThisValueBeAnArrayObject4()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A2_T4.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void CheckTouint32LengthForNonArrayObjects()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A3_T1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void CheckTouint32LengthForNonArrayObjects2()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A3_T2.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void CheckTouint32LengthForNonArrayObjects3()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A3_T3.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void GetFromNotAnInheritedProperty()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A4_T1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void GetFromNotAnInheritedProperty2()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A4_T2.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void GetFromNotAnInheritedProperty3()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A4_T3.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void TheLengthPropertyOfSpliceHasTheAttributeDontenum()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A5.1.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void TheLengthPropertyOfSpliceHasTheAttributeDontdelete()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A5.2.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void TheLengthPropertyOfSpliceHasTheAttributeReadonly()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A5.3.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void TheLengthPropertyOfSpliceIs2()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A5.4.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void TheSplicePropertyOfArrayHasTheAttributeDontenum()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A5.5.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void TheSplicePropertyOfArrayHasNotPrototypeProperty()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A5.6.js", false);
}
[Fact]
[Trait("Category", "15.4.4.12")]
public void TheSplicePropertyOfArrayCanTBeUsedAsConstructor()
{
RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A5.7.js", false);
}
}
}
| |
//
// System.Messaging.MessageQueuePermission.cs
//
// Authors:
// Peter Van Isacker (sclytrack@planetinternet.be)
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Peter Van Isacker
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Globalization;
using System.Security;
using System.Security.Permissions;
namespace System.Messaging {
[Serializable]
public sealed class MessageQueuePermission: CodeAccessPermission, IUnrestrictedPermission {
private const int version = 1;
private MessageQueuePermissionEntryCollection _list;
private bool _unrestricted;
public MessageQueuePermission ()
{
_list = new MessageQueuePermissionEntryCollection (this);
}
public MessageQueuePermission (MessageQueuePermissionEntry[] permissionAccessEntries)
: this ()
{
foreach (MessageQueuePermissionEntry entry in permissionAccessEntries)
_list.Add (entry);
}
public MessageQueuePermission (PermissionState state)
: this ()
{
_unrestricted = (state == PermissionState.Unrestricted);
}
public MessageQueuePermission (MessageQueuePermissionAccess permissionAccess, string path)
: this ()
{
MessageQueuePermissionEntry entry = new MessageQueuePermissionEntry (permissionAccess, path);
_list.Add (entry);
}
public MessageQueuePermission (MessageQueuePermissionAccess permissionAccess,
string machineName, string label, string category) : this ()
{
MessageQueuePermissionEntry entry = new MessageQueuePermissionEntry (permissionAccess, machineName, label, category);
_list.Add (entry);
}
public MessageQueuePermissionEntryCollection PermissionEntries {
get { return _list; }
}
public override IPermission Copy ()
{
if (_unrestricted)
return new MessageQueuePermission (PermissionState.Unrestricted);
else {
MessageQueuePermission copy = new MessageQueuePermission (PermissionState.None);
foreach (MessageQueuePermissionEntry entry in _list)
copy._list.Add (entry);
return copy;
}
}
public bool IsUnrestricted ()
{
return _unrestricted;
}
[MonoTODO]
public override void FromXml (SecurityElement securityElement)
{
CheckSecurityElement (securityElement, "securityElement", version, version);
// Note: we do not (yet) care about the return value
// as we only accept version 1 (min/max values)
_unrestricted = (IsUnrestricted (securityElement));
// TODO read elements
}
[MonoTODO]
public override IPermission Intersect (IPermission target)
{
MessageQueuePermission mqp = Cast (target);
return null;
}
[MonoTODO]
public override bool IsSubsetOf (IPermission target)
{
MessageQueuePermission mqp = Cast (target);
return false;
}
[MonoTODO]
public override SecurityElement ToXml ()
{
SecurityElement se = Element (version);
if (_unrestricted)
se.AddAttribute ("Unrestricted", "true");
else {
// TODO
}
return se;
}
[MonoTODO]
public override IPermission Union (IPermission target)
{
MessageQueuePermission mqp = Cast (target);
return null;
}
// helpers
private bool IsEmpty ()
{
return (!_unrestricted && (_list.Count == 0));
}
private MessageQueuePermission Cast (IPermission target)
{
if (target == null)
return null;
MessageQueuePermission mqp = (target as MessageQueuePermission);
if (mqp == null) {
ThrowInvalidPermission (target, typeof (MessageQueuePermission));
}
return mqp;
}
// static helpers
private static char[] invalidChars = new char[] { '\t', '\n', '\v', '\f', '\r', ' ', '\\', '\x160' };
internal static void ValidateMachineName (string name)
{
// FIXME: maybe other checks are required (but not documented)
if ((name == null) || (name.Length == 0) || (name.IndexOfAny (invalidChars) != -1)) {
string msg = Locale.GetText ("Invalid machine name '{0}'.");
if (name == null)
name = "(null)";
msg = String.Format (msg, name);
throw new ArgumentException (msg, "MachineName");
}
}
internal static void ValidatePath (string path)
{
// FIXME: maybe other checks are required (but not documented)
if ((path.Length > 0) && (path [0] != '\\')) {
string msg = Locale.GetText ("Invalid path '{0}'.");
throw new ArgumentException (String.Format (msg, path), "Path");
}
}
// NOTE: The following static methods should be moved out to a (static?) class
// if (ever) System.Drawing.dll gets more than one permission in it's assembly.
// snippet moved from FileIOPermission (nickd) to be reused in all derived classes
internal SecurityElement Element (int version)
{
SecurityElement se = new SecurityElement ("IPermission");
Type type = this.GetType ();
se.AddAttribute ("class", type.FullName + ", " + type.Assembly.ToString ().Replace ('\"', '\''));
se.AddAttribute ("version", version.ToString ());
return se;
}
internal static PermissionState CheckPermissionState (PermissionState state, bool allowUnrestricted)
{
string msg;
switch (state) {
case PermissionState.None:
break;
case PermissionState.Unrestricted:
if (!allowUnrestricted) {
msg = Locale.GetText ("Unrestricted isn't not allowed for identity permissions.");
throw new ArgumentException (msg, "state");
}
break;
default:
msg = String.Format (Locale.GetText ("Invalid enum {0}"), state);
throw new ArgumentException (msg, "state");
}
return state;
}
// logic isn't identical to CodeAccessPermission.CheckSecurityElement - see unit tests
internal static int CheckSecurityElement (SecurityElement se, string parameterName, int minimumVersion, int maximumVersion)
{
if (se == null)
throw new ArgumentNullException (parameterName);
if (se.Attribute ("class") == null) {
string msg = Locale.GetText ("Missing 'class' attribute.");
throw new ArgumentException (msg, parameterName);
}
// we assume minimum version if no version number is supplied
int version = minimumVersion;
string v = se.Attribute ("version");
if (v != null) {
try {
version = Int32.Parse (v);
}
catch (Exception e) {
string msg = Locale.GetText ("Couldn't parse version from '{0}'.");
msg = String.Format (msg, v);
throw new ArgumentException (msg, parameterName, e);
}
}
if ((version < minimumVersion) || (version > maximumVersion)) {
string msg = Locale.GetText ("Unknown version '{0}', expected versions between ['{1}','{2}'].");
msg = String.Format (msg, version, minimumVersion, maximumVersion);
throw new ArgumentException (msg, parameterName);
}
return version;
}
// must be called after CheckSecurityElement (i.e. se != null)
internal static bool IsUnrestricted (SecurityElement se)
{
string value = se.Attribute ("Unrestricted");
if (value == null)
return false;
return (String.Compare (value, Boolean.TrueString, true, CultureInfo.InvariantCulture) == 0);
}
internal static void ThrowInvalidPermission (IPermission target, Type expected)
{
string msg = Locale.GetText ("Invalid permission type '{0}', expected type '{1}'.");
msg = String.Format (msg, target.GetType (), expected);
throw new ArgumentException (msg, "target");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Sqloogle.Libs.DBDiff.Schema.Model;
using Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Model.Interfaces;
using Sqloogle.Libs.NLog;
namespace Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Model
{
public class UserDataType : SQLServerSchemaBase
{
private readonly Logger _logger = LogManager.GetLogger("DbDiff");
public UserDataType(ISchemaBase parent)
: base(parent, Enums.ObjectType.UserDataType)
{
Default = new Default(this);
Rule = new Rule(this);
Dependencys = new List<ObjectDependency>();
}
public List<ObjectDependency> Dependencys { get; private set; }
public Rule Rule { get; private set; }
public Default Default { get; private set; }
public string AssemblyName { get; set; }
public Boolean IsAssembly { get; set; }
public string AssemblyClass { get; set; }
public int AssemblyId { get; set; }
/// <summary>
/// Cantidad de digitos que permite el campo (solo para campos Numeric).
/// </summary>
public int Scale { get; set; }
/// <summary>
/// Cantidad de decimales que permite el campo (solo para campos Numeric).
/// </summary>
public int Precision { get; set; }
public Boolean AllowNull { get; set; }
public int Size { get; set; }
public string Type { get; set; }
public String AssemblyFullName
{
get
{
if (IsAssembly)
return AssemblyName + "." + AssemblyClass;
return "";
}
}
/// <summary>
/// Clona el objeto Column en una nueva instancia.
/// </summary>
public override ISchemaBase Clone(ISchemaBase parent)
{
var item = new UserDataType(parent)
{
Name = Name,
Id = Id,
Owner = Owner,
Guid = Guid,
AllowNull = AllowNull,
Precision = Precision,
Scale = Scale,
Size = Size,
Type = Type,
Default = Default.Clone(this),
Rule = Rule.Clone(this),
Dependencys = Dependencys,
IsAssembly = IsAssembly,
AssemblyClass = AssemblyClass,
AssemblyId = AssemblyId,
AssemblyName = AssemblyName
};
return item;
}
public static Boolean CompareRule(UserDataType origen, UserDataType destino)
{
if (destino == null) throw new ArgumentNullException("destino");
if (origen == null) throw new ArgumentNullException("origen");
if ((origen.Rule.Name != null) && (destino.Rule.Name == null)) return false;
if ((origen.Rule.Name == null) && (destino.Rule.Name != null)) return false;
if (origen.Rule.Name != null)
if (!origen.Rule.Name.Equals(destino.Rule.Name)) return false;
return true;
}
public static Boolean CompareDefault(UserDataType origen, UserDataType destino)
{
if (destino == null) throw new ArgumentNullException("destino");
if (origen == null) throw new ArgumentNullException("origen");
if ((origen.Default.Name != null) && (destino.Default.Name == null)) return false;
if ((origen.Default.Name == null) && (destino.Default.Name != null)) return false;
if (origen.Default.Name != null)
if (!origen.Default.Name.Equals(destino.Default.Name)) return false;
return true;
}
public override string ToSql()
{
string sql = "CREATE TYPE " + FullName;
if (!IsAssembly)
{
sql += " FROM [" + Type + "]";
if (Type.Equals("binary") || Type.Equals("varbinary") || Type.Equals("varchar") || Type.Equals("char") ||
Type.Equals("nchar") || Type.Equals("nvarchar"))
sql += "(" + Size.ToString(CultureInfo.InvariantCulture) + ")";
if (Type.Equals("numeric") || Type.Equals("decimal"))
sql += " (" + Precision.ToString(CultureInfo.InvariantCulture) + "," +
Scale.ToString(CultureInfo.InvariantCulture) + ")";
if (AllowNull)
sql += " NULL";
else
sql += " NOT NULL";
}
else
{
sql += " EXTERNAL NAME [" + AssemblyName + "].[" + AssemblyClass + "]";
}
sql += "\r\nGO\r\n";
return sql + ToSQLAddBinds();
}
public override string ToSqlDrop()
{
return "DROP TYPE " + FullName + "\r\nGO\r\n";
}
public override string ToSqlAdd()
{
return ToSql();
}
private string ToSQLAddBinds()
{
string sql = "";
if (!String.IsNullOrEmpty(Default.Name))
sql += Default.ToSQLAddBind();
if (!String.IsNullOrEmpty(Rule.Name))
sql += Rule.ToSQLAddBind();
return sql;
}
private SQLScriptList RebuildDependencys(Table table)
{
var list = new SQLScriptList();
List<ISchemaBase> items = ((Database) table.Parent).Dependencies.Find(table.Id);
items.ForEach(item =>
{
ISchemaBase realItem = ((Database) table.Parent).Find(item.FullName);
if (realItem.IsCodeType)
list.AddRange(((ICode) realItem).Rebuild());
});
return list;
}
private SQLScriptList ToSQLChangeColumns()
{
var fields = new Hashtable();
var list = new SQLScriptList();
var listDependencys = new SQLScriptList();
if ((Status == Enums.ObjectStatusType.AlterStatus) || (Status == Enums.ObjectStatusType.RebuildStatus))
{
foreach (ObjectDependency dependency in Dependencys)
{
ISchemaBase itemDepens = ((Database) Parent).Find(dependency.Name);
/*Si la dependencia es una funcion o una vista, reconstruye el objecto*/
if (dependency.IsCodeType)
{
if (itemDepens != null)
list.AddRange(((ICode) itemDepens).Rebuild());
}
/*Si la dependencia es una tabla, reconstruye los indices, constraint y columnas asociadas*/
if (dependency.Type == Enums.ObjectType.Table)
{
Column column = ((Table) itemDepens).Columns[dependency.ColumnName];
if ((column.Parent.Status != Enums.ObjectStatusType.DropStatus) &&
(column.Parent.Status != Enums.ObjectStatusType.CreateStatus) &&
((column.Status != Enums.ObjectStatusType.CreateStatus) || (column.IsComputed)))
{
if (!fields.ContainsKey(column.FullName))
{
listDependencys.AddRange(RebuildDependencys((Table) itemDepens));
if (column.HasToRebuildOnlyConstraint)
//column.Parent.Status = Enums.ObjectStatusType.AlterRebuildDependenciesStatus;
list.AddRange(column.RebuildDependencies());
if (!column.IsComputed)
{
list.AddRange(column.RebuildConstraint(true));
list.Add(
"ALTER TABLE " + column.Parent.FullName + " ALTER COLUMN " +
column.ToSQLRedefine(Type, Size, null) + "\r\nGO\r\n", 0,
Enums.ScripActionType.AlterColumn);
/*Si la columna va a ser eliminada o la tabla va a ser reconstruida, no restaura la columna*/
if ((column.Status != Enums.ObjectStatusType.DropStatus) &&
(column.Parent.Status != Enums.ObjectStatusType.RebuildStatus))
list.AddRange(column.Alter(Enums.ScripActionType.AlterColumnRestore));
}
else
{
if (column.Status != Enums.ObjectStatusType.CreateStatus)
{
if (!column.GetWasInsertInDiffList(Enums.ScripActionType.AlterColumnFormula))
{
column.SetWasInsertInDiffList(Enums.ScripActionType.AlterColumnFormula);
list.Add(column.ToSqlDrop(), 0, Enums.ScripActionType.AlterColumnFormula);
List<ISchemaBase> drops =
((Database) column.Parent.Parent).Dependencies.Find(column.Parent.Id,
column.Id, 0);
drops.ForEach(item =>
{
if (item.Status != Enums.ObjectStatusType.CreateStatus)
list.Add(item.Drop());
if (item.Status != Enums.ObjectStatusType.DropStatus)
list.Add(item.Create());
});
/*Si la columna va a ser eliminada o la tabla va a ser reconstruida, no restaura la columna*/
if ((column.Status != Enums.ObjectStatusType.DropStatus) &&
(column.Parent.Status != Enums.ObjectStatusType.RebuildStatus))
list.Add(column.ToSqlAdd(), 0,
Enums.ScripActionType.AlterColumnFormulaRestore);
}
}
}
fields.Add(column.FullName, column.FullName);
}
}
}
}
}
list.AddRange(listDependencys);
return list;
}
private Boolean HasAnotherUDTClass()
{
if (IsAssembly)
{
/*Si existe otro UDT con el mismo assembly que se va a crear, debe ser borrado ANTES de crearse el nuevo*/
UserDataType other =
((Database) Parent).UserTypes.Find(
item =>
(item.Status == Enums.ObjectStatusType.DropStatus) &&
(item.AssemblyName + "." + item.AssemblyClass).Equals((AssemblyName + "." + AssemblyClass)));
if (other != null)
return true;
}
return false;
}
private string SQLDropOlder()
{
UserDataType other =
((Database) Parent).UserTypes.Find(
item =>
(item.Status == Enums.ObjectStatusType.DropStatus) &&
(item.AssemblyName + "." + item.AssemblyClass).Equals((AssemblyName + "." + AssemblyClass)));
return other.ToSqlDrop();
}
public override SQLScript Create()
{
Enums.ScripActionType action = Enums.ScripActionType.AddUserDataType;
if (!GetWasInsertInDiffList(action))
{
SetWasInsertInDiffList(action);
return new SQLScript(ToSqlAdd(), 0, action);
}
else
return null;
}
public override SQLScript Drop()
{
const Enums.ScripActionType action = Enums.ScripActionType.DropUserDataType;
if (!GetWasInsertInDiffList(action))
{
SetWasInsertInDiffList(action);
return new SQLScript(ToSqlDrop(), 0, action);
}
return null;
}
public override SQLScriptList ToSqlDiff()
{
try
{
var list = new SQLScriptList();
if (Status == Enums.ObjectStatusType.DropStatus)
{
if (!HasAnotherUDTClass())
list.Add(Drop());
}
if (HasState(Enums.ObjectStatusType.CreateStatus))
{
list.Add(Create());
}
if (Status == Enums.ObjectStatusType.AlterStatus)
{
if (Default.Status == Enums.ObjectStatusType.CreateStatus)
list.Add(Default.ToSQLAddBind(), 0, Enums.ScripActionType.AddUserDataType);
if (Default.Status == Enums.ObjectStatusType.DropStatus)
list.Add(Default.ToSQLAddUnBind(), 0, Enums.ScripActionType.UnbindRuleType);
if (Rule.Status == Enums.ObjectStatusType.CreateStatus)
list.Add(Rule.ToSQLAddBind(), 0, Enums.ScripActionType.AddUserDataType);
if (Rule.Status == Enums.ObjectStatusType.DropStatus)
list.Add(Rule.ToSQLAddUnBind(), 0, Enums.ScripActionType.UnbindRuleType);
}
if (Status == Enums.ObjectStatusType.RebuildStatus)
{
list.AddRange(ToSQLChangeColumns());
if (!GetWasInsertInDiffList(Enums.ScripActionType.DropUserDataType))
{
list.Add(ToSqlDrop() + ToSql(), 0, Enums.ScripActionType.AddUserDataType);
}
else
list.Add(Create());
}
if (HasState(Enums.ObjectStatusType.DropOlderStatus))
{
list.Add(SQLDropOlder(), 0, Enums.ScripActionType.AddUserDataType);
}
return list;
}
catch (Exception ex)
{
_logger.ErrorException(ex.Message, ex);
return null;
}
}
public bool Compare(UserDataType obj)
{
if (obj == null) throw new ArgumentNullException("obj");
if (Scale != obj.Scale) return false;
if (Precision != obj.Precision) return false;
if (AllowNull != obj.AllowNull) return false;
if (Size != obj.Size) return false;
if (!Type.Equals(obj.Type)) return false;
if (IsAssembly != obj.IsAssembly) return false;
if (!AssemblyClass.Equals(obj.AssemblyClass)) return false;
if (!AssemblyName.Equals(obj.AssemblyName)) return false;
if (!CompareDefault(this, obj)) return false;
if (!CompareRule(this, obj)) return false;
return true;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using ovrBool = System.Byte;
using ovrTextureSwapChain = System.IntPtr;
namespace Oculus
{
public enum Result : Int32
{
#region Successful results.
/// <summary>
/// This is a general success result.
/// </summary>
Success = 0,
/// <summary>
/// Returned from a call to SubmitFrame. The call succeeded, but what the app
/// rendered will not be visible on the HMD. Ideally the app should continue
/// calling SubmitFrame, but not do any rendering. When the result becomes
/// ovrSuccess, rendering should continue as usual.
/// </summary>
SuccessNotVisible = 1000,
SuccessBoundaryInvalid = 1001, ///< Boundary is invalid due to sensor change or was not setup.
SuccessDeviceUnavailable = 1002, ///< Device is not available for the requested operation.
#endregion
#region General errors
/* General errors */
MemoryAllocationFailure = -1000, ///< Failure to allocate memory.
InvalidSession = -1002, ///< Invalid ovrSession parameter provided.
Timeout = -1003, ///< The operation timed out.
NotInitialized = -1004, ///< The system or component has not been initialized.
InvalidParameter = -1005, ///< Invalid parameter provided. See error info or log for details.
ServiceError = -1006, ///< Generic service error. See error info or log for details.
NoHmd = -1007, ///< The given HMD doesn't exist.
Unsupported = -1009, ///< Function call is not supported on this hardware/software
DeviceUnavailable = -1010, ///< Specified device type isn't available.
InvalidHeadsetOrientation = -1011, ///< The headset was in an invalid orientation for the requested operation (e.g. vertically oriented during ovr_RecenterPose).
ClientSkippedDestroy = -1012, ///< The client failed to call ovr_Destroy on an active session before calling ovr_Shutdown. Or the client crashed.
ClientSkippedShutdown = -1013, ///< The client failed to call ovr_Shutdown or the client crashed.
ServiceDeadlockDetected = -1014, ///< The service watchdog discovered a deadlock.
InvalidOperation = -1015, ///< Function call is invalid for object's current state
/* Audio error range, reserved for Audio errors. */
AudioDeviceNotFound = -2001, ///< Failure to find the specified audio device.
AudioComError = -2002, ///< Generic COM error.
/* Initialization errors. */
Initialize = -3000, ///< Generic initialization error.
LibLoad = -3001, ///< Couldn't load LibOVRRT.
LibVersion = -3002, ///< LibOVRRT version incompatibility.
ServiceConnection = -3003, ///< Couldn't connect to the OVR Service.
ServiceVersion = -3004, ///< OVR Service version incompatibility.
IncompatibleOS = -3005, ///< The operating system version is incompatible.
DisplayInit = -3006, ///< Unable to initialize the HMD display.
ServerStart = -3007, ///< Unable to start the server. Is it already running?
Reinitialization = -3008, ///< Attempting to re-initialize with a different version.
MismatchedAdapters = -3009, ///< Chosen rendering adapters between client and service do not match
LeakingResources = -3010, ///< Calling application has leaked resources
ClientVersion = -3011, ///< Client version too old to connect to service
OutOfDateOS = -3012, ///< The operating system is out of date.
OutOfDateGfxDriver = -3013, ///< The graphics driver is out of date.
IncompatibleGPU = -3014, ///< The graphics hardware is not supported
NoValidVRDisplaySystem = -3015, ///< No valid VR display system found.
Obsolete = -3016, ///< Feature or API is obsolete and no longer supported.
DisabledOrDefaultAdapter = -3017, ///< No supported VR display system found, but disabled or driverless adapter found.
HybridGraphicsNotSupported = -3018, ///< The system is using hybrid graphics (Optimus, etc...), which is not support.
DisplayManagerInit = -3019, ///< Initialization of the DisplayManager failed.
TrackerDriverInit = -3020, ///< Failed to get the interface for an attached tracker
LibSignCheck = -3021, ///< LibOVRRT signature check failure.
LibPath = -3022, ///< LibOVRRT path failure.
LibSymbols = -3023, ///< LibOVRRT symbol resolution failure.
RemoteSession = -3024, ///< Failed to connect to the service because remote connections to the service are not allowed.
/* Rendering errors */
DisplayLost = -6000, ///< In the event of a system-wide graphics reset or cable unplug this is returned to the app.
TextureSwapChainFull = -6001, ///< ovr_CommitTextureSwapChain was called too many times on a texture swapchain without calling submit to use the chain.
TextureSwapChainInvalid = -6002, ///< The ovrTextureSwapChain is in an incomplete or inconsistent state. Ensure ovr_CommitTextureSwapChain was called at least once first.
GraphicsDeviceReset = -6003, ///< Graphics device has been reset (TDR, etc...)
DisplayRemoved = -6004, ///< HMD removed from the display adapter
ContentProtectionNotAvailable = -6005,///<Content protection is not available for the display
ApplicationInvisible = -6006, ///< Application declared itself as an invisible type and is not allowed to submit frames.
Disallowed = -6007, ///< The given request is disallowed under the current conditions.
DisplayPluggedIncorrectly = -6008, ///< Display portion of HMD is plugged into an incompatible port (ex: IGP)
/* Fatal errors */
RuntimeException = -7000, ///< A runtime exception occurred. The application is required to shutdown LibOVR and re-initialize it before this error state will be cleared.
/* Calibration errors */
NoCalibration = -9000, ///< Result of a missing calibration block
OldVersion = -9001, ///< Result of an old calibration block
MisformattedBlock = -9002, ///< Result of a bad calibration block due to lengths
#endregion
}
#region Flags
/// <summary>
/// Enumerates all HMD types that we support.
/// </summary>
public enum HmdType : UInt32
{
None = 0,
DK1 = 3,
DKHD = 4,
DK2 = 6,
CB = 8,
Other = 9,
E3_2015 = 10,
ES06 = 11,
ES09 = 12,
ES11 = 13,
CV1 = 14,
}
/// <summary>
/// HMD capability bits reported by device.
/// </summary>
public enum HmdCaps :UInt32
{
/// <summary>
/// No flags.
/// </summary>
None = 0x0000,
// Read only flags
/// <summary>
/// Means HMD device is a virtual debug device.
/// </summary>
/// <remarks>
/// (read only)
/// </remarks>
DebugDevice = 0x0010,
}
/// <summary>
/// Tracking capability bits reported by the device.
/// Used with ovr_GetTrackingCaps.
/// </summary>
[Flags]
public enum TrackingCaps : UInt32
{
/// <summary>
/// Supports orientation tracking (IMU).
/// </summary>
Orientation = 0x0010,
/// <summary>
/// Supports yaw drift correction via a magnetometer or other means.
/// </summary>
MagYawCorrection = 0x0020,
/// <summary>
/// Supports positional tracking.
/// </summary>
Position = 0x0040,
}
/// <summary>
/// Specifies which eye is being used for rendering.
/// This type explicitly does not include a third "NoStereo" option, as such is
/// not required for an HMD-centered API.
/// </summary>
public enum EyeType : UInt32
{
Left = 0,
Right = 1,
Count = 2
}
/// <summary>
/// Specifies the coordinate system TrackingState returns tracking poses in.
/// Used with ovr_SetTrackingOriginType()
/// </summary>
public enum TrackingOrigin :UInt32
{
/// <summary>
/// Tracking system origin reported at eye (HMD) height
///
/// Prefer using this origin when your application requires
/// matching user's current physical head pose to a virtual head pose
/// without any regards to a the height of the floor. Cockpit-based,
/// or 3rd-person experiences are ideal candidates.
///
/// When used, all poses in TrackingState are reported as an offset
/// transform from the profile calibrated or recentered HMD pose.
/// It is recommended that apps using this origin type call ovr_RecenterTrackingOrigin
/// prior to starting the VR experience, but notify the user before doing so
/// to make sure the user is in a comfortable pose, facing a comfortable
/// direction.
/// </summary>
EyeLevel = 0,
/// <summary>
/// Tracking system origin reported at floor height
///
/// Prefer using this origin when your application requires the
/// physical floor height to match the virtual floor height, such as
/// standing experiences.
///
/// When used, all poses in TrackingState are reported as an offset
/// transform from the profile calibrated floor pose. Calling ovr_RecenterTrackingOrigin
/// will recenter the X & Z axes as well as yaw, but the Y-axis (i.e. height) will continue
/// to be reported using the floor height as the origin for all poses.
/// </summary>
FloorLevel = 1,
/// <summary>
/// Count of enumerated elements.
/// </summary>
Count = 2,
}
/// <summary>
/// Bit flags describing the current status of sensor tracking.
/// The values must be the same as in enum StatusBits
/// </summary>
/// <see cref="TrackingState"/>
[Flags]
public enum StatusBits : UInt32
{
/// <summary>
/// No flags.
/// </summary>
None = 0x0000,
/// <summary>
/// Orientation is currently tracked (connected and in use).
/// </summary>
OrientationTracked = 0x0001,
/// <summary>
/// Position is currently tracked (false if out of range).
/// </summary>
PositionTracked = 0x0002,
}
/// <summary>
/// Specifies sensor flags.
/// </summary>
/// <see cref="TrackerPose"/>
[Flags]
public enum TrackerFlags : UInt32
{
/// <summary>
/// The sensor is present, else the sensor is absent or offline.
/// </summary>
Connected = 0x0020,
/// <summary>
/// The sensor has a valid pose, else the pose is unavailable.
/// This will only be set if TrackerFlags.Connected is set.
/// </summary>
PoseTracked = 0x0004,
}
/// <summary>
/// The type of texture resource.
/// </summary>
/// <see cref="TextureSwapChainDesc"/>
public enum TextureType : UInt32
{
/// <summary>
/// 2D textures.
/// </summary>
Texture2D,
/// <summary>
/// External 2D texture.
///
/// Not used on PC.
/// </summary>
Texture2DExternal,
/// <summary>
/// Cube maps.
///
/// Not currently supported on PC.
/// </summary>
TextureCube,
/// <summary>
/// Undocumented.
/// </summary>
TextureCount,
}
/// <summary>
/// The bindings required for texture swap chain.
///
/// All texture swap chains are automatically bindable as shader
/// input resources since the Oculus runtime needs this to read them.
/// </summary>
/// <see cref="TextureSwapChainDesc"/>
[Flags]
public enum TextureBindFlags : UInt32
{
None,
/// <summary>
/// The application can write into the chain with pixel shader.
/// </summary>
DX_RenderTarget = 0x0001,
/// <summary>
/// The application can write to the chain with compute shader.
/// </summary>
DX_UnorderedAccess = 0x0002,
/// <summary>
/// The chain buffers can be bound as depth and/or stencil buffers.
/// </summary>
DX_DepthStencil = 0x0004,
}
/// <summary>
/// The format of a texture.
/// </summary>
/// <see cref="TextureSwapChainDesc"/>
public enum TextureFormat : UInt32
{
UNKNOWN = 0,
/// <summary>
/// Not currently supported on PC. Would require a DirectX 11.1 device.
/// </summary>
B5G6R5_UNORM = 1,
/// <summary>
/// Not currently supported on PC. Would require a DirectX 11.1 device.
/// </summary>
B5G5R5A1_UNORM = 2,
/// <summary>
/// Not currently supported on PC. Would require a DirectX 11.1 device.
/// </summary>
B4G4R4A4_UNORM = 3,
R8G8B8A8_UNORM = 4,
R8G8B8A8_UNORM_SRGB = 5,
B8G8R8A8_UNORM = 6,
/// <summary>
/// Not supported for OpenGL applications
/// </summary>
B8G8R8A8_UNORM_SRGB = 7,
/// <summary>
/// Not supported for OpenGL applications
/// </summary>
B8G8R8X8_UNORM = 8,
/// <summary>
/// Not supported for OpenGL applications
/// </summary>
B8G8R8X8_UNORM_SRGB = 9,
R16G16B16A16_FLOAT = 10,
R11G11B10_FLOAT = 25,
// Depth formats
D16_UNORM = 11,
D24_UNORM_S8_UINT = 12,
D32_FLOAT = 13,
D32_FLOAT_S8X24_UINT =14,
// Added in 1.5 compressed formats can be used for static layers
BC1_UNORM = 15,
BC1_UNORM_SRGB = 16,
BC2_UNORM = 17,
BC2_UNROM_SRGB = 18,
BC3_UNORM = 19,
BC3_UNORM_SRGB = 20,
BC6H_UF16 = 21,
BC6H_SF16 = 22,
BC7_UNORM = 23,
BC7_UNORM_SRGB = 24
}
/// <summary>
/// Misc flags overriding particular behaviors of a texture swap chain
/// </summary>
/// <see cref="TextureSwapChainDesc"/>
[Flags]
public enum TextureMiscFlags : UInt32
{
None = 0,
/// <summary>
/// DX only: The underlying texture is created with a TYPELESS equivalent of the
/// format specified in the texture desc. The SDK will still access the
/// texture using the format specified in the texture desc, but the app can
/// create views with different formats if this is specified.
/// </summary>
DX_Typeless = 0x0001,
/// <summary>
/// DX only: Allow generation of the mip chain on the GPU via the GenerateMips
/// call. This flag requires that RenderTarget binding also be specified.
/// </summary>
AllowGenerateMips = 0x0002,
/// Texture swap chain contains protected content, and requires
/// HDCP connection in order to display to HMD. Also prevents
/// mirroring or other redirection of any frame containing this contents
ProtectedContent = 0x0004
}
/// <summary>
/// Describes button input types.
/// Button inputs are combined; that is they will be reported as pressed if they are
/// pressed on either one of the two devices.
/// The ovrButton_Up/Down/Left/Right map to both XBox D-Pad and directional buttons.
/// The ovrButton_Enter and ovrButton_Return map to Start and Back controller buttons, respectively.
/// </summary>
[Flags]
public enum Button : UInt32
{
A = 0x00000001,
B = 0x00000002,
RThumb = 0x00000004,
RShoulder = 0x00000008,
/// <summary>
/// Bit mask of all buttons on the right Touch controller
/// </summary>
RMask = A | B | RThumb | RShoulder,
X = 0x00000100,
Y = 0x00000200,
LThumb = 0x00000400,
LShoulder = 0x00000800,
/// <summary>
/// Bit mask of all buttons on the left Touch controller
/// </summary>
LMask = X | Y | LThumb | LShoulder,
// Navigation through DPad.
Up = 0x00010000,
Down = 0x00020000,
Left = 0x00040000,
Right = 0x00080000,
/// <summary>
/// Start on XBox controller.
/// </summary>
Enter = 0x00100000,
/// <summary>
/// Back on Xbox controller.
/// </summary>
Back = 0x00200000,
/// <summary>
/// Only supported by Remote.
/// </summary>
VolUp = 0x00400000,
/// <summary>
/// Only supported by Remote.
/// </summary>
VolDown = 0x00800000,
Home = 0x01000000,
Private = VolUp | VolDown | Home,
}
/// <summary>
/// Describes touch input types.
/// These values map to capacitive touch values reported ovrInputState::Touch.
/// Some of these values are mapped to button bits for consistency.
/// </summary>
[Flags]
public enum Touch : UInt32
{
A = Button.A,
B = Button.B,
RThumb = Button.RThumb,
RIndexTrigger = 0x00000010,
/// <summary>
/// Bit mask of all the button touches on the right controller
/// </summary>
RButtonMask = A | B | RThumb | RIndexTrigger,
X = Button.X,
Y = Button.Y,
LThumb = Button.LThumb,
LIndexTrigger = 0x00001000,
/// <summary>
/// Bit mask of all the button touches on the left controller
/// </summary>
LButtonMask = X | Y | LThumb | LIndexTrigger,
// Finger pose state
// Derived internally based on distance, proximity to sensors and filtering.
RIndexPointing = 0x00000020,
RThumbUp = 0x00000040,
/// <summary>
/// Bit mask of all right controller poses
/// </summary>
RPoseMask = RIndexPointing | RThumbUp,
LIndexPointing = 0x00002000,
LThumbUp = 0x00004000,
/// <summary>
/// Bit mask of all left controller poses
/// </summary>
LPoseMask = LIndexPointing | LThumbUp,
}
/// <summary>
/// Specifies which controller is connected; multiple can be connected at once.
/// </summary>
[Flags]
public enum ControllerType : UInt32
{
None = 0x00,
LTouch = 0x01,
RTouch = 0x02,
Touch = LTouch | RTouch,
Remote = 0x04,
XBox = 0x10,
Object0 = 0x0100,
Object1 = 0x0200,
Object2 = 0x0400,
Object3 = 0x0800,
/// <summary>
/// Operate on or query whichever controller is active.
/// </summary>
Active = 0xffffffff
}
/// <summary>
/// Haptics buffer submit mode
/// </summary>
[Flags]
public enum HapticsBufferSubmitMode : UInt32
{
Enqueue
}
/// <summary>
/// Position tracked devices
/// </summary>
[Flags]
public enum TrackedDeviceType : UInt32
{
HMD = 0x0001,
LTouch = 0x0002,
RTouch = 0x0004,
Touch = (LTouch | RTouch),
Object0 = 0x0010,
Object1 = 0x0020,
Object2 = 0x0040,
Object3 = 0x0080,
All = 0xFFFF,
}
/// <summary>
/// Boundary types that specified while using the boundary system
/// </summary>
[Flags]
public enum BoundaryType : UInt32
{
Outer = 0x0001,
PlayerArea = 0x0100,
}
/// <summary>
/// Provides names for the left and right hand array indexes.
/// </summary>
/// <see cref="InputState"/>
/// <seealso cref="TrackingState"/>
public enum HandType : UInt32
{
Left = 0,
Right = 1,
Count = 2,
}
[Flags]
public enum CameraStatusFlags : UInt32
{
/// Initial state of camera
None = 0x0,
/// Bit set when the camera is connected to the system
Connected = 0x1,
/// Bit set when the camera is undergoing calibration
Calibrating = 0x2,
/// Bit set when the camera has tried & failed calibration
CalibrationFailed = 0x4,
/// Bit set when the camera has tried & passed calibration
Calibrated = 0x8,
}
[Flags]
public enum InitFlags : UInt32
{
None = 0x0,
/// When a debug library is requested, a slower debugging version of the library will
/// run which can be used to help solve problems in the library and debug application code.
Debug = 0x00000001,
/// When a version is requested, the LibOVR runtime respects the RequestedMinorVersion
/// field and verifies that the RequestedMinorVersion is supported. Normally when you
/// specify this flag you simply use OVR_MINOR_VERSION for ovrInitParams::RequestedMinorVersion,
/// though you could use a lower version than OVR_MINOR_VERSION to specify previous
/// version behavior.
RequestVersion = 0x00000004,
/// This client will not be visible in the HMD.
/// Typically set by diagnostic or debugging utilities.
Invisible = 0x00000010,
/// This client will alternate between VR and 2D rendering.
/// Typically set by game engine editors and VR-enabled web browsers.
MixedRendering = 0x00000020,
/// These bits are writable by user code.
WritableBits = 0x00ffffff,
}
public enum LogLevel : UInt32
{
Debug = 0, ///< Debug-level log event.
Info = 1, ///< Info-level log event.
Error = 2, ///< Error-level log event.
}
/// <summary>
/// Describes layer types that can be passed to ovr_SubmitFrame.
/// Each layer type has an associated struct, such as ovrLayerEyeFov.
/// </summary>
/// <see cref="LayerHeader"/>
public enum LayerType : UInt32
{
/// <summary>
/// Layer is disabled.
/// </summary>
Disabled = 0,
/// <summary>
/// Described by LayerEyeFov.
/// </summary>
EyeFov = 1,
/// <summary>
/// Described by LayerQuad.
///
/// Previously called QuadInWorld.
/// </summary>
Quad = 3,
// enum 4 used to be ovrLayerType_QuadHeadLocked.
// Instead, use ovrLayerType_Quad with ovrLayerFlag_HeadLocked.
/// <summary>
/// Described by LayerEyeMatrix.
/// </summary>
EyeMatrix = 5,
}
/// <summary>
/// Identifies flags used by LayerHeader and which are passed to ovr_SubmitFrame.
/// </summary>
/// <see cref="LayerHeader"/>
[Flags]
public enum LayerFlags : UInt32
{
/// <summary>
/// HighQuality enables 4x anisotropic sampling during the composition of the layer.
/// The benefits are mostly visible at the periphery for high-frequency & high-contrast visuals.
/// For best results consider combining this flag with an ovrTextureSwapChain that has mipmaps and
/// instead of using arbitrary sized textures, prefer texture sizes that are powers-of-two.
/// Actual rendered viewport and doesn't necessarily have to fill the whole texture.
/// </summary>
HighQuality = 0x01,
/// <summary>
/// TextureOriginAtBottomLeft: the opposite is TopLeft.
///
/// Generally this is false for D3D, true for OpenGL.
/// </summary>
TextureOriginAtBottomLeft = 0x02,
/// <summary>
/// Mark this surface as "headlocked", which means it is specified
/// relative to the HMD and moves with it, rather than being specified
/// relative to sensor/torso space and remaining still while the head moves.
///
/// What used to be ovrLayerType_QuadHeadLocked is now LayerType.Quad plus this flag.
/// However the flag can be applied to any layer type to achieve a similar effect.
/// </summary>
HeadLocked = 0x04
}
/// <summary>
/// Performance HUD enables the HMD user to see information critical to
/// the real-time operation of the VR application such as latency timing,
/// and CPU & GPU performance metrics
/// </summary>
/// <example>
/// App can toggle performance HUD modes as such:
///
/// PerfHudMode perfHudMode = PerfHudMode.Hud_LatencyTiming;
/// ovr_SetInt(Hmd, "PerfHudMode", (int) perfHudMode);
/// </example>
public enum PerfHudMode : UInt32
{
Off = 0,
/// <summary>
/// Shows performance summary and headroom
/// </summary>
PerfSummary = 1,
/// <summary>
/// Shows latency related timing info
/// </summary>
LatencyTiming = 2,
/// <summary>
/// Shows render timing info for application
/// </summary>
AppRenderTiming = 3,
/// <summary>
/// Shows render timing info for OVR compositor
/// </summary>
CompRenderTiming = 4,
/// <summary>
/// Shows SDK & HMD version Info
/// </summary>
VersionInfo = 5,
AswStats = 6,
/// <summary>
/// Count of enumerated elements.
/// </summary>
Count = 7
}
/// <summary>
/// Layer HUD enables the HMD user to see information about a layer
/// <example>
/// <code>
/// App can toggle layer HUD modes as such:
/// ovrLayerHudMode LayerHudMode = ovrLayerHud_Info;
/// ovr_SetInt(Hmd, OVR_LAYER_HUD_MODE, (int)LayerHudMode);
/// </code>
/// </example>
/// </summary>
public enum ovrLayerHudMode : UInt32
{
/// <summary>
/// Turns off the layer HUD
/// </summary>
Off = 0,
/// <summary>
/// Shows info about a specific layer
/// </summary>
Info = 1,
}
/// <summary>
/// Debug HUD is provided to help developers gauge and debug the fidelity of their app's
/// stereo rendering characteristics. Using the provided quad and crosshair guides,
/// the developer can verify various aspects such as VR tracking units (e.g. meters),
/// stereo camera-parallax properties (e.g. making sure objects at infinity are rendered
/// with the proper separation), measuring VR geometry sizes and distances and more.
///
/// App can toggle the debug HUD modes as such:
/// \code{.cpp}
/// \endcode
///
/// The app can modify the visual properties of the stereo guide (i.e. quad, crosshair)
/// using the ovr_SetFloatArray function. For a list of tweakable properties,
/// see the OVR_DEBUG_HUD_STEREO_GUIDE_* keys in the OVR_CAPI_Keys.h header file.
/// </summary>
/// <example>
/// ovrDebugHudStereoMode DebugHudMode = ovrDebugHudStereo.QuadWithCrosshair;
/// ovr_SetInt(Hmd, OVR_DEBUG_HUD_STEREO_MODE, (int)DebugHudMode);
/// </example>
public enum DebugHudStereoMode : UInt32
{
/// <summary>
/// Turns off the Stereo Debug HUD
/// </summary>
Off = 0,
/// <summary>
/// Renders Quad in world for Stereo Debugging
/// </summary>
Quad = 1,
/// <summary>
/// Renders Quad+crosshair in world for Stereo Debugging
/// </summary>
QuadWithCrosshair = 2,
/// <summary>
/// Renders screen-space crosshair at infinity for Stereo Debugging
/// </summary>
CrosshairAtInfinity = 3,
/// <summary>
/// Count of enumerated elements
/// </summary>
Count
}
/// <summary>
/// Enumerates modifications to the projection matrix based on the application's needs.
/// </summary>
/// <see cref="OVRBase.Matrix_Projection"/>
public enum ProjectionModifier
{
/// <summary>
/// Use for generating a default projection matrix that is:
/// * Right-handed.
/// * Near depth values stored in the depth buffer are smaller than far depth values.
/// * Both near and far are explicitly defined.
/// * With a clipping range that is (0 to w).
/// </summary>
None = 0x00,
/// <summary>
/// Enable if using left-handed transformations in your application.
/// </summary>
LeftHanded = 0x01,
/// <summary>
/// After the projection transform is applied, far values stored in the depth buffer will be less than closer depth values.
/// NOTE: Enable only if the application is using a floating-point depth buffer for proper precision.
/// </summary>
FarLessThanNear = 0x02,
/// <summary>
/// When this flag is used, the zfar value pushed into ovrMatrix_Projection() will be ignored
/// NOTE: Enable only if ovrProjection_FarLessThanNear is also enabled where the far clipping plane will be pushed to infinity.
/// </summary>
FarClipAtInfinity = 0x04,
/// <summary>
/// Enable if the application is rendering with OpenGL and expects a projection matrix with a clipping range of (-w to w).
/// Ignore this flag if your application already handles the conversion from D3D range (0 to w) to OpenGL.
/// </summary>
ClipRangeOpenGL = 0x08
}
public enum HapticsGenMode
{
PointSample,
Count,
}
#endregion
}
| |
// Copyright 2020 The Tilt Brush Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Newtonsoft.Json;
using System;
using System.Linq;
using UnityEngine;
namespace TiltBrush {
/* metadata.json format changes and additions
== v7.0: Single models introduced
New list added called Models
This list could theoretically contain as many models as the user liked, but we cut it back.
In the wild, this list should only ever be of length zero or one, never null.
"Models": [
{
"FilePath": "C:\\Users\\Person\\Documents\\Tilt Brush\\Models\\Lili.obj",
"Position": [ -6.38644, 12.7471752, 8.778034 ],
"Rotation": [ 0.018738009, -0.861053467, -0.00643645832, -0.5081283 ],
"Scale": [ 0.649798400, 0.649798400, 0.649798400 ]
}
]
== v7.5: Multiple models and images introduced
ModelIndex replaces Models
ImageIndex added
These lists contained one entry for every unique object. Each entry in the list contained
a transform for each instance of the object in the sketch.
Both ModelIndex and ImageIndex can be null, and will never be zero length.
"ImageIndex": [
{
"FileName": "Blue And teal gradient.png",
"AspectRatio": 1.77777779,
"Transforms": [ [ [ 86.13458, 78.30929, 58.5603828 ], [ 0.0259972736, -0.291850924, -0.00451487023, -0.956099868 ], 198.431992 ] ]
}
]
"ModelIndex": [
{
"FilePath": "Media Library\\Models\\3a. limbs 3\\5.obj",
"Transforms": [ [ [ -3.953864, 3.135213, -9.598504 ], [ 0.06734027, 0.287244231, -0.08482468, -0.9517147 ], 1.37809682 ]
]
},
...
]
== v7.5-experimental: Guides introduced
Guides are saved as a list of all models, one tranform per instance.
Their shapes are saved as indices since we can guarantee consistency in those.
"Guides": [
{
"Type": 0,
"Transform": [ [ -3.60909033, 9.355544, -0.7895982 ], [ 0.161795944, 0.100251839, -0.007717509, 0.9816884 ], 2.0 ]
}
]
== v7.5b: Guides updated.
List turned into an index.
Type stored as a string.
Size stored as transform.scale + Custom.
"GuideIndex": [
{
"Type": "Capsule",
"States": [
{
"Transform": [ [ 4.216275, 19.4874744, -0.2948996 ], [ 0.101220131, 0.190763831, -0.1001101, 0.971257746 ], 4 ],
"Custom": [ .5, 2, .5 ]
}
]
}
]
== v8: Guides updated
Extents stored explicitly.
Transform.scale is always 0.
Backwards-compatibility for 7.5b guides (finally removed in v19)
Type accidentally written out in hashed format :-P
"GuideIndex": [
{
"Type": "pmhghhkcdmp",
"States": [
{
"Transform": [ [ 4.216275, 19.4874744, -0.2948996 ], [ 0.101220131, 0.190763831, -0.1001101, 0.971257746 ], 0.0 ],
"Extents": [ 2.50599027, 9.098843, 2.50599027 ]
}
]
},
]
== v8.2: Prepare for fixing Guides.Type
Guides.Type supports human-readable values, although hashed values are still written
== v9.0b: Added initial version of Palette
"Palette": {
"Colors": [
{
"r": 50,
"g": 50,
"b": 230,
"a": 255
}
]
}
== v9.0: Removed Palette from save file until 9.1
== v9.1: Changed Palette format to use alpha-less and more-compact color values
"Palette": { "Entries": [ [ 50, 50, 230, 255 ] ] }
The 9.0b-style "Colors" field is ignored.
The alpha value is preserved when serializing, but will always be 255.
The alpha value is forced to 255 when deserializing.
== v10.0: Added CustomLights and CustomEnvironment to save file
"Environment": {
"GradientColors": [ [ 100, 100, 100, 255 ], [ 60, 64, 90, 255 ]
],
"GradientSkew": [ 0.0, 0.0, 0.0, 1.0 ],
"FogColor": [ 31, 31, 78, 255 ],
"FogDensity": 0.00141058769,
"ReflectionIntensity": 0.3
}
"Lights": {
"Ambient": [ 173, 173, 173, 255 ],
"Shadow": {
"Orientation": [ 0.5, 0.0, 0.0, 0.8660254 ],
"Color": [ 32.0, 31.8180237, 3.81469727E-06, 1.0 ]
},
"NoShadow": {
"Orientation": [ 0.883022249, -0.321393818, 0.116977736, 0.321393818 ],
"Color": [ 0.03125, 0.000550092547, 0.0, 1.0 ]
}
}
The "GradientColors" field of Environment is null if the gradient has not been accessed.
Orientation of lights is stored in scene space.
Colors stored as integer RGB are guaranteed to be LDR. Those as floating point RGB may be HDR.
"SourceId": "abcdefg"
If this sketch is derived from a Poly asset then SourceId is the id of that original asset.
== v12.0: Added Set to save file
The set of a sketch comprises of props (models) that have been brought in unscaled and have
the root pivot placed at the origin.
File paths are relative to the Models directory.
"Set": [
"Andy/Andy.obj",
"Tiltasaurus/Tiltasaurus.obj"
]
== v13.0: Added AssetId to Models
Models can be loaded via AssetId, a lookup value for assets stored in Poly.
FilePath and AssetId should never both be valid, but AssetId is preferred in that errant case.
Transforms are maintained for backward compatability for models. They can be read in but are no
longer written out. RawTransforms replaces it, where the new translation represents the pivot of
the models as specified in the original file instead of the center of the mesh bounds, and the
new scale represents the multiplier on the size of the original mesh instead of the normalization.
M13 was never actually released to the public.
"ModelIndex": [
{
"FilePath": null,
"AssetId": "bzolM7RH0n6",
"InSet": false,
"Transforms": null,
"RawTransforms": [ [ [ -3.953864, 3.135213, -9.598504 ], [ 0.06734027, 0.287244231, -0.08482468, -0.9517147 ], 1.37809682 ]
]
},
If a sketch has been uploaded to Poly we store the asset id so that future uploads can update
the existing asset rather than creating a new one.
Controls for adding a model to a set were hidden behind a flag in M12 and disabled in M14.
== v14.2: Deprecate Set
Models that are in the Set of the v12 metadata will be written out in ModelIndex with InSet = true.
== v15.0: Added Version, PinStates for models, images, and guides, TintStates for images
SchemaVersion = 1
TiltModels75: Added PinStates[] and TintStates[]. Each is a bool[] with the same length as Transforms[].
Files with SchemaVersion < 1 are upgraded to have PinStates and TintStates (both set to true)
...
"PinStates": [
true,
true,
false
],
"TintStates": [
true,
true,
false
],
"Transforms": [ [ [ 2.81081581, 5.47280025, 6.80550051 ], [ -0.0380054265, -0.219284073, 0.00313296262, -0.9749155 ], 2.41691542 ],
[ [ 3.466383, 5.71923733, 6.45537853 ], [ -0.0334184356, -0.237726957, 0.0122604668, -0.9706796 ], 0.800769 ],
[ [ 4.00411844, 5.71402025, 6.12121439 ], [ -0.03800745, -0.354895175, 0.00206097914, -0.9341309 ], 0.760676444 ]
]
...
Guide.State: added bool Pinned.
Files with SchemaVersion < 1 are upgraded with Pinned = true.
== v19.0: Remove Guides.State.Custom, TiltModels75.InSet
Guides.State.Custom only existed in the 7.5b file format, and was never released to the public.
Should have been removed long ago!
InSet is converted to a pinned model with identity transform.
== v22.0: Reference videos added. (TiltVideo[] Videos)
Camera paths added. (CameraPathMetadata[] CameraPaths)
Added GroupIds for TiltModels75, Guides.State, TiltImage75, and TiltVideo.
"CameraPaths": [
{
"PathKnots": [
{
"Xf": [ [ 2.81081581, 5.47280025, 6.80550051 ], [ -0.0380054265, -0.219284073, 0.00313296262, -0.9749155 ], 2.41691542 ],
"Speed": 2.81081581
},
{
...
}
],
"RotationKnots": [
{
"Xf": [ [ 2.81081581, 5.47280025, 6.80550051 ], [ -0.0380054265, -0.219284073, 0.00313296262, -0.9749155 ], 2.41691542 ],
"KnotIndex": 0,
"KnotT": 0.2,
},
{
...
}
"SpeedKnots": [
{
"Xf": [ [ 2.81081581, 5.47280025, 6.80550051 ], [ -0.0380054265, -0.219284073, 0.00313296262, -0.9749155 ], 2.41691542 ],
"KnotIndex": 0,
"KnotT": 0.2,
"Speed": 2.81081581
},
{
...
}
],
},
{
...
}
],
PathKnots, RotationKnots, and SpeedKnots may all have 0 elements. RotationKnots and SpeedKnots
will not have >0 elements if PathKnots has 0 elements.
*/
// From v7.0
[Serializable]
public class TiltModels70 {
/// Absolute path to model. Relative paths are not supported.
public string FilePath { get; set; }
public Vector3 Position { get; set; }
public Quaternion Rotation { get; set; }
public Vector3 Scale { get; set; }
public TiltModels75 Upgrade() {
string relativePath;
try {
relativePath = WidgetManager.GetModelSubpath(FilePath);
} catch (ArgumentException) {
relativePath = null;
}
// I guess keep it around, so we don't lose information.
if (relativePath == null) {
relativePath = FilePath;
}
return new TiltModels75 {
FilePath = relativePath,
PinStates = new[] { true },
Transforms = new[] { TrTransform.TRS(Position, Rotation, Scale.x) }
};
}
}
// Use for v7.5 and on
// Missing models are normally preserved, with these exceptions:
// - lost if a pre-M13 .tilt is saved in M13+
// - InSet models are lost if saved, at least through M18 (b/65633544)
[Serializable]
public class TiltModels75 {
/// Relative path to model from Media Library.
/// e.g. Media Library/Models/subdirectory/model.obj
/// With 14.0 on, this is unused if AssetId is valid.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string FilePath { get; set; }
/// AssetId for Poly.
/// Added in 14.0, this is preferred over FilePath.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string AssetId { get; set; }
// True if showing the untransformed, non-interactable model.
// Added in M13 in 97e210f041e20b87c72c87bafb71d7d399d46c13. Never released to public.
// Turned into RawTransforms in M19.
[JsonProperty(
PropertyName = "InSet", // Used to be called InSet
DefaultValueHandling = DefaultValueHandling.Ignore // Don't write "false" values into the .tilt any more
)]
[System.ComponentModel.DefaultValue(false)]
public bool InSet_deprecated { get; set; }
// True if model should be pinned on load. Added in M15.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public bool[] PinStates { get; set; }
/// Prior to M13, never null or empty; but an empty array is allowed on read.
/// Post M13, always null.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public TrTransform[] Transforms { get; set; }
/// Prior to M13, always null.
/// Post M13, never null or empty; but an empty array is allowed on read.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public TrTransform[] RawTransforms {
get { return m_rawTransforms; }
set { m_rawTransforms = MetadataUtils.Sanitize(value); }
}
// Only for use by MetadataUtils.cs
[JsonIgnore]
public TrTransform[] m_rawTransforms;
/// used to bridge the gap between strict Tilt Brush and not-so-strict json
[JsonIgnore]
public Model.Location Location {
get {
if (AssetId != null) {
return Model.Location.PolyAsset(AssetId, null);
} else if (FilePath != null) {
return Model.Location.File(FilePath);
} else {
return new Model.Location(); // invalid location
}
}
set {
if (value.GetLocationType() == Model.Location.Type.LocalFile) {
FilePath = value.RelativePath;
AssetId = null;
} else if (value.GetLocationType() == Model.Location.Type.PolyAssetId) {
FilePath = null;
AssetId = value.AssetId;
}
}
}
// Group IDs for widgets. 0 for ungrouped items. Added in M22.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public uint[] GroupIds { get; set; }
}
[Serializable]
public class Guides {
// In 8.x we mistakenly wrote out hashed names for these shapes.
const string kHashedCube = "ldeocipaedc";
const string kHashedSphere = "jminadgooco";
const string kHashedCapsule = "pmhghhkcdmp";
// Custom dimensions for non-uniformly scaled stencils
[Serializable]
public class State {
public TrTransform Transform { get; set; }
public Vector3 Extents { get; set; }
// True if guide should be pinned on load. Added in M15.
public bool Pinned { get; set; }
// Group ID for widget. 0 for ungrouped items. Added in M22.
public uint GroupId { get; set; }
}
// This is the accessor used by Json.NET for reading/writing the "Type" field.
// The getter is used for writing; the setter for reading.
[JsonProperty(PropertyName = "Type")]
private string SerializedType {
get {
string ret = Type.ToString();
if (! Char.IsUpper(ret[0])) {
// Must be an obfuscated value, or a numeric value (ie, an int that doesn't map
// to a valid enum name), neither of which is expected. Die early rather than
// generate garbage output, so we can catch it in testing.
Debug.LogErrorFormat("Writing bad stencil value {0}", ret);
return "Cube";
}
return ret;
}
set {
try {
Type = (StencilType)Enum.Parse(typeof(StencilType), value, true);
} catch (ArgumentException e) {
// Support the 8.x names for these
switch (value) {
case kHashedCube: Type = StencilType.Cube; break;
case kHashedSphere: Type = StencilType.Sphere; break;
case kHashedCapsule: Type = StencilType.Capsule; break;
default:
// TODO: log a user visible warning?
Debug.LogException(e);
Type = StencilType.Cube;
break;
}
}
}
}
[JsonIgnore]
public StencilType Type = StencilType.Cube;
public State[] States { get; set; }
}
[Serializable]
public class Palette {
// Protect Tilt Brush from getting bad alpha values from the user.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
private Color32[] Entries {
get { return Colors; }
set {
if (value != null) {
for (int i = 0; i < value.Length; ++i) {
value[i].a = 255;
}
}
Colors = value;
}
}
[JsonIgnore]
public Color32[] Colors { get; set; }
}
[Serializable]
public class CustomLights {
[Serializable]
public class DirectionalLight {
public Quaternion Orientation { get; set; }
public Color Color { get; set; }
}
public Color32 Ambient { get; set; }
public DirectionalLight Shadow { get; set; }
public DirectionalLight NoShadow { get; set; }
}
[Serializable]
public class CustomEnvironment {
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Color32[] GradientColors { get; set; }
public Quaternion GradientSkew { get; set; }
public Color32 FogColor { get; set; }
public float FogDensity { get; set; }
public float ReflectionIntensity { get; set; }
}
[Serializable]
public class CameraPathPositionKnotMetadata {
public TrTransform Xf;
public float TangentMagnitude;
}
[Serializable]
public class CameraPathRotationKnotMetadata {
public TrTransform Xf;
public float PathTValue;
}
[Serializable]
public class CameraPathSpeedKnotMetadata {
public TrTransform Xf;
public float PathTValue;
public float Speed;
}
[Serializable]
public class CameraPathFovKnotMetadata {
public TrTransform Xf;
public float PathTValue;
public float Fov;
}
[Serializable]
public class CameraPathMetadata {
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public CameraPathPositionKnotMetadata[] PathKnots { get; set; }
public CameraPathRotationKnotMetadata[] RotationKnots { get; set; }
public CameraPathSpeedKnotMetadata[] SpeedKnots { get; set; }
public CameraPathFovKnotMetadata[] FovKnots { get; set; }
}
// TODO: deprecate (7.5b-only)
// Left just to avoid breaking trusted testers' art
[Serializable]
public class TiltImages75b {
/// Absolute path to image; any path ending in .png or .jpg will work though.
public string FilePath { get; set; }
public TrTransform Transform { get; set; }
/// width / height
public float AspectRatio { get; set; }
public TiltImages75 Upgrade() {
return new TiltImages75 {
FileName = System.IO.Path.GetFileName(FilePath),
AspectRatio = AspectRatio,
PinStates = new[] { true },
TintStates = new[] { true },
Transforms = new[] { Transform },
GroupIds = new[] { 0u }
};
}
}
[Serializable]
public class TiltImages75 {
/// *.png or *.jpg, should have no path
public string FileName { get; set; }
/// width / height
public float AspectRatio { get; set; }
// True if image should be pinned on load. Added in M15.
public bool[] PinStates { get; set; }
// True if image should use legacy tinting. Added in M15.
public bool[] TintStates { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public TrTransform[] Transforms { get; set; }
// Group IDs for widgets. 0 for ungrouped items. Added in M22.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public uint[] GroupIds { get; set; }
}
[Serializable]
public class Mirror {
public TrTransform Transform { get; set; }
}
[Serializable]
public class TiltVideo {
public string FilePath { get; set; } // relative to Media Library folder
public float AspectRatio { get; set; }
public bool Pinned;
public TrTransform Transform;
public bool Paused { get; set; }
public float Time { get; set; }
public float Volume { get; set; }
// Group ID for widget. 0 for ungrouped items.
public uint GroupId { get; set; }
}
[Serializable]
// Serializable protects data members obfuscator, but we need to also protect
// method names like ShouldSerializeXxx(...) that are used by Json.NET
[System.Reflection.Obfuscation(Exclude = true)]
public class SketchMetadata {
static public int kSchemaVersion = 2;
// Reference to environment GUID.
public string EnvironmentPreset;
// Reference to sketch audio GUID.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string AudioPreset { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string[] Authors { get; set; }
public Guid[] BrushIndex { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string[] RequiredCapabilities { get; set; }
public TrTransform ThumbnailCameraTransformInRoomSpace = TrTransform.identity;
public TrTransform SceneTransformInRoomSpace = TrTransform.identity;
// Callback for JSON.net (name is magic and special)
public bool ShouldSerializeSceneTransformInRoomSpace() {
return SceneTransformInRoomSpace != TrTransform.identity;
}
public TrTransform CanvasTransformInSceneSpace = TrTransform.identity;
// Callback for JSON.net (name is magic and special)
public bool ShouldSerializeCanvasTransformInSceneSpace() {
return CanvasTransformInSceneSpace != TrTransform.identity;
}
// This was the old name of ThumbnailCameraTransformInRoomSpace.
[Serializable]
public struct UnusedSketchTransform {
public Vector3 position;
public Quaternion orientation;
}
// This is write-only to keep it from being serialized out
public UnusedSketchTransform ThumbnailCameraTransform {
set {
var xf = TrTransform.TR(value.position, value.orientation);
ThumbnailCameraTransformInRoomSpace = xf;
}
}
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int SchemaVersion { get; set; }
/// Deprecated
/// Only written in 7.0-7.2
/// Only should ever contains a single model but will create multiples if they are in the list
/// Write-only so it gets serialized in but not serialized out.
/// Models and ModelIndex will never coexist in the same .tilt, so we can upgrade in place.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public TiltModels70[] Models {
set {
ModelIndex = value.Select(m70 => m70.Upgrade()).ToArray();
}
}
/// Added in 7.5
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public TiltModels75[] ModelIndex { get; set; }
// Added in 7.5b; never released to public.
// Write-only so it gets serialized in but not serialized out.
// Images and ImageIndex will never coexist in the same .tilt, so we can upgrade in place.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public TiltImages75b[] Images {
set {
ImageIndex = value.Select(i75b => i75b.Upgrade()).ToArray();
}
}
// Added in 7.5
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public TiltImages75[] ImageIndex { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Mirror Mirror { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Guides[] GuideIndex { get; set; }
// Added in 9.1
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Palette Palette { get; set; }
// Added in 10.0
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public CustomLights Lights { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public CustomEnvironment Environment { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string SourceId { get; set; }
// Added in 12.0, deprecated in 13.0
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "Set")]
public string[] Set_deprecated { get; set; }
// Added in 13.0
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string AssetId { get; set; }
// Added in 22.0
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public TiltVideo[] Videos { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public CameraPathMetadata[] CameraPaths { get; set; }
// Added for 24.0b Open-source edition
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string ApplicationName { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string ApplicationVersion { get; set; }
}
}// namespace TiltBrush
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
{
public class SymbolEquivalenceComparerTests
{
[Fact]
public void TestArraysAreEquivalent()
{
var csharpCode =
@"class C
{
int intField1;
int[] intArrayField1;
string[] stringArrayField1;
int[][] intArrayArrayField1;
int[,] intArrayRank2Field1;
System.Int32 int32Field1;
int intField2;
int[] intArrayField2;
string[] stringArrayField2;
int[][] intArrayArrayField2;
int[,] intArrayRank2Field2;
System.Int32 int32Field2;
}";
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode))
{
var type = (ITypeSymbol)workspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var intField1 = (IFieldSymbol)type.GetMembers("intField1").Single();
var intArrayField1 = (IFieldSymbol)type.GetMembers("intArrayField1").Single();
var stringArrayField1 = (IFieldSymbol)type.GetMembers("stringArrayField1").Single();
var intArrayArrayField1 = (IFieldSymbol)type.GetMembers("intArrayArrayField1").Single();
var intArrayRank2Field1 = (IFieldSymbol)type.GetMembers("intArrayRank2Field1").Single();
var int32Field1 = (IFieldSymbol)type.GetMembers("int32Field1").Single();
var intField2 = (IFieldSymbol)type.GetMembers("intField2").Single();
var intArrayField2 = (IFieldSymbol)type.GetMembers("intArrayField2").Single();
var stringArrayField2 = (IFieldSymbol)type.GetMembers("stringArrayField2").Single();
var intArrayArrayField2 = (IFieldSymbol)type.GetMembers("intArrayArrayField2").Single();
var intArrayRank2Field2 = (IFieldSymbol)type.GetMembers("intArrayRank2Field2").Single();
var int32Field2 = (IFieldSymbol)type.GetMembers("int32Field2").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intField2.Type));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(intField1.Type),
SymbolEquivalenceComparer.Instance.GetHashCode(intField2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, intArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, intArrayField2.Type));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(intArrayField1.Type),
SymbolEquivalenceComparer.Instance.GetHashCode(intArrayField2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, stringArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, stringArrayField2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayArrayField2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, intArrayRank2Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, intArrayRank2Field2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, int32Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, int32Field2.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, stringArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, intArrayArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayRank2Field1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, int32Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, intField1.Type));
}
}
[Fact]
public void TestArraysInDifferentLanguagesAreEquivalent()
{
var csharpCode =
@"class C
{
int intField1;
int[] intArrayField1;
string[] stringArrayField1;
int[][] intArrayArrayField1;
int[,] intArrayRank2Field1;
System.Int32 int32Field1;
}";
var vbCode =
@"class C
dim intField1 as Integer;
dim intArrayField1 as Integer()
dim stringArrayField1 as String()
dim intArrayArrayField1 as Integer()()
dim intArrayRank2Field1 as Integer(,)
dim int32Field1 as System.Int32
end class";
using (var csharpWorkspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode))
using (var vbWorkspace = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode))
{
var csharpType = (ITypeSymbol)csharpWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var vbType = vbWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var csharpIntField1 = (IFieldSymbol)csharpType.GetMembers("intField1").Single();
var csharpIntArrayField1 = (IFieldSymbol)csharpType.GetMembers("intArrayField1").Single();
var csharpStringArrayField1 = (IFieldSymbol)csharpType.GetMembers("stringArrayField1").Single();
var csharpIntArrayArrayField1 = (IFieldSymbol)csharpType.GetMembers("intArrayArrayField1").Single();
var csharpIntArrayRank2Field1 = (IFieldSymbol)csharpType.GetMembers("intArrayRank2Field1").Single();
var csharpInt32Field1 = (IFieldSymbol)csharpType.GetMembers("int32Field1").Single();
var vbIntField1 = (IFieldSymbol)vbType.GetMembers("intField1").Single();
var vbIntArrayField1 = (IFieldSymbol)vbType.GetMembers("intArrayField1").Single();
var vbStringArrayField1 = (IFieldSymbol)vbType.GetMembers("stringArrayField1").Single();
var vbIntArrayArrayField1 = (IFieldSymbol)vbType.GetMembers("intArrayArrayField1").Single();
var vbIntArrayRank2Field1 = (IFieldSymbol)vbType.GetMembers("intArrayRank2Field1").Single();
var vbInt32Field1 = (IFieldSymbol)vbType.GetMembers("int32Field1").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntField1.Type, vbIntField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayField1.Type, vbIntArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpStringArrayField1.Type, vbStringArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayArrayField1.Type, vbIntArrayArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpInt32Field1.Type, vbInt32Field1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntField1.Type, vbIntArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayField1.Type, csharpStringArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpStringArrayField1.Type, vbIntArrayArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayArrayField1.Type, csharpIntArrayRank2Field1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayRank2Field1.Type, vbInt32Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpInt32Field1.Type, vbIntField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntField1.Type, csharpIntArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayField1.Type, vbStringArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbStringArrayField1.Type, csharpIntArrayArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayArrayField1.Type, vbIntArrayRank2Field1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayRank2Field1.Type, csharpInt32Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(vbInt32Field1.Type, csharpIntField1.Type));
}
}
[Fact]
public void TestFields()
{
var csharpCode1 =
@"class Type1
{
int field1;
string field2;
}
class Type2
{
bool field3;
short field4;
}";
var csharpCode2 =
@"class Type1
{
int field1;
short field4;
}
class Type2
{
bool field3;
string field2;
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var field1_v1 = type1_v1.GetMembers("field1").Single();
var field1_v2 = type1_v2.GetMembers("field1").Single();
var field2_v1 = type1_v1.GetMembers("field2").Single();
var field2_v2 = type2_v2.GetMembers("field2").Single();
var field3_v1 = type2_v1.GetMembers("field3").Single();
var field3_v2 = type2_v2.GetMembers("field3").Single();
var field4_v1 = type2_v1.GetMembers("field4").Single();
var field4_v2 = type1_v2.GetMembers("field4").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field1_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(field1_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(field1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field2_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(field3_v1, field3_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field4_v1, field4_v2));
}
}
[WorkItem(538124)]
[Fact]
public void TestFieldsAcrossLanguages()
{
var csharpCode1 =
@"class Type1
{
int field1;
string field2;
}
class Type2
{
bool field3;
short field4;
}";
var vbCode1 =
@"class Type1
dim field1 as Integer;
dim field4 as Short;
end class
class Type2
dim field3 as Boolean;
dim field2 as String;
end class";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode1))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var field1_v1 = type1_v1.GetMembers("field1").Single();
var field1_v2 = type1_v2.GetMembers("field1").Single();
var field2_v1 = type1_v1.GetMembers("field2").Single();
var field2_v2 = type2_v2.GetMembers("field2").Single();
var field3_v1 = type2_v1.GetMembers("field3").Single();
var field3_v2 = type2_v2.GetMembers("field3").Single();
var field4_v1 = type2_v1.GetMembers("field4").Single();
var field4_v2 = type1_v2.GetMembers("field4").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field2_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(field3_v1, field3_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field4_v1, field4_v2));
}
}
[Fact]
public void TestFieldsInGenericTypes()
{
var code =
@"class C<T>
{
int foo;
C<int> intInstantiation1;
C<string> stringInstantiation;
C<T> instanceInstantiation;
}
class D
{
C<int> intInstantiation2;
}
";
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var typeC = workspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var typeD = workspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("D").Single();
var intInstantiation1 = (IFieldSymbol)typeC.GetMembers("intInstantiation1").Single();
var stringInstantiation = (IFieldSymbol)typeC.GetMembers("stringInstantiation").Single();
var instanceInstantiation = (IFieldSymbol)typeC.GetMembers("instanceInstantiation").Single();
var intInstantiation2 = (IFieldSymbol)typeD.GetMembers("intInstantiation2").Single();
var foo = typeC.GetMembers("foo").Single();
var foo_intInstantiation1 = intInstantiation1.Type.GetMembers("foo").Single();
var foo_stringInstantiation = stringInstantiation.Type.GetMembers("foo").Single();
var foo_instanceInstantiation = instanceInstantiation.Type.GetMembers("foo").Single();
var foo_intInstantiation2 = intInstantiation2.Type.GetMembers("foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_intInstantiation1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_intInstantiation2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_stringInstantiation));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo_intInstantiation1, foo_stringInstantiation));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(foo, foo_instanceInstantiation));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(foo),
SymbolEquivalenceComparer.Instance.GetHashCode(foo_instanceInstantiation));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(foo_intInstantiation1, foo_intInstantiation2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(foo_intInstantiation1),
SymbolEquivalenceComparer.Instance.GetHashCode(foo_intInstantiation2));
}
}
[Fact]
public void TestMethodsAreEquivalentEvenWithDifferentReturnType()
{
var csharpCode1 =
@"class Type1
{
void Foo() {}
}";
var csharpCode2 =
@"class Type1
{
int Foo() {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentNamesAreNotEquivalent()
{
var csharpCode1 =
@"class Type1
{
void Foo() {}
}";
var csharpCode2 =
@"class Type1
{
void Foo1() {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo1").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentAritiesAreNotEquivalent()
{
var csharpCode1 =
@"class Type1
{
void Foo() {}
}";
var csharpCode2 =
@"class Type1
{
void Foo<T>() {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentParametersAreNotEquivalent()
{
var csharpCode1 =
@"class Type1
{
void Foo() {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentTypeParameters()
{
var csharpCode1 =
@"class Type1
{
void Foo<A>(A a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo<B>(B a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsWithSameParameters()
{
var csharpCode1 =
@"class Type1
{
void Foo(int a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentParameterNames()
{
var csharpCode1 =
@"class Type1
{
void Foo(int a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int b) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsAreNotEquivalentOutToRef()
{
var csharpCode1 =
@"class Type1
{
void Foo(out int a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(ref int a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsNotEquivalentRemoveOut()
{
var csharpCode1 =
@"class Type1
{
void Foo(out int a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsAreEquivalentIgnoreParams()
{
var csharpCode1 =
@"class Type1
{
void Foo(params int[] a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int[] a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsNotEquivalentDifferentParameterTypes()
{
var csharpCode1 =
@"class Type1
{
void Foo(int[] a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(string[] a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsAcrossLanguages()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1
{
T Foo<T>(IList<T> list, int a) {}
void Bar() { }
}";
var vbCode1 =
@"
Imports System.Collections.Generic
class Type1
function Foo(of U)(list as IList(of U), a as Integer) as U
end function
sub Quux()
end sub
end class";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode1))
{
var csharpType1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var vbType1 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var csharpFooMethod = csharpType1.GetMembers("Foo").Single();
var csharpBarMethod = csharpType1.GetMembers("Bar").Single();
var vbFooMethod = vbType1.GetMembers("Foo").Single();
var vbQuuxMethod = vbType1.GetMembers("Quux").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbFooMethod));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(csharpFooMethod),
SymbolEquivalenceComparer.Instance.GetHashCode(vbFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, csharpBarMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbQuuxMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, csharpFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbQuuxMethod));
}
}
[Fact]
public void TestMethodsInGenericTypesAcrossLanguages()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1<X>
{
T Foo<T>(IList<T> list, X a) {}
void Bar(X x) { }
}";
var vbCode1 =
@"
Imports System.Collections.Generic
class Type1(of M)
function Foo(of U)(list as IList(of U), a as M) as U
end function
sub Bar(x as Object)
end sub
end class";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode1))
{
var csharpType1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var vbType1 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var csharpFooMethod = csharpType1.GetMembers("Foo").Single();
var csharpBarMethod = csharpType1.GetMembers("Bar").Single();
var vbFooMethod = vbType1.GetMembers("Foo").Single();
var vbBarMethod = vbType1.GetMembers("Bar").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbFooMethod));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(csharpFooMethod),
SymbolEquivalenceComparer.Instance.GetHashCode(vbFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, csharpBarMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbBarMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, csharpFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbBarMethod));
}
}
[Fact]
public void TestObjectAndDynamicAreNotEqualNormally()
{
var csharpCode1 =
@"class Type1
{
object field1;
dynamic field2;
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var field1_v1 = type1_v1.GetMembers("field1").Single();
var field2_v1 = type1_v1.GetMembers("field2").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field2_v1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field1_v1));
}
}
[Fact]
public void TestObjectAndDynamicAreEqualInSignatures()
{
var csharpCode1 =
@"class Type1
{
void Foo(object o1) { }
}";
var csharpCode2 =
@"class Type1
{
void Foo(dynamic o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestUnequalGenericsInSignatures()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(IList<int> o1) { }
}";
var csharpCode2 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(IList<string> o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
}
}
[Fact]
public void TestGenericsWithDynamicAndObjectInSignatures()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(IList<object> o1) { }
}";
var csharpCode2 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(IList<dynamic> o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestDynamicAndUnrelatedTypeInSignatures()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(dynamic o1) { }
}";
var csharpCode2 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(string o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
}
}
[Fact]
public void TestNamespaces()
{
var csharpCode1 =
@"namespace Outer
{
namespace Inner
{
class Type
{
}
}
class Type
{
}
}
";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
{
var outer1 = (INamespaceSymbol)workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetMembers("Outer").Single();
var outer2 = (INamespaceSymbol)workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetMembers("Outer").Single();
var inner1 = (INamespaceSymbol)outer1.GetMembers("Inner").Single();
var inner2 = (INamespaceSymbol)outer2.GetMembers("Inner").Single();
var outerType1 = outer1.GetTypeMembers("Type").Single();
var outerType2 = outer2.GetTypeMembers("Type").Single();
var innerType1 = inner1.GetTypeMembers("Type").Single();
var innerType2 = inner2.GetTypeMembers("Type").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, outer2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1),
SymbolEquivalenceComparer.Instance.GetHashCode(outer2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(inner1, inner2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(inner1),
SymbolEquivalenceComparer.Instance.GetHashCode(inner2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outerType1, outerType2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outerType1),
SymbolEquivalenceComparer.Instance.GetHashCode(outerType2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(innerType1, innerType2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(innerType1),
SymbolEquivalenceComparer.Instance.GetHashCode(innerType2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(outer1, inner1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(inner1, outerType1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(outerType1, innerType1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(innerType1, outer1));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, inner1.ContainingSymbol));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1),
SymbolEquivalenceComparer.Instance.GetHashCode(inner1.ContainingSymbol));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, innerType1.ContainingSymbol.ContainingSymbol));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1),
SymbolEquivalenceComparer.Instance.GetHashCode(innerType1.ContainingSymbol.ContainingSymbol));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(inner1, innerType1.ContainingSymbol));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(inner1),
SymbolEquivalenceComparer.Instance.GetHashCode(innerType1.ContainingSymbol));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, outerType1.ContainingSymbol));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1),
SymbolEquivalenceComparer.Instance.GetHashCode(outerType1.ContainingSymbol));
}
}
[Fact]
public void TestNamedTypesEquivalent()
{
var csharpCode1 =
@"
class Type1
{
}
class Type2<X>
{
}
";
var csharpCode2 =
@"
class Type1
{
void Foo();
}
class Type2<Y>
{
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var type2_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(type1_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(type1_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(type2_v1, type2_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(type2_v2, type2_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(type2_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(type2_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type2_v1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type2_v1, type1_v1));
}
}
[Fact]
public void TestNamedTypesDifferentIfNameChanges()
{
var csharpCode1 =
@"
class Type1
{
}";
var csharpCode2 =
@"
class Type2
{
void Foo();
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
}
}
[Fact]
public void TestNamedTypesDifferentIfTypeKindChanges()
{
var csharpCode1 =
@"
struct Type1
{
}";
var csharpCode2 =
@"
class Type1
{
void Foo();
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
}
}
[Fact]
public void TestNamedTypesDifferentIfArityChanges()
{
var csharpCode1 =
@"
class Type1
{
}";
var csharpCode2 =
@"
class Type1<T>
{
void Foo();
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
}
}
[Fact]
public void TestNamedTypesDifferentIfContainerDifferent()
{
var csharpCode1 =
@"
class Outer
{
class Type1
{
}
}";
var csharpCode2 =
@"
class Other
{
class Type1
{
void Foo();
}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var outer = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Outer").Single();
var other = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Other").Single();
var type1_v1 = outer.GetTypeMembers("Type1").Single();
var type1_v2 = other.GetTypeMembers("Type1").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
}
}
[Fact]
public void TestAliasedTypes1()
{
var csharpCode1 =
@"
using i = System.Int32;
class Type1
{
void Foo(i o1) { }
}";
var csharpCode2 =
@"
class Type1
{
void Foo(int o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestCSharpReducedExtensionMethodsAreEquivalent()
{
var code = @"
class Zed {}
public static class Extensions
{
public static void NotGeneric(this Zed z, int data) { }
public static void GenericThis<T>(this T me, int data) where T : Zed { }
public static void GenericNotThis<T>(this Zed z, T data) { }
public static void GenericThisAndMore<T,S>(this T me, S data) where T : Zed { }
public static void GenericThisAndOther<T>(this T me, T data) where T : Zed { }
}
class Test
{
void NotGeneric()
{
Zed z;
int n;
z.NotGeneric(n);
}
void GenericThis()
{
Zed z;
int n;
z.GenericThis(n);
}
void GenericNotThis()
{
Zed z;
int n;
z.GenericNotThis(n);
}
void GenericThisAndMore()
{
Zed z;
int n;
z.GenericThisAndMore(n);
}
void GenericThisAndOther()
{
Zed z;
z.GenericThisAndOther(z);
}
}
";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var comp1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
var comp2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "NotGeneric");
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThis");
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericNotThis");
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndMore");
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndOther");
}
}
[Fact]
public void TestVisualBasicReducedExtensionMethodsAreEquivalent()
{
var code = @"
Imports System.Runtime.CompilerServices
Class Zed
End Class
Module Extensions
<Extension>
Public Sub NotGeneric(z As Zed, data As Integer)
End Sub
<Extension>
Public Sub GenericThis(Of T As Zed)(m As T, data as Integer)
End Sub
<Extension>
Public Sub GenericNotThis(Of T)(z As Zed, data As T)
End Sub
<Extension>
Public Sub GenericThisAndMore(Of T As Zed, S)(m As T, data As S)
End Sub
<Extension>
Public Sub GenericThisAndOther(Of T As Zed)(m As T, data As T)
End Sub
End Module
Class Test
Sub NotGeneric()
Dim z As Zed
Dim n As Integer
z.NotGeneric(n)
End Sub
Sub GenericThis()
Dim z As Zed
Dim n As Integer
z.GenericThis(n)
End Sub
Sub GenericNotThis()
Dim z As Zed
Dim n As Integer
z.GenericNotThis(n)
End Sub
Sub GenericThisAndMore()
Dim z As Zed
Dim n As Integer
z.GenericThisAndMore(n)
End Sub
Sub GenericThisAndOther()
Dim z As Zed
z.GenericThisAndOther(z)
End Sub
End Class
";
using (var workspace1 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(code))
using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var comp1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
var comp2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "NotGeneric");
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThis");
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericNotThis");
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndMore");
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndOther");
}
}
[Fact]
public void TestDifferentModules()
{
var csharpCode =
@"namespace N
{
namespace M
{
}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(new[] { csharpCode }, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "FooModule")))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(new[] { csharpCode }, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "BarModule")))
{
var namespace1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetNamespaceMembers().Single(n => n.Name == "N").GetNamespaceMembers().Single(n => n.Name == "M");
var namespace2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetNamespaceMembers().Single(n => n.Name == "N").GetNamespaceMembers().Single(n => n.Name == "M");
Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(namespace1, namespace2));
Assert.Equal(SymbolEquivalenceComparer.IgnoreAssembliesInstance.GetHashCode(namespace1),
SymbolEquivalenceComparer.IgnoreAssembliesInstance.GetHashCode(namespace2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(namespace1, namespace2));
Assert.NotEqual(SymbolEquivalenceComparer.Instance.GetHashCode(namespace1),
SymbolEquivalenceComparer.Instance.GetHashCode(namespace2));
}
}
private void TestReducedExtension<TInvocation>(Compilation comp1, Compilation comp2, string typeName, string methodName)
where TInvocation : SyntaxNode
{
var method1 = GetInvokedSymbol<TInvocation>(comp1, typeName, methodName);
var method2 = GetInvokedSymbol<TInvocation>(comp2, typeName, methodName);
Assert.NotNull(method1);
Assert.Equal(method1.MethodKind, MethodKind.ReducedExtension);
Assert.NotNull(method2);
Assert.Equal(method2.MethodKind, MethodKind.ReducedExtension);
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method1, method2));
var cfmethod1 = method1.ConstructedFrom;
var cfmethod2 = method2.ConstructedFrom;
Assert.True(SymbolEquivalenceComparer.Instance.Equals(cfmethod1, cfmethod2));
}
private IMethodSymbol GetInvokedSymbol<TInvocation>(Compilation compilation, string typeName, string methodName)
where TInvocation : SyntaxNode
{
var type1 = compilation.GlobalNamespace.GetTypeMembers(typeName).Single();
var method = type1.GetMembers(methodName).Single();
var method_root = method.DeclaringSyntaxReferences[0].GetSyntax();
var invocation = method_root.DescendantNodes().OfType<TInvocation>().FirstOrDefault();
if (invocation == null)
{
// vb method root is statement, but we need block to find body with invocation
invocation = method_root.Parent.DescendantNodes().OfType<TInvocation>().First();
}
var model = compilation.GetSemanticModel(invocation.SyntaxTree);
var info = model.GetSymbolInfo(invocation);
return info.Symbol as IMethodSymbol;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Management.Automation.Internal;
using System.Xml;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Class to load the XML document into data structures.
/// It encapsulates the file format specific code.
/// </summary>
internal sealed partial class TypeInfoDataBaseLoader : XmlLoaderBase
{
private ListControlBody LoadListControl(XmlNode controlNode)
{
using (this.StackFrame(controlNode))
{
ListControlBody listBody = new ListControlBody();
bool listViewEntriesFound = false;
foreach (XmlNode n in controlNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.ListEntriesNode))
{
if (listViewEntriesFound)
{
this.ProcessDuplicateNode(n);
continue;
}
listViewEntriesFound = true;
// now read the columns section
LoadListControlEntries(n, listBody);
if (listBody.defaultEntryDefinition == null)
{
return null; // fatal error
}
}
else
{
this.ProcessUnknownNode(n);
}
}
if (!listViewEntriesFound)
{
this.ReportMissingNode(XmlTags.ListEntriesNode);
return null; // fatal error
}
return listBody;
}
}
private void LoadListControlEntries(XmlNode listViewEntriesNode, ListControlBody listBody)
{
using (this.StackFrame(listViewEntriesNode))
{
int entryIndex = 0;
foreach (XmlNode n in listViewEntriesNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.ListEntryNode))
{
ListControlEntryDefinition lved = LoadListControlEntryDefinition(n, entryIndex++);
if (lved == null)
{
// Error at XPath {0} in file {1}: {2} failed to load.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.ListEntryNode));
listBody.defaultEntryDefinition = null;
return; // fatal error
}
// determine if we have a default entry and if it's already set
if (lved.appliesTo == null)
{
if (listBody.defaultEntryDefinition == null)
{
listBody.defaultEntryDefinition = lved;
}
else
{
// Error at XPath {0} in file {1}: There cannot be more than one default {2}.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.TooManyDefaultShapeEntry, ComputeCurrentXPath(), FilePath, XmlTags.ListEntryNode));
listBody.defaultEntryDefinition = null;
return; // fatal error
}
}
else
{
listBody.optionalEntryList.Add(lved);
}
}
else
{
this.ProcessUnknownNode(n);
}
}
if (listBody.optionalEntryList == null)
{
// Error at XPath {0} in file {1}: There must be at least one default {2}.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefaultShapeEntry, ComputeCurrentXPath(), FilePath, XmlTags.ListEntryNode));
}
}
}
private ListControlEntryDefinition LoadListControlEntryDefinition(XmlNode listViewEntryNode, int index)
{
using (this.StackFrame(listViewEntryNode, index))
{
bool appliesToNodeFound = false; // cardinality 0..1
bool bodyNodeFound = false; // cardinality 1
ListControlEntryDefinition lved = new ListControlEntryDefinition();
foreach (XmlNode n in listViewEntryNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.EntrySelectedByNode))
{
if (appliesToNodeFound)
{
this.ProcessDuplicateNode(n);
return null; // fatal
}
appliesToNodeFound = true;
// optional section
lved.appliesTo = LoadAppliesToSection(n, true);
}
else if (MatchNodeName(n, XmlTags.ListItemsNode))
{
if (bodyNodeFound)
{
this.ProcessDuplicateNode(n);
return null; // fatal
}
bodyNodeFound = true;
LoadListControlItemDefinitions(lved, n);
}
else
{
this.ProcessUnknownNode(n);
}
}
if (lved.itemDefinitionList == null)
{
// Error at XPath {0} in file {1}: Missing definition list.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefinitionList, ComputeCurrentXPath(), FilePath));
return null;
}
return lved;
}
}
private void LoadListControlItemDefinitions(ListControlEntryDefinition lved, XmlNode bodyNode)
{
using (this.StackFrame(bodyNode))
{
int index = 0;
foreach (XmlNode n in bodyNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.ListItemNode))
{
index++;
ListControlItemDefinition lvid = LoadListControlItemDefinition(n);
if (lvid == null)
{
// Error at XPath {0} in file {1}: Invalid property entry.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidPropertyEntry, ComputeCurrentXPath(), FilePath));
lved.itemDefinitionList = null;
return; // fatal
}
lved.itemDefinitionList.Add(lvid);
}
else
{
this.ProcessUnknownNode(n);
}
}
// we must have at least a definition in th elist
if (lved.itemDefinitionList.Count == 0)
{
// Error at XPath {0} in file {1}: At least one list view item must be specified.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoListViewItem, ComputeCurrentXPath(), FilePath));
lved.itemDefinitionList = null;
return; // fatal
}
}
}
private ListControlItemDefinition LoadListControlItemDefinition(XmlNode propertyEntryNode)
{
using (this.StackFrame(propertyEntryNode))
{
// process Mshexpression, format string and text token
ViewEntryNodeMatch match = new ViewEntryNodeMatch(this);
List<XmlNode> unprocessedNodes = new List<XmlNode>();
if (!match.ProcessExpressionDirectives(propertyEntryNode, unprocessedNodes))
{
return null; // fatal error
}
// process the remaining nodes
TextToken labelToken = null;
ExpressionToken condition = null;
bool labelNodeFound = false; // cardinality 0..1
bool itemSelectionConditionNodeFound = false; // cardinality 0..1
foreach (XmlNode n in unprocessedNodes)
{
if (MatchNodeName(n, XmlTags.ItemSelectionConditionNode))
{
if (itemSelectionConditionNodeFound)
{
this.ProcessDuplicateNode(n);
return null; // fatal error
}
itemSelectionConditionNodeFound = true;
condition = LoadItemSelectionCondition(n);
if (condition == null)
{
return null; // fatal error
}
}
else if (MatchNodeNameWithAttributes(n, XmlTags.LabelNode))
{
if (labelNodeFound)
{
this.ProcessDuplicateNode(n);
return null; // fatal error
}
labelNodeFound = true;
labelToken = LoadLabel(n);
if (labelToken == null)
{
return null; // fatal error
}
}
else
{
this.ProcessUnknownNode(n);
}
}
// finally build the item to return
ListControlItemDefinition lvid = new ListControlItemDefinition();
// add the label
lvid.label = labelToken;
// add condition
lvid.conditionToken = condition;
// add either the text token or the PSPropertyExpression with optional format string
if (match.TextToken != null)
{
lvid.formatTokenList.Add(match.TextToken);
}
else
{
FieldPropertyToken fpt = new FieldPropertyToken();
fpt.expression = match.Expression;
fpt.fieldFormattingDirective.formatString = match.FormatString;
lvid.formatTokenList.Add(fpt);
}
return lvid;
}
}
private ExpressionToken LoadItemSelectionCondition(XmlNode itemNode)
{
using (this.StackFrame(itemNode))
{
bool expressionNodeFound = false; // cardinality 1
ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch(this);
foreach (XmlNode n in itemNode.ChildNodes)
{
if (expressionMatch.MatchNode(n))
{
if (expressionNodeFound)
{
this.ProcessDuplicateNode(n);
return null; // fatal error
}
expressionNodeFound = true;
if (!expressionMatch.ProcessNode(n))
return null;
}
else
{
this.ProcessUnknownNode(n);
}
}
return expressionMatch.GenerateExpressionToken();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata
{
public partial class MetadataReader
{
internal const string ClrPrefix = "<CLR>";
internal static readonly byte[] WinRTPrefix = new[] {
(byte)'<',
(byte)'W',
(byte)'i',
(byte)'n',
(byte)'R',
(byte)'T',
(byte)'>'
};
#region Projection Tables
// Maps names of projected types to projection information for each type.
// Both arrays are of the same length and sorted by the type name.
private static string[] s_projectedTypeNames;
private static ProjectionInfo[] s_projectionInfos;
private readonly struct ProjectionInfo
{
public readonly string WinRTNamespace;
public readonly StringHandle.VirtualIndex ClrNamespace;
public readonly StringHandle.VirtualIndex ClrName;
public readonly AssemblyReferenceHandle.VirtualIndex AssemblyRef;
public readonly TypeDefTreatment Treatment;
public readonly TypeRefSignatureTreatment SignatureTreatment;
public readonly bool IsIDisposable;
public ProjectionInfo(
string winRtNamespace,
StringHandle.VirtualIndex clrNamespace,
StringHandle.VirtualIndex clrName,
AssemblyReferenceHandle.VirtualIndex clrAssembly,
TypeDefTreatment treatment = TypeDefTreatment.RedirectedToClrType,
TypeRefSignatureTreatment signatureTreatment = TypeRefSignatureTreatment.None,
bool isIDisposable = false)
{
this.WinRTNamespace = winRtNamespace;
this.ClrNamespace = clrNamespace;
this.ClrName = clrName;
this.AssemblyRef = clrAssembly;
this.Treatment = treatment;
this.SignatureTreatment = signatureTreatment;
this.IsIDisposable = isIDisposable;
}
}
private TypeDefTreatment GetWellKnownTypeDefinitionTreatment(TypeDefinitionHandle typeDef)
{
InitializeProjectedTypes();
StringHandle name = TypeDefTable.GetName(typeDef);
int index = StringHeap.BinarySearchRaw(s_projectedTypeNames, name);
if (index < 0)
{
return TypeDefTreatment.None;
}
StringHandle namespaceName = TypeDefTable.GetNamespace(typeDef);
if (StringHeap.EqualsRaw(namespaceName, StringHeap.GetVirtualString(s_projectionInfos[index].ClrNamespace)))
{
return s_projectionInfos[index].Treatment;
}
// TODO: we can avoid this comparison if info.DotNetNamespace == info.WinRtNamespace
if (StringHeap.EqualsRaw(namespaceName, s_projectionInfos[index].WinRTNamespace))
{
return s_projectionInfos[index].Treatment | TypeDefTreatment.MarkInternalFlag;
}
return TypeDefTreatment.None;
}
private int GetProjectionIndexForTypeReference(TypeReferenceHandle typeRef, out bool isIDisposable)
{
InitializeProjectedTypes();
int index = StringHeap.BinarySearchRaw(s_projectedTypeNames, TypeRefTable.GetName(typeRef));
if (index >= 0 && StringHeap.EqualsRaw(TypeRefTable.GetNamespace(typeRef), s_projectionInfos[index].WinRTNamespace))
{
isIDisposable = s_projectionInfos[index].IsIDisposable;
return index;
}
isIDisposable = false;
return -1;
}
internal static AssemblyReferenceHandle GetProjectedAssemblyRef(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return AssemblyReferenceHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].AssemblyRef);
}
internal static StringHandle GetProjectedName(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrName);
}
internal static StringHandle GetProjectedNamespace(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrNamespace);
}
internal static TypeRefSignatureTreatment GetProjectedSignatureTreatment(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return s_projectionInfos[projectionIndex].SignatureTreatment;
}
private static void InitializeProjectedTypes()
{
if (s_projectedTypeNames == null || s_projectionInfos == null)
{
var systemRuntimeWindowsRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime;
var systemRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime;
var systemObjectModel = AssemblyReferenceHandle.VirtualIndex.System_ObjectModel;
var systemRuntimeWindowsUiXaml = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml;
var systemRuntimeInterop = AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime;
var systemNumericsVectors = AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors;
// sorted by name
var keys = new string[50];
var values = new ProjectionInfo[50];
int k = 0, v = 0;
// WARNING: Keys must be sorted by name and must only contain ASCII characters. WinRTNamespace must also be ASCII only.
keys[k++] = "AttributeTargets"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeTargets, systemRuntime);
keys[k++] = "AttributeUsageAttribute"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeUsageAttribute, systemRuntime, treatment: TypeDefTreatment.RedirectedToClrAttribute);
keys[k++] = "Color"; values[v++] = new ProjectionInfo("Windows.UI", StringHandle.VirtualIndex.Windows_UI, StringHandle.VirtualIndex.Color, systemRuntimeWindowsRuntime);
keys[k++] = "CornerRadius"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.CornerRadius, systemRuntimeWindowsUiXaml);
keys[k++] = "DateTime"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.DateTimeOffset, systemRuntime);
keys[k++] = "Duration"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Duration, systemRuntimeWindowsUiXaml);
keys[k++] = "DurationType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.DurationType, systemRuntimeWindowsUiXaml);
keys[k++] = "EventHandler`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.EventHandler1, systemRuntime);
keys[k++] = "EventRegistrationToken"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime, StringHandle.VirtualIndex.EventRegistrationToken, systemRuntimeInterop);
keys[k++] = "GeneratorPosition"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Controls.Primitives", StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives, StringHandle.VirtualIndex.GeneratorPosition, systemRuntimeWindowsUiXaml);
keys[k++] = "GridLength"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridLength, systemRuntimeWindowsUiXaml);
keys[k++] = "GridUnitType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridUnitType, systemRuntimeWindowsUiXaml);
keys[k++] = "HResult"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Exception, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToClass);
keys[k++] = "IBindableIterable"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IEnumerable, systemRuntime);
keys[k++] = "IBindableVector"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IList, systemRuntime);
keys[k++] = "IClosable"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.IDisposable, systemRuntime, isIDisposable: true);
keys[k++] = "ICommand"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Input", StringHandle.VirtualIndex.System_Windows_Input, StringHandle.VirtualIndex.ICommand, systemObjectModel);
keys[k++] = "IIterable`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IEnumerable1, systemRuntime);
keys[k++] = "IKeyValuePair`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.KeyValuePair2, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToValueType);
keys[k++] = "IMapView`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyDictionary2, systemRuntime);
keys[k++] = "IMap`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IDictionary2, systemRuntime);
keys[k++] = "INotifyCollectionChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.INotifyCollectionChanged, systemObjectModel);
keys[k++] = "INotifyPropertyChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.INotifyPropertyChanged, systemObjectModel);
keys[k++] = "IReference`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Nullable1, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToValueType);
keys[k++] = "IVectorView`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyList1, systemRuntime);
keys[k++] = "IVector`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IList1, systemRuntime);
keys[k++] = "KeyTime"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.KeyTime, systemRuntimeWindowsUiXaml);
keys[k++] = "Matrix"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media", StringHandle.VirtualIndex.Windows_UI_Xaml_Media, StringHandle.VirtualIndex.Matrix, systemRuntimeWindowsUiXaml);
keys[k++] = "Matrix3D"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Media3D", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D, StringHandle.VirtualIndex.Matrix3D, systemRuntimeWindowsUiXaml);
keys[k++] = "Matrix3x2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix3x2, systemNumericsVectors);
keys[k++] = "Matrix4x4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix4x4, systemNumericsVectors);
keys[k++] = "NotifyCollectionChangedAction"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedAction, systemObjectModel);
keys[k++] = "NotifyCollectionChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs, systemObjectModel);
keys[k++] = "NotifyCollectionChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler, systemObjectModel);
keys[k++] = "Plane"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Plane, systemNumericsVectors);
keys[k++] = "Point"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Point, systemRuntimeWindowsRuntime);
keys[k++] = "PropertyChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventArgs, systemObjectModel);
keys[k++] = "PropertyChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventHandler, systemObjectModel);
keys[k++] = "Quaternion"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Quaternion, systemNumericsVectors);
keys[k++] = "Rect"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Rect, systemRuntimeWindowsRuntime);
keys[k++] = "RepeatBehavior"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehavior, systemRuntimeWindowsUiXaml);
keys[k++] = "RepeatBehaviorType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehaviorType, systemRuntimeWindowsUiXaml);
keys[k++] = "Size"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Size, systemRuntimeWindowsRuntime);
keys[k++] = "Thickness"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Thickness, systemRuntimeWindowsUiXaml);
keys[k++] = "TimeSpan"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.TimeSpan, systemRuntime);
keys[k++] = "TypeName"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Type, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToClass);
keys[k++] = "Uri"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Uri, systemRuntime);
keys[k++] = "Vector2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector2, systemNumericsVectors);
keys[k++] = "Vector3"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector3, systemNumericsVectors);
keys[k++] = "Vector4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector4, systemNumericsVectors);
Debug.Assert(k == keys.Length && v == keys.Length && k == v);
AssertSorted(keys);
s_projectedTypeNames = keys;
s_projectionInfos = values;
}
}
[Conditional("DEBUG")]
private static void AssertSorted(string[] keys)
{
for (int i = 0; i < keys.Length - 1; i++)
{
Debug.Assert(string.CompareOrdinal(keys[i], keys[i + 1]) < 0);
}
}
// test only
internal static string[] GetProjectedTypeNames()
{
InitializeProjectedTypes();
return s_projectedTypeNames;
}
#endregion
private static uint TreatmentAndRowId(byte treatment, int rowId)
{
return ((uint)treatment << TokenTypeIds.RowIdBitCount) | (uint)rowId;
}
#region TypeDef
[MethodImpl(MethodImplOptions.NoInlining)]
internal uint CalculateTypeDefTreatmentAndRowId(TypeDefinitionHandle handle)
{
Debug.Assert(_metadataKind != MetadataKind.Ecma335);
TypeDefTreatment treatment;
TypeAttributes flags = TypeDefTable.GetFlags(handle);
EntityHandle extends = TypeDefTable.GetExtends(handle);
if ((flags & TypeAttributes.WindowsRuntime) != 0)
{
if (_metadataKind == MetadataKind.WindowsMetadata)
{
treatment = GetWellKnownTypeDefinitionTreatment(handle);
if (treatment != TypeDefTreatment.None)
{
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
// Is this an attribute?
if (extends.Kind == HandleKind.TypeReference && IsSystemAttribute((TypeReferenceHandle)extends))
{
treatment = TypeDefTreatment.NormalAttribute;
}
else
{
treatment = TypeDefTreatment.NormalNonAttribute;
}
}
else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && NeedsWinRTPrefix(flags, extends))
{
// WinMDExp emits two versions of RuntimeClasses and Enums:
//
// public class Foo {} // the WinRT reference class
// internal class <CLR>Foo {} // the implementation class that we want WinRT consumers to ignore
//
// The adapter's job is to undo WinMDExp's transformations. I.e. turn the above into:
//
// internal class <WinRT>Foo {} // the WinRT reference class that we want CLR consumers to ignore
// public class Foo {} // the implementation class
//
// We only add the <WinRT> prefix here since the WinRT view is the only view that is marked WindowsRuntime
// De-mangling the CLR name is done below.
// tomat: The CLR adapter implements a back-compat quirk: Enums exported with an older WinMDExp have only one version
// not marked with tdSpecialName. These enums should *not* be mangled and flipped to private.
// We don't implement this flag since the WinMDs produced by the older WinMDExp are not used in the wild.
treatment = TypeDefTreatment.PrefixWinRTName;
}
else
{
treatment = TypeDefTreatment.None;
}
// Scan through Custom Attributes on type, looking for interesting bits. We only
// need to do this for RuntimeClasses
if ((treatment == TypeDefTreatment.PrefixWinRTName || treatment == TypeDefTreatment.NormalNonAttribute))
{
if ((flags & TypeAttributes.Interface) == 0
&& HasAttribute(handle, "Windows.UI.Xaml", "TreatAsAbstractComposableClassAttribute"))
{
treatment |= TypeDefTreatment.MarkAbstractFlag;
}
}
}
else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && IsClrImplementationType(handle))
{
// <CLR> implementation classes are not marked WindowsRuntime, but still need to be modified
// by the adapter.
treatment = TypeDefTreatment.UnmangleWinRTName;
}
else
{
treatment = TypeDefTreatment.None;
}
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
private bool IsClrImplementationType(TypeDefinitionHandle typeDef)
{
var attrs = TypeDefTable.GetFlags(typeDef);
if ((attrs & (TypeAttributes.VisibilityMask | TypeAttributes.SpecialName)) != TypeAttributes.SpecialName)
{
return false;
}
return StringHeap.StartsWithRaw(TypeDefTable.GetName(typeDef), ClrPrefix);
}
#endregion
#region TypeRef
internal uint CalculateTypeRefTreatmentAndRowId(TypeReferenceHandle handle)
{
Debug.Assert(_metadataKind != MetadataKind.Ecma335);
bool isIDisposable;
int projectionIndex = GetProjectionIndexForTypeReference(handle, out isIDisposable);
if (projectionIndex >= 0)
{
return TreatmentAndRowId((byte)TypeRefTreatment.UseProjectionInfo, projectionIndex);
}
else
{
return TreatmentAndRowId((byte)GetSpecialTypeRefTreatment(handle), handle.RowId);
}
}
private TypeRefTreatment GetSpecialTypeRefTreatment(TypeReferenceHandle handle)
{
if (StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "System"))
{
StringHandle name = TypeRefTable.GetName(handle);
if (StringHeap.EqualsRaw(name, "MulticastDelegate"))
{
return TypeRefTreatment.SystemDelegate;
}
if (StringHeap.EqualsRaw(name, "Attribute"))
{
return TypeRefTreatment.SystemAttribute;
}
}
return TypeRefTreatment.None;
}
private bool IsSystemAttribute(TypeReferenceHandle handle)
{
return StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") &&
StringHeap.EqualsRaw(TypeRefTable.GetName(handle), "Attribute");
}
private bool NeedsWinRTPrefix(TypeAttributes flags, EntityHandle extends)
{
if ((flags & (TypeAttributes.VisibilityMask | TypeAttributes.Interface)) != TypeAttributes.Public)
{
return false;
}
if (extends.Kind != HandleKind.TypeReference)
{
return false;
}
// Check if the type is a delegate, struct, or attribute
TypeReferenceHandle extendsRefHandle = (TypeReferenceHandle)extends;
if (StringHeap.EqualsRaw(TypeRefTable.GetNamespace(extendsRefHandle), "System"))
{
StringHandle nameHandle = TypeRefTable.GetName(extendsRefHandle);
if (StringHeap.EqualsRaw(nameHandle, "MulticastDelegate")
|| StringHeap.EqualsRaw(nameHandle, "ValueType")
|| StringHeap.EqualsRaw(nameHandle, "Attribute"))
{
return false;
}
}
return true;
}
#endregion
#region MethodDef
private uint CalculateMethodDefTreatmentAndRowId(MethodDefinitionHandle methodDef)
{
MethodDefTreatment treatment = MethodDefTreatment.Implementation;
TypeDefinitionHandle parentTypeDef = GetDeclaringType(methodDef);
TypeAttributes parentFlags = TypeDefTable.GetFlags(parentTypeDef);
if ((parentFlags & TypeAttributes.WindowsRuntime) != 0)
{
if (IsClrImplementationType(parentTypeDef))
{
treatment = MethodDefTreatment.Implementation;
}
else if (parentFlags.IsNested())
{
treatment = MethodDefTreatment.Implementation;
}
else if ((parentFlags & TypeAttributes.Interface) != 0)
{
treatment = MethodDefTreatment.InterfaceMethod;
}
else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && (parentFlags & TypeAttributes.Public) == 0)
{
treatment = MethodDefTreatment.Implementation;
}
else
{
treatment = MethodDefTreatment.Other;
var parentBaseType = TypeDefTable.GetExtends(parentTypeDef);
if (parentBaseType.Kind == HandleKind.TypeReference)
{
switch (GetSpecialTypeRefTreatment((TypeReferenceHandle)parentBaseType))
{
case TypeRefTreatment.SystemAttribute:
treatment = MethodDefTreatment.AttributeMethod;
break;
case TypeRefTreatment.SystemDelegate:
treatment = MethodDefTreatment.DelegateMethod | MethodDefTreatment.MarkPublicFlag;
break;
}
}
}
}
if (treatment == MethodDefTreatment.Other)
{
// we want to hide the method if it implements
// only redirected interfaces
// We also want to check if the methodImpl is IClosable.Close,
// so we can change the name
bool seenRedirectedInterfaces = false;
bool seenNonRedirectedInterfaces = false;
bool isIClosableClose = false;
foreach (var methodImplHandle in new MethodImplementationHandleCollection(this, parentTypeDef))
{
MethodImplementation methodImpl = GetMethodImplementation(methodImplHandle);
if (methodImpl.MethodBody == methodDef)
{
EntityHandle declaration = methodImpl.MethodDeclaration;
// See if this MethodImpl implements a redirected interface
// In WinMD, MethodImpl will always use MemberRef and TypeRefs to refer to redirected interfaces,
// even if they are in the same module.
if (declaration.Kind == HandleKind.MemberReference &&
ImplementsRedirectedInterface((MemberReferenceHandle)declaration, out isIClosableClose))
{
seenRedirectedInterfaces = true;
if (isIClosableClose)
{
// This method implements IClosable.Close
// Let's rename to IDisposable later
// Once we know this implements IClosable.Close, we are done
// looking
break;
}
}
else
{
// Now we know this implements a non-redirected interface
// But we need to keep looking, just in case we got a methodimpl that
// implements the IClosable.Close method and needs to be renamed
seenNonRedirectedInterfaces = true;
}
}
}
if (isIClosableClose)
{
treatment = MethodDefTreatment.DisposeMethod;
}
else if (seenRedirectedInterfaces && !seenNonRedirectedInterfaces)
{
// Only hide if all the interfaces implemented are redirected
treatment = MethodDefTreatment.HiddenInterfaceImplementation;
}
}
// If treatment is other, then this is a non-managed WinRT runtime class definition
// Find out about various bits that we apply via attributes and name parsing
if (treatment == MethodDefTreatment.Other)
{
treatment |= GetMethodTreatmentFromCustomAttributes(methodDef);
}
return TreatmentAndRowId((byte)treatment, methodDef.RowId);
}
private MethodDefTreatment GetMethodTreatmentFromCustomAttributes(MethodDefinitionHandle methodDef)
{
MethodDefTreatment treatment = 0;
foreach (var caHandle in GetCustomAttributes(methodDef))
{
StringHandle namespaceHandle, nameHandle;
if (!GetAttributeTypeNameRaw(caHandle, out namespaceHandle, out nameHandle))
{
continue;
}
Debug.Assert(!namespaceHandle.IsVirtual && !nameHandle.IsVirtual);
if (StringHeap.EqualsRaw(namespaceHandle, "Windows.UI.Xaml"))
{
if (StringHeap.EqualsRaw(nameHandle, "TreatAsPublicMethodAttribute"))
{
treatment |= MethodDefTreatment.MarkPublicFlag;
}
if (StringHeap.EqualsRaw(nameHandle, "TreatAsAbstractMethodAttribute"))
{
treatment |= MethodDefTreatment.MarkAbstractFlag;
}
}
}
return treatment;
}
#endregion
#region FieldDef
/// <summary>
/// The backing field of a WinRT enumeration type is not public although the backing fields
/// of managed enumerations are. To allow managed languages to directly access this field,
/// it is made public by the metadata adapter.
/// </summary>
private uint CalculateFieldDefTreatmentAndRowId(FieldDefinitionHandle handle)
{
var flags = FieldTable.GetFlags(handle);
FieldDefTreatment treatment = FieldDefTreatment.None;
if ((flags & FieldAttributes.RTSpecialName) != 0 && StringHeap.EqualsRaw(FieldTable.GetName(handle), "value__"))
{
TypeDefinitionHandle typeDef = GetDeclaringType(handle);
EntityHandle baseTypeHandle = TypeDefTable.GetExtends(typeDef);
if (baseTypeHandle.Kind == HandleKind.TypeReference)
{
var typeRef = (TypeReferenceHandle)baseTypeHandle;
if (StringHeap.EqualsRaw(TypeRefTable.GetName(typeRef), "Enum") &&
StringHeap.EqualsRaw(TypeRefTable.GetNamespace(typeRef), "System"))
{
treatment = FieldDefTreatment.EnumValue;
}
}
}
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
#endregion
#region MemberRef
private uint CalculateMemberRefTreatmentAndRowId(MemberReferenceHandle handle)
{
MemberRefTreatment treatment;
// We need to rename the MemberRef for IClosable.Close as well
// so that the MethodImpl for the Dispose method can be correctly shown
// as IDisposable.Dispose instead of IDisposable.Close
bool isIDisposable;
if (ImplementsRedirectedInterface(handle, out isIDisposable) && isIDisposable)
{
treatment = MemberRefTreatment.Dispose;
}
else
{
treatment = MemberRefTreatment.None;
}
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
/// <summary>
/// We want to know if a given method implements a redirected interface.
/// For example, if we are given the method RemoveAt on a class "A"
/// which implements the IVector interface (which is redirected
/// to IList in .NET) then this method would return true. The most
/// likely reason why we would want to know this is that we wish to hide
/// (mark private) all methods which implement methods on a redirected
/// interface.
/// </summary>
/// <param name="memberRef">The declaration token for the method</param>
/// <param name="isIDisposable">
/// Returns true if the redirected interface is <see cref="IDisposable"/>.
/// </param>
/// <returns>True if the method implements a method on a redirected interface.
/// False otherwise.</returns>
private bool ImplementsRedirectedInterface(MemberReferenceHandle memberRef, out bool isIDisposable)
{
isIDisposable = false;
EntityHandle parent = MemberRefTable.GetClass(memberRef);
TypeReferenceHandle typeRef;
if (parent.Kind == HandleKind.TypeReference)
{
typeRef = (TypeReferenceHandle)parent;
}
else if (parent.Kind == HandleKind.TypeSpecification)
{
BlobHandle blob = TypeSpecTable.GetSignature((TypeSpecificationHandle)parent);
BlobReader sig = new BlobReader(BlobHeap.GetMemoryBlock(blob));
if (sig.Length < 2 ||
sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_GENERICINST ||
sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_CLASS)
{
return false;
}
EntityHandle token = sig.ReadTypeHandle();
if (token.Kind != HandleKind.TypeReference)
{
return false;
}
typeRef = (TypeReferenceHandle)token;
}
else
{
return false;
}
return GetProjectionIndexForTypeReference(typeRef, out isIDisposable) >= 0;
}
#endregion
#region AssemblyRef
private int FindMscorlibAssemblyRefNoProjection()
{
for (int i = 1; i <= AssemblyRefTable.NumberOfNonVirtualRows; i++)
{
if (StringHeap.EqualsRaw(AssemblyRefTable.GetName(i), "mscorlib"))
{
return i;
}
}
throw new BadImageFormatException(SR.WinMDMissingMscorlibRef);
}
#endregion
#region CustomAttribute
internal CustomAttributeValueTreatment CalculateCustomAttributeValueTreatment(CustomAttributeHandle handle)
{
Debug.Assert(_metadataKind != MetadataKind.Ecma335);
var parent = CustomAttributeTable.GetParent(handle);
// Check for Windows.Foundation.Metadata.AttributeUsageAttribute.
// WinMD rules:
// - The attribute is only applicable on TypeDefs.
// - Constructor must be a MemberRef with TypeRef.
if (!IsWindowsAttributeUsageAttribute(parent, handle))
{
return CustomAttributeValueTreatment.None;
}
var targetTypeDef = (TypeDefinitionHandle)parent;
if (StringHeap.EqualsRaw(TypeDefTable.GetNamespace(targetTypeDef), "Windows.Foundation.Metadata"))
{
if (StringHeap.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "VersionAttribute"))
{
return CustomAttributeValueTreatment.AttributeUsageVersionAttribute;
}
if (StringHeap.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "DeprecatedAttribute"))
{
return CustomAttributeValueTreatment.AttributeUsageDeprecatedAttribute;
}
}
bool allowMultiple = HasAttribute(targetTypeDef, "Windows.Foundation.Metadata", "AllowMultipleAttribute");
return allowMultiple ? CustomAttributeValueTreatment.AttributeUsageAllowMultiple : CustomAttributeValueTreatment.AttributeUsageAllowSingle;
}
private bool IsWindowsAttributeUsageAttribute(EntityHandle targetType, CustomAttributeHandle attributeHandle)
{
// Check for Windows.Foundation.Metadata.AttributeUsageAttribute.
// WinMD rules:
// - The attribute is only applicable on TypeDefs.
// - Constructor must be a MemberRef with TypeRef.
if (targetType.Kind != HandleKind.TypeDefinition)
{
return false;
}
var attributeCtor = CustomAttributeTable.GetConstructor(attributeHandle);
if (attributeCtor.Kind != HandleKind.MemberReference)
{
return false;
}
var attributeType = MemberRefTable.GetClass((MemberReferenceHandle)attributeCtor);
if (attributeType.Kind != HandleKind.TypeReference)
{
return false;
}
var attributeTypeRef = (TypeReferenceHandle)attributeType;
return StringHeap.EqualsRaw(TypeRefTable.GetName(attributeTypeRef), "AttributeUsageAttribute") &&
StringHeap.EqualsRaw(TypeRefTable.GetNamespace(attributeTypeRef), "Windows.Foundation.Metadata");
}
private bool HasAttribute(EntityHandle token, string asciiNamespaceName, string asciiTypeName)
{
foreach (var caHandle in GetCustomAttributes(token))
{
StringHandle namespaceName, typeName;
if (GetAttributeTypeNameRaw(caHandle, out namespaceName, out typeName) &&
StringHeap.EqualsRaw(typeName, asciiTypeName) &&
StringHeap.EqualsRaw(namespaceName, asciiNamespaceName))
{
return true;
}
}
return false;
}
private bool GetAttributeTypeNameRaw(CustomAttributeHandle caHandle, out StringHandle namespaceName, out StringHandle typeName)
{
namespaceName = typeName = default(StringHandle);
EntityHandle typeDefOrRef = GetAttributeTypeRaw(caHandle);
if (typeDefOrRef.IsNil)
{
return false;
}
if (typeDefOrRef.Kind == HandleKind.TypeReference)
{
TypeReferenceHandle typeRef = (TypeReferenceHandle)typeDefOrRef;
var resolutionScope = TypeRefTable.GetResolutionScope(typeRef);
if (!resolutionScope.IsNil && resolutionScope.Kind == HandleKind.TypeReference)
{
// we don't need to handle nested types
return false;
}
// other resolution scopes don't affect full name
typeName = TypeRefTable.GetName(typeRef);
namespaceName = TypeRefTable.GetNamespace(typeRef);
}
else if (typeDefOrRef.Kind == HandleKind.TypeDefinition)
{
TypeDefinitionHandle typeDef = (TypeDefinitionHandle)typeDefOrRef;
if (TypeDefTable.GetFlags(typeDef).IsNested())
{
// we don't need to handle nested types
return false;
}
typeName = TypeDefTable.GetName(typeDef);
namespaceName = TypeDefTable.GetNamespace(typeDef);
}
else
{
// invalid metadata
return false;
}
return true;
}
/// <summary>
/// Returns the type definition or reference handle of the attribute type.
/// </summary>
/// <returns><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/> or nil token if the metadata is invalid and the type can't be determined.</returns>
private EntityHandle GetAttributeTypeRaw(CustomAttributeHandle handle)
{
var ctor = CustomAttributeTable.GetConstructor(handle);
if (ctor.Kind == HandleKind.MethodDefinition)
{
return GetDeclaringType((MethodDefinitionHandle)ctor);
}
if (ctor.Kind == HandleKind.MemberReference)
{
// In general the parent can be MethodDef, ModuleRef, TypeDef, TypeRef, or TypeSpec.
// For attributes only TypeDef and TypeRef are applicable.
EntityHandle typeDefOrRef = MemberRefTable.GetClass((MemberReferenceHandle)ctor);
HandleKind handleType = typeDefOrRef.Kind;
if (handleType == HandleKind.TypeReference || handleType == HandleKind.TypeDefinition)
{
return typeDefOrRef;
}
}
return default(EntityHandle);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Its.Domain.Api.Documentation;
using Microsoft.Its.Domain.Api.Serialization;
using Microsoft.Its.Recipes;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Its.Domain.Api
{
/// <summary>
/// An API controller for a specific aggregate type.
/// </summary>
/// <typeparam name="TAggregate">The type of the aggregate.</typeparam>
[CommandAuthorizationExceptionFilter]
[CommandValidationExceptionFilter]
[ConcurrencyExceptionFilter]
[SerializationExceptionFilter]
[ServesJsonByDefault]
public abstract class DomainApiController<TAggregate> : ApiController
where TAggregate : class, IEventSourced
{
private readonly IEventSourcedRepository<TAggregate> repository;
protected static readonly JsonSerializer Serializer = JsonSerializer.Create(Domain.Serialization.Serializer.Settings);
/// <summary>
/// Initializes a new instance of the <see cref="DomainApiController{TAggregate}" /> class.
/// </summary>
/// <param name="repository">The repository.</param>
/// <exception cref="System.ArgumentNullException">repository</exception>
protected DomainApiController(IEventSourcedRepository<TAggregate> repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
this.repository = repository;
}
/// <summary>
/// Sends a command to the aggregate having id <paramref name="id" />.
/// </summary>
/// <param name="id">The id of the aggregate.</param>
/// <param name="commandName">The name of the command to send to the aggregate.</param>
/// <param name="command">The command to apply.</param>
/// <returns></returns>
[AcceptVerbs("POST")]
public async Task<object> Apply(
[FromUri] Guid id,
[FromUri] string commandName,
[FromBody] JObject command)
{
var aggregate = await GetAggregate(id);
var existingVersion = aggregate.Version;
await ApplyCommand(aggregate, commandName, command);
await repository.Save(aggregate);
return Request.CreateResponse(aggregate.Version == existingVersion
? HttpStatusCode.NotModified
: HttpStatusCode.OK);
}
[AcceptVerbs("POST")]
public async Task<object> Create(
[FromUri] Guid id,
[FromUri] string commandName,
[FromBody] JObject command)
{
var c = CreateCommand(commandName, command);
c.AggregateId = id;
var ctor = typeof (TAggregate).GetConstructor(new[] { ((object) c).GetType() });
var aggregate = (TAggregate) ctor.Invoke(new[] { c });
await repository.Save(aggregate);
return Request.CreateResponse(HttpStatusCode.Created);
}
private async Task ApplyCommand(TAggregate aggregate, string commandName, JObject command)
{
var c = CreateCommand(commandName, command);
var etag = Request.Headers
.IfNoneMatch
.IfNotNull()
.Then(hs => hs.Where(h => !string.IsNullOrEmpty(h.Tag))
.Select(t => t.Tag.Replace("\"", ""))
.FirstOrDefault())
.ElseDefault();
if (etag != null)
{
c.ETag = etag;
}
await aggregate.ApplyAsync((ICommand<TAggregate>) c);
}
private dynamic CreateCommand(string commandName, JObject command)
{
var commandType = GetCommandType(commandName);
return (command ?? new JObject()).ToObject(commandType, Serializer);
}
private static Type GetCommandType(string commandName)
{
var commandType = Command<TAggregate>.Named(commandName);
if (commandType == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return commandType;
}
/// <summary>
/// Applies a batch of commands to the aggregate having id <paramref name="id" />.
/// </summary>
/// <param name="id">The id of the aggregate.</param>
/// <param name="batch">The batch of commands to apply.</param>
/// <returns></returns>
[AcceptVerbs("POST")]
public async Task<object> ApplyBatch(
[FromUri] Guid id,
[FromBody] JArray batch)
{
var aggregate = await GetAggregate(id);
foreach (var command in batch)
{
foreach (JProperty property in command)
{
try
{
await ApplyCommand(aggregate, property.Name, property.Value as JObject);
}
catch (HttpResponseException ex)
{
if (ex.Response.StatusCode == HttpStatusCode.NotFound)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
{
ReasonPhrase = string.Format("Unrecognized command {0}", property.Name)
});
}
}
}
}
await repository.Save(aggregate);
return new HttpResponseMessage(HttpStatusCode.Accepted);
}
/// <summary>
/// Validates an aggregate having the specified id.
/// </summary>
[AcceptVerbs("POST")]
public async Task<object> Validate(
[FromUri] Guid id,
[FromUri] string commandName,
[FromBody] JObject command)
{
var commandTypes = Command<TAggregate>.KnownTypes
.Where(t => string.Equals(t.Name, commandName, StringComparison.OrdinalIgnoreCase))
.ToArray();
if (commandTypes.Length == 0)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
// for now, only a single event definition is allowed
var commandType = commandTypes.Single();
var deserializedCommand = command.IfNotNull()
.Then(json => json.ToObject(commandType))
.Else(() => Activator.CreateInstance(commandType)) as Command<TAggregate>;
var aggregate = await GetAggregate(id);
var validationReport = aggregate.Validate(deserializedCommand);
return new ValidationReportModel(validationReport);
}
/// <summary>
/// Returns documentation for all known commands applicable <typeparamref name="TAggregate" />.
/// </summary>
[AcceptVerbs("GET")]
public object CommandDocumentation(string name)
{
if (string.IsNullOrEmpty(name))
{
return Command<TAggregate>.KnownTypes
.Select(CommandDocument.For);
}
return CommandDocument.For(Command<TAggregate>.Named(name));
}
[AcceptVerbs("GET")]
public object CommandValidationRules(string commandName)
{
// TODO: (CommandValidationRules) client-usable descriptions of the validation rules
return null;
// return CommandDocument.For(Command<TAggregate>.Named(commandName)).ValdationRules;
}
/// <summary>
/// Gets the aggregate having the corresponding id.
/// </summary>
#if !DEBUG
[NonAction]
#endif
public async Task<TAggregate> GetAggregate(Guid id)
{
var aggregate = await repository.GetLatest(id);
if (aggregate == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return aggregate;
}
/// <summary>
/// A repository for accessing aggregate instances.
/// </summary>
protected IEventSourcedRepository<TAggregate> Repository
{
get
{
return repository;
}
}
}
}
| |
using Amalgama.PhotoAutoPicker.Views;
using Excel;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Input;
namespace Amalgama.PhotoAutoPicker.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase
{
public ICommand OpenExcelFileCommand { get; private set; }
public ICommand PickSourceFolderCommand { get; private set; }
public ICommand PickDestinationFolderCommand { get; private set; }
public ICommand ImportPhotosCommand { get; private set; }
public ICommand InfoCommand { get; private set; }
private string _excelPath;
private string _sourceFolderPath;
private string _destinationFolderPath;
private List<string> _fileNames;
private string _firstLineMessage;
private string _secondLineMessage;
private bool _isBusy;
public string ExcelPath
{
get
{
return this._excelPath;
}
set
{
this.Set(() => this.ExcelPath, ref this._excelPath, value);
}
}
public string SourceFolderPath
{
get
{
return this._sourceFolderPath;
}
set
{
this.Set(() => this.SourceFolderPath, ref this._sourceFolderPath, value);
}
}
public string DestinationFolderPath
{
get
{
return this._destinationFolderPath;
}
set
{
this.Set(() => this.DestinationFolderPath, ref this._destinationFolderPath, value);
}
}
public string FirstLineMessage
{
get
{
return this._firstLineMessage;
}
set
{
this.Set(() => this.FirstLineMessage, ref this._firstLineMessage, value);
}
}
public string SecondLineMessage
{
get
{
return this._secondLineMessage;
}
set
{
this.Set(() => this.SecondLineMessage, ref this._secondLineMessage, value);
}
}
public bool IsBusy
{
get
{
return this._isBusy;
}
set
{
this.Set(() => this.IsBusy, ref this._isBusy, value);
}
}
public MainViewModel()
{
this._fileNames = new List<string>();
this.CreateCommans();
}
private void CreateCommans()
{
this.OpenExcelFileCommand = new RelayCommand(this.OpenExcel);
this.PickSourceFolderCommand = new RelayCommand(this.PickSourceFolder);
this.PickDestinationFolderCommand = new RelayCommand(this.PickDestinationFolder);
this.ImportPhotosCommand = new RelayCommand(this.ImportPhotos);
this.InfoCommand = new RelayCommand(this.ShowInfo);
}
private void ShowInfo()
{
var info = new InfoWindow();
info.Show();
}
private void PickDestinationFolder()
{
var dialog = new FolderBrowserDialog();
var result = dialog.ShowDialog();
if (result != DialogResult.OK)
{
return;
}
this.DestinationFolderPath = dialog.SelectedPath;
}
private void PickSourceFolder()
{
var dialog = new FolderBrowserDialog();
var result = dialog.ShowDialog();
if (result != DialogResult.OK)
{
return;
}
this.SourceFolderPath = dialog.SelectedPath;
}
private void OpenExcel()
{
var dialog = new OpenFileDialog();
dialog.Filter = "Excel Files (*.xlsx, *.xls)|*.xlsx;*.xls";
var result = dialog.ShowDialog();
if (result != DialogResult.OK)
{
return;
}
this.ExcelPath = dialog.FileName;
this.ImportExcelData();
}
private void ImportExcelData()
{
if (string.IsNullOrWhiteSpace(this.ExcelPath))
{
return;
}
FileStream stream = File.Open(this.ExcelPath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = null;
var extension = Path.GetExtension(this.ExcelPath);
if (extension.Contains("xlsx"))
{
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
else
{
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
if (excelReader != null)
{
DataSet result = excelReader.AsDataSet();
//5. Data Reader methods
while (excelReader.Read())
{
var name = excelReader.GetString(0);
this._fileNames.Add(name);
}
//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
}
this.FirstLineMessage = this._fileNames.Count + " nombres encontrados en el Excel";
}
private void ImportPhotos()
{
var copyCount = 0;
this.IsBusy = true;
foreach (var fileName in this._fileNames)
{
var allFiles = Directory.EnumerateFiles(this.SourceFolderPath, "*", SearchOption.AllDirectories).Select(x => Path.GetFullPath(x)).ToList();
var matchingFile = allFiles.Where(x => Path.GetFileNameWithoutExtension(x) == fileName).ToList();
foreach (var file in matchingFile)
{
var dest = Path.Combine(this.DestinationFolderPath, Path.GetFileName(file));
if (File.Exists(file))
{
File.Copy(file, dest, true);
copyCount++;
}
}
}
this.IsBusy = false;
MessageBox.Show("Se han importado " + copyCount + " archivos", "Hecho!");
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyDate
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Date operations.
/// </summary>
public partial class Date : IServiceOperations<AutoRestDateTestService>, IDate
{
/// <summary>
/// Initializes a new instance of the Date class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Date(AutoRestDateTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestDateTestService
/// </summary>
public AutoRestDateTestService Client { get; private set; }
/// <summary>
/// Get null date value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/null").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get invalid date value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetInvalidDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalidDate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/invaliddate").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get overflow date value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetOverflowDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetOverflowDate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/overflowdate").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get underflow date value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetUnderflowDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetUnderflowDate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/underflowdate").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put max date value 9999-12-31
/// </summary>
/// <param name='dateBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutMaxDateWithHttpMessagesAsync(DateTime? dateBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (dateBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "dateBody");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("dateBody", dateBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutMaxDate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/max").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter());
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get max date value 9999-12-31
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetMaxDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMaxDate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/max").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put min date value 0000-01-01
/// </summary>
/// <param name='dateBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutMinDateWithHttpMessagesAsync(DateTime? dateBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (dateBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "dateBody");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("dateBody", dateBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutMinDate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/min").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter());
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get min date value 0000-01-01
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetMinDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMinDate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/min").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
namespace XenAdmin.Dialogs
{
partial class NewDiskDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NewDiskDialog));
this.DiskSizeNumericUpDown = new System.Windows.Forms.NumericUpDown();
this.SrListBox = new XenAdmin.Controls.SrPicker();
this.GbLabel = new System.Windows.Forms.Label();
this.CloseButton = new System.Windows.Forms.Button();
this.OkButton = new System.Windows.Forms.Button();
this.NameTextBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.DescriptionTextBox = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.panel1 = new System.Windows.Forms.FlowLayoutPanel();
this.label4 = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.comboBoxUnits = new System.Windows.Forms.ComboBox();
this.labelError = new System.Windows.Forms.Label();
this.pictureBoxError = new System.Windows.Forms.PictureBox();
this.label6 = new System.Windows.Forms.Label();
this.labelAllocationQuantum = new System.Windows.Forms.Label();
this.labelInitialAllocation = new System.Windows.Forms.Label();
this.initialAllocationNumericUpDown = new System.Windows.Forms.NumericUpDown();
this.allocationQuantumNumericUpDown = new System.Windows.Forms.NumericUpDown();
this.init_alloc_units = new System.Windows.Forms.ComboBox();
this.incr_alloc_units = new System.Windows.Forms.ComboBox();
this.queuedBackgroundWorker1 = new XenCenterLib.QueuedBackgroundWorker();
((System.ComponentModel.ISupportInitialize)(this.DiskSizeNumericUpDown)).BeginInit();
this.tableLayoutPanel1.SuspendLayout();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.initialAllocationNumericUpDown)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.allocationQuantumNumericUpDown)).BeginInit();
this.SuspendLayout();
//
// DiskSizeNumericUpDown
//
resources.ApplyResources(this.DiskSizeNumericUpDown, "DiskSizeNumericUpDown");
this.DiskSizeNumericUpDown.Maximum = new decimal(new int[] {
1000000000,
0,
0,
0});
this.DiskSizeNumericUpDown.Name = "DiskSizeNumericUpDown";
this.DiskSizeNumericUpDown.Value = new decimal(new int[] {
1,
0,
0,
0});
this.DiskSizeNumericUpDown.ValueChanged += new System.EventHandler(this.DiskSizeNumericUpDown_ValueChanged);
this.DiskSizeNumericUpDown.KeyUp += new System.Windows.Forms.KeyEventHandler(this.DiskSizeNumericUpDown_KeyUp);
//
// SrListBox
//
this.tableLayoutPanel1.SetColumnSpan(this.SrListBox, 3);
this.SrListBox.Connection = null;
resources.ApplyResources(this.SrListBox, "SrListBox");
this.SrListBox.Name = "SrListBox";
//
// GbLabel
//
resources.ApplyResources(this.GbLabel, "GbLabel");
this.GbLabel.Name = "GbLabel";
//
// CloseButton
//
resources.ApplyResources(this.CloseButton, "CloseButton");
this.CloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CloseButton.Name = "CloseButton";
this.CloseButton.UseVisualStyleBackColor = true;
this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click);
//
// OkButton
//
resources.ApplyResources(this.OkButton, "OkButton");
this.OkButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.OkButton.Name = "OkButton";
this.OkButton.UseVisualStyleBackColor = true;
this.OkButton.Click += new System.EventHandler(this.OkButton_Click);
//
// NameTextBox
//
this.tableLayoutPanel1.SetColumnSpan(this.NameTextBox, 3);
resources.ApplyResources(this.NameTextBox, "NameTextBox");
this.NameTextBox.Name = "NameTextBox";
this.NameTextBox.TextChanged += new System.EventHandler(this.NameTextBox_TextChanged);
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// DescriptionTextBox
//
this.tableLayoutPanel1.SetColumnSpan(this.DescriptionTextBox, 3);
resources.ApplyResources(this.DescriptionTextBox, "DescriptionTextBox");
this.DescriptionTextBox.Name = "DescriptionTextBox";
this.DescriptionTextBox.TextChanged += new System.EventHandler(this.NameTextBox_TextChanged);
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.label2, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.label1, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.NameTextBox, 1, 2);
this.tableLayoutPanel1.Controls.Add(this.DescriptionTextBox, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.SrListBox, 1, 5);
this.tableLayoutPanel1.Controls.Add(this.label3, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.DiskSizeNumericUpDown, 1, 4);
this.tableLayoutPanel1.Controls.Add(this.panel1, 1, 9);
this.tableLayoutPanel1.Controls.Add(this.label4, 0, 5);
this.tableLayoutPanel1.Controls.Add(this.panel2, 2, 4);
this.tableLayoutPanel1.Controls.Add(this.label6, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.labelAllocationQuantum, 0, 7);
this.tableLayoutPanel1.Controls.Add(this.labelInitialAllocation, 0, 6);
this.tableLayoutPanel1.Controls.Add(this.initialAllocationNumericUpDown, 1, 6);
this.tableLayoutPanel1.Controls.Add(this.allocationQuantumNumericUpDown, 1, 7);
this.tableLayoutPanel1.Controls.Add(this.init_alloc_units, 2, 6);
this.tableLayoutPanel1.Controls.Add(this.incr_alloc_units, 2, 7);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.tableLayoutPanel1.SetColumnSpan(this.panel1, 3);
this.panel1.Controls.Add(this.CloseButton);
this.panel1.Controls.Add(this.OkButton);
this.panel1.Name = "panel1";
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// panel2
//
resources.ApplyResources(this.panel2, "panel2");
this.tableLayoutPanel1.SetColumnSpan(this.panel2, 2);
this.panel2.Controls.Add(this.comboBoxUnits);
this.panel2.Controls.Add(this.labelError);
this.panel2.Controls.Add(this.pictureBoxError);
this.panel2.Name = "panel2";
//
// comboBoxUnits
//
this.comboBoxUnits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.comboBoxUnits, "comboBoxUnits");
this.comboBoxUnits.FormattingEnabled = true;
this.comboBoxUnits.Items.AddRange(new object[] {
resources.GetString("comboBoxUnits.Items"),
resources.GetString("comboBoxUnits.Items1")});
this.comboBoxUnits.Name = "comboBoxUnits";
//
// labelError
//
resources.ApplyResources(this.labelError, "labelError");
this.labelError.ForeColor = System.Drawing.Color.Red;
this.labelError.Name = "labelError";
//
// pictureBoxError
//
resources.ApplyResources(this.pictureBoxError, "pictureBoxError");
this.pictureBoxError.Name = "pictureBoxError";
this.pictureBoxError.TabStop = false;
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.tableLayoutPanel1.SetColumnSpan(this.label6, 4);
this.label6.Name = "label6";
//
// labelAllocationQuantum
//
resources.ApplyResources(this.labelAllocationQuantum, "labelAllocationQuantum");
this.labelAllocationQuantum.Name = "labelAllocationQuantum";
//
// labelInitialAllocation
//
resources.ApplyResources(this.labelInitialAllocation, "labelInitialAllocation");
this.labelInitialAllocation.Name = "labelInitialAllocation";
//
// initialAllocationNumericUpDown
//
resources.ApplyResources(this.initialAllocationNumericUpDown, "initialAllocationNumericUpDown");
this.initialAllocationNumericUpDown.DecimalPlaces = 1;
this.initialAllocationNumericUpDown.Name = "initialAllocationNumericUpDown";
this.initialAllocationNumericUpDown.Value = new decimal(new int[] {
10,
0,
0,
0});
this.initialAllocationNumericUpDown.ValueChanged += new System.EventHandler(this.initialAllocationNumericUpDown_ValueChanged);
this.initialAllocationNumericUpDown.Enter += new System.EventHandler(this.initialAllocationNumericUpDown_Enter);
this.initialAllocationNumericUpDown.Leave += new System.EventHandler(this.initialAllocationNumericUpDown_Leave);
//
// allocationQuantumNumericUpDown
//
resources.ApplyResources(this.allocationQuantumNumericUpDown, "allocationQuantumNumericUpDown");
this.allocationQuantumNumericUpDown.DecimalPlaces = 1;
this.allocationQuantumNumericUpDown.Name = "allocationQuantumNumericUpDown";
this.allocationQuantumNumericUpDown.Value = new decimal(new int[] {
10,
0,
0,
0});
//
// init_alloc_units
//
this.init_alloc_units.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.init_alloc_units, "init_alloc_units");
this.init_alloc_units.FormattingEnabled = true;
this.init_alloc_units.Items.AddRange(new object[] {
resources.GetString("init_alloc_units.Items"),
resources.GetString("init_alloc_units.Items1")});
this.init_alloc_units.Name = "init_alloc_units";
this.init_alloc_units.SelectedIndexChanged += new System.EventHandler(this.init_alloc_units_SelectedIndexChanged);
//
// incr_alloc_units
//
this.incr_alloc_units.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.incr_alloc_units, "incr_alloc_units");
this.incr_alloc_units.FormattingEnabled = true;
this.incr_alloc_units.Items.AddRange(new object[] {
resources.GetString("incr_alloc_units.Items"),
resources.GetString("incr_alloc_units.Items1")});
this.incr_alloc_units.Name = "incr_alloc_units";
this.incr_alloc_units.SelectedIndexChanged += new System.EventHandler(this.incr_alloc_units_SelectedIndexChanged);
//
// NewDiskDialog
//
this.AcceptButton = this.OkButton;
resources.ApplyResources(this, "$this");
this.CancelButton = this.CloseButton;
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.GbLabel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
this.Name = "NewDiskDialog";
((System.ComponentModel.ISupportInitialize)(this.DiskSizeNumericUpDown)).EndInit();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.initialAllocationNumericUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.allocationQuantumNumericUpDown)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label GbLabel;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label1;
public System.Windows.Forms.NumericUpDown DiskSizeNumericUpDown;
public XenAdmin.Controls.SrPicker SrListBox;
public System.Windows.Forms.Button CloseButton;
public System.Windows.Forms.Button OkButton;
public System.Windows.Forms.TextBox NameTextBox;
public System.Windows.Forms.TextBox DescriptionTextBox;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.FlowLayoutPanel panel1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label labelError;
private System.Windows.Forms.PictureBox pictureBoxError;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ComboBox comboBoxUnits;
private XenCenterLib.QueuedBackgroundWorker queuedBackgroundWorker1;
private System.Windows.Forms.Label labelAllocationQuantum;
private System.Windows.Forms.Label labelInitialAllocation;
private System.Windows.Forms.NumericUpDown initialAllocationNumericUpDown;
private System.Windows.Forms.NumericUpDown allocationQuantumNumericUpDown;
private System.Windows.Forms.ComboBox init_alloc_units;
private System.Windows.Forms.ComboBox incr_alloc_units;
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.Security.PassportIdentity.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.Security
{
sealed public partial class PassportIdentity : System.Security.Principal.IIdentity, IDisposable
{
#region Methods and constructors
public string AuthUrl(string strReturnUrl, int iTimeWindow, int iForceLogin, string strCoBrandedArgs, int iLangID, string strNameSpace, int iKPP, int iUseSecureAuth)
{
return default(string);
}
public string AuthUrl(string strReturnUrl)
{
return default(string);
}
public string AuthUrl()
{
return default(string);
}
public string AuthUrl(string strReturnUrl, int iTimeWindow, bool fForceLogin, string strCoBrandedArgs, int iLangID, string strNameSpace, int iKPP, bool bUseSecureAuth)
{
return default(string);
}
public string AuthUrl2(string strReturnUrl)
{
return default(string);
}
public string AuthUrl2()
{
return default(string);
}
public string AuthUrl2(string strReturnUrl, int iTimeWindow, bool fForceLogin, string strCoBrandedArgs, int iLangID, string strNameSpace, int iKPP, bool bUseSecureAuth)
{
return default(string);
}
public string AuthUrl2(string strReturnUrl, int iTimeWindow, int iForceLogin, string strCoBrandedArgs, int iLangID, string strNameSpace, int iKPP, int iUseSecureAuth)
{
return default(string);
}
public static string Compress(string strData)
{
return default(string);
}
public static bool CryptIsValid()
{
return default(bool);
}
public static int CryptPutHost(string strHost)
{
return default(int);
}
public static int CryptPutSite(string strSite)
{
return default(int);
}
public static string Decompress(string strData)
{
return default(string);
}
public static string Decrypt(string strData)
{
return default(string);
}
public static string Encrypt(string strData)
{
return default(string);
}
public Object GetCurrentConfig(string strAttribute)
{
return default(Object);
}
public string GetDomainAttribute(string strAttribute, int iLCID, string strDomain)
{
return default(string);
}
public string GetDomainFromMemberName(string strMemberName)
{
return default(string);
}
public bool GetIsAuthenticated(int iTimeWindow, int iForceLogin, int iCheckSecure)
{
return default(bool);
}
public bool GetIsAuthenticated(int iTimeWindow, bool bForceLogin, bool bCheckSecure)
{
return default(bool);
}
public string GetLoginChallenge()
{
return default(string);
}
public string GetLoginChallenge(string szRetURL, int iTimeWindow, int fForceLogin, string szCOBrandArgs, int iLangID, string strNameSpace, int iKPP, int iUseSecureAuth, Object oExtraParams)
{
return default(string);
}
public string GetLoginChallenge(string strReturnUrl)
{
return default(string);
}
public Object GetOption(string strOpt)
{
return default(Object);
}
public Object GetProfileObject(string strProfileName)
{
return default(Object);
}
public bool HasFlag(int iFlagMask)
{
return default(bool);
}
public bool HasProfile(string strProfile)
{
return default(bool);
}
public bool HaveConsent(bool bNeedFullConsent, bool bNeedBirthdate)
{
return default(bool);
}
public int LoginUser()
{
return default(int);
}
public int LoginUser(string szRetURL, int iTimeWindow, int fForceLogin, string szCOBrandArgs, int iLangID, string strNameSpace, int iKPP, int iUseSecureAuth, Object oExtraParams)
{
return default(int);
}
public int LoginUser(string szRetURL, int iTimeWindow, bool fForceLogin, string szCOBrandArgs, int iLangID, string strNameSpace, int iKPP, bool fUseSecureAuth, Object oExtraParams)
{
return default(int);
}
public int LoginUser(string strReturnUrl)
{
return default(int);
}
public string LogoTag()
{
return default(string);
}
public string LogoTag(string strReturnUrl, int iTimeWindow, int iForceLogin, string strCoBrandedArgs, int iLangID, int iSecure, string strNameSpace, int iKPP, int iUseSecureAuth)
{
return default(string);
}
public string LogoTag(string strReturnUrl)
{
return default(string);
}
public string LogoTag(string strReturnUrl, int iTimeWindow, bool fForceLogin, string strCoBrandedArgs, int iLangID, bool fSecure, string strNameSpace, int iKPP, bool bUseSecureAuth)
{
return default(string);
}
public string LogoTag2(string strReturnUrl)
{
return default(string);
}
public string LogoTag2()
{
return default(string);
}
public string LogoTag2(string strReturnUrl, int iTimeWindow, int iForceLogin, string strCoBrandedArgs, int iLangID, int iSecure, string strNameSpace, int iKPP, int iUseSecureAuth)
{
return default(string);
}
public string LogoTag2(string strReturnUrl, int iTimeWindow, bool fForceLogin, string strCoBrandedArgs, int iLangID, bool fSecure, string strNameSpace, int iKPP, bool bUseSecureAuth)
{
return default(string);
}
public string LogoutURL(string szReturnURL, string szCOBrandArgs, int iLangID, string strDomain, int iUseSecureAuth)
{
return default(string);
}
public string LogoutURL()
{
return default(string);
}
public PassportIdentity()
{
}
public void SetOption(string strOpt, Object vOpt)
{
}
public static void SignOut(string strSignOutDotGifFileName)
{
}
void System.IDisposable.Dispose()
{
}
public Object Ticket(string strAttribute)
{
return default(Object);
}
#endregion
#region Properties and indexers
public string AuthenticationType
{
get
{
return default(string);
}
}
public int Error
{
get
{
return default(int);
}
}
public bool GetFromNetworkServer
{
get
{
return default(bool);
}
}
public bool HasSavedPassword
{
get
{
return default(bool);
}
}
public bool HasTicket
{
get
{
return default(bool);
}
}
public string HexPUID
{
get
{
return default(string);
}
}
public bool IsAuthenticated
{
get
{
return default(bool);
}
}
public string this [string strProfileName]
{
get
{
return default(string);
}
}
public string Name
{
get
{
return default(string);
}
}
public int TicketAge
{
get
{
return default(int);
}
}
public int TimeSinceSignIn
{
get
{
return default(int);
}
}
#endregion
}
}
| |
//
// Copyright 2013 Matthew Ducker
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace Obscur.Core.Cryptography
{
/// <summary>
/// Extension methods for cryptographic use.
/// </summary>
public static class CryptographyExtensions
{
/// <summary>
/// A constant time equals comparison - does not terminate early if
/// test will fail.
/// Checks as far as <paramref name="a"/> is in length.
/// </summary>
/// <param name="a">Array to compare against.</param>
/// <param name="b">Array to test for equality.</param>
/// <returns>If <c>true</c>, array section tested is equal.</returns>
public static bool SequenceEqual_ConstantTime(this byte[] a, byte[] b)
{
return a.SequenceEqual_ConstantTime(0, b, 0, a.Length);
}
/// <summary>
/// A constant time equals comparison - does not terminate early if
/// test will fail.
/// </summary>
/// <param name="x">Array to compare against.</param>
/// <param name="xOffset">Index in <paramref name="x"/> to start comparison at.</param>
/// <param name="y">Array to test for equality.</param>
/// <param name="yOffset">Index in <paramref name="y"/> to start comparison at.</param>
/// <param name="length">Number of bytes to compare.</param>
/// <returns>If <c>true</c>, array section tested is equal.</returns>
public static bool SequenceEqual_ConstantTime(this byte[] x, int xOffset, byte[] y, int yOffset, int length)
{
if (x == null && y == null) {
return true;
}
if (x == null) {
throw new ArgumentNullException("x");
}
if (xOffset < 0) {
throw new ArgumentOutOfRangeException("xOffset", "xOffset < 0");
}
if (y == null) {
throw new ArgumentNullException("y");
}
if (yOffset < 0) {
throw new ArgumentOutOfRangeException("yOffset", "yOffset < 0");
}
if (length < 0) {
throw new ArgumentOutOfRangeException("length", "length < 0");
}
if ((uint) xOffset + (uint) length > (uint) x.Length) {
throw new ArgumentOutOfRangeException("length", "xOffset + length > x.Length");
}
if ((uint) yOffset + (uint) length > (uint) y.Length) {
throw new ArgumentOutOfRangeException("length", "yOffset + length > y.Length");
}
return SequenceEqual_ConstantTime_NoChecks(x, xOffset, y, yOffset, length);
}
// From CodesInChaos
private static bool SequenceEqual_ConstantTime_NoChecks(byte[] x, int xOffset, byte[] y, int yOffset, int length)
{
int differentbits = 0;
for (int i = 0; i < length; i++) {
differentbits |= x[xOffset + i] ^ y[yOffset + i];
}
return (1 & (((uint) differentbits - 1) >> 8)) != 0;
}
/// <summary>
/// XOR byte arrays <paramref name="a"/> and <paramref name="b"/> together into <paramref name="output"/>.
/// </summary>
/// <param name="a">Source #0 array.</param>
/// <param name="aOff">Source array #0 offset.</param>
/// <param name="b">Source #1 array.</param>
/// <param name="bOff">Source #1 array offset.</param>
/// <param name="output">Output array.</param>
/// <param name="outputOff">Output array offset.</param>
/// <param name="length">Length to XOR.</param>
public static void Xor(this byte[] a, int aOff, byte[] b, int bOff, byte[] output, int outputOff, int length)
{
if (length <= 0) {
throw new ArgumentException("Length is not positive.", "length");
}
if (a == null) {
throw new ArgumentNullException("a");
}
if (aOff < 0) {
throw new ArgumentOutOfRangeException("aOff", "aOff must be 0 or positive.");
}
if (aOff + length > a.Length) {
throw new ArgumentException("Insufficient length.", "a");
}
if (b == null) {
throw new ArgumentNullException("b");
}
if (bOff < 0) {
throw new ArgumentOutOfRangeException("bOff", "bOff must be 0 or positive.");
}
if (bOff + length > b.Length) {
throw new ArgumentException("Insufficient length.", "b");
}
if (output == null) {
throw new ArgumentNullException("output");
}
if (outputOff < 0) {
throw new ArgumentOutOfRangeException("outputOff", "outputOff must be 0 or positive.");
}
if (outputOff + length > output.Length) {
throw new DataLengthException("Insufficient length.", "output");
}
XorInternal(a, aOff, b, bOff, output, outputOff, length);
}
private const int XorUnmanagedLengthThreshold = 128;
internal static void XorInternal(this byte[] a, int aOff, byte[] b, int bOff, byte[] output, int outputOff,
int length)
{
#if (INCLUDE_UNSAFE)
if (length > XorUnmanagedLengthThreshold) {
unsafe {
fixed (byte* aPtr = a) {
fixed (byte* bPtr = b) {
fixed (byte* outPtr = output) {
XorMemory(aPtr + aOff, bPtr + bOff, outPtr + outputOff, length);
}
}
}
}
}
#endif
for (var i = 0; i < length; i++) {
output[outputOff + i] = (byte) (a[aOff + i] ^ b[bOff + i]);
}
}
/// <summary>
/// XOR the specified byte array <paramref name="b"/> into <paramref name="a"/> in-place.
/// </summary>
/// <param name="a">Destination and source #0 array.</param>
/// <param name="aOff">Destination and source array #0 offset.</param>
/// <param name="b">Source #1 array.</param>
/// <param name="bOff">Source #1 array offset.</param>
/// <param name="length">Length to XOR.</param>
public static void XorInPlace(this byte[] a, int aOff, byte[] b, int bOff, int length)
{
if (length <= 0) {
throw new ArgumentException("Length is not positive.", "length");
}
if (aOff < 0) {
throw new ArgumentOutOfRangeException("aOff", "aOff must be 0 or positive.");
}
if (aOff + length > a.Length) {
throw new ArgumentException("Insufficient length.", "a");
}
if (bOff < 0) {
throw new ArgumentOutOfRangeException("bOff", "bOff must be 0 or positive.");
}
if (bOff + length > b.Length) {
throw new ArgumentException("Insufficient length.", "b");
}
XorInPlaceInternal(a, aOff, b, bOff, length);
}
internal static void XorInPlaceInternal(this byte[] a, int aOff, byte[] b, int bOff, int length)
{
#if (INCLUDE_UNSAFE)
if (length > XorUnmanagedLengthThreshold) {
unsafe {
fixed (byte* aPtr = a) {
fixed (byte* bPtr = b) {
XorMemoryInPlace(aPtr + aOff, bPtr + bOff, length);
}
}
}
}
#endif
for (var i = 0; i < length; i++) {
a[aOff + i] ^= b[bOff + i];
}
}
#if INCLUDE_UNSAFE
internal static unsafe void XorMemory(byte* a, byte* b, byte* output, int length)
{
byte* outputEnd = output + length;
const int u32Size = sizeof(UInt32);
if (StratCom.PlatformWordSize == u32Size) {
// 32-bit
while (output + (u32Size * 2) <= outputEnd) {
*(UInt32*)output = *(UInt32*)a ^ *(UInt32*)b;
a += u32Size;
b += u32Size;
output += u32Size;
*(UInt32*)output = *(UInt32*)a ^ *(UInt32*)b;
a += u32Size;
b += u32Size;
output += u32Size;
}
} else if (StratCom.PlatformWordSize == sizeof(UInt64)) {
// 64-bit
const int u64Size = sizeof(UInt64);
while (output + (u64Size * 2) <= outputEnd) {
*(UInt32*)output = *(UInt32*)a ^ *(UInt32*)b;
a += u64Size;
b += u64Size;
output += u64Size;
*(UInt32*)output = *(UInt32*)a ^ *(UInt32*)b;
a += u64Size;
b += u64Size;
output += u64Size;
}
if (output + u64Size <= outputEnd) {
*(UInt64*) output = *(UInt64*) a ^ *(UInt64*) b;
a += u64Size;
b += u64Size;
output += u64Size;
}
}
if (output + u32Size <= outputEnd) {
*(UInt32*)output = *(UInt32*)a ^ *(UInt32*)b;
a += u32Size;
b += u32Size;
output += u32Size;
}
if (output + sizeof(UInt16) <= outputEnd) {
*(UInt16*)output = (UInt16)(*(UInt16*)a ^ *(UInt16*)b);
a += sizeof(UInt16);
b += sizeof(UInt16);
output += sizeof(UInt16);
}
if (output + 1 <= outputEnd) {
*output = (byte)(*a ^ *b);
}
}
/// <summary>
/// XOR the specified data in <paramref name="b"/> into <paramref name="a"/> in-place.
/// </summary>
/// <param name="a">Pointer to source of and destination for data.</param>
/// <param name="b">Pointer to source of data.</param>
/// <param name="length">Length of data to copy in bytes.</param>
internal static unsafe void XorMemoryInPlace(byte* a, byte* b, int length)
{
const int u32Size = sizeof(UInt32);
byte* aEnd = a + length;
if (StratCom.PlatformWordSize == u32Size) {
// 32-bit
while (a + u32Size * 2 <= aEnd) {
*(UInt32*) a ^= *(UInt32*) b;
a += u32Size;
b += u32Size;
*(UInt32*) a ^= *(UInt32*) b;
a += u32Size;
b += u32Size;
}
} else if (StratCom.PlatformWordSize == sizeof(UInt64)) {
// 64-bit
const int u64Size = sizeof(UInt64);
while (a + u64Size * 2 <= aEnd) {
*(UInt64*) a ^= *(UInt64*) b;
a += u64Size;
b += u64Size;
*(UInt64*) a ^= *(UInt64*) b;
a += u64Size;
b += u64Size;
}
if (a + u64Size <= aEnd) {
*(UInt64*) a ^= *(UInt64*) b;
a += u64Size;
b += u64Size;
}
}
if (a + u32Size <= aEnd) {
*(UInt32*)a ^= *(UInt32*)b;
a += u32Size;
b += u32Size;
}
if (a + sizeof(UInt16) >= aEnd) {
*(UInt16*)a ^= *(UInt16*)b;
a += sizeof(UInt16);
b += sizeof(UInt16);
}
if (a + 1 <= aEnd) {
*a ^= *b;
}
}
#endif
/// <summary>
/// Securely erase <paramref name="data"/> by clearing the memory used to store it.
/// </summary>
/// <param name="data">Data to erase.</param>
public static void SecureWipe<T>(this T[] data) where T : struct
{
if (data == null) {
throw new ArgumentNullException("data");
}
InternalWipe(data, 0, data.Length);
}
/// <summary>
/// Securely erase <paramref name="data"/> by clearing the memory used to store it.
/// </summary>
/// <param name="data">Data to erase.</param>
/// <param name="offset">Offset in <paramref name="data"/> to erase from.</param>
/// <param name="count">Number of elements to erase.</param>
public static void SecureWipe<T>(this T[] data, int offset, int count) where T : struct
{
Contract.Requires<ArgumentNullException>(data != null);
Contract.Requires<ArgumentOutOfRangeException>(offset >= 0);
Contract.Requires<ArgumentOutOfRangeException>(count > 0);
Contract.Ensures(offset + count <= data.Length);
InternalWipe(data, offset, count);
}
/// <summary>
/// Securely erase <paramref name="data"/> by clearing the memory used to store it.
/// </summary>
/// <param name="data">Data to erase.</param>
public static void SecureWipe(this byte[] data)
{
Contract.Requires<ArgumentNullException>(data != null);
InternalWipe(data, 0, data.Length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InternalWipe<T>(T[] data, int offset, int count) where T : struct
{
Array.Clear(data, offset, count);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InternalWipe(byte[] data, int offset, int count)
{
#if INCLUDE_UNSAFE
unsafe {
fixed (byte* ptr = data) {
WipeMemory(ptr + offset, count);
}
}
#else
Array.Clear(data, offset, count);
#endif
}
#if INCLUDE_UNSAFE
internal static unsafe void WipeMemory(ushort* src, int length)
{
WipeMemory((byte*)src, sizeof(ushort) * length);
}
internal static unsafe void WipeMemory(uint* src, int length)
{
WipeMemory((byte*)src, sizeof(uint) * length);
}
internal static unsafe void WipeMemory(ulong* src, int length)
{
WipeMemory((byte*)src, sizeof(ulong) * length);
}
internal static unsafe void WipeMemory(byte* src, int length)
{
const int u32Size = sizeof(UInt32);
if (StratCom.PlatformWordSize == u32Size) {
while (length >= u32Size * 2) {
*(UInt32*)src = 0u;
src += u32Size;
*(UInt32*)src = 0u;
src += u32Size;
length -= u32Size * 2;
}
} else if (StratCom.PlatformWordSize == sizeof(UInt64)) {
const int u64Size = sizeof(UInt64);
while (length >= u64Size * 2) {
*(UInt64*)src = 0ul;
src += u64Size;
*(UInt64*)src = 0ul;
src += u64Size;
length -= u64Size * 2;
}
if (length >= u64Size) {
*(UInt64*)src = 0ul;
src += u64Size;
length -= u64Size;
}
}
if (length >= u32Size) {
*(UInt32*) src = 0u;
src += u32Size;
length -= u32Size;
}
if (length >= sizeof(UInt16)) {
*(UInt16*)src = (UInt16)0u;
src += sizeof(UInt16);
length -= sizeof(UInt16);
}
if (length > 0) {
*src = (byte)0;
}
}
internal static unsafe void SetMemory(byte* src, byte val, int length)
{
byte* val64 = stackalloc byte[sizeof(UInt64)];
for (int i = 0; i < sizeof(UInt64); i++) {
val64[i] = val;
}
if (StratCom.PlatformWordSize == sizeof(UInt32)) {
while (length >= sizeof(UInt64)) {
*(UInt32*)src = *(UInt32*)val64;
src += sizeof(UInt32);
*(UInt32*)src = *(UInt32*)val64;
src += sizeof(UInt32);
length -= sizeof(UInt64);
}
} else if (StratCom.PlatformWordSize == sizeof(UInt64)) {
while (length >= sizeof(UInt64) * 2) {
*(UInt64*)src = *val64;
src += sizeof(UInt64);
*(UInt64*)src = *val64;
src += sizeof(UInt64);
length -= sizeof(UInt64) * 2;
}
if (length >= sizeof(UInt64)) {
*(UInt64*)src = *val64;
src += sizeof(UInt64);
length -= sizeof(UInt64);
}
}
if (length >= sizeof(UInt32)) {
*(UInt32*)src = *(UInt32*)val64;
src += sizeof(UInt32);
length -= sizeof(UInt32);
}
if (length >= sizeof(UInt16)) {
*(UInt16*)src = *(UInt16*)val64;
src += sizeof(UInt16);
length -= sizeof(UInt16);
}
if (length > 0) {
*src = val;
}
}
#endif
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudioTools.Parsing;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
using VSConstants = Microsoft.VisualStudio.VSConstants;
namespace Microsoft.VisualStudioTools.Navigation
{
/// <summary>
/// This is a specialized version of the LibraryNode that handles the dynamic languages
/// items. The main difference from the generic one is that it supports navigation
/// to the location inside the source code where the element is defined.
/// </summary>
internal abstract class CommonLibraryNode : LibraryNode
{
private readonly IVsHierarchy _ownerHierarchy;
private readonly uint _fileId;
private readonly TextSpan _sourceSpan;
private readonly IScopeNode _scope;
private string _fileMoniker;
protected CommonLibraryNode(LibraryNode parent, IScopeNode scope, string namePrefix, IVsHierarchy hierarchy, uint itemId) :
base(parent, GetLibraryNodeName(scope, namePrefix), namePrefix + scope.Name, scope.NodeType)
{
this._ownerHierarchy = hierarchy;
this._fileId = itemId;
// Now check if we have all the information to navigate to the source location.
if ((null != this._ownerHierarchy) && (VSConstants.VSITEMID_NIL != this._fileId))
{
if ((SourceLocation.Invalid != scope.Start) && (SourceLocation.Invalid != scope.End))
{
this._sourceSpan = new TextSpan();
this._sourceSpan.iStartIndex = scope.Start.Column - 1;
if (scope.Start.Line > 0)
{
this._sourceSpan.iStartLine = scope.Start.Line - 1;
}
this._sourceSpan.iEndIndex = scope.End.Column;
if (scope.End.Line > 0)
{
this._sourceSpan.iEndLine = scope.End.Line - 1;
}
this.CanGoToSource = true;
}
}
this._scope = scope;
}
internal IScopeNode ScopeNode => this._scope;
public TextSpan SourceSpan => this._sourceSpan;
private static string GetLibraryNodeName(IScopeNode node, string namePrefix)
{
namePrefix = namePrefix.Substring(namePrefix.LastIndexOf(':') + 1); // remove filename prefix
return node.NodeType == LibraryNodeType.Members ? node.Name : string.Format(CultureInfo.InvariantCulture, "{0}{1}", namePrefix, node.Name);
}
protected CommonLibraryNode(CommonLibraryNode node) :
base(node)
{
this._fileId = node._fileId;
this._ownerHierarchy = node._ownerHierarchy;
this._fileMoniker = node._fileMoniker;
this._sourceSpan = node._sourceSpan;
}
protected CommonLibraryNode(CommonLibraryNode node, string newFullName) :
base(node, newFullName)
{
this._scope = node._scope;
this._fileId = node._fileId;
this._ownerHierarchy = node._ownerHierarchy;
this._fileMoniker = node._fileMoniker;
this._sourceSpan = node._sourceSpan;
}
public override uint CategoryField(LIB_CATEGORY category)
{
switch (category)
{
case (LIB_CATEGORY)_LIB_CATEGORY2.LC_MEMBERINHERITANCE:
if (this.NodeType == LibraryNodeType.Members || this.NodeType == LibraryNodeType.Definitions)
{
return (uint)_LIBCAT_MEMBERINHERITANCE.LCMI_IMMEDIATE;
}
break;
}
return base.CategoryField(category);
}
public override void GotoSource(VSOBJGOTOSRCTYPE gotoType)
{
// We do not support the "Goto Reference"
if (VSOBJGOTOSRCTYPE.GS_REFERENCE == gotoType)
{
return;
}
// There is no difference between definition and declaration, so here we
// don't check for the other flags.
IVsWindowFrame frame = null;
var documentData = FindDocDataFromRDT();
try
{
// Now we can try to open the editor. We assume that the owner hierarchy is
// a project and we want to use its OpenItem method.
var project = this._ownerHierarchy as IVsProject3;
if (null == project)
{
return;
}
var viewGuid = VSConstants.LOGVIEWID_Code;
ErrorHandler.ThrowOnFailure(project.OpenItem(this._fileId, ref viewGuid, documentData, out frame));
}
finally
{
if (IntPtr.Zero != documentData)
{
Marshal.Release(documentData);
documentData = IntPtr.Zero;
}
}
// Make sure that the document window is visible.
ErrorHandler.ThrowOnFailure(frame.Show());
// Get the code window from the window frame.
object docView;
ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out docView));
var codeWindow = docView as IVsCodeWindow;
if (null == codeWindow)
{
object docData;
ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData));
codeWindow = docData as IVsCodeWindow;
if (null == codeWindow)
{
return;
}
}
// Get the primary view from the code window.
IVsTextView textView;
ErrorHandler.ThrowOnFailure(codeWindow.GetPrimaryView(out textView));
// Set the cursor at the beginning of the declaration.
ErrorHandler.ThrowOnFailure(textView.SetCaretPos(this._sourceSpan.iStartLine, this._sourceSpan.iStartIndex));
// Make sure that the text is visible.
var visibleSpan = new TextSpan();
visibleSpan.iStartLine = this._sourceSpan.iStartLine;
visibleSpan.iStartIndex = this._sourceSpan.iStartIndex;
visibleSpan.iEndLine = this._sourceSpan.iStartLine;
visibleSpan.iEndIndex = this._sourceSpan.iStartIndex + 1;
ErrorHandler.ThrowOnFailure(textView.EnsureSpanVisible(visibleSpan));
}
public override void SourceItems(out IVsHierarchy hierarchy, out uint itemId, out uint itemsCount)
{
hierarchy = this._ownerHierarchy;
itemId = this._fileId;
itemsCount = 1;
}
public override string UniqueName
{
get
{
if (string.IsNullOrEmpty(this._fileMoniker))
{
ErrorHandler.ThrowOnFailure(this._ownerHierarchy.GetCanonicalName(this._fileId, out this._fileMoniker));
}
return string.Format(CultureInfo.InvariantCulture, "{0}/{1}", this._fileMoniker, this.Name);
}
}
private IntPtr FindDocDataFromRDT()
{
// Get a reference to the RDT.
var rdt = Package.GetGlobalService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (null == rdt)
{
return IntPtr.Zero;
}
// Get the enumeration of the running documents.
IEnumRunningDocuments documents;
ErrorHandler.ThrowOnFailure(rdt.GetRunningDocumentsEnum(out documents));
var documentData = IntPtr.Zero;
var docCookie = new uint[1];
uint fetched;
while ((VSConstants.S_OK == documents.Next(1, docCookie, out fetched)) && (1 == fetched))
{
uint flags;
uint editLocks;
uint readLocks;
string moniker;
IVsHierarchy docHierarchy;
uint docId;
var docData = IntPtr.Zero;
try
{
ErrorHandler.ThrowOnFailure(
rdt.GetDocumentInfo(docCookie[0], out flags, out readLocks, out editLocks, out moniker, out docHierarchy, out docId, out docData));
// Check if this document is the one we are looking for.
if ((docId == this._fileId) && (this._ownerHierarchy.Equals(docHierarchy)))
{
documentData = docData;
docData = IntPtr.Zero;
break;
}
}
finally
{
if (IntPtr.Zero != docData)
{
Marshal.Release(docData);
}
}
}
return documentData;
}
}
}
| |
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2017 Baldur Karlsson
* Copyright (c) 2014 Crytek
*
* 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.Runtime.InteropServices;
using System.Collections.Generic;
namespace renderdoc
{
// this isn't an Interop struct, since it needs to be passed C# -> C++ and
// it's not POD which we don't support. It's here just as a utility container
public class EnvironmentModification
{
public string variable;
public string value;
public EnvironmentModificationType type;
public EnvironmentSeparator separator;
public string GetTypeString()
{
string ret;
if (type == EnvironmentModificationType.Append)
ret = String.Format("Append, {0}", separator.Str());
else if (type == EnvironmentModificationType.Prepend)
ret = String.Format("Prepend, {0}", separator.Str());
else
ret = "Set";
return ret;
}
public string GetDescription()
{
string ret;
if (type == EnvironmentModificationType.Append)
ret = String.Format("Append {0} with {1} using {2}", variable, value, separator.Str());
else if (type == EnvironmentModificationType.Prepend)
ret = String.Format("Prepend {0} with {1} using {2}", variable, value, separator.Str());
else
ret = String.Format("Set {0} to {1}", variable, value);
return ret;
}
}
[StructLayout(LayoutKind.Sequential)]
public class TargetControlMessage
{
public TargetControlMessageType Type;
[StructLayout(LayoutKind.Sequential)]
public struct NewCaptureData
{
public UInt32 ID;
public UInt64 timestamp;
[CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
public byte[] thumbnail;
public Int32 thumbWidth;
public Int32 thumbHeight;
[CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
public string path;
public bool local;
};
[CustomMarshalAs(CustomUnmanagedType.CustomClass)]
public NewCaptureData NewCapture;
[StructLayout(LayoutKind.Sequential)]
public struct RegisterAPIData
{
[CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
public string APIName;
};
[CustomMarshalAs(CustomUnmanagedType.CustomClass)]
public RegisterAPIData RegisterAPI;
[StructLayout(LayoutKind.Sequential)]
public struct BusyData
{
[CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
public string ClientName;
};
[CustomMarshalAs(CustomUnmanagedType.CustomClass)]
public BusyData Busy;
[StructLayout(LayoutKind.Sequential)]
public struct NewChildData
{
public UInt32 PID;
public UInt32 ident;
};
[CustomMarshalAs(CustomUnmanagedType.CustomClass)]
public NewChildData NewChild;
};
public class ReplayOutput
{
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_SetTextureDisplay(IntPtr real, TextureDisplay o);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_SetMeshDisplay(IntPtr real, MeshDisplay o);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_ClearThumbnails(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_AddThumbnail(IntPtr real, UInt32 windowSystem, IntPtr wnd, ResourceId texID, FormatComponentType typeHint);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_Display(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_SetPixelContext(IntPtr real, UInt32 windowSystem, IntPtr wnd);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_SetPixelContextLocation(IntPtr real, UInt32 x, UInt32 y);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_DisablePixelContext(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_GetCustomShaderTexID(IntPtr real, ref ResourceId texid);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_GetDebugOverlayTexID(IntPtr real, ref ResourceId texid);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_GetMinMax(IntPtr real, IntPtr outminval, IntPtr outmaxval);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_GetHistogram(IntPtr real, float minval, float maxval, bool[] channels, IntPtr outhistogram);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_PickPixel(IntPtr real, ResourceId texID, bool customShader,
UInt32 x, UInt32 y, UInt32 sliceFace, UInt32 mip, UInt32 sample, IntPtr outval);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 ReplayOutput_PickVertex(IntPtr real, UInt32 eventID, UInt32 x, UInt32 y, IntPtr outPickedInstance);
private IntPtr m_Real = IntPtr.Zero;
public ReplayOutput(IntPtr real) { m_Real = real; }
public void SetTextureDisplay(TextureDisplay o)
{
ReplayOutput_SetTextureDisplay(m_Real, o);
}
public void SetMeshDisplay(MeshDisplay o)
{
ReplayOutput_SetMeshDisplay(m_Real, o);
}
public void ClearThumbnails()
{
ReplayOutput_ClearThumbnails(m_Real);
}
public bool AddThumbnail(IntPtr wnd, ResourceId texID, FormatComponentType typeHint)
{
// 1 == eWindowingSystem_Win32
return ReplayOutput_AddThumbnail(m_Real, 1u, wnd, texID, typeHint);
}
public void Display()
{
ReplayOutput_Display(m_Real);
}
public bool SetPixelContext(IntPtr wnd)
{
// 1 == eWindowingSystem_Win32
return ReplayOutput_SetPixelContext(m_Real, 1u, wnd);
}
public void SetPixelContextLocation(UInt32 x, UInt32 y)
{
ReplayOutput_SetPixelContextLocation(m_Real, x, y);
}
public void DisablePixelContext()
{
ReplayOutput_DisablePixelContext(m_Real);
}
public ResourceId GetCustomShaderTexID()
{
ResourceId ret = ResourceId.Null;
ReplayOutput_GetCustomShaderTexID(m_Real, ref ret);
return ret;
}
public ResourceId GetDebugOverlayTexID()
{
ResourceId ret = ResourceId.Null;
ReplayOutput_GetDebugOverlayTexID(m_Real, ref ret);
return ret;
}
public void GetMinMax(out PixelValue minval, out PixelValue maxval)
{
IntPtr mem1 = CustomMarshal.Alloc(typeof(PixelValue));
IntPtr mem2 = CustomMarshal.Alloc(typeof(PixelValue));
ReplayOutput_GetMinMax(m_Real, mem1, mem2);
minval = (PixelValue)CustomMarshal.PtrToStructure(mem1, typeof(PixelValue), true);
maxval = (PixelValue)CustomMarshal.PtrToStructure(mem2, typeof(PixelValue), true);
CustomMarshal.Free(mem1);
CustomMarshal.Free(mem2);
}
public void GetHistogram(float minval, float maxval,
bool Red, bool Green, bool Blue, bool Alpha,
out UInt32[] histogram)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool[] channels = new bool[] { Red, Green, Blue, Alpha };
ReplayOutput_GetHistogram(m_Real, minval, maxval, channels, mem);
histogram = (UInt32[])CustomMarshal.GetTemplatedArray(mem, typeof(UInt32), true);
CustomMarshal.Free(mem);
}
public PixelValue PickPixel(ResourceId texID, bool customShader, UInt32 x, UInt32 y, UInt32 sliceFace, UInt32 mip, UInt32 sample)
{
IntPtr mem = CustomMarshal.Alloc(typeof(PixelValue));
ReplayOutput_PickPixel(m_Real, texID, customShader, x, y, sliceFace, mip, sample, mem);
PixelValue ret = (PixelValue)CustomMarshal.PtrToStructure(mem, typeof(PixelValue), false);
CustomMarshal.Free(mem);
return ret;
}
public UInt32 PickVertex(UInt32 eventID, UInt32 x, UInt32 y, out UInt32 pickedInstance)
{
IntPtr mem = CustomMarshal.Alloc(typeof(UInt32));
UInt32 pickedVertex = ReplayOutput_PickVertex(m_Real, eventID, x, y, mem);
pickedInstance = (UInt32)CustomMarshal.PtrToStructure(mem, typeof(UInt32), true);
CustomMarshal.Free(mem);
return pickedVertex;
}
};
public class ReplayRenderer
{
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_Shutdown(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetAPIProperties(IntPtr real, IntPtr propsOut);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ReplayRenderer_CreateOutput(IntPtr real, UInt32 windowSystem, IntPtr WindowHandle, OutputType type);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_ShutdownOutput(IntPtr real, IntPtr replayOutput);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_FileChanged(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_HasCallstacks(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_InitResolver(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_SetFrameEvent(IntPtr real, UInt32 eventID, bool force);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetD3D11PipelineState(IntPtr real, IntPtr mem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetD3D12PipelineState(IntPtr real, IntPtr mem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetGLPipelineState(IntPtr real, IntPtr mem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetVulkanPipelineState(IntPtr real, IntPtr mem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetDisassemblyTargets(IntPtr real, IntPtr targets);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_DisassembleShader(IntPtr real, IntPtr refl, IntPtr target, IntPtr isa);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_BuildCustomShader(IntPtr real, IntPtr entry, IntPtr source, UInt32 compileFlags, ShaderStageType type, ref ResourceId shaderID, IntPtr errorMem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_FreeCustomShader(IntPtr real, ResourceId id);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_BuildTargetShader(IntPtr real, IntPtr entry, IntPtr source, UInt32 compileFlags, ShaderStageType type, ref ResourceId shaderID, IntPtr errorMem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_ReplaceResource(IntPtr real, ResourceId from, ResourceId to);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_RemoveReplacement(IntPtr real, ResourceId id);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_FreeTargetResource(IntPtr real, ResourceId id);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetFrameInfo(IntPtr real, IntPtr outframe);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetDrawcalls(IntPtr real, IntPtr outdraws);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_FetchCounters(IntPtr real, IntPtr counters, UInt32 numCounters, IntPtr outresults);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_EnumerateCounters(IntPtr real, IntPtr outcounters);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_DescribeCounter(IntPtr real, UInt32 counter, IntPtr outdesc);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetTextures(IntPtr real, IntPtr outtexs);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetBuffers(IntPtr real, IntPtr outbufs);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetResolve(IntPtr real, UInt64[] callstack, UInt32 callstackLen, IntPtr outtrace);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetDebugMessages(IntPtr real, IntPtr outmsgs);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_PixelHistory(IntPtr real, ResourceId target, UInt32 x, UInt32 y, UInt32 slice, UInt32 mip, UInt32 sampleIdx, FormatComponentType typeHint, IntPtr history);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_DebugVertex(IntPtr real, UInt32 vertid, UInt32 instid, UInt32 idx, UInt32 instOffset, UInt32 vertOffset, IntPtr outtrace);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_DebugPixel(IntPtr real, UInt32 x, UInt32 y, UInt32 sample, UInt32 primitive, IntPtr outtrace);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_DebugThread(IntPtr real, UInt32[] groupid, UInt32[] threadid, IntPtr outtrace);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetUsage(IntPtr real, ResourceId id, IntPtr outusage);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetCBufferVariableContents(IntPtr real, ResourceId shader, IntPtr entryPoint, UInt32 cbufslot, ResourceId buffer, UInt64 offs, IntPtr outvars);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_SaveTexture(IntPtr real, TextureSave saveData, IntPtr path);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetPostVSData(IntPtr real, UInt32 instID, MeshDataStage stage, IntPtr outdata);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetBufferData(IntPtr real, ResourceId buff, UInt64 offset, UInt64 len, IntPtr outdata);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetTextureData(IntPtr real, ResourceId tex, UInt32 arrayIdx, UInt32 mip, IntPtr outdata);
private IntPtr m_Real = IntPtr.Zero;
public IntPtr Real { get { return m_Real; } }
public ReplayRenderer(IntPtr real) { m_Real = real; }
public void Shutdown()
{
if (m_Real != IntPtr.Zero)
{
ReplayRenderer_Shutdown(m_Real);
m_Real = IntPtr.Zero;
}
}
public APIProperties GetAPIProperties()
{
IntPtr mem = CustomMarshal.Alloc(typeof(APIProperties));
ReplayRenderer_GetAPIProperties(m_Real, mem);
APIProperties ret = (APIProperties)CustomMarshal.PtrToStructure(mem, typeof(APIProperties), true);
CustomMarshal.Free(mem);
return ret;
}
public ReplayOutput CreateOutput(IntPtr WindowHandle, OutputType type)
{
// 0 == eWindowingSystem_Unknown
// 1 == eWindowingSystem_Win32
IntPtr ret = ReplayRenderer_CreateOutput(m_Real, WindowHandle == IntPtr.Zero ? 0u : 1u, WindowHandle, type);
if (ret == IntPtr.Zero)
return null;
return new ReplayOutput(ret);
}
public void FileChanged()
{ ReplayRenderer_FileChanged(m_Real); }
public bool HasCallstacks()
{ return ReplayRenderer_HasCallstacks(m_Real); }
public bool InitResolver()
{ return ReplayRenderer_InitResolver(m_Real); }
public void SetFrameEvent(UInt32 eventID, bool force)
{ ReplayRenderer_SetFrameEvent(m_Real, eventID, force); }
public GLPipelineState GetGLPipelineState()
{
IntPtr mem = CustomMarshal.Alloc(typeof(GLPipelineState));
ReplayRenderer_GetGLPipelineState(m_Real, mem);
GLPipelineState ret = (GLPipelineState)CustomMarshal.PtrToStructure(mem, typeof(GLPipelineState), true);
CustomMarshal.Free(mem);
return ret;
}
public D3D11PipelineState GetD3D11PipelineState()
{
IntPtr mem = CustomMarshal.Alloc(typeof(D3D11PipelineState));
ReplayRenderer_GetD3D11PipelineState(m_Real, mem);
D3D11PipelineState ret = (D3D11PipelineState)CustomMarshal.PtrToStructure(mem, typeof(D3D11PipelineState), true);
CustomMarshal.Free(mem);
return ret;
}
public D3D12PipelineState GetD3D12PipelineState()
{
IntPtr mem = CustomMarshal.Alloc(typeof(D3D12PipelineState));
ReplayRenderer_GetD3D12PipelineState(m_Real, mem);
D3D12PipelineState ret = (D3D12PipelineState)CustomMarshal.PtrToStructure(mem, typeof(D3D12PipelineState), true);
CustomMarshal.Free(mem);
return ret;
}
public VulkanPipelineState GetVulkanPipelineState()
{
IntPtr mem = CustomMarshal.Alloc(typeof(VulkanPipelineState));
ReplayRenderer_GetVulkanPipelineState(m_Real, mem);
VulkanPipelineState ret = (VulkanPipelineState)CustomMarshal.PtrToStructure(mem, typeof(VulkanPipelineState), true);
CustomMarshal.Free(mem);
return ret;
}
public string[] GetDisassemblyTargets()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetDisassemblyTargets(m_Real, mem);
string[] ret = CustomMarshal.TemplatedArrayToStringArray(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public string DisassembleShader(ShaderReflection refl, string target)
{
IntPtr disasmMem = CustomMarshal.Alloc(typeof(templated_array));
IntPtr target_mem = CustomMarshal.MakeUTF8String(target);
ReplayRenderer_DisassembleShader(m_Real, refl.origPtr, target_mem, disasmMem);
string disasm = CustomMarshal.TemplatedArrayToString(disasmMem, true);
CustomMarshal.Free(target_mem);
CustomMarshal.Free(disasmMem);
return disasm;
}
public ResourceId BuildCustomShader(string entry, string source, UInt32 compileFlags, ShaderStageType type, out string errors)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ResourceId ret = ResourceId.Null;
IntPtr entry_mem = CustomMarshal.MakeUTF8String(entry);
IntPtr source_mem = CustomMarshal.MakeUTF8String(source);
ReplayRenderer_BuildCustomShader(m_Real, entry_mem, source_mem, compileFlags, type, ref ret, mem);
CustomMarshal.Free(entry_mem);
CustomMarshal.Free(source_mem);
errors = CustomMarshal.TemplatedArrayToString(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public void FreeCustomShader(ResourceId id)
{ ReplayRenderer_FreeCustomShader(m_Real, id); }
public ResourceId BuildTargetShader(string entry, string source, UInt32 compileFlags, ShaderStageType type, out string errors)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ResourceId ret = ResourceId.Null;
IntPtr entry_mem = CustomMarshal.MakeUTF8String(entry);
IntPtr source_mem = CustomMarshal.MakeUTF8String(source);
ReplayRenderer_BuildTargetShader(m_Real, entry_mem, source_mem, compileFlags, type, ref ret, mem);
CustomMarshal.Free(entry_mem);
CustomMarshal.Free(source_mem);
errors = CustomMarshal.TemplatedArrayToString(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public void ReplaceResource(ResourceId from, ResourceId to)
{ ReplayRenderer_ReplaceResource(m_Real, from, to); }
public void RemoveReplacement(ResourceId id)
{ ReplayRenderer_RemoveReplacement(m_Real, id); }
public void FreeTargetResource(ResourceId id)
{ ReplayRenderer_FreeTargetResource(m_Real, id); }
public FetchFrameInfo GetFrameInfo()
{
IntPtr mem = CustomMarshal.Alloc(typeof(FetchFrameInfo));
ReplayRenderer_GetFrameInfo(m_Real, mem);
FetchFrameInfo ret = (FetchFrameInfo)CustomMarshal.PtrToStructure(mem, typeof(FetchFrameInfo), true);
CustomMarshal.Free(mem);
return ret;
}
private void PopulateDraws(ref Dictionary<Int64, FetchDrawcall> map, FetchDrawcall[] draws)
{
if (draws.Length == 0) return;
foreach (var d in draws)
{
map.Add((Int64)d.eventID, d);
PopulateDraws(ref map, d.children);
}
}
private void FixupDraws(Dictionary<Int64, FetchDrawcall> map, FetchDrawcall[] draws)
{
if (draws.Length == 0) return;
foreach (var d in draws)
{
if (d.previousDrawcall != 0 && map.ContainsKey(d.previousDrawcall)) d.previous = map[d.previousDrawcall];
if (d.nextDrawcall != 0 && map.ContainsKey(d.nextDrawcall)) d.next = map[d.nextDrawcall];
if (d.parentDrawcall != 0 && map.ContainsKey(d.parentDrawcall)) d.parent = map[d.parentDrawcall];
FixupDraws(map, d.children);
}
}
public Dictionary<uint, List<CounterResult>> FetchCounters(UInt32[] counters)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
IntPtr countersmem = CustomMarshal.Alloc(typeof(UInt32), counters.Length);
// there's no Marshal.Copy for uint[], which is stupid.
for (int i = 0; i < counters.Length; i++)
Marshal.WriteInt32(countersmem, sizeof(UInt32) * i, (int)counters[i]);
ReplayRenderer_FetchCounters(m_Real, countersmem, (uint)counters.Length, mem);
CustomMarshal.Free(countersmem);
Dictionary<uint, List<CounterResult>> ret = null;
{
CounterResult[] resultArray = (CounterResult[])CustomMarshal.GetTemplatedArray(mem, typeof(CounterResult), true);
// fixup previous/next/parent pointers
ret = new Dictionary<uint, List<CounterResult>>();
foreach (var result in resultArray)
{
if (!ret.ContainsKey(result.eventID))
ret.Add(result.eventID, new List<CounterResult>());
ret[result.eventID].Add(result);
}
}
CustomMarshal.Free(mem);
return ret;
}
public UInt32[] EnumerateCounters()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_EnumerateCounters(m_Real, mem);
UInt32[] ret = (UInt32[])CustomMarshal.GetTemplatedArray(mem, typeof(UInt32), true);
CustomMarshal.Free(mem);
return ret;
}
public CounterDescription DescribeCounter(UInt32 counterID)
{
IntPtr mem = CustomMarshal.Alloc(typeof(CounterDescription));
ReplayRenderer_DescribeCounter(m_Real, counterID, mem);
CounterDescription ret = (CounterDescription)CustomMarshal.PtrToStructure(mem, typeof(CounterDescription), false);
CustomMarshal.Free(mem);
return ret;
}
public FetchDrawcall[] GetDrawcalls()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetDrawcalls(m_Real, mem);
FetchDrawcall[] ret = null;
{
ret = (FetchDrawcall[])CustomMarshal.GetTemplatedArray(mem, typeof(FetchDrawcall), true);
// fixup previous/next/parent pointers
var map = new Dictionary<Int64, FetchDrawcall>();
PopulateDraws(ref map, ret);
FixupDraws(map, ret);
}
CustomMarshal.Free(mem);
return ret;
}
public FetchTexture[] GetTextures()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetTextures(m_Real, mem);
FetchTexture[] ret = (FetchTexture[])CustomMarshal.GetTemplatedArray(mem, typeof(FetchTexture), true);
CustomMarshal.Free(mem);
return ret;
}
public FetchBuffer[] GetBuffers()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetBuffers(m_Real, mem);
FetchBuffer[] ret = (FetchBuffer[])CustomMarshal.GetTemplatedArray(mem, typeof(FetchBuffer), true);
CustomMarshal.Free(mem);
return ret;
}
public string[] GetResolve(UInt64[] callstack)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
UInt32 len = (UInt32)callstack.Length;
ReplayRenderer_GetResolve(m_Real, callstack, len, mem);
string[] ret = CustomMarshal.TemplatedArrayToStringArray(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public DebugMessage[] GetDebugMessages()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetDebugMessages(m_Real, mem);
DebugMessage[] ret = (DebugMessage[])CustomMarshal.GetTemplatedArray(mem, typeof(DebugMessage), true);
CustomMarshal.Free(mem);
return ret;
}
public PixelModification[] PixelHistory(ResourceId target, UInt32 x, UInt32 y, UInt32 slice, UInt32 mip, UInt32 sampleIdx, FormatComponentType typeHint)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_PixelHistory(m_Real, target, x, y, slice, mip, sampleIdx, typeHint, mem);
PixelModification[] ret = (PixelModification[])CustomMarshal.GetTemplatedArray(mem, typeof(PixelModification), true);
CustomMarshal.Free(mem);
return ret;
}
public ShaderDebugTrace DebugVertex(UInt32 vertid, UInt32 instid, UInt32 idx, UInt32 instOffset, UInt32 vertOffset)
{
IntPtr mem = CustomMarshal.Alloc(typeof(ShaderDebugTrace));
ReplayRenderer_DebugVertex(m_Real, vertid, instid, idx, instOffset, vertOffset, mem);
ShaderDebugTrace ret = (ShaderDebugTrace)CustomMarshal.PtrToStructure(mem, typeof(ShaderDebugTrace), true);
CustomMarshal.Free(mem);
return ret;
}
public ShaderDebugTrace DebugPixel(UInt32 x, UInt32 y, UInt32 sample, UInt32 primitive)
{
IntPtr mem = CustomMarshal.Alloc(typeof(ShaderDebugTrace));
ReplayRenderer_DebugPixel(m_Real, x, y, sample, primitive, mem);
ShaderDebugTrace ret = (ShaderDebugTrace)CustomMarshal.PtrToStructure(mem, typeof(ShaderDebugTrace), true);
CustomMarshal.Free(mem);
return ret;
}
public ShaderDebugTrace DebugThread(UInt32[] groupid, UInt32[] threadid)
{
IntPtr mem = CustomMarshal.Alloc(typeof(ShaderDebugTrace));
ReplayRenderer_DebugThread(m_Real, groupid, threadid, mem);
ShaderDebugTrace ret = (ShaderDebugTrace)CustomMarshal.PtrToStructure(mem, typeof(ShaderDebugTrace), true);
CustomMarshal.Free(mem);
return ret;
}
public EventUsage[] GetUsage(ResourceId id)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetUsage(m_Real, id, mem);
EventUsage[] ret = (EventUsage[])CustomMarshal.GetTemplatedArray(mem, typeof(EventUsage), true);
CustomMarshal.Free(mem);
return ret;
}
public ShaderVariable[] GetCBufferVariableContents(ResourceId shader, string entryPoint, UInt32 cbufslot, ResourceId buffer, UInt64 offs)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
IntPtr entry_mem = CustomMarshal.MakeUTF8String(entryPoint);
ReplayRenderer_GetCBufferVariableContents(m_Real, shader, entry_mem, cbufslot, buffer, offs, mem);
ShaderVariable[] ret = (ShaderVariable[])CustomMarshal.GetTemplatedArray(mem, typeof(ShaderVariable), true);
CustomMarshal.Free(entry_mem);
CustomMarshal.Free(mem);
return ret;
}
public bool SaveTexture(TextureSave saveData, string path)
{
IntPtr path_mem = CustomMarshal.MakeUTF8String(path);
bool ret = ReplayRenderer_SaveTexture(m_Real, saveData, path_mem);
CustomMarshal.Free(path_mem);
return ret;
}
public MeshFormat GetPostVSData(UInt32 instID, MeshDataStage stage)
{
IntPtr mem = CustomMarshal.Alloc(typeof(MeshFormat));
ReplayRenderer_GetPostVSData(m_Real, instID, stage, mem);
MeshFormat ret = (MeshFormat)CustomMarshal.PtrToStructure(mem, typeof(MeshFormat), true);
CustomMarshal.Free(mem);
return ret;
}
public byte[] GetBufferData(ResourceId buff, UInt64 offset, UInt64 len)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetBufferData(m_Real, buff, offset, len, mem);
byte[] ret = (byte[])CustomMarshal.GetTemplatedArray(mem, typeof(byte), true);
CustomMarshal.Free(mem);
return ret;
}
public byte[] GetTextureData(ResourceId tex, UInt32 arrayIdx, UInt32 mip)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetTextureData(m_Real, tex, arrayIdx, mip, mem);
byte[] ret = (byte[])CustomMarshal.GetTemplatedArray(mem, typeof(byte), true);
CustomMarshal.Free(mem);
return ret;
}
};
public class RemoteServer
{
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_ShutdownConnection(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_ShutdownServerAndConnection(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool RemoteServer_Ping(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_LocalProxies(IntPtr real, IntPtr outlist);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_RemoteSupportedReplays(IntPtr real, IntPtr outlist);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_GetHomeFolder(IntPtr real, IntPtr outfolder);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_ListFolder(IntPtr real, IntPtr path, IntPtr outlist);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 RemoteServer_ExecuteAndInject(IntPtr real, IntPtr app, IntPtr workingDir, IntPtr cmdLine, IntPtr env, CaptureOptions opts);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_TakeOwnershipCapture(IntPtr real, IntPtr filename);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_CopyCaptureToRemote(IntPtr real, IntPtr filename, ref float progress, IntPtr remotepath);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_CopyCaptureFromRemote(IntPtr real, IntPtr remotepath, IntPtr localpath, ref float progress);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern ReplayCreateStatus RemoteServer_OpenCapture(IntPtr real, UInt32 proxyid, IntPtr logfile, ref float progress, ref IntPtr rendPtr);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_CloseCapture(IntPtr real, IntPtr rendPtr);
// static exports for lists of environment modifications
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr RENDERDOC_MakeEnvironmentModificationList(int numElems);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RENDERDOC_SetEnvironmentModification(IntPtr mem, int idx, IntPtr variable, IntPtr value,
EnvironmentModificationType type, EnvironmentSeparator separator);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RENDERDOC_FreeEnvironmentModificationList(IntPtr mem);
private IntPtr m_Real = IntPtr.Zero;
public RemoteServer(IntPtr real) { m_Real = real; }
public void ShutdownConnection()
{
if (m_Real != IntPtr.Zero)
{
RemoteServer_ShutdownConnection(m_Real);
m_Real = IntPtr.Zero;
}
}
public void ShutdownServerAndConnection()
{
if (m_Real != IntPtr.Zero)
{
RemoteServer_ShutdownServerAndConnection(m_Real);
m_Real = IntPtr.Zero;
}
}
public string GetHomeFolder()
{
IntPtr homepath_mem = CustomMarshal.Alloc(typeof(templated_array));
RemoteServer_GetHomeFolder(m_Real, homepath_mem);
string home = CustomMarshal.TemplatedArrayToString(homepath_mem, true);
CustomMarshal.Free(homepath_mem);
// normalise to /s and with no trailing /s
home = home.Replace('\\', '/');
if (home[home.Length - 1] == '/')
home = home.Remove(0, home.Length - 1);
return home;
}
public DirectoryFile[] ListFolder(string path)
{
IntPtr path_mem = CustomMarshal.MakeUTF8String(path);
IntPtr out_mem = CustomMarshal.Alloc(typeof(templated_array));
RemoteServer_ListFolder(m_Real, path_mem, out_mem);
DirectoryFile[] ret = (DirectoryFile[])CustomMarshal.GetTemplatedArray(out_mem, typeof(DirectoryFile), true);
CustomMarshal.Free(out_mem);
CustomMarshal.Free(path_mem);
Array.Sort(ret);
return ret;
}
public bool Ping()
{
return RemoteServer_Ping(m_Real);
}
public string[] LocalProxies()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
RemoteServer_LocalProxies(m_Real, mem);
string[] ret = CustomMarshal.TemplatedArrayToStringArray(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public string[] RemoteSupportedReplays()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
RemoteServer_RemoteSupportedReplays(m_Real, mem);
string[] ret = CustomMarshal.TemplatedArrayToStringArray(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public UInt32 ExecuteAndInject(string app, string workingDir, string cmdLine, EnvironmentModification[] env, CaptureOptions opts)
{
IntPtr app_mem = CustomMarshal.MakeUTF8String(app);
IntPtr workingDir_mem = CustomMarshal.MakeUTF8String(workingDir);
IntPtr cmdLine_mem = CustomMarshal.MakeUTF8String(cmdLine);
IntPtr env_mem = RENDERDOC_MakeEnvironmentModificationList(env.Length);
for (int i = 0; i < env.Length; i++)
{
IntPtr var_mem = CustomMarshal.MakeUTF8String(env[i].variable);
IntPtr val_mem = CustomMarshal.MakeUTF8String(env[i].value);
RENDERDOC_SetEnvironmentModification(env_mem, i, var_mem, val_mem, env[i].type, env[i].separator);
CustomMarshal.Free(var_mem);
CustomMarshal.Free(val_mem);
}
UInt32 ret = RemoteServer_ExecuteAndInject(m_Real, app_mem, workingDir_mem, cmdLine_mem, env_mem, opts);
RENDERDOC_FreeEnvironmentModificationList(env_mem);
CustomMarshal.Free(app_mem);
CustomMarshal.Free(workingDir_mem);
CustomMarshal.Free(cmdLine_mem);
return ret;
}
public void TakeOwnershipCapture(string filename)
{
IntPtr filename_mem = CustomMarshal.MakeUTF8String(filename);
RemoteServer_TakeOwnershipCapture(m_Real, filename_mem);
CustomMarshal.Free(filename_mem);
}
public string CopyCaptureToRemote(string filename, ref float progress)
{
IntPtr remotepath = CustomMarshal.Alloc(typeof(templated_array));
IntPtr filename_mem = CustomMarshal.MakeUTF8String(filename);
RemoteServer_CopyCaptureToRemote(m_Real, filename_mem, ref progress, remotepath);
CustomMarshal.Free(filename_mem);
string remote = CustomMarshal.TemplatedArrayToString(remotepath, true);
CustomMarshal.Free(remotepath);
return remote;
}
public void CopyCaptureFromRemote(string remotepath, string localpath, ref float progress)
{
IntPtr remotepath_mem = CustomMarshal.MakeUTF8String(remotepath);
IntPtr localpath_mem = CustomMarshal.MakeUTF8String(localpath);
RemoteServer_CopyCaptureFromRemote(m_Real, remotepath_mem, localpath_mem, ref progress);
CustomMarshal.Free(remotepath_mem);
CustomMarshal.Free(localpath_mem);
}
public ReplayRenderer OpenCapture(int proxyid, string logfile, ref float progress)
{
IntPtr rendPtr = IntPtr.Zero;
IntPtr logfile_mem = CustomMarshal.MakeUTF8String(logfile);
ReplayCreateStatus ret = RemoteServer_OpenCapture(m_Real, proxyid == -1 ? UInt32.MaxValue : (UInt32)proxyid, logfile_mem, ref progress, ref rendPtr);
CustomMarshal.Free(logfile_mem);
if (rendPtr == IntPtr.Zero || ret != ReplayCreateStatus.Success)
{
throw new ReplayCreateException(ret, "Failed to set up local proxy replay with remote connection");
}
return new ReplayRenderer(rendPtr);
}
public void CloseCapture(ReplayRenderer renderer)
{
RemoteServer_CloseCapture(m_Real, renderer.Real);
}
};
public class TargetControl
{
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_Shutdown(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr TargetControl_GetTarget(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr TargetControl_GetAPI(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 TargetControl_GetPID(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr TargetControl_GetBusyClient(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_TriggerCapture(IntPtr real, UInt32 numFrames);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_QueueCapture(IntPtr real, UInt32 frameNumber);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_CopyCapture(IntPtr real, UInt32 remoteID, IntPtr localpath);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_DeleteCapture(IntPtr real, UInt32 remoteID);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_ReceiveMessage(IntPtr real, IntPtr outmsg);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 RENDERDOC_EnumerateRemoteConnections(IntPtr host, UInt32[] idents);
private IntPtr m_Real = IntPtr.Zero;
private bool m_Connected;
public TargetControl(IntPtr real)
{
m_Real = real;
if (real == IntPtr.Zero)
{
m_Connected = false;
Target = "";
API = "";
BusyClient = "";
}
else
{
m_Connected = true;
Target = CustomMarshal.PtrToStringUTF8(TargetControl_GetTarget(m_Real));
API = CustomMarshal.PtrToStringUTF8(TargetControl_GetAPI(m_Real));
PID = TargetControl_GetPID(m_Real);
BusyClient = CustomMarshal.PtrToStringUTF8(TargetControl_GetBusyClient(m_Real));
}
CaptureExists = false;
CaptureCopied = false;
InfoUpdated = false;
}
public static UInt32[] GetRemoteIdents(string host)
{
UInt32 numIdents = RENDERDOC_EnumerateRemoteConnections(IntPtr.Zero, null);
UInt32[] idents = new UInt32[numIdents];
IntPtr host_mem = CustomMarshal.MakeUTF8String(host);
RENDERDOC_EnumerateRemoteConnections(host_mem, idents);
CustomMarshal.Free(host_mem);
return idents;
}
public bool Connected { get { return m_Connected; } }
public void Shutdown()
{
m_Connected = false;
if (m_Real != IntPtr.Zero) TargetControl_Shutdown(m_Real);
m_Real = IntPtr.Zero;
}
public void TriggerCapture(UInt32 numFrames)
{
TargetControl_TriggerCapture(m_Real, numFrames);
}
public void QueueCapture(UInt32 frameNum)
{
TargetControl_QueueCapture(m_Real, frameNum);
}
public void CopyCapture(UInt32 id, string localpath)
{
IntPtr localpath_mem = CustomMarshal.MakeUTF8String(localpath);
TargetControl_CopyCapture(m_Real, id, localpath_mem);
CustomMarshal.Free(localpath_mem);
}
public void DeleteCapture(UInt32 id)
{
TargetControl_DeleteCapture(m_Real, id);
}
public void ReceiveMessage()
{
if (m_Real != IntPtr.Zero)
{
TargetControlMessage msg = null;
{
IntPtr mem = CustomMarshal.Alloc(typeof(TargetControlMessage));
TargetControl_ReceiveMessage(m_Real, mem);
if (mem != IntPtr.Zero)
msg = (TargetControlMessage)CustomMarshal.PtrToStructure(mem, typeof(TargetControlMessage), true);
CustomMarshal.Free(mem);
}
if (msg == null)
return;
if (msg.Type == TargetControlMessageType.Disconnected)
{
m_Connected = false;
TargetControl_Shutdown(m_Real);
m_Real = IntPtr.Zero;
}
else if (msg.Type == TargetControlMessageType.NewCapture)
{
CaptureFile = msg.NewCapture;
CaptureExists = true;
}
else if (msg.Type == TargetControlMessageType.CaptureCopied)
{
CaptureFile.ID = msg.NewCapture.ID;
CaptureFile.path = msg.NewCapture.path;
CaptureCopied = true;
}
else if (msg.Type == TargetControlMessageType.RegisterAPI)
{
API = msg.RegisterAPI.APIName;
InfoUpdated = true;
}
else if (msg.Type == TargetControlMessageType.NewChild)
{
NewChild = msg.NewChild;
ChildAdded = true;
}
}
}
public string BusyClient;
public string Target;
public string API;
public UInt32 PID;
public bool CaptureExists;
public bool ChildAdded;
public bool CaptureCopied;
public bool InfoUpdated;
public TargetControlMessage.NewCaptureData CaptureFile = new TargetControlMessage.NewCaptureData();
public TargetControlMessage.NewChildData NewChild = new TargetControlMessage.NewChildData();
};
};
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NetGore.Features.ActionDisplays;
using NetGore.IO;
using NetGore.IO.PropertySync;
using NetGore.World;
using NUnit.Framework;
using SFML.Graphics;
// ReSharper disable UnusedMember.Local
namespace NetGore.Tests.NetGore.IO
{
[TestFixture]
public class PropertySyncTests
{
static void TestSync(string propertyName, object value)
{
// Get the property
var property = typeof(TestClass).GetProperty(propertyName);
// Set the value and ensure it was set correctly
var cSrc = new TestClass();
property.SetValue(cSrc, value, null);
Assert.AreEqual(value, property.GetValue(cSrc, null));
// Serialize
var bs = new BitStream();
cSrc.Serialize(bs);
// Deserialize
var cDest = new TestClass();
bs.PositionBits = 0;
cDest.Deserialize(bs);
// Check
Assert.AreEqual(value, property.GetValue(cDest, null));
}
static void TestSyncNullable(string propertyName, object value)
{
// Get the property
var property = typeof(NullableTestClass).GetProperty(propertyName);
// Set the value and ensure it was set correctly
var cSrc = new NullableTestClass();
property.SetValue(cSrc, value, null);
Assert.AreEqual(value, property.GetValue(cSrc, null));
// Serialize
var bs = new BitStream();
cSrc.Serialize(bs);
// Deserialize
var cDest = new NullableTestClass();
bs.PositionBits = 0;
cDest.Deserialize(bs);
// Check
Assert.AreEqual(value, property.GetValue(cDest, null));
}
#region Unit tests
[Test]
public void AutomaticNullableTypesTest()
{
TestSyncNullable("mBool", true);
TestSyncNullable("mByte", null);
TestSyncNullable("mColor", new Color(255, 243, 234, 12));
TestSyncNullable("mFloat", null);
TestSyncNullable("mGrhIndex", null);
TestSyncNullable("mGrhIndex", new GrhIndex(5));
TestSyncNullable("mInt", null);
TestSyncNullable("mLong", (long)1032);
TestSyncNullable("mMapEntityIndex", null);
TestSyncNullable("mActionDisplayID", null);
TestSyncNullable("mActionDisplayID", new ActionDisplayID(5));
}
[Test]
public void BoolTest()
{
TestSync("mBool", true);
}
[Test]
public void ByteTest()
{
TestSync("mByte", (byte)5);
}
[Test]
public void ColorTest()
{
TestSync("mColor", new Color(255, 243, 234, 12));
}
[Test]
public void FloatTest()
{
TestSync("mFloat", 57.0f);
}
[Test]
public void GrhIndexTest()
{
TestSync("mGrhIndex", new GrhIndex(5));
}
[Test]
public void IntTest()
{
TestSync("mInt", 5);
}
[Test]
public void LongTest()
{
TestSync("mLong", (long)1032);
}
[Test]
public void MapEntityIndexTest()
{
TestSyncNullable("mMapEntityIndex", null);
TestSyncNullable("mMapEntityIndex", new MapEntityIndex(55));
TestSync("mMapEntityIndex", new MapEntityIndex(55));
}
[Test]
public void ActionDisplayIDTest()
{
TestSyncNullable("mActionDisplayID", null);
TestSyncNullable("mActionDisplayID", new ActionDisplayID(55));
TestSync("mActionDisplayID", new ActionDisplayID(55));
}
[Test]
public void SByteTest()
{
TestSync("mSByte", (sbyte)23);
}
[Test]
public void ShortTest()
{
TestSync("mShort", (short)23);
}
[Test]
public void UIntTest()
{
TestSync("mUInt", (uint)23);
}
[Test]
public void ULongTest()
{
TestSync("mULong", (ulong)23);
}
[Test]
public void UShortTest()
{
TestSync("mUShort", (ushort)23);
}
[Test]
public void Vector2Test()
{
TestSync("mVector2", new Vector2(23, 32));
}
#endregion
/// <summary>
/// Test class containing all the nullable values to test the syncing on.
/// </summary>
class NullableTestClass
{
readonly IPropertySync[] _propertySyncs;
public NullableTestClass()
{
_propertySyncs = PropertySyncHelper.GetPropertySyncs(GetType()).ToArray();
}
[SyncValue]
public bool? mBool { get; set; }
[SyncValue]
public byte? mByte { get; set; }
[SyncValue]
public Color? mColor { get; set; }
[SyncValue]
public double? mDouble { get; set; }
[SyncValue]
public float? mFloat { get; set; }
[SyncValue]
public GrhIndex? mGrhIndex { get; set; }
[SyncValue]
public int? mInt { get; set; }
[SyncValue]
public long? mLong { get; set; }
[SyncValue]
public MapEntityIndex? mMapEntityIndex { get; set; }
[SyncValue]
public sbyte? mSByte { get; set; }
[SyncValue]
public short? mShort { get; set; }
[SyncValue]
public uint? mUInt { get; set; }
[SyncValue]
public ulong? mULong { get; set; }
[SyncValue]
public ushort? mUShort { get; set; }
[SyncValue]
public Vector2? mVector2 { get; set; }
[SyncValue]
public ActionDisplayID? mActionDisplayID { get; set; }
public void Deserialize(IValueReader reader)
{
int count = reader.ReadByte("Count");
for (var i = 0; i < count; i++)
{
int propIndex = reader.ReadByte("PropertyIndex" + i);
_propertySyncs[propIndex].ReadValue(this, reader);
}
}
public void Serialize(IValueWriter writer)
{
var changed = new Queue<int>();
for (var i = 0; i < _propertySyncs.Length; i++)
{
if (_propertySyncs[i].HasValueChanged(this))
changed.Enqueue(i);
}
writer.Write("Count", (byte)changed.Count);
var index = 0;
foreach (var i in changed)
{
writer.Write("PropertyIndex" + index++, (byte)i);
_propertySyncs[i].WriteValue(this, writer);
}
}
}
/// <summary>
/// Test class containing all the values to test the syncing on.
/// </summary>
class TestClass
{
readonly IPropertySync[] _propertySyncs;
public TestClass()
{
_propertySyncs = PropertySyncHelper.GetPropertySyncs(GetType()).ToArray();
}
[SyncValue]
public bool mBool { get; set; }
[SyncValue]
public byte mByte { get; set; }
[SyncValue]
public Color mColor { get; set; }
[SyncValue]
public double mDouble { get; set; }
[SyncValue]
public float mFloat { get; set; }
[SyncValue]
public GrhIndex mGrhIndex { get; set; }
[SyncValue]
public int mInt { get; set; }
[SyncValue]
public long mLong { get; set; }
[SyncValue]
public MapEntityIndex mMapEntityIndex { get; set; }
[SyncValue]
public sbyte mSByte { get; set; }
[SyncValue]
public short mShort { get; set; }
[SyncValue]
public string mString { get; set; }
[SyncValue]
public uint mUInt { get; set; }
[SyncValue]
public ulong mULong { get; set; }
[SyncValue]
public ushort mUShort { get; set; }
[SyncValue]
public Vector2 mVector2 { get; set; }
[SyncValue]
public ActionDisplayID mActionDisplayID { get; set; }
public void Deserialize(IValueReader reader)
{
int count = reader.ReadByte("Count");
for (var i = 0; i < count; i++)
{
int propIndex = reader.ReadByte("PropertyIndex" + i);
_propertySyncs[propIndex].ReadValue(this, reader);
}
}
public void Serialize(IValueWriter writer)
{
var changed = new Queue<int>();
for (var i = 0; i < _propertySyncs.Length; i++)
{
if (_propertySyncs[i].HasValueChanged(this))
changed.Enqueue(i);
}
writer.Write("Count", (byte)changed.Count);
var index = 0;
foreach (var i in changed)
{
writer.Write("PropertyIndex" + index++, (byte)i);
_propertySyncs[i].WriteValue(this, writer);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Runtime.Caching;
using Microsoft.Internal.Web.Utils;
using NuGet.Resources;
namespace NuGet {
public class ZipPackage : IPackage {
private const string AssemblyReferencesDir = "lib";
private const string ResourceAssemblyExtension = ".resources.dll";
private const string CacheKeyFormat = "NUGET_ZIP_PACKAGE_{0}_{1}{2}";
private const string AssembliesCacheKey = "ASSEMBLIES";
private const string FilesCacheKey = "FILES";
private readonly bool _enableCaching;
private static readonly string[] AssemblyReferencesExtensions = new[] { ".dll", ".exe" };
private static readonly TimeSpan CacheTimeout = TimeSpan.FromSeconds(15);
// paths to exclude
private static readonly string[] _excludePaths = new[] { "_rels", "package" };
// We don't store the steam itself, just a way to open the stream on demand
// so we don't have to hold on to that resource
private Func<Stream> _streamFactory;
public ZipPackage(string fileName)
: this(fileName, enableCaching: false) {
}
public ZipPackage(Stream stream) {
if (stream == null) {
throw new ArgumentNullException("stream");
}
_enableCaching = false;
_streamFactory = stream.ToStreamFactory();
EnsureManifest();
}
internal ZipPackage(string fileName, bool enableCaching) {
if (String.IsNullOrEmpty(fileName)) {
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "fileName");
}
_enableCaching = enableCaching;
_streamFactory = () => File.OpenRead(fileName);
EnsureManifest();
}
internal ZipPackage(Func<Stream> streamFactory) {
if (streamFactory == null) {
throw new ArgumentNullException("streamFactory");
}
_enableCaching = true;
_streamFactory = streamFactory;
EnsureManifest();
}
public string Id {
get;
set;
}
public Version Version {
get;
set;
}
public string Title {
get;
set;
}
public IEnumerable<string> Authors {
get;
set;
}
public IEnumerable<string> Owners {
get;
set;
}
public Uri IconUrl {
get;
set;
}
public Uri LicenseUrl {
get;
set;
}
public Uri ProjectUrl {
get;
set;
}
public Uri ReportAbuseUrl {
get {
return null;
}
}
public int DownloadCount {
get {
return -1;
}
}
public double Rating {
get {
return -1;
}
}
public int RatingsCount {
get {
return 0;
}
}
public bool RequireLicenseAcceptance {
get;
set;
}
public string Description {
get;
set;
}
public string Summary {
get;
set;
}
public string Language {
get;
set;
}
public string Tags {
get;
set;
}
public IEnumerable<PackageDependency> Dependencies {
get;
set;
}
public IEnumerable<IPackageAssemblyReference> AssemblyReferences {
get {
if (_enableCaching) {
return MemoryCache.Default.GetOrAdd(GetAssembliesCacheKey(), GetAssembliesNoCache, CacheTimeout);
}
return GetAssembliesNoCache();
}
}
public IEnumerable<FrameworkAssemblyReference> FrameworkAssemblies {
get;
set;
}
public IEnumerable<IPackageFile> GetFiles() {
if (_enableCaching) {
return MemoryCache.Default.GetOrAdd(GetFilesCacheKey(), GetFilesNoCache, CacheTimeout);
}
return GetFilesNoCache();
}
public Stream GetStream() {
return _streamFactory();
}
private List<IPackageAssemblyReference> GetAssembliesNoCache() {
return (from file in GetFiles()
where IsAssemblyReference(file)
select (IPackageAssemblyReference)new ZipPackageAssemblyReference(file)).ToList();
}
private List<IPackageFile> GetFilesNoCache() {
using (Stream stream = _streamFactory()) {
Package package = Package.Open(stream);
return (from part in package.GetParts()
where IsPackageFile(part)
select (IPackageFile)new ZipPackageFile(part)).ToList();
}
}
private void EnsureManifest() {
using (Stream stream = _streamFactory()) {
Package package = Package.Open(stream);
PackageRelationship relationshipType = package.GetRelationshipsByType(Constants.SchemaNamespace + PackageBuilder.ManifestRelationType).SingleOrDefault();
if (relationshipType == null) {
throw new InvalidOperationException(NuGetResources.PackageDoesNotContainManifest);
}
PackagePart manifestPart = package.GetPart(relationshipType.TargetUri);
if (manifestPart == null) {
throw new InvalidOperationException(NuGetResources.PackageDoesNotContainManifest);
}
using (Stream manifestStream = manifestPart.GetStream()) {
Manifest manifest = Manifest.ReadFrom(manifestStream);
IPackageMetadata metadata = manifest.Metadata;
Id = metadata.Id;
Version = metadata.Version;
Title = metadata.Title;
Authors = metadata.Authors;
Owners = metadata.Owners;
IconUrl = metadata.IconUrl;
LicenseUrl = metadata.LicenseUrl;
ProjectUrl = metadata.ProjectUrl;
RequireLicenseAcceptance = metadata.RequireLicenseAcceptance;
Description = metadata.Description;
Summary = metadata.Summary;
Language = metadata.Language;
Tags = metadata.Tags;
Dependencies = metadata.Dependencies;
FrameworkAssemblies = metadata.FrameworkAssemblies;
// Ensure tags start and end with an empty " " so we can do contains filtering reliably
if (!String.IsNullOrEmpty(Tags)) {
Tags = " " + Tags + " ";
}
}
}
}
private static bool IsAssemblyReference(IPackageFile file) {
// Assembly references are in lib/ and have a .dll/.exe extension
var path = file.Path;
return path.StartsWith(AssemblyReferencesDir, StringComparison.OrdinalIgnoreCase) &&
// Exclude resource assemblies
!path.EndsWith(ResourceAssemblyExtension, StringComparison.OrdinalIgnoreCase) &&
AssemblyReferencesExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase);
}
private static bool IsPackageFile(PackagePart part) {
string path = UriUtility.GetPath(part.Uri);
// We exclude any opc files and the manifest file (.nuspec)
return !_excludePaths.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)) &&
!PackageUtility.IsManifest(path);
}
public override string ToString() {
return this.GetFullName();
}
private string GetFilesCacheKey() {
return String.Format(CultureInfo.InvariantCulture, CacheKeyFormat, FilesCacheKey, Id, Version);
}
private string GetAssembliesCacheKey() {
return String.Format(CultureInfo.InvariantCulture, CacheKeyFormat, AssembliesCacheKey, Id, Version);
}
internal static void ClearCache(IPackage package) {
var zipPackage = package as ZipPackage;
// Remove the cache entries for files and assemblies
if (zipPackage != null) {
MemoryCache.Default.Remove(zipPackage.GetAssembliesCacheKey());
MemoryCache.Default.Remove(zipPackage.GetFilesCacheKey());
}
}
}
}
| |
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Xml;
namespace HtmlToXamlDemo
{
internal class CssStylesheet
{
private List<StyleDefinition> _styleDefinitions;
// Constructor
public CssStylesheet(XmlElement htmlElement)
{
if (htmlElement != null)
{
DiscoverStyleDefinitions(htmlElement);
}
}
// Recursively traverses an html tree, discovers STYLE elements and creates a style definition table
// for further cascading style application
public void DiscoverStyleDefinitions(XmlElement htmlElement)
{
if (htmlElement.LocalName.ToLower() == "link")
{
return;
// Add LINK elements processing for included stylesheets
// <LINK href="http://sc.msn.com/global/css/ptnr/orange.css" type=text/css \r\nrel=stylesheet>
}
if (htmlElement.LocalName.ToLower() != "style")
{
// This is not a STYLE element. Recurse into it
for (var htmlChildNode = htmlElement.FirstChild;
htmlChildNode != null;
htmlChildNode = htmlChildNode.NextSibling)
{
if (htmlChildNode is XmlElement)
{
DiscoverStyleDefinitions((XmlElement) htmlChildNode);
}
}
return;
}
// Add style definitions from this style.
// Collect all text from this style definition
var stylesheetBuffer = new StringBuilder();
for (var htmlChildNode = htmlElement.FirstChild;
htmlChildNode != null;
htmlChildNode = htmlChildNode.NextSibling)
{
if (htmlChildNode is XmlText || htmlChildNode is XmlComment)
{
stylesheetBuffer.Append(RemoveComments(htmlChildNode.Value));
}
}
// CssStylesheet has the following syntactical structure:
// @import declaration;
// selector { definition }
// where "selector" is one of: ".classname", "tagname"
// It can contain comments in the following form: /*...*/
var nextCharacterIndex = 0;
while (nextCharacterIndex < stylesheetBuffer.Length)
{
// Extract selector
var selectorStart = nextCharacterIndex;
while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '{')
{
// Skip declaration directive starting from @
if (stylesheetBuffer[nextCharacterIndex] == '@')
{
while (nextCharacterIndex < stylesheetBuffer.Length &&
stylesheetBuffer[nextCharacterIndex] != ';')
{
nextCharacterIndex++;
}
selectorStart = nextCharacterIndex + 1;
}
nextCharacterIndex++;
}
if (nextCharacterIndex < stylesheetBuffer.Length)
{
// Extract definition
var definitionStart = nextCharacterIndex;
while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '}')
{
nextCharacterIndex++;
}
// Define a style
if (nextCharacterIndex - definitionStart > 2)
{
AddStyleDefinition(
stylesheetBuffer.ToString(selectorStart, definitionStart - selectorStart),
stylesheetBuffer.ToString(definitionStart + 1, nextCharacterIndex - definitionStart - 2));
}
// Skip closing brace
if (nextCharacterIndex < stylesheetBuffer.Length)
{
Debug.Assert(stylesheetBuffer[nextCharacterIndex] == '}');
nextCharacterIndex++;
}
}
}
}
// Returns a string with all c-style comments replaced by spaces
private string RemoveComments(string text)
{
var commentStart = text.IndexOf("/*", StringComparison.Ordinal);
if (commentStart < 0)
{
return text;
}
var commentEnd = text.IndexOf("*/", commentStart + 2, StringComparison.Ordinal);
if (commentEnd < 0)
{
return text.Substring(0, commentStart);
}
return text.Substring(0, commentStart) + " " + RemoveComments(text.Substring(commentEnd + 2));
}
public void AddStyleDefinition(string selector, string definition)
{
// Notrmalize parameter values
selector = selector.Trim().ToLower();
definition = definition.Trim().ToLower();
if (selector.Length == 0 || definition.Length == 0)
{
return;
}
if (_styleDefinitions == null)
{
_styleDefinitions = new List<StyleDefinition>();
}
var simpleSelectors = selector.Split(',');
foreach (string t in simpleSelectors)
{
var simpleSelector = t.Trim();
if (simpleSelector.Length > 0)
{
_styleDefinitions.Add(new StyleDefinition(simpleSelector, definition));
}
}
}
public string GetStyle(string elementName, List<XmlElement> sourceContext)
{
Debug.Assert(sourceContext.Count > 0);
Debug.Assert(elementName == sourceContext[sourceContext.Count - 1].LocalName);
// Add id processing for style selectors
if (_styleDefinitions != null)
{
for (var i = _styleDefinitions.Count - 1; i >= 0; i--)
{
var selector = _styleDefinitions[i].Selector;
var selectorLevels = selector.Split(' ');
var indexInSelector = selectorLevels.Length - 1;
var indexInContext = sourceContext.Count - 1;
var selectorLevel = selectorLevels[indexInSelector].Trim();
if (MatchSelectorLevel(selectorLevel, sourceContext[sourceContext.Count - 1]))
{
return _styleDefinitions[i].Definition;
}
}
}
return null;
}
private bool MatchSelectorLevel(string selectorLevel, XmlElement xmlElement)
{
if (selectorLevel.Length == 0)
{
return false;
}
var indexOfDot = selectorLevel.IndexOf('.');
var indexOfPound = selectorLevel.IndexOf('#');
string selectorClass = null;
string selectorId = null;
string selectorTag = null;
if (indexOfDot >= 0)
{
if (indexOfDot > 0)
{
selectorTag = selectorLevel.Substring(0, indexOfDot);
}
selectorClass = selectorLevel.Substring(indexOfDot + 1);
}
else if (indexOfPound >= 0)
{
if (indexOfPound > 0)
{
selectorTag = selectorLevel.Substring(0, indexOfPound);
}
selectorId = selectorLevel.Substring(indexOfPound + 1);
}
else
{
selectorTag = selectorLevel;
}
if (selectorTag != null && selectorTag != xmlElement.LocalName)
{
return false;
}
if (selectorId != null && HtmlToXamlConverter.GetAttribute(xmlElement, "id") != selectorId)
{
return false;
}
if (selectorClass != null && HtmlToXamlConverter.GetAttribute(xmlElement, "class") != selectorClass)
{
return false;
}
return true;
}
private class StyleDefinition
{
public readonly string Definition;
public readonly string Selector;
public StyleDefinition(string selector, string definition)
{
Selector = selector;
Definition = definition;
}
}
}
}
| |
using System.Collections.Generic;
using UnityEngine.UI.Windows.Audio;
#if UNITY_EDITOR
using UnityEditor;
using ADB = UnityEditor.AssetDatabase;
#endif
namespace UnityEngine.UI.Windows.Plugins.Flow {
public class FlowSystem {
public FlowData data;
private static FlowSystem _instance;
private static FlowSystem instance {
get {
if (FlowSystem._instance == null) FlowSystem._instance = new FlowSystem();
return FlowSystem._instance;
}
}
public static Vector2 grid;
public static Rect Grid(Rect rect) {
rect.x = Mathf.Floor(rect.x / FlowSystem.grid.x) * FlowSystem.grid.x;
rect.y = Mathf.Floor(rect.y / FlowSystem.grid.y) * FlowSystem.grid.y;
return rect;
}
public static void Save() {
FlowSystem.instance.data.Save();
}
public static bool IsCompileDirty() {
return FlowSystem.instance.data.IsCompileDirty();
}
public static void SetCompileDirty(bool state = true) {
if (FlowSystem.instance == null ||
FlowSystem.instance.data == null) {
return;
}
FlowSystem.instance.data.SetCompileDirty(state);
}
public static void SetDirty() {
if (FlowSystem.instance == null ||
FlowSystem.instance.data == null) {
return;
}
FlowSystem.instance.data.isDirty = true;
}
public static FlowData GetData() {
return FlowSystem.instance.data;
}
public static void SetData(FlowData data) {
var _data = FlowSystem.instance.data;
if (_data != data && data != null) data.ResetCache();
FlowSystem.instance.data = data;
}
public static bool HasData() {
return FlowSystem.instance.data != null;
}
public static void SetZoom(float value) {
if (FlowSystem.instance == null ||
FlowSystem.instance.data == null) return;
var changed = (FlowSystem.instance.data.zoom != value);
if (value > 0.98f) value = 1f;
FlowSystem.instance.data.zoom = value;
if (changed == true) FlowSystem.SetDirty();
}
public static float GetZoom() {
if (FlowSystem.instance.data == null) return 1f;
return FlowSystem.instance.data.zoom;
}
public static AttachItem GetAttachItem(int from, int to) {
return FlowSystem.instance.data.GetAttachItem(from, to);
}
#region TAGS
public static List<FlowTag> GetTags() {
if (FlowSystem.HasData() == false) return null;
return FlowSystem.instance.data.tags;
}
public static void AddTag(Data.FlowWindow window, FlowTag tag) {
FlowSystem.instance.data.AddTag(window, tag);
}
public static void RemoveTag(Data.FlowWindow window, FlowTag tag) {
FlowSystem.instance.data.RemoveTag(window, tag);
}
#endregion
#region AUDIO
public static List<Audio.Data.State> GetAudioItems(ClipType clipType) {
if (FlowSystem.HasData() == false) return null;
return FlowSystem.instance.data.audio.GetStates(clipType);
}
public static void AddAudioItem(ClipType clipType, Audio.Data.State state) {
FlowSystem.instance.data.AddAudioItem(clipType, state);
}
public static void RemoveAudioItem(ClipType clipType, int key) {
FlowSystem.instance.data.RemoveAudioItem(clipType, key);
}
#endregion
public static void SetRootWindow(int id) {
if (FlowSystem.HasData() == false) return;
FlowSystem.instance.data.SetRootWindow(id);
}
public static int GetRootWindow() {
if (FlowSystem.HasData() == false) return -1;
return FlowSystem.instance.data.GetRootWindow();
}
public static List<int> GetDefaultWindows() {
if (FlowSystem.HasData() == false) return null;
return FlowSystem.instance.data.GetDefaultWindows();
}
public static void SetDefaultWindows(List<int> list) {
FlowSystem.instance.data.SetDefaultWindows(list);
}
public static IEnumerable<Data.FlowWindow> GetWindows() {
if (FlowSystem.HasData() == false) return null;
return FlowSystem.instance.data.GetWindows();
}
public static IEnumerable<Data.FlowWindow> GetContainers() {
if (FlowSystem.HasData() == false) return null;
return FlowSystem.instance.data.GetContainers();
}
public static IEnumerable<Data.FlowWindow> GetContainersAndWindows() {
if (FlowSystem.HasData() == false) return null;
return FlowSystem.instance.data.GetContainersAndWindows();
}
public static Data.FlowWindow GetWindow(WindowBase window, bool runtime) {
if (FlowSystem.HasData() == false) return null;
return FlowSystem.instance.data.GetWindow(window, runtime);
}
public static Data.FlowWindow GetWindow(int id) {
if (FlowSystem.HasData() == false) return null;
return FlowSystem.instance.data.GetWindow(id);
}
public static Data.FlowWindow CreateContainer() {
return FlowSystem.instance.data.CreateContainer();
}
public static Data.FlowWindow CreateWindow() {
return FlowSystem.instance.data.CreateWindow();
}
public static Data.FlowWindow CreateWindow(Data.FlowWindow.Flags flags) {
return FlowSystem.instance.data.CreateWindow(flags);
}
public static Data.FlowWindow CreateDefaultLink() {
return FlowSystem.instance.data.CreateDefaultLink();
}
#if UNITY_EDITOR
public static void DestroyWindow(int id) {
FlowSystem.instance.data.DestroyWindow(id);
FlowSystem.SetCompileDirty();
}
public static void Attach(int source, int other, bool oneWay, WindowLayoutElement component = null) {
FlowSystem.instance.data.Attach(source, other, oneWay, component);
FlowSystem.SetCompileDirty();
}
public static void Detach(int source, int other, bool oneWay, WindowLayoutElement component = null) {
FlowSystem.instance.data.Detach(source, other, oneWay, component);
FlowSystem.SetCompileDirty();
}
public static bool AlreadyAttached(int source, int other, WindowLayoutElement component = null) {
return FlowSystem.instance.data.AlreadyAttached(source, other, component);
}
public static void Attach(int source, int index, int other, bool oneWay, WindowLayoutElement component = null) {
FlowSystem.instance.data.Attach(source, index, other, oneWay, component);
FlowSystem.SetCompileDirty();
}
public static void Detach(int source, int index, int other, bool oneWay, WindowLayoutElement component = null) {
FlowSystem.instance.data.Detach(source, index, other, oneWay, component);
FlowSystem.SetCompileDirty();
}
public static bool AlreadyAttached(int source, int index, int other, WindowLayoutElement component = null) {
return FlowSystem.instance.data.AlreadyAttached(source, index, other, component);
}
#endif
public static void SetScrollPosition(Vector2 pos) {
if (FlowSystem.HasData() == false) return;
FlowSystem.instance.data.SetScrollPosition(pos);
}
public static Vector2 GetScrollPosition() {
if (FlowSystem.HasData() == false) return Vector2.zero;
return FlowSystem.instance.data.GetScrollPosition();
}
public static void MoveContainerOrWindow(int id, Vector2 delta) {
var window = FlowSystem.GetWindow(id);
window.isMovingState = true;
if (window.IsContainer() == true) {
var childs = window.attachItems;
foreach (var child in childs) {
FlowSystem.MoveContainerOrWindow(child.targetId, delta);
}
} else {
window.Move(delta);
}
}
public static void ForEachContainer(int startId, System.Func<Data.FlowWindow, string, string> each, string accumulate = "") {
var window = FlowSystem.GetWindow(startId);
if (window.IsContainer() == true) {
accumulate += each(window, accumulate);
var childs = window.attachItems;
foreach (var child in childs) {
FlowSystem.ForEachContainer(child.targetId, each, accumulate);
}
}
}
public static void SelectWindows(params int[] ids) {
if (FlowSystem.HasData() == false) return;
FlowSystem.instance.data.SelectWindows(ids);
}
public static void SelectWindowsInRect(Rect rect, System.Func<Data.FlowWindow, bool> predicate = null) {
if (FlowSystem.HasData() == false) return;
FlowSystem.instance.data.SelectWindowsInRect(rect, predicate);
}
public static List<int> GetSelected() {
return FlowSystem.instance.data.GetSelected();
}
public static void ResetSelection() {
FlowSystem.instance.data.ResetSelection();
}
#if UNITY_EDITOR
public static void DrawEditorGetKeyButton(GUISkin skin, string title = "Get Key") {
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (GUILayout.Button(title, skin.button, GUILayout.Height(40f), GUILayout.Width(150f)) == true) {
Application.OpenURL(VersionInfo.GETKEY_LINK);
}
GUILayout.FlexibleSpace();
}
GUILayout.EndHorizontal();
}
#endif
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Configuration;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Optimization;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Data.Storage;
using ASC.Data.Storage.Configuration;
using ASC.Data.Storage.DiscStorage;
namespace ASC.Web.Core.Client.Bundling
{
class DiscTransform : IBundleTransform
{
private static readonly ILog log;
public static readonly bool SuccessInitialized;
const string BaseVirtualPath = "/discbundle/";
static readonly string BaseStoragePath;
static DiscTransform()
{
try
{
log = LogManager.GetLogger("ASC.Web.Bundle.DiscTransform");
var section = (StorageConfigurationSection)ConfigurationManagerExtension.GetSection("storage");
if (section == null)
{
throw new Exception("Storage section not found.");
}
foreach (HandlerConfigurationElement h in section.Handlers)
{
if (h.Name == "disc")
{
BaseStoragePath = Path.Combine(h.HandlerProperties["$STORAGE_ROOT"].Value, "bundle");
break;
}
}
if (!string.IsNullOrEmpty(BaseStoragePath))
{
DiscDataHandler.RegisterVirtualPath(BaseVirtualPath, GetFullPhysicalPath("/"), true);
SuccessInitialized = CoreContext.Configuration.Standalone && !StaticUploader.CanUpload();
}
}
catch (Exception fatal)
{
log.Fatal(fatal);
}
}
public void Process(BundleContext context, BundleResponse response)
{
if (!SuccessInitialized || !BundleTable.Bundles.UseCdn) return;
try
{
var bundle = context.BundleCollection.GetBundleFor(context.BundleVirtualPath);
if (bundle != null)
{
UploadToDisc(new CdnItem { Bundle = bundle, Response = response });
}
}
catch (Exception fatal)
{
log.Fatal(fatal);
throw;
}
}
private static void UploadToDisc(CdnItem item)
{
var filePath = GetFullFileName(item.Bundle.Path, item.Response.ContentType).TrimStart('/');
var fullFilePath = GetFullPhysicalPath(filePath);
try
{
using (var mutex = new Mutex(true, filePath))
{
var wait = mutex.WaitOne(60000);
try
{
CreateDir(fullFilePath);
if (!File.Exists(fullFilePath))
{
var gzip = ClientSettings.GZipEnabled;
using (var fs = File.OpenWrite(fullFilePath))
using (var tw = new StreamWriter(fs))
{
tw.WriteLine(item.Response.Content);
}
item.Bundle.CdnPath = GetUri(filePath);
if (gzip)
{
using (var fs = File.OpenWrite(fullFilePath + ".gz"))
using (var zip = new GZipStream(fs, CompressionMode.Compress, true))
using (var tw = new StreamWriter(zip))
{
tw.WriteLine(item.Response.Content);
}
}
}
else
{
item.Bundle.CdnPath = GetUri(item.Bundle.Path, item.Response.ContentType);
}
}
finally
{
if (wait)
{
mutex.ReleaseMutex();
}
}
}
}
catch (Exception err)
{
log.Error(err);
}
}
internal static string GetUri(string path)
{
return BaseVirtualPath + path.TrimStart('/');
}
internal static string GetUri(string path, string contentType)
{
return GetUri(GetFullFileName(path, contentType));
}
internal static string GetFullFileName(string path, string contentType)
{
var href = Path.GetFileNameWithoutExtension(path);
var category = GetCategoryFromPath(path);
var hrefTokenSource = href;
if (Uri.IsWellFormedUriString(href, UriKind.Relative))
hrefTokenSource = (SecureHelper.IsSecure() ? "https" : "http") + href;
var hrefToken = string.Concat(HttpServerUtility.UrlTokenEncode(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(hrefTokenSource))));
if (string.Compare(contentType, "text/css", StringComparison.OrdinalIgnoreCase) == 0)
return string.Format("/{0}/css/{1}.css", category, hrefToken);
return string.Format("/{0}/javascript/{1}.js", category, hrefToken);
}
internal static bool IsFile(string path)
{
var filePath = GetFullPhysicalPath(path);
var staticPath = GetFullStaticPhysicalPath(path);
if (!File.Exists(filePath) && File.Exists(staticPath))
{
using (var mutex = new Mutex(true, path))
{
mutex.WaitOne();
try
{
CreateDir(filePath);
if (File.Exists(staticPath))
{
File.Copy(staticPath, filePath, true);
}
if (File.Exists(staticPath + ".gz"))
{
File.Copy(staticPath + ".gz", filePath + ".gz", true);
}
}
finally
{
mutex.ReleaseMutex();
}
}
}
return File.Exists(filePath);
}
private static string GetCategoryFromPath(string controlPath)
{
var result = "common";
controlPath = controlPath.ToLower();
var matches = Regex.Match(controlPath, "~/(\\w+)/(\\w+)-(\\w+)/?", RegexOptions.Compiled);
if (matches.Success && matches.Groups.Count > 3 && matches.Groups[2].Success)
result = matches.Groups[2].Value;
return result;
}
private static string GetFullPhysicalPath(string path)
{
return Path.GetFullPath(Path.Combine(HttpContext.Current.Server.MapPath("~/"), BaseStoragePath, path.TrimStart('/')));
}
private static string GetFullStaticPhysicalPath(string path)
{
return Path.GetFullPath(Path.Combine(HttpContext.Current.Server.MapPath("~/"), "App_Data/static/bundle/", path.TrimStart('/')));
}
private static void CreateDir(string path)
{
var dir = Path.GetDirectoryName(path);
if (dir != null && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Sinks.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Pattern;
using Akka.Streams.Actors;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation.Stages;
using Akka.Streams.Stage;
using Akka.Streams.Supervision;
using Akka.Streams.Util;
using Akka.Util;
using Reactive.Streams;
using Decider = Akka.Streams.Supervision.Decider;
using Directive = Akka.Streams.Supervision.Directive;
namespace Akka.Streams.Implementation
{
/// <summary>
/// TBD
/// </summary>
internal interface ISinkModule
{
/// <summary>
/// TBD
/// </summary>
Shape Shape { get; }
/// <summary>
/// TBD
/// </summary>
object Create(MaterializationContext context, out object materializer);
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
public abstract class SinkModule<TIn, TMat> : AtomicModule, ISinkModule
{
private readonly SinkShape<TIn> _shape;
/// <summary>
/// TBD
/// </summary>
/// <param name="shape">TBD</param>
protected SinkModule(SinkShape<TIn> shape)
{
_shape = shape;
}
/// <summary>
/// TBD
/// </summary>
public override Shape Shape => _shape;
/// <summary>
/// TBD
/// </summary>
protected virtual string Label => GetType().Name;
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public sealed override string ToString() => $"{Label} [{GetHashCode()}%08x]";
/// <summary>
/// TBD
/// </summary>
/// <param name="shape">TBD</param>
/// <returns>TBD</returns>
protected abstract SinkModule<TIn, TMat> NewInstance(SinkShape<TIn> shape);
/// <summary>
/// Create the Subscriber or VirtualPublisher that consumes the incoming
/// stream, plus the materialized value. Since Subscriber and VirtualPublisher
/// do not share a common supertype apart from AnyRef this is what the type
/// union devolves into; unfortunately we do not have union types at our
/// disposal at this point.
/// </summary>
/// <param name="context">TBD</param>
/// <param name="materializer">TBD</param>
/// <returns>TBD</returns>
public abstract object Create(MaterializationContext context, out TMat materializer);
object ISinkModule.Create(MaterializationContext context, out object materializer)
{
TMat m;
var result = Create(context, out m);
materializer = m;
return result;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="shape">TBD</param>
/// <exception cref="NotSupportedException">TBD</exception>
/// <returns>TBD</returns>
public override IModule ReplaceShape(Shape shape)
{
if (Equals(_shape, shape))
return this;
throw new NotSupportedException(
"cannot replace the shape of a Sink, you need to wrap it in a Graph for that");
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override IModule CarbonCopy()
=> NewInstance(new SinkShape<TIn>(Inlet.Create<TIn>(_shape.Inlet.CarbonCopy())));
/// <summary>
/// TBD
/// </summary>
/// <param name="attrs">TBD</param>
/// <returns>TBD</returns>
protected SinkShape<TIn> AmendShape(Attributes attrs)
{
var thisN = Attributes.GetNameOrDefault(null);
var thatN = attrs.GetNameOrDefault(null);
return (thatN == null) || thisN == thatN
? _shape
: new SinkShape<TIn>(new Inlet<TIn>(thatN + ".in"));
}
}
/// <summary>
/// INTERNAL API
///
/// Holds the downstream-most <see cref="IPublisher{T}"/> interface of the materialized flow.
/// The stream will not have any subscribers attached at this point, which means that after prefetching
/// elements to fill the internal buffers it will assert back-pressure until
/// a subscriber connects and creates demand for elements to be emitted.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
internal class PublisherSink<TIn> : SinkModule<TIn, IPublisher<TIn>>
{
/// <summary>
/// TBD
/// </summary>
/// <param name="attributes">TBD</param>
/// <param name="shape">TBD</param>
public PublisherSink(Attributes attributes, SinkShape<TIn> shape)
: base(shape)
{
Attributes = attributes;
}
/// <summary>
/// TBD
/// </summary>
public override Attributes Attributes { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="attributes">TBD</param>
/// <returns>TBD</returns>
public override IModule WithAttributes(Attributes attributes)
=> new PublisherSink<TIn>(attributes, AmendShape(attributes));
/// <summary>
/// TBD
/// </summary>
/// <param name="shape">TBD</param>
/// <returns>TBD</returns>
protected override SinkModule<TIn, IPublisher<TIn>> NewInstance(SinkShape<TIn> shape)
=> new PublisherSink<TIn>(Attributes, shape);
/// <summary>
/// This method is the reason why SinkModule.create may return something that is
/// not a Subscriber: a VirtualPublisher is used in order to avoid the immediate
/// subscription a VirtualProcessor would perform (and it also saves overhead).
/// </summary>
/// <param name="context">TBD</param>
/// <param name="materializer">TBD</param>
/// <returns>TBD</returns>
public override object Create(MaterializationContext context, out IPublisher<TIn> materializer)
{
var processor = new VirtualProcessor<TIn>();
materializer = processor;
return processor;
}
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
internal sealed class FanoutPublisherSink<TIn> : SinkModule<TIn, IPublisher<TIn>>
{
/// <summary>
/// TBD
/// </summary>
/// <param name="attributes">TBD</param>
/// <param name="shape">TBD</param>
public FanoutPublisherSink(Attributes attributes, SinkShape<TIn> shape) : base(shape)
{
Attributes = attributes;
}
/// <summary>
/// TBD
/// </summary>
public override Attributes Attributes { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="attributes">TBD</param>
/// <returns>TBD</returns>
public override IModule WithAttributes(Attributes attributes)
=> new FanoutPublisherSink<TIn>(attributes, AmendShape(attributes));
/// <summary>
/// TBD
/// </summary>
/// <param name="shape">TBD</param>
/// <returns>TBD</returns>
protected override SinkModule<TIn, IPublisher<TIn>> NewInstance(SinkShape<TIn> shape)
=> new FanoutPublisherSink<TIn>(Attributes, shape);
/// <summary>
/// TBD
/// </summary>
/// <param name="context">TBD</param>
/// <param name="materializer">TBD</param>
/// <returns>TBD</returns>
public override object Create(MaterializationContext context, out IPublisher<TIn> materializer)
{
var actorMaterializer = ActorMaterializerHelper.Downcast(context.Materializer);
var settings = actorMaterializer.EffectiveSettings(Attributes);
var impl = actorMaterializer.ActorOf(context, FanoutProcessorImpl<TIn>.Props(settings));
var fanoutProcessor = new ActorProcessor<TIn, TIn>(impl);
impl.Tell(new ExposedPublisher(fanoutProcessor));
// Resolve cyclic dependency with actor. This MUST be the first message no matter what.
materializer = fanoutProcessor;
return fanoutProcessor;
}
}
/// <summary>
/// INTERNAL API
///
/// Attaches a subscriber to this stream.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
public sealed class SubscriberSink<TIn> : SinkModule<TIn, NotUsed>
{
private readonly ISubscriber<TIn> _subscriber;
/// <summary>
/// TBD
/// </summary>
/// <param name="subscriber">TBD</param>
/// <param name="attributes">TBD</param>
/// <param name="shape">TBD</param>
public SubscriberSink(ISubscriber<TIn> subscriber, Attributes attributes, SinkShape<TIn> shape) : base(shape)
{
Attributes = attributes;
_subscriber = subscriber;
}
/// <summary>
/// TBD
/// </summary>
public override Attributes Attributes { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="attributes">TBD</param>
/// <returns>TBD</returns>
public override IModule WithAttributes(Attributes attributes)
=> new SubscriberSink<TIn>(_subscriber, attributes, AmendShape(attributes));
/// <summary>
/// TBD
/// </summary>
/// <param name="shape">TBD</param>
/// <returns>TBD</returns>
protected override SinkModule<TIn, NotUsed> NewInstance(SinkShape<TIn> shape)
=> new SubscriberSink<TIn>(_subscriber, Attributes, shape);
/// <summary>
/// TBD
/// </summary>
/// <param name="context">TBD</param>
/// <param name="materializer">TBD</param>
/// <returns>TBD</returns>
public override object Create(MaterializationContext context, out NotUsed materializer)
{
materializer = NotUsed.Instance;
return _subscriber;
}
}
/// <summary>
/// INTERNAL API
///
/// A sink that immediately cancels its upstream upon materialization.
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public sealed class CancelSink<T> : SinkModule<T, NotUsed>
{
/// <summary>
/// TBD
/// </summary>
/// <param name="attributes">TBD</param>
/// <param name="shape">TBD</param>
public CancelSink(Attributes attributes, SinkShape<T> shape)
: base(shape)
{
Attributes = attributes;
}
/// <summary>
/// TBD
/// </summary>
public override Attributes Attributes { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="shape">TBD</param>
/// <returns>TBD</returns>
protected override SinkModule<T, NotUsed> NewInstance(SinkShape<T> shape)
=> new CancelSink<T>(Attributes, shape);
/// <summary>
/// TBD
/// </summary>
/// <param name="context">TBD</param>
/// <param name="materializer">TBD</param>
/// <returns>TBD</returns>
public override object Create(MaterializationContext context, out NotUsed materializer)
{
materializer = NotUsed.Instance;
return new CancellingSubscriber<T>();
}
/// <summary>
/// TBD
/// </summary>
/// <param name="attributes">TBD</param>
/// <returns>TBD</returns>
public override IModule WithAttributes(Attributes attributes)
=> new CancelSink<T>(attributes, AmendShape(attributes));
}
/// <summary>
/// INTERNAL API
///
/// Creates and wraps an actor into <see cref="ISubscriber{T}"/> from the given <see cref="Props"/>,
/// which should be <see cref="Props"/> for an <see cref="ActorSubscriber"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
public sealed class ActorSubscriberSink<TIn> : SinkModule<TIn, IActorRef>
{
private readonly Props _props;
private readonly Attributes _attributes;
/// <summary>
/// TBD
/// </summary>
/// <param name="props">TBD</param>
/// <param name="attributes">TBD</param>
/// <param name="shape">TBD</param>
public ActorSubscriberSink(Props props, Attributes attributes, SinkShape<TIn> shape)
: base(shape)
{
_props = props;
_attributes = attributes;
}
/// <summary>
/// TBD
/// </summary>
public override Attributes Attributes => _attributes;
/// <summary>
/// TBD
/// </summary>
/// <param name="attributes">TBD</param>
/// <returns>TBD</returns>
public override IModule WithAttributes(Attributes attributes)
=> new ActorSubscriberSink<TIn>(_props, attributes, AmendShape(attributes));
/// <summary>
/// TBD
/// </summary>
/// <param name="shape">TBD</param>
/// <returns>TBD</returns>
protected override SinkModule<TIn, IActorRef> NewInstance(SinkShape<TIn> shape)
=> new ActorSubscriberSink<TIn>(_props, _attributes, shape);
/// <summary>
/// TBD
/// </summary>
/// <param name="context">TBD</param>
/// <param name="materializer">TBD</param>
/// <returns>TBD</returns>
public override object Create(MaterializationContext context, out IActorRef materializer)
{
var subscriberRef = ActorMaterializerHelper.Downcast(context.Materializer).ActorOf(context, _props);
materializer = subscriberRef;
return ActorSubscriber.Create<TIn>(subscriberRef);
}
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
public sealed class ActorRefSink<TIn> : SinkModule<TIn, NotUsed>
{
private readonly IActorRef _ref;
private readonly object _onCompleteMessage;
private readonly Attributes _attributes;
/// <summary>
/// TBD
/// </summary>
/// <param name="ref">TBD</param>
/// <param name="onCompleteMessage">TBD</param>
/// <param name="attributes">TBD</param>
/// <param name="shape">TBD</param>
public ActorRefSink(IActorRef @ref, object onCompleteMessage, Attributes attributes, SinkShape<TIn> shape)
: base(shape)
{
_ref = @ref;
_onCompleteMessage = onCompleteMessage;
_attributes = attributes;
}
/// <summary>
/// TBD
/// </summary>
public override Attributes Attributes => _attributes;
/// <summary>
/// TBD
/// </summary>
/// <param name="attributes">TBD</param>
/// <returns>TBD</returns>
public override IModule WithAttributes(Attributes attributes)
=> new ActorRefSink<TIn>(_ref, _onCompleteMessage, attributes, AmendShape(attributes));
/// <summary>
/// TBD
/// </summary>
/// <param name="shape">TBD</param>
/// <returns>TBD</returns>
protected override SinkModule<TIn, NotUsed> NewInstance(SinkShape<TIn> shape)
=> new ActorRefSink<TIn>(_ref, _onCompleteMessage, _attributes, shape);
/// <summary>
/// TBD
/// </summary>
/// <param name="context">TBD</param>
/// <param name="materializer">TBD</param>
/// <returns>TBD</returns>
public override object Create(MaterializationContext context, out NotUsed materializer)
{
var actorMaterializer = ActorMaterializerHelper.Downcast(context.Materializer);
var effectiveSettings = actorMaterializer.EffectiveSettings(context.EffectiveAttributes);
var subscriberRef = actorMaterializer.ActorOf(context,
ActorRefSinkActor.Props(_ref, effectiveSettings.MaxInputBufferSize, _onCompleteMessage));
materializer = null;
return new ActorSubscriberImpl<TIn>(subscriberRef);
}
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public sealed class LastOrDefaultStage<T> : GraphStageWithMaterializedValue<SinkShape<T>, Task<T>>
{
#region stage logic
private sealed class Logic : InGraphStageLogic
{
private readonly TaskCompletionSource<T> _promise;
private readonly LastOrDefaultStage<T> _stage;
private T _prev;
public Logic(TaskCompletionSource<T> promise, LastOrDefaultStage<T> stage) : base(stage.Shape)
{
_promise = promise;
_stage = stage;
SetHandler(stage.In, this);
}
public override void OnPush()
{
_prev = Grab(_stage.In);
Pull(_stage.In);
}
public override void OnUpstreamFinish()
{
var head = _prev;
_prev = default(T);
_promise.TrySetResult(head);
CompleteStage();
}
public override void OnUpstreamFailure(Exception e)
{
_prev = default(T);
_promise.TrySetException(e);
FailStage(e);
}
public override void PreStart() => Pull(_stage.In);
}
#endregion
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T> In = new Inlet<T>("LastOrDefault.in");
/// <summary>
/// TBD
/// </summary>
public LastOrDefaultStage()
{
Shape = new SinkShape<T>(In);
}
/// <summary>
/// TBD
/// </summary>
public override SinkShape<T> Shape { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
public override ILogicAndMaterializedValue<Task<T>> CreateLogicAndMaterializedValue(
Attributes inheritedAttributes)
{
var promise = new TaskCompletionSource<T>();
return new LogicAndMaterializedValue<Task<T>>(new Logic(promise, this), promise.Task);
}
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public sealed class FirstOrDefaultStage<T> : GraphStageWithMaterializedValue<SinkShape<T>, Task<T>>
{
#region stage logic
private sealed class Logic : InGraphStageLogic
{
private readonly TaskCompletionSource<T> _promise;
private readonly FirstOrDefaultStage<T> _stage;
public Logic(TaskCompletionSource<T> promise, FirstOrDefaultStage<T> stage) : base(stage.Shape)
{
_promise = promise;
_stage = stage;
SetHandler(stage.In, this);
}
public override void OnPush()
{
_promise.TrySetResult(Grab(_stage.In));
CompleteStage();
}
public override void OnUpstreamFinish()
{
_promise.TrySetResult(default(T));
CompleteStage();
}
public override void OnUpstreamFailure(Exception e)
{
_promise.TrySetException(e);
FailStage(e);
}
public override void PreStart() => Pull(_stage.In);
}
#endregion
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T> In = new Inlet<T>("FirstOrDefault.in");
/// <summary>
/// TBD
/// </summary>
public FirstOrDefaultStage()
{
Shape = new SinkShape<T>(In);
}
/// <summary>
/// TBD
/// </summary>
public override SinkShape<T> Shape { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
public override ILogicAndMaterializedValue<Task<T>> CreateLogicAndMaterializedValue(
Attributes inheritedAttributes)
{
var promise = new TaskCompletionSource<T>();
return new LogicAndMaterializedValue<Task<T>>(new Logic(promise, this), promise.Task);
}
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public sealed class SeqStage<T> : GraphStageWithMaterializedValue<SinkShape<T>, Task<IImmutableList<T>>>
{
#region stage logic
private sealed class Logic : InGraphStageLogic
{
private readonly SeqStage<T> _stage;
private readonly TaskCompletionSource<IImmutableList<T>> _promise;
private IImmutableList<T> _buf = ImmutableList<T>.Empty;
public Logic(SeqStage<T> stage, TaskCompletionSource<IImmutableList<T>> promise) : base(stage.Shape)
{
_stage = stage;
_promise = promise;
SetHandler(stage.In, this);
}
public override void OnPush()
{
_buf = _buf.Add(Grab(_stage.In));
Pull(_stage.In);
}
public override void OnUpstreamFinish()
{
_promise.TrySetResult(_buf);
CompleteStage();
}
public override void OnUpstreamFailure(Exception e)
{
_promise.TrySetException(e);
FailStage(e);
}
public override void PreStart() => Pull(_stage.In);
}
#endregion
/// <summary>
/// TBD
/// </summary>
public SeqStage()
{
Shape = new SinkShape<T>(In);
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.SeqSink;
/// <summary>
/// TBD
/// </summary>
public override SinkShape<T> Shape { get; }
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T> In = new Inlet<T>("Seq.in");
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
public override ILogicAndMaterializedValue<Task<IImmutableList<T>>> CreateLogicAndMaterializedValue(
Attributes inheritedAttributes)
{
var promise = new TaskCompletionSource<IImmutableList<T>>();
return new LogicAndMaterializedValue<Task<IImmutableList<T>>>(new Logic(this, promise), promise.Task);
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "SeqStage";
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public sealed class QueueSink<T> : GraphStageWithMaterializedValue<SinkShape<T>, ISinkQueue<T>>
{
#region stage logic
private sealed class Logic : GraphStageLogicWithCallbackWrapper<TaskCompletionSource<Option<T>>>, IInHandler
{
private readonly QueueSink<T> _stage;
private readonly int _maxBuffer;
private IBuffer<Result<Option<T>>> _buffer;
private Option<TaskCompletionSource<Option<T>>> _currentRequest;
public Logic(QueueSink<T> stage, int maxBuffer) : base(stage.Shape)
{
_stage = stage;
_maxBuffer = maxBuffer;
_currentRequest = new Option<TaskCompletionSource<Option<T>>>();
SetHandler(stage.In, this);
}
public void OnPush()
{
EnqueueAndNotify(new Result<Option<T>>(Grab(_stage.In)));
if (_buffer.Used < _maxBuffer) Pull(_stage.In);
}
public void OnUpstreamFinish() => EnqueueAndNotify(new Result<Option<T>>(Option<T>.None));
public void OnUpstreamFailure(Exception e) => EnqueueAndNotify(new Result<Option<T>>(e));
public override void PreStart()
{
// Allocates one additional element to hold stream closed/failure indicators
_buffer = Buffer.Create<Result<Option<T>>>(_maxBuffer + 1, Materializer);
SetKeepGoing(true);
InitCallback(Callback());
Pull(_stage.In);
}
public override void PostStop()
{
StopCallback(
promise =>
promise.SetException(new IllegalStateException("Stream is terminated. QueueSink is detached")));
}
private Action<TaskCompletionSource<Option<T>>> Callback()
{
return GetAsyncCallback<TaskCompletionSource<Option<T>>>(
promise =>
{
if (_currentRequest.HasValue)
promise.SetException(
new IllegalStateException(
"You have to wait for previous future to be resolved to send another request"));
else
{
if (_buffer.IsEmpty)
_currentRequest = promise;
else
{
if (_buffer.Used == _maxBuffer)
TryPull(_stage.In);
SendDownstream(promise);
}
}
});
}
private void SendDownstream(TaskCompletionSource<Option<T>> promise)
{
var e = _buffer.Dequeue();
if (e.IsSuccess)
{
promise.SetResult(e.Value);
if (!e.Value.HasValue)
CompleteStage();
}
else
{
promise.SetException(e.Exception);
FailStage(e.Exception);
}
}
private void EnqueueAndNotify(Result<Option<T>> requested)
{
_buffer.Enqueue(requested);
if (_currentRequest.HasValue)
{
SendDownstream(_currentRequest.Value);
_currentRequest = Option<TaskCompletionSource<Option<T>>>.None;
}
}
internal void Invoke(TaskCompletionSource<Option<T>> tuple) => InvokeCallbacks(tuple);
}
private sealed class Materialized : ISinkQueue<T>
{
private readonly Action<TaskCompletionSource<Option<T>>> _invokeLogic;
public Materialized(Action<TaskCompletionSource<Option<T>>> invokeLogic)
{
_invokeLogic = invokeLogic;
}
public Task<Option<T>> PullAsync()
{
var promise = new TaskCompletionSource<Option<T>>();
_invokeLogic(promise);
return promise.Task;
}
}
#endregion
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<T> In = new Inlet<T>("QueueSink.in");
/// <summary>
/// TBD
/// </summary>
public QueueSink()
{
Shape = new SinkShape<T>(In);
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.QueueSink;
/// <summary>
/// TBD
/// </summary>
public override SinkShape<T> Shape { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
public override ILogicAndMaterializedValue<ISinkQueue<T>> CreateLogicAndMaterializedValue(
Attributes inheritedAttributes)
{
var maxBuffer = inheritedAttributes.GetAttribute(new Attributes.InputBuffer(16, 16)).Max;
if (maxBuffer <= 0)
throw new ArgumentException("Buffer must be greater than zero", nameof(inheritedAttributes));
var logic = new Logic(this, maxBuffer);
return new LogicAndMaterializedValue<ISinkQueue<T>>(logic, new Materialized(t => logic.Invoke(t)));
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "QueueSink";
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
internal sealed class LazySink<TIn, TMat> : GraphStageWithMaterializedValue<SinkShape<TIn>, Task<TMat>>
{
#region Logic
private sealed class Logic : InGraphStageLogic
{
private readonly LazySink<TIn, TMat> _stage;
private readonly TaskCompletionSource<TMat> _completion;
private readonly Lazy<Decider> _decider;
private bool _completed;
public Logic(LazySink<TIn, TMat> stage, Attributes inheritedAttributes,
TaskCompletionSource<TMat> completion) : base(stage.Shape)
{
_stage = stage;
_completion = completion;
_decider = new Lazy<Decider>(() =>
{
var attr = inheritedAttributes.GetAttribute<ActorAttributes.SupervisionStrategy>(null);
return attr != null ? attr.Decider : Deciders.StoppingDecider;
});
SetHandler(stage.In, this);
}
public override void OnPush()
{
try
{
var element = Grab(_stage.In);
var callback = GetAsyncCallback<Result<Sink<TIn, TMat>>>(result =>
{
if (result.IsSuccess)
InitInternalSource(result.Value, element);
else
Failure(result.Exception);
});
_stage._sinkFactory(element)
.ContinueWith(t => callback(Result.FromTask(t)),
TaskContinuationOptions.ExecuteSynchronously);
SetHandler(_stage.In, new LambdaInHandler(
onPush: () => { },
onUpstreamFinish: GotCompletionEvent,
onUpstreamFailure: Failure
));
}
catch (Exception ex)
{
if (_decider.Value(ex) == Directive.Stop)
Failure(ex);
else
Pull(_stage.In);
}
}
public override void OnUpstreamFinish()
{
CompleteStage();
try
{
_completion.TrySetResult(_stage._zeroMaterialised());
}
catch (Exception ex)
{
_completion.SetException(ex);
}
}
public override void OnUpstreamFailure(Exception e) => Failure(e);
private void GotCompletionEvent()
{
SetKeepGoing(true);
_completed = true;
}
public override void PreStart() => Pull(_stage.In);
private void Failure(Exception ex)
{
FailStage(ex);
_completion.SetException(ex);
}
private void InitInternalSource(Sink<TIn, TMat> sink, TIn firstElement)
{
var sourceOut = new SubSource(this, firstElement);
try {
var matVal = Source.FromGraph(sourceOut.Source)
.RunWith(sink, Interpreter.SubFusingMaterializer);
_completion.TrySetResult(matVal);
}
catch (Exception ex)
{
_completion.TrySetException(ex);
FailStage(ex);
}
}
#region SubSource
private sealed class SubSource : SubSourceOutlet<TIn>
{
private readonly Logic _logic;
private readonly LazySink<TIn, TMat> _stage;
public SubSource(Logic logic, TIn firstElement) : base(logic, "LazySink")
{
_logic = logic;
_stage = logic._stage;
SetHandler(new LambdaOutHandler(onPull: () =>
{
Push(firstElement);
if (_logic._completed)
SourceComplete();
else
SwitchToFinalHandler();
}, onDownstreamFinish: SourceComplete));
logic.SetHandler(_stage.In, new LambdaInHandler(
onPush: () => Push(logic.Grab(_stage.In)),
onUpstreamFinish: logic.GotCompletionEvent,
onUpstreamFailure: SourceFailure));
}
private void SourceFailure(Exception ex)
{
Fail(ex);
_logic.FailStage(ex);
}
private void SwitchToFinalHandler()
{
SetHandler(new LambdaOutHandler(
onPull: () => _logic.Pull(_stage.In),
onDownstreamFinish: SourceComplete));
_logic.SetHandler(_stage.In, new LambdaInHandler(
onPush: () => Push(_logic.Grab(_stage.In)),
onUpstreamFinish: SourceComplete,
onUpstreamFailure: SourceFailure));
}
private void SourceComplete()
{
Complete();
_logic.CompleteStage();
}
}
#endregion
}
#endregion
private readonly Func<TIn, Task<Sink<TIn, TMat>>> _sinkFactory;
private readonly Func<TMat> _zeroMaterialised;
/// <summary>
/// TBD
/// </summary>
/// <param name="sinkFactory">TBD</param>
/// <param name="zeroMaterialised">TBD</param>
public LazySink(Func<TIn, Task<Sink<TIn, TMat>>> sinkFactory, Func<TMat> zeroMaterialised)
{
_sinkFactory = sinkFactory;
_zeroMaterialised = zeroMaterialised;
Shape = new SinkShape<TIn>(In);
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.LazySink;
/// <summary>
/// TBD
/// </summary>
public Inlet<TIn> In { get; } = new Inlet<TIn>("lazySink.in");
/// <summary>
/// TBD
/// </summary>
public override SinkShape<TIn> Shape { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
public override ILogicAndMaterializedValue<Task<TMat>> CreateLogicAndMaterializedValue(Attributes inheritedAttributes)
{
var completion = new TaskCompletionSource<TMat>();
var stageLogic = new Logic(this, inheritedAttributes, completion);
return new LogicAndMaterializedValue<Task<TMat>>(stageLogic, completion.Task);
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "LazySink";
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Versions;
namespace Orleans.Runtime.Placement
{
/// <summary>
/// Central point for placement decisions.
/// </summary>
internal class PlacementService : IPlacementContext
{
private const int PlacementWorkerCount = 16;
private readonly PlacementStrategyResolver _strategyResolver;
private readonly PlacementDirectorResolver _directorResolver;
private readonly ILogger<PlacementService> _logger;
private readonly GrainLocator _grainLocator;
private readonly GrainVersionManifest _grainInterfaceVersions;
private readonly CachedVersionSelectorManager _versionSelectorManager;
private readonly ISiloStatusOracle _siloStatusOracle;
private readonly bool _assumeHomogeneousSilosForTesting;
private readonly PlacementWorker[] _workers;
/// <summary>
/// Create a <see cref="PlacementService"/> instance.
/// </summary>
public PlacementService(
IOptionsMonitor<SiloMessagingOptions> siloMessagingOptions,
ILocalSiloDetails localSiloDetails,
ISiloStatusOracle siloStatusOracle,
ILogger<PlacementService> logger,
GrainLocator grainLocator,
GrainVersionManifest grainInterfaceVersions,
CachedVersionSelectorManager versionSelectorManager,
PlacementDirectorResolver directorResolver,
PlacementStrategyResolver strategyResolver)
{
LocalSilo = localSiloDetails.SiloAddress;
_strategyResolver = strategyResolver;
_directorResolver = directorResolver;
_logger = logger;
_grainLocator = grainLocator;
_grainInterfaceVersions = grainInterfaceVersions;
_versionSelectorManager = versionSelectorManager;
_siloStatusOracle = siloStatusOracle;
_assumeHomogeneousSilosForTesting = siloMessagingOptions.CurrentValue.AssumeHomogenousSilosForTesting;
_workers = new PlacementWorker[PlacementWorkerCount];
for (var i = 0; i < PlacementWorkerCount; i++)
{
_workers[i] = new(this);
}
}
public SiloAddress LocalSilo { get; }
public SiloStatus LocalSiloStatus => _siloStatusOracle.CurrentStatus;
/// <summary>
/// Gets or places an activation.
/// </summary>
public Task AddressMessage(Message message)
{
if (message.IsFullyAddressed) return Task.CompletedTask;
if (message.TargetGrain.IsDefault) ThrowMissingAddress();
var grainId = message.TargetGrain;
if (_grainLocator.TryLookupInCache(grainId, out var result))
{
SetMessageTargetPlacement(message, result.Activation, result.Silo);
return Task.CompletedTask;
}
var worker = _workers[grainId.GetUniformHashCode() % PlacementWorkerCount];
return worker.AddressMessage(message);
[MethodImpl(MethodImplOptions.NoInlining)]
static void ThrowMissingAddress() => throw new InvalidOperationException("Cannot address a message without a target");
}
private void SetMessageTargetPlacement(Message message, ActivationId activationId, SiloAddress targetSilo)
{
message.TargetActivation = activationId;
message.TargetSilo = targetSilo;
#if DEBUG
if (_logger.IsEnabled(LogLevel.Trace)) _logger.Trace(ErrorCode.Dispatcher_AddressMsg_SelectTarget, "AddressMessage Placement SelectTarget {0}", message);
#endif
}
public SiloAddress[] GetCompatibleSilos(PlacementTarget target)
{
// For test only: if we have silos that are not yet in the Cluster TypeMap, we assume that they are compatible
// with the current silo
if (_assumeHomogeneousSilosForTesting)
{
return AllActiveSilos;
}
var grainType = target.GrainIdentity.Type;
var silos = target.InterfaceVersion > 0
? _versionSelectorManager.GetSuitableSilos(grainType, target.InterfaceType, target.InterfaceVersion).SuitableSilos
: _grainInterfaceVersions.GetSupportedSilos(grainType).Result;
var compatibleSilos = silos.Intersect(AllActiveSilos).ToArray();
if (compatibleSilos.Length == 0)
{
var allWithType = _grainInterfaceVersions.GetSupportedSilos(grainType).Result;
var versions = _grainInterfaceVersions.GetSupportedSilos(target.InterfaceType, target.InterfaceVersion).Result;
var allWithTypeString = string.Join(", ", allWithType.Select(s => s.ToString())) is string withGrain && !string.IsNullOrWhiteSpace(withGrain) ? withGrain : "none";
var allWithInterfaceString = string.Join(", ", versions.Select(s => s.ToString())) is string withIface && !string.IsNullOrWhiteSpace(withIface) ? withIface : "none";
throw new OrleansException(
$"No active nodes are compatible with grain {grainType} and interface {target.InterfaceType} version {target.InterfaceVersion}. "
+ $"Known nodes with grain type: {allWithTypeString}. "
+ $"All known nodes compatible with interface version: {allWithTypeString}");
}
return compatibleSilos;
}
public SiloAddress[] AllActiveSilos
{
get
{
var result = _siloStatusOracle.GetApproximateSiloStatuses(true).Keys.ToArray();
if (result.Length > 0) return result;
_logger.Warn(ErrorCode.Catalog_GetApproximateSiloStatuses, "AllActiveSilos SiloStatusOracle.GetApproximateSiloStatuses empty");
return new SiloAddress[] { LocalSilo };
}
}
public IReadOnlyDictionary<ushort, SiloAddress[]> GetCompatibleSilosWithVersions(PlacementTarget target)
{
if (target.InterfaceVersion == 0)
{
throw new ArgumentException("Interface version not provided", nameof(target));
}
var grainType = target.GrainIdentity.Type;
var silos = _versionSelectorManager
.GetSuitableSilos(grainType, target.InterfaceType, target.InterfaceVersion)
.SuitableSilosByVersion;
return silos;
}
private class PlacementWorker
{
private readonly Dictionary<GrainId, GrainPlacementWorkItem> _inProgress = new();
private readonly SingleWaiterAutoResetEvent _workSignal = new();
private readonly ILogger _logger;
private readonly Task _processLoopTask;
private readonly object _lockObj = new();
private readonly PlacementService _placementService;
private List<(Message Message, TaskCompletionSource<bool> Completion)> _messages = new();
public PlacementWorker(PlacementService placementService)
{
_logger = placementService._logger;
_placementService = placementService;
_processLoopTask = Task.Run(ProcessLoop);
}
public Task AddressMessage(Message message)
{
var completion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (_lockObj)
{
_messages ??= new();
_messages.Add((message, completion));
}
_workSignal.Signal();
return completion.Task;
}
private List<(Message Message, TaskCompletionSource<bool> Completion)> GetMessages()
{
lock (_lockObj)
{
if (_messages is { Count: > 0 } result)
{
_messages = null;
return result;
}
return null;
}
}
private async Task ProcessLoop()
{
var toRemove = new List<GrainId>();
while (true)
{
try
{
// Start processing new requests
var messages = GetMessages();
if (messages is not null)
{
foreach (var message in messages)
{
var target = message.Message.TargetGrain;
if (!_inProgress.TryGetValue(target, out var workItem))
{
_inProgress[target] = workItem = new();
}
workItem.Messages.Add(message);
if (workItem.Result is null)
{
// Note that the first message is used as the target to place the message,
// so if subsequent messsages do not agree with the first message's interface
// type or version, then they may be sent to an incompatible silo, which is
// fine since the remote silo will handle that incompatibility.
workItem.Result = GetOrPlaceActivationAsync(message.Message);
// Wake up this processing loop when the task completes
workItem.Result.SignalOnCompleted(_workSignal);
}
}
}
// Complete processing any completed request
foreach (var pair in _inProgress)
{
var workItem = pair.Value;
if (workItem.Result.IsCompleted)
{
AddressWaitingMessages(workItem);
toRemove.Add(pair.Key);
}
}
// Clean up after completed requests
if (toRemove.Count > 0)
{
foreach (var grainId in toRemove)
{
_inProgress.Remove(grainId);
}
toRemove.Clear();
}
}
catch (Exception exception)
{
_logger.LogWarning(exception, "Exception in placement worker");
}
await _workSignal.WaitAsync();
}
}
private void AddressWaitingMessages(GrainPlacementWorkItem completedWorkItem)
{
var resultTask = completedWorkItem.Result;
var messages = completedWorkItem.Messages;
if (resultTask.IsCompletedSuccessfully)
{
foreach (var message in messages)
{
var result = resultTask.Result;
_placementService.SetMessageTargetPlacement(message.Message, result.Activation, result.Silo);
message.Completion.TrySetResult(true);
}
messages.Clear();
}
else
{
foreach (var message in messages)
{
message.Completion.TrySetException(resultTask.Exception.OriginalException());
}
messages.Clear();
}
}
private async Task<ActivationAddress> GetOrPlaceActivationAsync(Message firstMessage)
{
await Task.Yield();
var target = new PlacementTarget(
firstMessage.TargetGrain,
firstMessage.RequestContextData,
firstMessage.InterfaceType,
firstMessage.InterfaceVersion);
var targetGrain = target.GrainIdentity;
var result = await _placementService._grainLocator.Lookup(targetGrain);
if (result is not null)
{
return result;
}
var strategy = _placementService._strategyResolver.GetPlacementStrategy(target.GrainIdentity.Type);
var director = _placementService._directorResolver.GetPlacementDirector(strategy);
var siloAddress = await director.OnAddActivation(strategy, target, _placementService);
// Give the grain locator one last chance to tell us that the grain has already been placed
if (_placementService._grainLocator.TryLookupInCache(targetGrain, out result))
{
return result;
}
ActivationId activationId;
if (strategy.IsDeterministicActivationId)
{
// Use the grain id as the activation id.
activationId = ActivationId.GetDeterministic(target.GrainIdentity);
}
else
{
activationId = ActivationId.NewId();
}
result = ActivationAddress.GetAddress(siloAddress, targetGrain, activationId);
_placementService._grainLocator.InvalidateCache(targetGrain);
_placementService._grainLocator.CachePlacementDecision(result);
return result;
}
private class GrainPlacementWorkItem
{
public List<(Message Message, TaskCompletionSource<bool> Completion)> Messages { get; } = new();
public Task<ActivationAddress> Result { get; set; }
}
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Utilities
// File : ImageReference.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 06/06/2010
// Note : Copyright 2008-2010, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a class representing a conceptual content image that can
// be used to insert a reference to an image in a topic.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.6.0.7 04/24/2008 EFW Created the code
// 1.8.0.0 07/25/2008 EFW Reworked to support new MSBuild project format
//=============================================================================
using System;
using System.ComponentModel;
using System.Globalization;
namespace SandcastleBuilder.Utils.ConceptualContent
{
/// <summary>
/// This represents a conceptual content image that can be used to insert
/// a reference to an image in a topic.
/// </summary>
/// <remarks>This class is serializable so that it can be copied to the
/// clipboard.</remarks>
[DefaultProperty("ImageFile")]
public class ImageReference
{
#region Private data members
//=====================================================================
private FileItem fileItem;
#endregion
#region Properties
//=====================================================================
/// <summary>
/// This is used to get the image filename
/// </summary>
[Category("File"), Description("The image filename")]
public string Filename
{
get { return fileItem.Name; }
}
/// <summary>
/// This is used to get the full path to the image file
/// </summary>
[Category("File"), Description("The full path to the image file")]
public string FullPath
{
get { return fileItem.FullPath; }
}
/// <summary>
/// This is used to get the unique ID of the image
/// </summary>
[Category("Metadata"), Description("The unique ID of the image"),
DefaultValue(null)]
public string Id
{
get { return fileItem.ImageId; }
set
{
if(value == null || value.Trim().Length == 0)
value = Guid.NewGuid().ToString();
fileItem.ImageId = value;
}
}
/// <summary>
/// This is used to get or set whether or not to copy the image to the
/// <b>.\Output\[HelpFormat]\media</b> folder if it is not referenced
/// in a media link.
/// </summary>
/// <value>The default is false and the image will not be copied
/// unless it is referenced in a media link. If set to true, the
/// image will be copied even if it is not referenced. This is useful
/// for forcing the copy of images referenced in external links
/// which are not handled by the art reference build component.</value>
[Category("Metadata"), Description("If true, the image is always " +
"copied to the output media folder. If false, it will only be " +
"copied if referenced in a media link."), DefaultValue(false)]
public bool CopyToMedia
{
get { return fileItem.CopyToMedia; }
set { fileItem.CopyToMedia = value; }
}
/// <summary>
/// This is used to get or set the optional alternate text for the image
/// </summary>
[Category("Metadata"), Description("The optional alternate text for the image"),
DefaultValue(null)]
public string AlternateText
{
get { return fileItem.AlternateText; }
set { fileItem.AlternateText = value; }
}
/// <summary>
/// This read-only property is used to get a title for display
/// (i.e. in the designer).
/// </summary>
/// <value>If there is <see cref="AlternateText" /> specified, it is
/// returned along with the filename and the image ID in parentheses.
/// If not, the filename is returned along with the image ID in
/// parentheses.</value>
[Browsable(false)]
public string DisplayTitle
{
get
{
if(!String.IsNullOrEmpty(fileItem.AlternateText))
return String.Format(CultureInfo.CurrentCulture,
"{0} ({1}, {2})", fileItem.AlternateText,
fileItem.Name, fileItem.ImageId);
return fileItem.Name + " (" + fileItem.ImageId + ")";
}
}
/// <summary>
/// This is used to get the file item associated with the image
/// reference.
/// </summary>
[Browsable(false)]
public FileItem FileItem
{
get { return fileItem; }
}
#endregion
#region Constructors
//=====================================================================
/// <summary>
/// Constructor
/// </summary>
/// <param name="buildItem">The build item to associate with the
/// image reference.</param>
public ImageReference(FileItem buildItem)
{
fileItem = buildItem;
}
#endregion
#region Convert to link element format
//=====================================================================
/// <summary>
/// Convert the image reference to a <c><mediaLink></c> element.
/// </summary>
/// <returns>The image in its <c><mediaLink></c> element form</returns>
public string ToMediaLink()
{
string caption;
if(!String.IsNullOrEmpty(fileItem.AlternateText))
caption = String.Concat("<caption>", fileItem.AlternateText,
"</caption>\r\n");
else
caption = String.Empty;
return String.Format(CultureInfo.CurrentCulture,
"<mediaLink>\r\n{0}<image xlink:href=\"{1}\"/>\r\n" +
"</mediaLink>", caption, fileItem.ImageId);
}
/// <summary>
/// Convert the image reference to a <c><mediaLinkInline></c>
/// element.
/// </summary>
/// <returns>The image in its <c><mediaLinkInline></c> element form</returns>
public string ToMediaLinkInline()
{
return String.Format(CultureInfo.CurrentCulture,
"<mediaLinkInline><image xlink:href=\"{0}\"/>" +
"</mediaLinkInline>", fileItem.ImageId);
}
/// <summary>
/// Convert the image reference to an <c><externalLink></c> element.
/// </summary>
/// <returns>The image in its <c><externalLink></c> element form</returns>
public string ToExternalLink()
{
string linkAltText, linkText;
if(!String.IsNullOrEmpty(fileItem.AlternateText))
{
linkText = String.Concat("<linkText>", fileItem.AlternateText,
"</linkText>\r\n");
linkAltText = String.Concat("<linkAlternateText>",
fileItem.AlternateText, "</linkAlternateText>\r\n");
}
else
{
linkText = String.Concat("<linkText>", fileItem.ImageId,
"</linkText>\r\n");
linkAltText = String.Empty;
}
return String.Format(CultureInfo.CurrentCulture,
"<externalLink>\r\n{0}{1}<linkUri>../Media/{2}" +
"</linkUri>\r\n<linkTarget>_self</linkTarget>\r\n" +
"</externalLink>", linkText, linkAltText, fileItem.Name);
}
/// <summary>
/// Convert the image reference to an <c><img></c> element.
/// </summary>
/// <returns>The image in its <c><img></c> element form</returns>
public string ToImageLink()
{
string linkAltText;
if(!String.IsNullOrEmpty(fileItem.AlternateText))
linkAltText = fileItem.AlternateText;
else
linkAltText = String.Empty;
return String.Format(CultureInfo.CurrentCulture,
"<img src=\"../Media/{0}\" alt=\"{1}\" />", fileItem.Name,
linkAltText);
}
#endregion
}
}
| |
// 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.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal.AnyOS
{
internal sealed partial class ManagedPkcsPal : PkcsPal
{
internal new static readonly ManagedPkcsPal Instance = new ManagedPkcsPal();
public override void AddCertsFromStoreForDecryption(X509Certificate2Collection certs)
{
certs.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.CurrentUser, openExistingOnly: false));
try
{
// This store exists on macOS, but not Linux
certs.AddRange(
PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.LocalMachine, openExistingOnly: false));
}
catch (CryptographicException)
{
}
}
public override byte[] GetSubjectKeyIdentifier(X509Certificate2 certificate)
{
Debug.Assert(certificate != null);
X509Extension extension = certificate.Extensions[Oids.SubjectKeyIdentifier];
if (extension == null)
{
// Construct the value from the public key info.
extension = new X509SubjectKeyIdentifierExtension(
certificate.PublicKey,
X509SubjectKeyIdentifierHashAlgorithm.CapiSha1,
false);
}
// Certificates are DER encoded.
AsnReader reader = new AsnReader(extension.RawData, AsnEncodingRules.DER);
if (reader.TryGetPrimitiveOctetStringBytes(out ReadOnlyMemory<byte> contents))
{
reader.ThrowIfNotEmpty();
return contents.ToArray();
}
// TryGetPrimitiveOctetStringBytes will have thrown if the next tag wasn't
// Universal (primitive) OCTET STRING, since we're in DER mode.
// So there's really no way we can get here.
Debug.Fail($"TryGetPrimitiveOctetStringBytes returned false in DER mode");
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
public override T GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent)
{
return GetPrivateKey<T>(certificate);
}
public override T GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent)
{
return GetPrivateKey<T>(certificate);
}
private T GetPrivateKey<T>(X509Certificate2 certificate) where T : AsymmetricAlgorithm
{
if (typeof(T) == typeof(RSA))
return (T)(object)certificate.GetRSAPrivateKey();
if (typeof(T) == typeof(ECDsa))
return (T)(object)certificate.GetECDsaPrivateKey();
#if netcoreapp
if (typeof(T) == typeof(DSA))
return (T)(object)certificate.GetDSAPrivateKey();
#endif
Debug.Fail($"Unknown key type requested: {typeof(T).FullName}");
return null;
}
private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifierAsn contentEncryptionAlgorithm)
{
SymmetricAlgorithm alg = OpenAlgorithm(contentEncryptionAlgorithm.Algorithm);
if (alg is RC2)
{
if (contentEncryptionAlgorithm.Parameters == null)
{
// Windows issues CRYPT_E_BAD_DECODE
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
Rc2CbcParameters rc2Params = Rc2CbcParameters.Decode(
contentEncryptionAlgorithm.Parameters.Value,
AsnEncodingRules.BER);
alg.KeySize = rc2Params.GetEffectiveKeyBits();
alg.IV = rc2Params.Iv.ToArray();
}
else
{
if (contentEncryptionAlgorithm.Parameters == null)
{
// Windows issues CRYPT_E_BAD_DECODE
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
AsnReader reader = new AsnReader(contentEncryptionAlgorithm.Parameters.Value, AsnEncodingRules.BER);
if (reader.TryGetPrimitiveOctetStringBytes(out ReadOnlyMemory<byte> primitiveBytes))
{
alg.IV = primitiveBytes.ToArray();
}
else
{
byte[] iv = new byte[alg.BlockSize / 8];
if (!reader.TryCopyOctetStringBytes(iv, out int bytesWritten) ||
bytesWritten != iv.Length)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
alg.IV = iv;
}
}
return alg;
}
private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifier algorithmIdentifier)
{
SymmetricAlgorithm alg = OpenAlgorithm(algorithmIdentifier.Oid);
if (alg is RC2)
{
if (algorithmIdentifier.KeyLength != 0)
{
alg.KeySize = algorithmIdentifier.KeyLength;
}
else
{
alg.KeySize = KeyLengths.Rc2_128Bit;
}
}
return alg;
}
private static SymmetricAlgorithm OpenAlgorithm(Oid algorithmIdentifier)
{
Debug.Assert(algorithmIdentifier != null);
SymmetricAlgorithm alg;
switch (algorithmIdentifier.Value)
{
case Oids.Rc2Cbc:
#pragma warning disable CA5351
alg = RC2.Create();
#pragma warning restore CA5351
break;
case Oids.DesCbc:
#pragma warning disable CA5351
alg = DES.Create();
#pragma warning restore CA5351
break;
case Oids.TripleDesCbc:
#pragma warning disable CA5350
alg = TripleDES.Create();
#pragma warning restore CA5350
break;
case Oids.Aes128Cbc:
alg = Aes.Create();
alg.KeySize = 128;
break;
case Oids.Aes192Cbc:
alg = Aes.Create();
alg.KeySize = 192;
break;
case Oids.Aes256Cbc:
alg = Aes.Create();
alg.KeySize = 256;
break;
default:
throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, algorithmIdentifier.Value);
}
// These are the defaults, but they're restated here for clarity.
alg.Padding = PaddingMode.PKCS7;
alg.Mode = CipherMode.CBC;
return alg;
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
using Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
internal partial class frmPOSsetup : System.Windows.Forms.Form
{
private ADODB.Recordset withEventsField_adoPrimaryRS;
public ADODB.Recordset adoPrimaryRS {
get { return withEventsField_adoPrimaryRS; }
set {
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord;
}
withEventsField_adoPrimaryRS = value;
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord;
}
}
}
bool mbChangedByCode;
int mvBookMark;
bool mbEditFlag;
bool mbAddNewFlag;
bool mbDataChanged;
bool loading;
int gID;
int gLines;
List<TextBox> txtFields = new List<TextBox>();
List<TextBox> txtInteger = new List<TextBox>();
List<TextBox> txtPrice = new List<TextBox>();
List<RadioButton> optDeposits = new List<RadioButton>();
List<RadioButton> optPrint = new List<RadioButton>();
const short bit_deposit1 = 1;
const short bit_deposit2 = 2;
const short bit_Sets = 4;
const short bit_Shrink = 8;
const short bit_Suppress = 16;
const short bit_Lines = 32;
const short bit_SuppressCashup = 64;
const short bit_BlindDeclaration = 128;
const short bit_DeclarationQuick = 256;
const short bit_OpenTill = 512;
const short bit_autoSearch = 1024;
const short bit_bypassTender = 2048;
const short bit_bypassSecurity = 4096;
const short bit_itemNoReceipt = 8192;
const short bit_autoLogoff = 16384;
//Printing exclusive A4 Invoice
const int bit_A4Paramet = 32768;
//Card Ref parameter
const int bit_Cardrefere = 65536;
//Order Ref parameter
const int bit_OrderRefer = 131072;
//Serial Ref parameter
const int bit_SerialRef = 262144;
const int bit_SerialTra = 524288;
//To enable currecncy bit
const int bit_IntVATPrint = 1048576;
const int bit_LearningPOS = 2097152;
const int bit_DisplaySell = 4194304;
const int bit_FinalizeCash = 8388608;
const int bit_CheckCash = 16777216;
const int bit_ConCashUp = 33554432;
const int bit_CustBal = 67108864;
private void loadLanguage()
{
//frmPOSsetup = No Code [Point Of Sale Parameters]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmPOSsetup.Caption = rsLang("LanguageLayoutLnk_Description"): frmPOSsetup.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074;
//Undo|Checked
if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//_lbl_5 = Receipt Details [Receipt Details]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lbl_5.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_5.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_lblLabels_0 = No Code [First Receipt Heading Line]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lblLabels_0.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_0.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_lblLabels_1 = No Code [Second Receipt Heading Line]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lblLabels_1.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_lblLabels_2 = No Code [Third Receipt Heading Line]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lblLabels_2.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_lblLabels_3 = No Code [Receipt Footer]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lblLabels_3.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_3.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_lblLabels_4 = No Code [VAT Number]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lblLabels_4.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_4.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_lbl_0 = No Code [Transaction Prints]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lbl_0.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_0.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Frame1 = No Code [Print POS Transaction]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Frame1.Caption = rsLang("LanguageLayoutLnk_Description"): Frame1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2362;
//Yes|Checked
if (modRecordSet.rsLang.RecordCount){optPrint[1].Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;optPrint[1].RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2363;
//No|Checked
if (modRecordSet.rsLang.RecordCount){optPrint[2].Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;optPrint[2].RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//optPrint(0) = No Code [Ask]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then optPrint(0).Caption = rsLang("LanguageLayoutLnk_Description"): optPrint(0).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_lblLabels_5 = No Code [No of Account Payment Prints]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lblLabels_5.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_5.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_lblLabels_6 = No Code [No of Account Sale Prints]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lblLabels_6.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_6.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_lblLabels_7 = No Code [Cash Before Delivery Prints]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lblLabels_7.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_7.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_lblLabels_8 = No Code [No of Consignement Prints]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lblLabels_8.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_8.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Note: _lblLabels_9.Caption has a grammar/spelling mistake!!!
//_lblLabels_9 = No Code [No of Payout Prints]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lblLabels_9.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_9.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_lbl_1 = No Code [Other Parameters]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lbl_1.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1201;
//Deposits|Checked
if (modRecordSet.rsLang.RecordCount){frmDeposits.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;frmDeposits.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//optDeposits(0) = No Code [Pricing Group One]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then optDeposits(0).Caption = rsLang("LanguageLayoutLnk_Description"): optDeposits(0).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//optDeposits(1) = No Code [Pricing Group Two]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then optDeposits(1).Caption = rsLang("LanguageLayoutLnk_Description"): optDeposits(1).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//optDeposits(2) = No Code [Automatically Determined]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then optDeposits(2).Caption = rsLang("LanguageLayoutLnk_Description"): optDeposits(2).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkPrintinvoice = No Code [Do Not Print VAT on Invoice]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkPrintinvoice.Caption = rsLang("LanguageLayoutLnk_Description"): chkPrintinvoice.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkConCashup = No Code [Activate Consolidate Cashup]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkConCashup.Caption = rsLang("LanguageLayoutLnk_Description"): chkConCashup.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkCustBal = No Code [Print Customer Balances]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkCustBal.Caption = rsLang("LanguageLayoutLnk_Description"): chkCustBal.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkCardNumber = No Code [Card Number Reference]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkCardNumber.Caption = rsLang("LanguageLayoutLnk_Description"): chkCardNumber.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkOrderNumber = No Code [Order Number Reference]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkOrderNumber.Caption = rsLang("LanguageLayoutLnk_Description"): chkOrderNumber.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkSerialNumber = No Code [Serial Reference Number]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkSerialNumber.Caption = rsLang("LanguageLayoutLnk_Description"): chkSerialNumber.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkSets = No Code [Automatically Build Sets]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkSets.Caption = rsLang("LanguageLayoutLnk_Description"): chkSets.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkShrink = No Code [Automatically Build Shrinks]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkShrink.Caption = rsLang("LanguageLayoutLnk_Description"): chkShrink.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkSuppress = No Code [Switch on Suppress After Cashup]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkSuppress.Caption = rsLang("LanguageLayoutLnk_Description"): chkSuppress.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkBlindCashup = No Code [Blind Cashup]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkBlindCashup.Caption = rsLang("LanguageLayoutLnk_Description"): cmdBlindCashup.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkQuickCashup = No Code [Quick Cashup]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkQuickCashup.Caption = rsLang("LanguageLayoutLnk_Description"): chkQuickCashup.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkOpenTill = No Code [Only Open Till for Cash Transaction]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkOpenTill.Caption = rsLang("LanguageLayoutLnk_Description"): chkOpenTill.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkDevidingLine = No Code [Print Deviding Line on Receipt]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkPrintDividingLine.Caption = rsLang("LanguageLayoutLnk_Description"): chkPrintDividingLine.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkSearchAuto = No Code [Automatically search for stock items]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkSearchAuto.Caption = rsLang("LanguageLayoutLnk_Description"): chkSearchAuto.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkSecurityPopup = No Code [Bypass Security Popup]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkSecurityPopup.Caption = rsLang("LanguageLayoutLnk_Description"): chkSecurityPopup.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkBypassTender = No Code [Bypass Cashout Tender]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkBypassTender.Caption = rsLang("LanguageLayoutLnk_Description"): chkBypassTender.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkReceiptBarcode = No Code [Print Barcodes on Receipts]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkReceiptBarcode.Caption = rsLang("LanguageLayoutLnk_Description"): chkReceiptBarcode.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkLogoffAuto = No Code [Automatically Logoff Cashier]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkLogoffauto.Caption = rsLang("LanguageLayoutLnk_Description"): chkLogoffAuto.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkPrintA4 = No Code [Print A4 Invoice with Exclusive Total]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkPrintA4.Caption = rsLang("LanguageLayoutLnk_Description"): chkPrintA4.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkLearningPOS = No Code [POS Learning Mode]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkLearningPOS.Caption = rsLang("LanguageLayoutLnk_Description"): chkLearningPOS.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkDisplaySelling = No Code [Display Selling Price]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkDisplaySelling.Caption = rsLang("LanguageLayoutLnk_Description"): chkDisplaySelling.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkFinalizeCash = No Code [Cash sales have to be finalized (Touch)
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkFinalizeCash.Caption = rsLang("LanguageLayoutLnk_Description"): chkFinalizeCash.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")]
//chkCheckCash = No Code [Remove Excess Cash from Till]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkCheckCash.Caption = rsLang("LanguageLayoutLnk_Description"): chkCheckCash.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Note: Grammar for _lblLabels_10.Caption not 100%
//_lblLabels_10 = No Code [Cent Rounding: Default = 5 Cents, Max = 50 Cents]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lblLabels_10.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_10.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmPOSsetup.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void buildDataControls()
{
loading = true;
if ((adoPrimaryRS.Fields("Company_POSparameters").Value & bit_deposit1)) {
if ((adoPrimaryRS.Fields("Company_POSparameters").Value & bit_deposit2)) {
_optDeposits_2.Checked = true;
} else {
_optDeposits_0.Checked = true;
}
} else {
_optDeposits_1.Checked = true;
}
this.chkSets.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_Sets)));
this.chkShrink.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_Shrink)));
this.chkSuppress.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_Suppress)));
this.chkBlindCashup.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_BlindDeclaration)));
this.chkDividingLine.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_Lines)));
this.chkQuickCashup.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_DeclarationQuick)));
this.chkOpenTill.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_OpenTill)));
this.chkSearchAuto.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_autoSearch)));
this.chkBypassTender.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_autoSearch)));
this.chkBypassTender.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_bypassTender)));
this.chkSecurityPopup.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_bypassSecurity)));
this.chkReceiptBarcode.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_itemNoReceipt)));
this.chkLogoffAuto.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_autoLogoff)));
this.chkPrintA4.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_A4Paramet)));
this.chkCardNumber.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_Cardrefere)));
this.chkOrderNumber.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_OrderRefer)));
this.chkSerialNumber.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_SerialRef)));
this.chkSerialTracking.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_SerialTra)));
this.chkLearningPOS.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_LearningPOS)));
this.chkDisplaySelling.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_DisplaySell)));
this.chkFinalizeCash.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_FinalizeCash)));
this.chkPrintinvoice.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_IntVATPrint)));
this.chkCheckCash.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_CheckCash)));
this.chkConCashup.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_ConCashUp)));
this.chkCustBal.CheckState = System.Math.Abs(Convert.ToInt16(Convert.ToBoolean(adoPrimaryRS.Fields("Company_POSparameters").Value & bit_CustBal)));
loading = false;
}
private void updateBit()
{
if (loading)
return;
int lBit = 0;
if (this.chkShrink.CheckState)
lBit = lBit + bit_Shrink;
if (this.chkSuppress.CheckState)
lBit = lBit + bit_Suppress;
if (this.chkSets.CheckState)
lBit = lBit + bit_Sets;
if (this.chkBlindCashup.CheckState)
lBit = lBit + bit_BlindDeclaration;
if (this.chkDividingLine.CheckState)
lBit = lBit + bit_Lines;
if (this.chkQuickCashup.CheckState)
lBit = lBit + bit_DeclarationQuick;
if (this.chkOpenTill.CheckState)
lBit = lBit + bit_OpenTill;
if (this.optDeposits[0].Checked)
lBit = lBit + bit_deposit1;
if (this.optDeposits[1].Checked)
lBit = lBit + bit_deposit2;
if (this.optDeposits[2].Checked)
lBit = lBit + bit_deposit2 + bit_deposit1;
if (chkSearchAuto.CheckState)
lBit = lBit + bit_autoSearch;
if (this.chkBypassTender.CheckState)
lBit = lBit + bit_bypassTender;
if (chkSecurityPopup.CheckState)
lBit = lBit + bit_bypassSecurity;
if (chkReceiptBarcode.CheckState)
lBit = lBit + bit_itemNoReceipt;
if (this.chkLogoffAuto.CheckState)
lBit = lBit + bit_autoLogoff;
if (this.chkPrintA4.CheckState)
lBit = lBit + bit_A4Paramet;
if (this.chkCardNumber.CheckState)
lBit = lBit + bit_Cardrefere;
if (this.chkOrderNumber.CheckState)
lBit = lBit + bit_OrderRefer;
if (this.chkSerialNumber.CheckState)
lBit = lBit + bit_SerialRef;
if (this.chkSerialTracking.CheckState)
lBit = lBit + bit_SerialTra;
if (this.chkLearningPOS.CheckState)
lBit = lBit + bit_LearningPOS;
if (this.chkDisplaySelling.CheckState)
lBit = lBit + bit_DisplaySell;
if (this.chkFinalizeCash.CheckState)
lBit = lBit + bit_FinalizeCash;
if (this.chkPrintinvoice.CheckState)
lBit = lBit + bit_IntVATPrint;
if (this.chkCheckCash.CheckState)
lBit = lBit + bit_CheckCash;
if (this.chkConCashup.CheckState)
lBit = lBit + bit_ConCashUp;
if (this.chkCustBal.CheckState)
lBit = lBit + bit_CustBal;
_txtFields_9.Text = Convert.ToString(lBit);
}
private void doDataControl(ref System.Windows.Forms.Control dataControl, ref string sql, ref string DataField, ref string boundColumn, ref string listField)
{
//Dim rs As ADODB.Recordset
//rs = getRS(sql)
//UPGRADE_WARNING: Couldn't resolve default property of object dataControl.DataSource. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//dataControl.DataSource = rs
//UPGRADE_ISSUE: Control method dataControl.DataSource was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
//dataControl.DataSource = adoPrimaryRS
//UPGRADE_ISSUE: Control method dataControl.DataField was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
//dataControl.DataField = DataField
//UPGRADE_WARNING: Couldn't resolve default property of object dataControl.boundColumn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//dataControl.boundColumn = boundColumn
//UPGRADE_WARNING: Couldn't resolve default property of object dataControl.listField. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//dataControl.listField = listField
}
public void loadItem()
{
ADODB.Recordset rs = default(ADODB.Recordset);
System.Windows.Forms.TextBox oText = null;
System.Windows.Forms.CheckBox oCheck = null;
// ERROR: Not supported in C#: OnErrorStatement
//Old
//Set adoPrimaryRS = getRS("select CompanyID, Company_PosHeading1,Company_PosHeading2,Company_PosHeading3,Company_PosFooter,Company_TaxNumber,Company_PosPrintAccountPayments,Company_PosPrintAccountSales,Company_PosPrintAccountCOD,Company_PosPrintConsignment,Company_PosParameters,Company_POSRecieptPrint from Company")
//New with text narative
adoPrimaryRS = modRecordSet.getRS(ref "select CompanyID, Company_PosHeading1,Company_PosHeading2,Company_PosHeading3,Company_PosFooter,Company_TaxNumber,Company_PosPrintAccountPayments,Company_PosPrintAccountSales,Company_PosPrintAccountCOD,Company_PosPrintConsignment,Company_POSExcess,Company_PosParameters,Company_POSRecieptPrint,Company_PosPrintPayouts,Company_PosCentRound from Company");
setup();
foreach (TextBox oText_loopVariable in txtFields) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
oText.MaxLength = adoPrimaryRS.Fields(oText.DataBindings).DefinedSize;
}
foreach (TextBox oText_loopVariable in this.txtInteger) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
oText.Leave += txtInteger_Leave;
//txtInteger_Leave(txtInteger.Item((oText.Index)), New System.EventArgs())
}
foreach (TextBox oText_loopVariable in this.txtPrice) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
oText.Leave += txtPrice_Leave;
//txtPrice_Leave(txtPrice.Item((oText.Index)), New System.EventArgs())
}
this._txtPrice_0.Text = Strings.FormatNumber(adoPrimaryRS.Fields("Company_POSExcess").Value, 2);
//_txtFields_9.MaxLength = 7
_txtFields_9.MaxLength = 8;
buildDataControls();
mbDataChanged = false;
//Me.optPrint(_txtFields_5).Checked = True
if (_txtFields_5.Text == "0") {
_optPrint_0.Checked = true;
} else if (_txtFields_5.Text == "1") {
_optPrint_1.Checked = true;
} else {
_optPrint_2.Checked = true;
}
loadLanguage();
ShowDialog();
}
private void setup()
{
}
private void Check1_Click()
{
updateBit();
}
private void chkBlindCashup_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkBypassTender_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkCardNumber_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkConCashup_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkCurrency_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkCustBal_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkDisplaySelling_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkDividingLine_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkFinalizeCash_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkLearningPOS_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkLogoffAuto_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkOpenTill_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkOrderNumber_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkPrintA4_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkPrintinvoice_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkCheckCash_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkQuickCashup_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkReceiptBarcode_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkSearchAuto_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkSecurityPopup_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkSerialNumber_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkSerialTracking_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkSets_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkShrink_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void chkSuppress_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
updateBit();
}
private void frmPOSsetup_Load(System.Object eventSender, System.EventArgs eventArgs)
{
modBResolutions.ResizeForm(ref this, ref sizeConvertors.pixelToTwips(this.Width, true), ref sizeConvertors.pixelToTwips(this.Height, false), ref 0);
}
private void frmPOSsetup_Resize(System.Object eventSender, System.EventArgs eventArgs)
{
Button cmdLast = new Button();
Button cmdNext = new Button();
Label lblStatus = new Label();
// ERROR: Not supported in C#: OnErrorStatement
lblStatus.Width = sizeConvertors.pixelToTwips(this.Width, true) - 1500;
cmdNext.Left = lblStatus.Width + 700;
cmdLast.Left = cmdNext.Left + 340;
}
private void frmPOSsetup_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
KeyAscii = 0;
System.Windows.Forms.Application.DoEvents();
adoPrimaryRS.Move(0);
cmdClose_Click(cmdClose, new System.EventArgs());
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmPOSsetup_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
}
private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This will display the current record position for this recordset
}
private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This is where you put validation code
//This event gets called when the following actions occur
bool bCancel = false;
switch (adReason) {
case ADODB.EventReasonEnum.adRsnAddNew:
break;
case ADODB.EventReasonEnum.adRsnClose:
break;
case ADODB.EventReasonEnum.adRsnDelete:
break;
case ADODB.EventReasonEnum.adRsnFirstChange:
break;
case ADODB.EventReasonEnum.adRsnMove:
break;
case ADODB.EventReasonEnum.adRsnRequery:
break;
case ADODB.EventReasonEnum.adRsnResynch:
break;
case ADODB.EventReasonEnum.adRsnUndoAddNew:
break;
case ADODB.EventReasonEnum.adRsnUndoDelete:
break;
case ADODB.EventReasonEnum.adRsnUndoUpdate:
break;
case ADODB.EventReasonEnum.adRsnUpdate:
break;
}
if (bCancel)
adStatus = ADODB.EventStatusEnum.adStatusCancel;
}
private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs)
{
// ERROR: Not supported in C#: OnErrorStatement
if (mbAddNewFlag) {
this.Close();
} else {
mbEditFlag = false;
mbAddNewFlag = false;
adoPrimaryRS.CancelUpdate();
if (mvBookMark > 0) {
adoPrimaryRS.Bookmark = mvBookMark;
} else {
adoPrimaryRS.MoveFirst();
}
mbDataChanged = false;
}
}
private bool update_Renamed()
{
bool functionReturnValue = false;
// ERROR: Not supported in C#: OnErrorStatement
bool lDirty = false;
short x = 0;
short lBit = 0;
lDirty = false;
functionReturnValue = true;
if (mbAddNewFlag) {
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
adoPrimaryRS.MoveLast();
//move to the new record
} else {
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
adoPrimaryRS.MoveLast();
//move to the new record
}
mbEditFlag = false;
mbAddNewFlag = false;
mbDataChanged = false;
return functionReturnValue;
UpdateErr:
Interaction.MsgBox(Err().Description);
functionReturnValue = false;
return functionReturnValue;
}
private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
{
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
if (update_Renamed()) {
this.Close();
}
}
//Handles optDeposits.CheckedChanged
private void optDeposits_CheckedChanged(System.Object eventSender, System.EventArgs eventArgs)
{
if (eventSender.Checked) {
RadioButton rb = new RadioButton();
rb = (RadioButton)eventSender;
int Index = GetIndex.GetIndexer(ref rb, ref optDeposits);
updateBit();
}
}
//Handles optPrint.CheckedChanged
private void optPrint_CheckedChanged(System.Object eventSender, System.EventArgs eventArgs)
{
if (eventSender.Checked) {
RadioButton rb = new RadioButton();
rb = (RadioButton)eventSender;
int Index = GetIndex.GetIndexer(ref rb, ref optPrint);
_txtFields_5.Text = Convert.ToString(Index);
}
}
// Handles txtFields.Enter
private void txtFields_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
TextBox txtbox = new TextBox();
txtbox = (TextBox)eventSender;
int Index = GetIndex.GetIndexer(ref txtbox, ref txtFields);
modUtilities.MyGotFocus(ref txtFields[Index]);
//_txtFields_6.Text = FormatNumber(adoPrimaryRS("Company_POSExcess"), 2)
}
//Handles txtFields.Leave
private void txtFields_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
TextBox txtbox = new TextBox();
txtbox = (TextBox)eventSender;
int Index = GetIndex.GetIndexer(ref txtbox, ref txtFields);
modUtilities.MyGotFocus(ref txtFields[Index]);
//_txtFields_6.Text = FormatNumber(adoPrimaryRS("Company_POSExcess"), 2)
}
//Handles txtInteger.Enter
private void txtInteger_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
TextBox txtbox = new TextBox();
txtbox = (TextBox)eventSender;
int Index = GetIndex.GetIndexer(ref txtbox, ref txtInteger);
modUtilities.MyGotFocusNumeric(ref txtInteger[Index]);
}
//Handles txtInteger.KeyPress
private void txtInteger_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
//Dim Index As Short = txtInteger.GetIndex(eventSender)
modUtilities.MyKeyPress(ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
//Handles txtInteger.Leave
private void txtInteger_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
TextBox txtbox = new TextBox();
txtbox = (TextBox)eventSender;
int Index = GetIndex.GetIndexer(ref txtbox, ref txtInteger);
modUtilities.MyLostFocus(ref txtInteger[Index], ref 0);
if (Index == 0) {
if (Convert.ToInt16(_txtInteger_0.Text) > 50) {
Interaction.MsgBox("Maximum 50 Cents allowed!", MsgBoxStyle.Critical);
_txtInteger_0.Text = Convert.ToString(50);
_txtInteger_0.Focus();
} else if (Convert.ToInt16(_txtInteger_0.Text) < 1) {
Interaction.MsgBox("Minimum 1 Cents allowed!", MsgBoxStyle.Critical);
_txtInteger_0.Text = Convert.ToString(1);
_txtInteger_0.Focus();
}
}
}
private void txtFloat_MyGotFocus(ref short Index)
{
// MyGotFocusNumeric txtFloat(Index)
}
private void txtFloat_KeyPress(ref short Index, ref short KeyAscii)
{
// KeyPress KeyAscii
}
private void txtFloat_MyLostFocus(ref short Index)
{
// LostFocus txtFloat(Index), 2
}
private void txtFloatNegative_MyGotFocus(ref short Index)
{
// MyGotFocusNumeric txtFloatNegative(Index)
}
private void txtFloatNegative_KeyPress(ref short Index, ref short KeyAscii)
{
// KeyPressNegative txtFloatNegative(Index), KeyAscii
}
private void txtFloatNegative_MyLostFocus(ref short Index)
{
// LostFocus txtFloatNegative(Index), 2
}
//Handles txtPrice.Enter
private void txtPrice_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
TextBox txtbox = new TextBox();
txtbox = (TextBox)eventSender;
int Index = GetIndex.GetIndexer(ref txtbox, ref txtPrice);
if (!string.IsNullOrEmpty(txtPrice[Index].Text)) {
modUtilities.MyGotFocusNumeric(ref txtPrice[Index]);
}
}
//Handles txtPrice.KeyPress
private void txtPrice_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
//Dim Index As Short = txtPrice.GetIndex(eventSender)
modUtilities.MyKeyPress(ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
//Handles txtPrice.Leave
private void txtPrice_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
TextBox txtbox = new TextBox();
txtbox = (TextBox)eventSender;
int Index = GetIndex.GetIndexer(ref txtbox, ref txtPrice);
if (!string.IsNullOrEmpty(txtPrice[Index].Text)) {
modUtilities.MyLostFocus(ref txtPrice[Index], ref 2);
}
}
private void frmPOSsetup_Load1(object sender, System.EventArgs e)
{
txtFields.AddRange(new TextBox[] {
_txtFields_0,
_txtFields_1,
_txtFields_2,
_txtFields_3,
_txtFields_4,
_txtFields_5,
_txtFields_9
});
txtPrice.AddRange(new TextBox[] { _txtPrice_0 });
txtInteger.AddRange(new TextBox[] {
_txtInteger_0,
_txtInteger_5,
_txtInteger_6,
_txtInteger_7,
_txtInteger_8,
_txtInteger_9
});
optDeposits.AddRange(new RadioButton[] {
_optDeposits_0,
_optDeposits_1,
_optDeposits_2
});
optPrint.AddRange(new RadioButton[] {
_optPrint_0,
_optPrint_1,
_optPrint_2
});
TextBox tb = new TextBox();
RadioButton rb = new RadioButton();
foreach (TextBox tb_loopVariable in txtFields) {
tb = tb_loopVariable;
tb.Enter += txtFields_Enter;
tb.Leave += txtFields_Leave;
}
_txtPrice_0.Enter += txtPrice_Enter;
_txtPrice_0.KeyPress += txtPrice_KeyPress;
foreach (RadioButton rb_loopVariable in optDeposits) {
rb = rb_loopVariable;
rb.Click += optDeposits_CheckedChanged;
}
foreach (RadioButton rb_loopVariable in optPrint) {
rb = rb_loopVariable;
rb.Click += optPrint_CheckedChanged;
}
}
}
}
| |
// 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 Xunit;
namespace System.Xml.Tests
{
public class InsertAfterTests
{
private XmlDocument CreateDocumentWithElement()
{
var doc = new XmlDocument();
doc.AppendChild(doc.CreateElement("root"));
return doc;
}
[Fact]
public void InsertAfterWithSameRefAttrKeepsOrderIntactAndReturnsTheArgument()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute attr1, attr2, attr3;
attr1 = element.Attributes.Append(doc.CreateAttribute("attr1"));
attr2 = element.Attributes.Append(doc.CreateAttribute("attr2"));
attr3 = element.Attributes.Append(doc.CreateAttribute("attr3"));
XmlAttributeCollection target = element.Attributes;
XmlAttribute result = target.InsertAfter(attr2, attr2);
Assert.Equal(3, target.Count);
Assert.Same(attr1, target[0]);
Assert.Same(attr2, target[1]);
Assert.Same(attr3, target[2]);
Assert.Same(attr2, result);
}
[Fact]
public void InsertAfterWithNullRefAttrAddsToTheBeginning()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute attr1, attr2, attr3;
attr1 = element.Attributes.Append(doc.CreateAttribute("attr1"));
attr2 = element.Attributes.Append(doc.CreateAttribute("attr2"));
attr3 = doc.CreateAttribute("attr3");
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(attr3, null);
Assert.Equal(3, target.Count);
Assert.Same(attr3, target[0]);
Assert.Same(attr1, target[1]);
Assert.Same(attr2, target[2]);
}
[Fact]
public void InsertAfterWithRefAttrWithAnotherOwnerElementThrows()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute newAttr = doc.CreateAttribute("newAttr");
XmlElement anotherElement = doc.CreateElement("anotherElement");
XmlAttribute anotherOwnerElementAttr = anotherElement.SetAttributeNode("anotherOwnerElementAttr", string.Empty);
XmlAttributeCollection target = element.Attributes;
Assert.Throws<ArgumentException>(() => target.InsertAfter(newAttr, anotherOwnerElementAttr));
}
[Fact]
public void InsertAfterWithAttrWithAnotherOwnerDocumentThrows()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute existingAttr = doc.CreateAttribute("existingAttr");
element.Attributes.Append(existingAttr);
XmlAttribute anotherOwnerDocumentAttr = new XmlDocument().CreateAttribute("anotherOwnerDocumentAttr");
XmlAttributeCollection target = element.Attributes;
Assert.Throws<ArgumentException>(() => target.InsertAfter(anotherOwnerDocumentAttr, existingAttr));
}
[Fact]
public void InsertAfterDetachesAttrFromCurrentOwnerElement()
{
const string attributeName = "movingAttr";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute attr = element.Attributes.Append(doc.CreateAttribute(attributeName));
// assert on implicitly set preconditions
Assert.Same(element, attr.OwnerElement);
Assert.True(element.HasAttribute(attributeName));
XmlElement destinationElement = doc.CreateElement("anotherElement");
XmlAttribute refAttr = destinationElement.Attributes.Append(doc.CreateAttribute("anotherAttr"));
XmlAttributeCollection target = destinationElement.Attributes;
target.InsertAfter(attr, refAttr);
Assert.Same(destinationElement, attr.OwnerElement);
Assert.False(element.HasAttribute(attributeName));
}
[Fact]
public void InsertAfterCanInsertAfterTheFirst()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
element.Attributes.Append(doc.CreateAttribute("attr3", "some:uri3"));
XmlAttribute newAttr = doc.CreateAttribute("newAttr");
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(4, target.Count);
Assert.Same(refAttr, target[0]);
Assert.Same(newAttr, target[1]);
}
[Fact]
public void InsertAfterCanInsertAfterTheLast()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr3", "some:uri3"));
XmlAttribute newAttr = doc.CreateAttribute("newAttr");
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(4, target.Count);
Assert.Same(refAttr, target[2]);
Assert.Same(newAttr, target[3]);
}
[Fact]
public void InsertAfterCanInsertInTheMiddle()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
element.Attributes.Append(doc.CreateAttribute("attr3", "some:uri3"));
XmlAttribute newAttr = doc.CreateAttribute("newAttr");
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(4, target.Count);
Assert.Same(refAttr, target[1]);
Assert.Same(newAttr, target[2]);
}
[Fact]
public void InsertAfterRemovesDupAttrAfterTheRef()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute anotherAttr = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(3, target.Count);
Assert.Same(refAttr, target[0]);
Assert.Same(newAttr, target[1]);
Assert.Same(anotherAttr, target[2]);
}
[Fact]
public void InsertAfterRemovesDupAttrBeforeTheRef()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute anotherAttr = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(3, target.Count);
Assert.Same(anotherAttr, target[0]);
Assert.Same(refAttr, target[1]);
Assert.Same(newAttr, target[2]);
}
[Fact]
public void InsertAfterReturnsInsertedAttr()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute newAttr = doc.CreateAttribute("attr2", "some:uri2");
XmlAttributeCollection target = element.Attributes;
Assert.Same(newAttr, target.InsertAfter(newAttr, refAttr));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] //Fix for this edge case was only made in NetCore
public void InsertAfterRemovesDupRefAttrAtTheEnd()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute anotherAttr1 = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute anotherAttr2 = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(3, target.Count);
Assert.Same(anotherAttr1, target[0]);
Assert.Same(anotherAttr2, target[1]);
Assert.Same(newAttr, target[2]);
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] //Fix for this edge case was only made in NetCore
public void InsertAfterThrowsArgumentOutOfRangeExceptionForDupRefAttrAtTheEnd_OldBehavior()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute anotherAttr1 = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute anotherAttr2 = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
Assert.Throws<ArgumentOutOfRangeException> (() => target.InsertAfter(newAttr, refAttr));
Assert.Equal(2, target.Count);
Assert.Same(anotherAttr1, target[0]);
Assert.Same(anotherAttr2, target[1]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] //Fix for this edge case was only made in NetCore
public void InsertAfterReplacesDupRefAttr()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute anotherAttr1 = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute anotherAttr2 = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute anotherAttr3 = element.Attributes.Append(doc.CreateAttribute("attr3", "some:uri3"));
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(4, target.Count);
Assert.Same(anotherAttr1, target[0]);
Assert.Same(anotherAttr2, target[1]);
Assert.Same(newAttr, target[2]);
Assert.Same(anotherAttr3, target[3]);
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] //Fix for this edge case was only made in NetCore
public void InsertAfterDoesNotReplaceDupRefAttr_OldBehavior()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute anotherAttr1 = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute anotherAttr2 = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute anotherAttr3 = element.Attributes.Append(doc.CreateAttribute("attr3", "some:uri3"));
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(4, target.Count);
Assert.Same(anotherAttr1, target[0]);
Assert.Same(anotherAttr2, target[1]);
Assert.Same(anotherAttr3, target[2]);
Assert.Same(newAttr, target[3]);
}
[Fact]
public void InsertAfterRemovesDupRefAttrAfterAttrAndTheRef()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute anotherAttr2 = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute anotherAttr3 = element.Attributes.Append(doc.CreateAttribute("attr3", "some:uri3"));
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(4, target.Count);
Assert.Same(refAttr, target[0]);
Assert.Same(newAttr, target[1]);
Assert.Same(anotherAttr2, target[2]);
Assert.Same(anotherAttr3, target[3]);
}
}
}
| |
/**
* Copyright 2016 Dartmouth-Hitchcock
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Linq;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Caesar.Legion;
namespace Caesar {
public partial class Services : System.Web.UI.Page {
internal static void GetAssemblies(XmlDocument dom) {
DirectoryInfo dir;
Assembly assembly;
string assemblyDirectory;
XmlElement assemblies = (XmlElement)dom.DocumentElement.AppendChild(dom.CreateElement("assemblies"));
LegionXmlService service = new LegionXmlService("Caesar", ConfigurationManager.AppSettings["LegionKey"]);
LegionReply<XmlElement> reply = service.Call("GetAssemblyDirectory");
if(!reply.HasFault && ! reply.HasError){
assemblyDirectory = reply.Result.SelectSingleNode("assemblydirectory").InnerText;
dir = new DirectoryInfo(assemblyDirectory);
foreach (FileInfo file in dir.GetFiles("*.dll")) {
assembly = Assembly.LoadFile(file.FullName);
assemblies.AppendChild(dom.CreateElement("assembly")).InnerText = assembly.GetName().Name;
}
}
}
internal static void GetAssemblyManifest(XmlDocument dom) {
string assemblyName = HttpContext.Current.Request.Form["assembly"];
string assemblyDirectory;
XmlElement classes = (XmlElement)dom.DocumentElement.AppendChild(dom.CreateElement("classes"));
LegionXmlService service = new LegionXmlService("Caesar", ConfigurationManager.AppSettings["LegionKey"]);
LegionReply<XmlElement> reply = service.Call("GetAssemblyDirectory");
if (!reply.HasFault && !reply.HasError) {
assemblyDirectory = reply.Result.SelectSingleNode("assemblydirectory").InnerText;
try {
Assembly assembly = Assembly.LoadFile(string.Format(@"{0}\{1}.dll", assemblyDirectory, assemblyName));
Type[] types = assembly.GetTypes();
foreach (Type type in types) {
classes.AppendChild(dom.CreateElement("class")).InnerText = type.Name;
}
}
catch (System.IO.FileNotFoundException e) {
//LegionException lex = new LegionException(string.Format("Assembly '{0}' not found", result.AssemblyName), e, "AssemblyNotFound");
}
}
}
internal static void GetClassManifest(XmlDocument dom) {
string assemblyName = HttpContext.Current.Request.Form["assembly"];
string className = HttpContext.Current.Request.Form["class"];
string assemblyDirectory;
XmlElement methods = (XmlElement)dom.DocumentElement.AppendChild(dom.CreateElement("methods"));
LegionXmlService service = new LegionXmlService("Caesar", ConfigurationManager.AppSettings["LegionKey"]);
LegionReply<XmlElement> reply = service.Call("GetAssemblyDirectory");
if (!reply.HasFault && !reply.HasError) {
assemblyDirectory = reply.Result.SelectSingleNode("assemblydirectory").InnerText;
try {
Assembly assembly = Assembly.LoadFile(string.Format(@"{0}\{1}.dll", assemblyDirectory, assemblyName));
Type t = assembly.GetType(assemblyName + "." + className);
SortedDictionary<string, MethodInfo> classMethods = new SortedDictionary<string,MethodInfo>(t.GetMethods(BindingFlags.Public | BindingFlags.Static).ToDictionary(m => m.Name, m => m));
foreach (KeyValuePair<string, MethodInfo> method in classMethods) {
methods.AppendChild(dom.CreateElement("method")).InnerText = method.Value.Name;
}
}
catch (System.IO.FileNotFoundException e) {
//LegionException lex = new LegionException(string.Format("Assembly '{0}' not found", result.AssemblyName), e, "AssemblyNotFound");
}
}
}
internal static void ImportService(XmlDocument dom) {
LegionXmlService caesar = new LegionXmlService("Caesar", ConfigurationManager.AppSettings["LegionKey"]);
ServiceHandler.Initialize(ConfigurationManager.AppSettings["LegionKey"]);
string[] elements = HttpContext.Current.Request["elements"].Split(';');
string id = HttpContext.Current.Request["id"];
XmlDocument import = new XmlDocument();
import.LoadXml(HttpContext.Current.Request.Params["dom"]);
string servicekey = null, assembly = null, interfaceclass = null, description = null, consumeriprange = null, islogged = null, isrestricted = null, ispublic = null;
if (elements.Contains("servicekey"))
servicekey = GetNodeText(import, "servicekey");
if (elements.Contains("assembly"))
assembly = GetNodeText(import, "assembly");
if (elements.Contains("interfaceclass"))
interfaceclass = GetNodeText(import, "interfaceclass");
if (elements.Contains("description"))
description = GetNodeText(import, "description");
if (elements.Contains("consumeriprange"))
consumeriprange = GetNodeText(import, "consumeriprange");
if (elements.Contains("flags")) {
islogged = GetNodeText(import, "logged");
isrestricted = GetNodeText(import, "restricted");
ispublic = GetNodeText(import, "public");
}
if (id == null) {
dom.DocumentElement.AppendChild(dom.CreateElement("error")).InnerText = "bad id";
return;
}
if (servicekey == null || assembly == null || interfaceclass == null) {
if (id == "-1") {
dom.DocumentElement.AppendChild(dom.CreateElement("error")).InnerText = "unable to create service, missing required elements";
return;
}
else {
LegionReply<XmlElement> current = caesar.Call("getService", new Dictionary<string, string>(){
{"serviceid", id}
});
if (servicekey == null)
servicekey = current.Result.SelectSingleNode("./servicekey").InnerText;
if(assembly == null)
assembly = current.Result.SelectSingleNode("./assemblyname").InnerText;
if (interfaceclass == null)
interfaceclass = current.Result.SelectSingleNode("./classname").InnerText;
}
}
LegionReply<XmlElement> service = caesar.Call("updateService", new Dictionary<string, string>() {
{"id", id},
{"servicekey", servicekey},
{"description", description},
{"consumeriprange", consumeriprange},
{"assembly", assembly},
{"class", interfaceclass},
{"logged", islogged},
{"restricted", isrestricted},
{"public", ispublic}
});
if (id == "-1")
id = service.Result.SelectSingleNode("//id").InnerText;
if (elements.Contains("settings")) {
foreach (XmlNode setting in import.SelectNodes("//setting")) {
caesar.Call("updateServiceSetting", new Dictionary<string, string>() {
{"serviceid", id},
{"id", "-1"},
{"name", setting.SelectSingleNode("./name").InnerText},
{"value", setting.SelectSingleNode("./value").InnerText},
{"encrypted", setting.SelectSingleNode("./encrypted").InnerText}
});
}
}
if (elements.Contains("methods")) {
foreach (XmlNode method in import.SelectNodes("//method")) {
caesar.Call("updateServiceMethod", new Dictionary<string, string>() {
{"serviceid", id},
{"id", "-1"},
{"methodkey", method.SelectSingleNode("./key").InnerText},
{"methodname", method.SelectSingleNode("./name").InnerText},
{"cachedresultlifetime", method.SelectSingleNode("./cachedresultlifetime").InnerText},
{"cacheresult", method.SelectSingleNode("./cacheresult").InnerText},
{"restricted", method.SelectSingleNode("./restricted").InnerText},
{"logged", method.SelectSingleNode("./logged").InnerText},
{"public", method.SelectSingleNode("./public").InnerText}
});
}
}
dom.DocumentElement.AppendChild(dom.CreateElement("serviceid")).InnerText = id;
dom.DocumentElement.AppendChild(dom.CreateElement("resultcode")).InnerText = "SUCCESS";
}
internal static string GetNodeText(XmlDocument dom, string name) {
XmlElement node = (XmlElement)dom.SelectSingleNode("//" + name);
if (node != null)
return node.InnerText;
else
return null;
}
protected void Page_Load(object sender, EventArgs e) {
if (Request["exportservice"] == "true" && Request["serviceid"] != null && Request["elements"] != null) {
string serviceid = Request["serviceid"];
string[] elements = Request["elements"].Split(';');
LegionXmlService caesar = new LegionXmlService("Caesar", ConfigurationManager.AppSettings["LegionKey"]);
XmlDocument dom = new XmlDocument();
XmlElement root = (XmlElement)dom.AppendChild(dom.CreateElement("service"));
LegionReply<XmlElement> service = caesar.Call("getService", new Dictionary<string, string>(){
{"serviceid", serviceid}
});
DateTime exporttime = DateTime.Now;
string servicekey = service.Result.SelectSingleNode("./servicekey").InnerText.Trim();
string filename = string.Format("{0}-{1:yyyyMMddHHmmss}.legion", servicekey, exporttime);
root.SetAttribute("exporttime", string.Format("{0:yyyy-MM-dd HH:mm:ss}", exporttime));
if (elements.Contains("servicekey"))
root.AppendChild(dom.CreateElement("servicekey")).InnerText = servicekey;
if (elements.Contains("assembly"))
root.AppendChild(dom.CreateElement("assembly")).InnerText = service.Result.SelectSingleNode("./assemblyname").InnerText.Trim();
if (elements.Contains("interfaceclass"))
root.AppendChild(dom.CreateElement("interfaceclass")).InnerText = service.Result.SelectSingleNode("./classname").InnerText.Trim();
if (elements.Contains("description"))
root.AppendChild(dom.CreateElement("description")).AppendChild(dom.CreateCDataSection(service.Result.SelectSingleNode("./description").InnerText.Trim()));
if (elements.Contains("consumeriprange"))
root.AppendChild(dom.CreateElement("consumeriprange")).InnerText = service.Result.SelectSingleNode("./consumeriprange").InnerText.Trim();
if (elements.Contains("flags")) {
root.AppendChild(dom.CreateElement("logged")).InnerText = service.Result.SelectSingleNode("./logged").InnerText.Trim();
root.AppendChild(dom.CreateElement("restricted")).InnerText = service.Result.SelectSingleNode("./restricted").InnerText.Trim();
root.AppendChild(dom.CreateElement("public")).InnerText = service.Result.SelectSingleNode("./public").InnerText.Trim();
}
if (elements.Contains("settings")) {
LegionReply<XmlElement> serviceSettings = caesar.Call("getServiceSettings", new Dictionary<string, string>(){
{"id", serviceid}
});
int count = 0;
XmlElement setting, settings = (XmlElement)root.AppendChild(dom.CreateElement("settings"));
foreach(XmlElement x in serviceSettings.Result.SelectNodes("//settings/setting")){
setting = (XmlElement)settings.AppendChild(dom.CreateElement("setting"));
setting.AppendChild(dom.CreateElement("name")).InnerText = x.SelectSingleNode("./name").InnerText.Trim();
setting.AppendChild(dom.CreateElement("value")).AppendChild(dom.CreateCDataSection(x.SelectSingleNode("./value").InnerText.Trim()));
setting.AppendChild(dom.CreateElement("encrypted")).InnerText = x.SelectSingleNode("./encrypted").InnerText.Trim();
count++;
}
settings.SetAttribute("count", count.ToString());
}
if (elements.Contains("methods")) {
LegionReply<XmlElement> serviceMethods = caesar.Call("getServiceMethods", new Dictionary<string, string>(){
{"serviceId", serviceid}
});
int count = 0;
XmlElement method, methods = (XmlElement)root.AppendChild(dom.CreateElement("methods"));
foreach (XmlElement x in serviceMethods.Result.SelectNodes("//methods/method")) {
method = (XmlElement)methods.AppendChild(dom.CreateElement("method"));
method.AppendChild(dom.CreateElement("key")).InnerText = x.SelectSingleNode("./key").InnerText.Trim();
method.AppendChild(dom.CreateElement("name")).InnerText = x.SelectSingleNode("./name").InnerText.Trim();
method.AppendChild(dom.CreateElement("cachedresultlifetime")).InnerText = x.SelectSingleNode("./cachedresultlifetime").InnerText.Trim();
method.AppendChild(dom.CreateElement("cacheresult")).InnerText = x.SelectSingleNode("./cacheresult").InnerText.Trim();
method.AppendChild(dom.CreateElement("restricted")).InnerText = x.SelectSingleNode("./restricted").InnerText.Trim();
method.AppendChild(dom.CreateElement("logged")).InnerText = x.SelectSingleNode("./logged").InnerText.Trim();
method.AppendChild(dom.CreateElement("public")).InnerText = x.SelectSingleNode("./logged").InnerText.Trim();
count++;
}
methods.SetAttribute("count", count.ToString());
}
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.ContentType = "text/xml";
Response.Write(dom.OuterXml);
Response.End();
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework;
using OpenSim.Region.CoreModules.Framework.EntityTransfer;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation;
using OpenSim.Region.CoreModules.World.Land;
using OpenSim.Region.OptionalModules;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
namespace OpenSim.Region.Framework.Scenes.Tests
{
public class SceneObjectCrossingTests : OpenSimTestCase
{
[TestFixtureSetUp]
public void FixtureInit()
{
// Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread.
Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest;
}
[TestFixtureTearDown]
public void TearDown()
{
// We must set this back afterwards, otherwise later tests will fail since they're expecting multiple
// threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression
// tests really shouldn't).
Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod;
}
/// <summary>
/// Test cross with no prim limit module.
/// </summary>
[Test]
public void TestCrossOnSameSimulator()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID userId = TestHelpers.ParseTail(0x1);
int sceneObjectIdTail = 0x2;
EntityTransferModule etmA = new EntityTransferModule();
EntityTransferModule etmB = new EntityTransferModule();
LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();
IConfigSource config = new IniConfigSource();
IConfig modulesConfig = config.AddConfig("Modules");
modulesConfig.Set("EntityTransferModule", etmA.Name);
modulesConfig.Set("SimulationServices", lscm.Name);
SceneHelpers sh = new SceneHelpers();
TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999);
SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
SceneHelpers.SetupSceneModules(sceneA, config, etmA);
SceneHelpers.SetupSceneModules(sceneB, config, etmB);
SceneObjectGroup so1 = SceneHelpers.AddSceneObject(sceneA, 1, userId, "", sceneObjectIdTail);
UUID so1Id = so1.UUID;
so1.AbsolutePosition = new Vector3(128, 10, 20);
// Cross with a negative value
so1.AbsolutePosition = new Vector3(128, -10, 20);
Assert.IsNull(sceneA.GetSceneObjectGroup(so1Id));
Assert.NotNull(sceneB.GetSceneObjectGroup(so1Id));
}
/// <summary>
/// Test cross with no prim limit module.
/// </summary>
/// <remarks>
/// Possibly this should belong in ScenePresenceCrossingTests, though here it is the object that is being moved
/// where the avatar is just a passenger.
/// </remarks>
[Test]
public void TestCrossOnSameSimulatorWithSittingAvatar()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID userId = TestHelpers.ParseTail(0x1);
int sceneObjectIdTail = 0x2;
Vector3 so1StartPos = new Vector3(128, 10, 20);
EntityTransferModule etmA = new EntityTransferModule();
EntityTransferModule etmB = new EntityTransferModule();
LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();
IConfigSource config = new IniConfigSource();
IConfig modulesConfig = config.AddConfig("Modules");
modulesConfig.Set("EntityTransferModule", etmA.Name);
modulesConfig.Set("SimulationServices", lscm.Name);
IConfig entityTransferConfig = config.AddConfig("EntityTransfer");
// In order to run a single threaded regression test we do not want the entity transfer module waiting
// for a callback from the destination scene before removing its avatar data.
entityTransferConfig.Set("wait_for_callback", false);
SceneHelpers sh = new SceneHelpers();
TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999);
SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA);
SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), etmB);
SceneObjectGroup so1 = SceneHelpers.AddSceneObject(sceneA, 1, userId, "", sceneObjectIdTail);
UUID so1Id = so1.UUID;
so1.AbsolutePosition = so1StartPos;
AgentCircuitData acd = SceneHelpers.GenerateAgentData(userId);
TestClient tc = new TestClient(acd, sceneA);
List<TestClient> destinationTestClients = new List<TestClient>();
EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);
ScenePresence sp1SceneA = SceneHelpers.AddScenePresence(sceneA, tc, acd);
sp1SceneA.AbsolutePosition = so1StartPos;
sp1SceneA.HandleAgentRequestSit(sp1SceneA.ControllingClient, sp1SceneA.UUID, so1.UUID, Vector3.Zero);
// Cross
sceneA.SceneGraph.UpdatePrimGroupPosition(
so1.LocalId, new Vector3(so1StartPos.X, so1StartPos.Y - 20, so1StartPos.Z), userId);
SceneObjectGroup so1PostCross;
{
ScenePresence sp1SceneAPostCross = sceneA.GetScenePresence(userId);
Assert.IsTrue(sp1SceneAPostCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly false");
ScenePresence sp1SceneBPostCross = sceneB.GetScenePresence(userId);
TestClient sceneBTc = ((TestClient)sp1SceneBPostCross.ControllingClient);
sceneBTc.CompleteMovement();
Assert.IsFalse(sp1SceneBPostCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly true");
Assert.IsTrue(sp1SceneBPostCross.IsSatOnObject);
Assert.IsNull(sceneA.GetSceneObjectGroup(so1Id), "uck");
so1PostCross = sceneB.GetSceneObjectGroup(so1Id);
Assert.NotNull(so1PostCross);
Assert.AreEqual(1, so1PostCross.GetSittingAvatarsCount());
}
Vector3 so1PostCrossPos = so1PostCross.AbsolutePosition;
// Console.WriteLine("CRISSCROSS");
// Recross
sceneB.SceneGraph.UpdatePrimGroupPosition(
so1PostCross.LocalId, new Vector3(so1PostCrossPos.X, so1PostCrossPos.Y + 20, so1PostCrossPos.Z), userId);
{
ScenePresence sp1SceneBPostReCross = sceneB.GetScenePresence(userId);
Assert.IsTrue(sp1SceneBPostReCross.IsChildAgent, "sp1SceneBPostReCross.IsChildAgent unexpectedly false");
ScenePresence sp1SceneAPostReCross = sceneA.GetScenePresence(userId);
TestClient sceneATc = ((TestClient)sp1SceneAPostReCross.ControllingClient);
sceneATc.CompleteMovement();
Assert.IsFalse(sp1SceneAPostReCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly true");
Assert.IsTrue(sp1SceneAPostReCross.IsSatOnObject);
Assert.IsNull(sceneB.GetSceneObjectGroup(so1Id), "uck2");
SceneObjectGroup so1PostReCross = sceneA.GetSceneObjectGroup(so1Id);
Assert.NotNull(so1PostReCross);
Assert.AreEqual(1, so1PostReCross.GetSittingAvatarsCount());
}
}
/// <summary>
/// Test cross with no prim limit module.
/// </summary>
/// <remarks>
/// XXX: This test may FCbe better off in a specific PrimLimitsModuleTest class in optional module tests in the
/// future (though it is configured as active by default, so not really optional).
/// </remarks>
[Test]
public void TestCrossOnSameSimulatorPrimLimitsOkay()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID userId = TestHelpers.ParseTail(0x1);
int sceneObjectIdTail = 0x2;
EntityTransferModule etmA = new EntityTransferModule();
EntityTransferModule etmB = new EntityTransferModule();
LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();
LandManagementModule lmmA = new LandManagementModule();
LandManagementModule lmmB = new LandManagementModule();
IConfigSource config = new IniConfigSource();
IConfig modulesConfig = config.AddConfig("Modules");
modulesConfig.Set("EntityTransferModule", etmA.Name);
modulesConfig.Set("SimulationServices", lscm.Name);
IConfig permissionsConfig = config.AddConfig("Permissions");
permissionsConfig.Set("permissionmodules", "PrimLimitsModule");
SceneHelpers sh = new SceneHelpers();
TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999);
SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
SceneHelpers.SetupSceneModules(
sceneA, config, etmA, lmmA, new PrimLimitsModule(), new PrimCountModule());
SceneHelpers.SetupSceneModules(
sceneB, config, etmB, lmmB, new PrimLimitsModule(), new PrimCountModule());
// We must set up the parcel for this to work. Normally this is taken care of by OpenSimulator startup
// code which is not yet easily invoked by tests.
lmmA.EventManagerOnNoLandDataFromStorage();
lmmB.EventManagerOnNoLandDataFromStorage();
SceneObjectGroup so1 = SceneHelpers.AddSceneObject(sceneA, 1, userId, "", sceneObjectIdTail);
UUID so1Id = so1.UUID;
so1.AbsolutePosition = new Vector3(128, 10, 20);
// Cross with a negative value. We must make this call rather than setting AbsolutePosition directly
// because only this will execute permission checks in the source region.
sceneA.SceneGraph.UpdatePrimGroupPosition(so1.LocalId, new Vector3(128, -10, 20), userId);
Assert.IsNull(sceneA.GetSceneObjectGroup(so1Id));
Assert.NotNull(sceneB.GetSceneObjectGroup(so1Id));
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// PartitionerQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Linq.Parallel;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// A QueryOperator that represents the output of the query partitioner.AsParallel().
/// </summary>
internal class PartitionerQueryOperator<TElement> : QueryOperator<TElement>
{
private Partitioner<TElement> _partitioner; // The partitioner to use as data source.
internal PartitionerQueryOperator(Partitioner<TElement> partitioner)
: base(false, QuerySettings.Empty)
{
_partitioner = partitioner;
}
internal bool Orderable
{
get { return _partitioner is OrderablePartitioner<TElement>; }
}
internal override QueryResults<TElement> Open(QuerySettings settings, bool preferStriping)
{
// Notice that the preferStriping argument is not used. Partitioner<T> does not support
// striped partitioning.
return new PartitionerQueryOperatorResults(_partitioner, settings);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TElement> AsSequentialQuery(CancellationToken token)
{
using (IEnumerator<TElement> enumerator = _partitioner.GetPartitions(1)[0])
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
}
//---------------------------------------------------------------------------------------
// The state of the order index of the results returned by this operator.
//
internal override OrdinalIndexState OrdinalIndexState
{
get { return GetOrdinalIndexState(_partitioner); }
}
/// <summary>
/// Determines the OrdinalIndexState for a partitioner
/// </summary>
internal static OrdinalIndexState GetOrdinalIndexState(Partitioner<TElement> partitioner)
{
OrderablePartitioner<TElement> orderablePartitioner = partitioner as OrderablePartitioner<TElement>;
if (orderablePartitioner == null)
{
return OrdinalIndexState.Shuffled;
}
if (orderablePartitioner.KeysOrderedInEachPartition)
{
if (orderablePartitioner.KeysNormalized)
{
return OrdinalIndexState.Correct;
}
else
{
return OrdinalIndexState.Increasing;
}
}
else
{
return OrdinalIndexState.Shuffled;
}
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
/// <summary>
/// QueryResults for a PartitionerQueryOperator
/// </summary>
private class PartitionerQueryOperatorResults : QueryResults<TElement>
{
private Partitioner<TElement> _partitioner; // The data source for the query
private QuerySettings _settings; // Settings collected from the query
internal PartitionerQueryOperatorResults(Partitioner<TElement> partitioner, QuerySettings settings)
{
_partitioner = partitioner;
_settings = settings;
}
internal override void GivePartitionedStream(IPartitionedStreamRecipient<TElement> recipient)
{
Debug.Assert(_settings.DegreeOfParallelism.HasValue);
int partitionCount = _settings.DegreeOfParallelism.Value;
OrderablePartitioner<TElement> orderablePartitioner = _partitioner as OrderablePartitioner<TElement>;
// If the partitioner is not orderable, it will yield zeros as order keys. The order index state
// is irrelevant.
OrdinalIndexState indexState = (orderablePartitioner != null)
? GetOrdinalIndexState(orderablePartitioner)
: OrdinalIndexState.Shuffled;
PartitionedStream<TElement, int> partitions = new PartitionedStream<TElement, int>(
partitionCount,
Util.GetDefaultComparer<int>(),
indexState);
if (orderablePartitioner != null)
{
IList<IEnumerator<KeyValuePair<long, TElement>>> partitionerPartitions =
orderablePartitioner.GetOrderablePartitions(partitionCount);
if (partitionerPartitions == null)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_NullPartitionList);
}
if (partitionerPartitions.Count != partitionCount)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_WrongNumberOfPartitions);
}
for (int i = 0; i < partitionCount; i++)
{
IEnumerator<KeyValuePair<long, TElement>> partition = partitionerPartitions[i];
if (partition == null)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_NullPartition);
}
partitions[i] = new OrderablePartitionerEnumerator(partition);
}
}
else
{
IList<IEnumerator<TElement>> partitionerPartitions =
_partitioner.GetPartitions(partitionCount);
if (partitionerPartitions == null)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_NullPartitionList);
}
if (partitionerPartitions.Count != partitionCount)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_WrongNumberOfPartitions);
}
for (int i = 0; i < partitionCount; i++)
{
IEnumerator<TElement> partition = partitionerPartitions[i];
if (partition == null)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_NullPartition);
}
partitions[i] = new PartitionerEnumerator(partition);
}
}
recipient.Receive<int>(partitions);
}
}
/// <summary>
/// Enumerator that converts an enumerator over key-value pairs exposed by a partitioner
/// to a QueryOperatorEnumerator used by PLINQ internally.
/// </summary>
private class OrderablePartitionerEnumerator : QueryOperatorEnumerator<TElement, int>
{
private IEnumerator<KeyValuePair<long, TElement>> _sourceEnumerator;
internal OrderablePartitionerEnumerator(IEnumerator<KeyValuePair<long, TElement>> sourceEnumerator)
{
_sourceEnumerator = sourceEnumerator;
}
internal override bool MoveNext(ref TElement currentElement, ref int currentKey)
{
if (!_sourceEnumerator.MoveNext()) return false;
KeyValuePair<long, TElement> current = _sourceEnumerator.Current;
currentElement = current.Value;
checked
{
currentKey = (int)current.Key;
}
return true;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_sourceEnumerator != null);
_sourceEnumerator.Dispose();
}
}
/// <summary>
/// Enumerator that converts an enumerator over key-value pairs exposed by a partitioner
/// to a QueryOperatorEnumerator used by PLINQ internally.
/// </summary>
private class PartitionerEnumerator : QueryOperatorEnumerator<TElement, int>
{
private IEnumerator<TElement> _sourceEnumerator;
internal PartitionerEnumerator(IEnumerator<TElement> sourceEnumerator)
{
_sourceEnumerator = sourceEnumerator;
}
internal override bool MoveNext(ref TElement currentElement, ref int currentKey)
{
if (!_sourceEnumerator.MoveNext()) return false;
currentElement = _sourceEnumerator.Current;
currentKey = 0;
return true;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_sourceEnumerator != null);
_sourceEnumerator.Dispose();
}
}
}
}
| |
// 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.
//
//
//
// StrongName is an IIdentity representing strong names.
//
namespace System.Security.Policy {
using System.IO;
using System.Reflection;
using System.Security.Util;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class StrongName : EvidenceBase, IIdentityPermissionFactory, IDelayEvaluatedEvidence
{
private StrongNamePublicKeyBlob m_publicKeyBlob;
private String m_name;
private Version m_version;
// Delay evaluated evidence is for policy resolution only, so it doesn't make sense to save that
// state away and then try to evaluate the strong name later.
[NonSerialized]
private RuntimeAssembly m_assembly = null;
[NonSerialized]
private bool m_wasUsed = false;
internal StrongName() {}
public StrongName( StrongNamePublicKeyBlob blob, String name, Version version ) : this(blob, name, version, null)
{
}
internal StrongName(StrongNamePublicKeyBlob blob, String name, Version version, Assembly assembly)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (String.IsNullOrEmpty(name))
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyStrongName"));
if (blob == null)
throw new ArgumentNullException(nameof(blob));
if (version == null)
throw new ArgumentNullException(nameof(version));
Contract.EndContractBlock();
RuntimeAssembly rtAssembly = assembly as RuntimeAssembly;
if (assembly != null && rtAssembly == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(assembly));
m_publicKeyBlob = blob;
m_name = name;
m_version = version;
m_assembly = rtAssembly;
}
public StrongNamePublicKeyBlob PublicKey
{
get
{
return m_publicKeyBlob;
}
}
public String Name
{
get
{
return m_name;
}
}
public Version Version
{
get
{
return m_version;
}
}
bool IDelayEvaluatedEvidence.IsVerified
{
[System.Security.SecurityCritical] // auto-generated
get
{
#if FEATURE_CAS_POLICY
return m_assembly != null ? m_assembly.IsStrongNameVerified : true;
#else // !FEATURE_CAS_POLICY
return true;
#endif // FEATURE_CAS_POLICY
}
}
bool IDelayEvaluatedEvidence.WasUsed
{
get { return m_wasUsed; }
}
void IDelayEvaluatedEvidence.MarkUsed()
{
m_wasUsed = true;
}
internal static bool CompareNames( String asmName, String mcName )
{
if (mcName.Length > 0 && mcName[mcName.Length-1] == '*' && mcName.Length - 1 <= asmName.Length)
return String.Compare( mcName, 0, asmName, 0, mcName.Length - 1, StringComparison.OrdinalIgnoreCase) == 0;
else
return String.Compare( mcName, asmName, StringComparison.OrdinalIgnoreCase) == 0;
}
public IPermission CreateIdentityPermission( Evidence evidence )
{
return new StrongNameIdentityPermission( m_publicKeyBlob, m_name, m_version );
}
public override EvidenceBase Clone()
{
return new StrongName(m_publicKeyBlob, m_name, m_version);
}
public Object Copy()
{
return Clone();
}
#if FEATURE_CAS_POLICY
internal SecurityElement ToXml()
{
SecurityElement root = new SecurityElement( "StrongName" );
root.AddAttribute( "version", "1" );
if (m_publicKeyBlob != null)
root.AddAttribute( "Key", System.Security.Util.Hex.EncodeHexString( m_publicKeyBlob.PublicKey ) );
if (m_name != null)
root.AddAttribute( "Name", m_name );
if (m_version != null)
root.AddAttribute( "Version", m_version.ToString() );
return root;
}
internal void FromXml (SecurityElement element)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (String.Compare(element.Tag, "StrongName", StringComparison.Ordinal) != 0)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML"));
Contract.EndContractBlock();
m_publicKeyBlob = null;
m_version = null;
string key = element.Attribute("Key");
if (key != null)
m_publicKeyBlob = new StrongNamePublicKeyBlob(System.Security.Util.Hex.DecodeHexString(key));
m_name = element.Attribute("Name");
string version = element.Attribute("Version");
if (version != null)
m_version = new Version(version);
}
public override String ToString()
{
return ToXml().ToString();
}
#endif // FEATURE_CAS_POLICY
public override bool Equals( Object o )
{
StrongName that = (o as StrongName);
return (that != null) &&
Equals( this.m_publicKeyBlob, that.m_publicKeyBlob ) &&
Equals( this.m_name, that.m_name ) &&
Equals( this.m_version, that.m_version );
}
public override int GetHashCode()
{
if (m_publicKeyBlob != null)
{
return m_publicKeyBlob.GetHashCode();
}
else if (m_name != null || m_version != null)
{
return (m_name == null ? 0 : m_name.GetHashCode()) + (m_version == null ? 0 : m_version.GetHashCode());
}
else
{
return typeof( StrongName ).GetHashCode();
}
}
// INormalizeForIsolatedStorage is not implemented for startup perf
// equivalent to INormalizeForIsolatedStorage.Normalize()
internal Object Normalize()
{
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(m_publicKeyBlob.PublicKey);
bw.Write(m_version.Major);
bw.Write(m_name);
ms.Position = 0;
return ms;
}
}
}
| |
#region License
// Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com>
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using FluentMigrator.Exceptions;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Conventions;
using FluentMigrator.Runner.Exceptions;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Initialization.NetFramework;
using FluentMigrator.Runner.Logging;
using FluentMigrator.Runner.Processors;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Mono.Options;
using static FluentMigrator.Runner.ConsoleUtilities;
namespace FluentMigrator.Console
{
public class MigratorConsole
{
[Obsolete("Use dependency injection to access 'application state'.")]
public string ApplicationContext;
public string Connection;
public string ConnectionStringConfigPath;
public string Namespace;
public bool NestedNamespaces;
public bool Output;
public string OutputFilename;
public bool OutputSemicolonDelimiter = false;
public bool PreviewOnly;
public string ProcessorType;
public string Profile;
public bool ShowHelp;
public int Steps;
public List<string> Tags = new List<string>();
public bool IncludeUntaggedMaintenances;
public bool IncludeUntaggedMigrations = true;
public string TargetAssembly;
public string Task;
public int? Timeout;
public bool Verbose;
public bool StopOnError;
public long Version;
public long StartVersion;
public bool NoConnection;
public string WorkingDirectory;
public bool TransactionPerSession;
public bool AllowBreakingChange;
public string ProviderSwitches;
public bool StripComments = true;
public string DefaultSchemaName { get; set; }
public int Run(params string[] args)
{
var dbChoicesList = new List<string>();
string dbChoices;
var services = CreateCoreServices()
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader("No connection"));
using (var sp = services.BuildServiceProvider(validateScopes: false))
{
var processors = sp.GetRequiredService<IEnumerable<IMigrationProcessor>>().ToList();
dbChoicesList.AddRange(processors.Select(p => p.DatabaseType));
}
dbChoices = string.Join(
", ",
dbChoicesList
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(x => x, StringComparer.OrdinalIgnoreCase));
System.Console.Out.WriteHeader();
try
{
var optionSet = new OptionSet
{
{
"assembly=|a=|target=",
"REQUIRED. The assembly containing the migrations you want to execute.",
v => { TargetAssembly = v; }
},
{
"provider=|dbType=|db=",
$"REQUIRED. The kind of database you are migrating against. Available choices are: {dbChoices}.",
v => { ProcessorType = v; }
},
{
"connectionString=|connection=|conn=|c=",
"The name of the connection string (falls back to machine name) or the connection string itself to the server and database you want to execute your migrations against.",
v => { Connection = v; }
},
{
"connectionStringConfigPath=|configPath=",
string.Format(
"The path of the machine.config where the connection string named by connectionString" +
" is found. If not specified, it defaults to the machine.config used by the currently running CLR version"),
v => { ConnectionStringConfigPath = v; }
},
{
"namespace=|ns=",
"The namespace contains the migrations you want to run. Default is all migrations found within the Target Assembly will be run.",
v => { Namespace = v; }
},
{
"nested",
"Whether migrations in nested namespaces should be included. Used in conjunction with the namespace option.",
v => { NestedNamespaces = v != null; }
},
{
"output|out|o",
"Output generated SQL to a file. Default is no output. Use outputFilename to control the filename, otherwise [assemblyname].sql is the default.",
v => { Output = v != null; }
},
{
"outputSemicolonDelimiter|outsemdel|osd",
"Whether each command should be delimited with a semicolon.",
v => { OutputSemicolonDelimiter = v != null; }
},
{
"outputFilename=|outfile=|of=",
"The name of the file to output the generated SQL to. The output option must be included for output to be saved to the file.",
v => { OutputFilename = v; }
},
{
"preview|p",
"Only output the SQL generated by the migration - do not execute it. Default is false.",
v => { PreviewOnly = v != null; }
},
{
"steps=",
"The number of versions to rollback if the task is 'rollback'. Default is 1.",
v => { Steps = int.Parse(v); }
},
{
"task=|t=",
"The task you want FluentMigrator to perform. Available choices are: migrate:up, migrate (same as migrate:up), migrate:down, rollback, rollback:toversion, rollback:all, validateversionorder, listmigrations. Default is 'migrate'.",
v => { Task = v; }
},
{
"version=",
"The specific version to migrate. Default is 0, which will run all migrations.",
v => { Version = long.Parse(v); }
},
{
"startVersion=",
"The specific version to start migrating from. Only used when NoConnection is true. Default is 0",
v => { StartVersion = long.Parse(v); }
},
{
"noConnection",
"Indicates that migrations will be generated without consulting a target database. Should only be used when generating an output file.",
v => { NoConnection = v != null; }
},
{
"verbose=",
"Show the SQL statements generated and execution time in the console. Default is false.",
v => { Verbose = v != null; }
},
{
"stopOnError=",
"Pauses migration execution until the user input if any error occured. Default is false.",
v => { StopOnError = v != null; }
},
{
"workingdirectory=|wd=",
"The directory to load SQL scripts specified by migrations from.",
v => { WorkingDirectory = v; }
},
{
"profile=",
"The profile to run after executing migrations.",
v => { Profile = v; }
},
{
"context=",
"Set ApplicationContext to the given string.",
v => { ApplicationContext = v; }
},
{
"timeout=",
"Overrides the default SqlCommand timeout of 30 seconds.",
v => { Timeout = int.Parse(v); }
},
{
"tag=",
"Filters the migrations to be run by tag.",
v => { Tags.Add(v); }
},
{
"include-untagged:",
"Include untagged migrations and/or maintenance objects.",
v =>
{
if (string.IsNullOrEmpty(v))
{
IncludeUntaggedMigrations = IncludeUntaggedMaintenances = true;
}
else
{
var items = v.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.ToLowerInvariant().Trim())
.Where(x => !string.IsNullOrEmpty(x))
.Select(
x =>
{
var hasOption = x.EndsWith("+") || x.EndsWith("-");
var enable = !x.EndsWith("-");
var name = hasOption ? x.Substring(0, x.Length - 1) : x;
return new
{
FullName = x,
ShortName = name.Substring(Math.Min(2, name.Length)),
Enable = enable,
};
});
foreach (var item in items)
{
switch (item.ShortName)
{
case "ma":
IncludeUntaggedMaintenances = item.Enable;
break;
case "mi":
IncludeUntaggedMigrations = item.Enable;
break;
default:
throw new ArgumentOutOfRangeException(
$"The argument {item.FullName} is not supported. "
+ "Valid values are: ma, maintenance, mi, migrations with an optional '+' or '-' at the end to enable or disable the option. "
+ "Multiple values may be given when separated by a comma.");
}
}
}
}
},
{
"providerswitches=",
"Provider specific switches",
v => { ProviderSwitches = v; }
},
{
"strip|strip-comments",
"Strip comments from the SQL scripts. Default is true. To disable, use --strip- or --strip-comments-",
v => { StripComments = v != null; }
},
{
"help|h|?",
"Displays this help menu.",
v => { ShowHelp = true; }
},
{
"transaction-per-session|tps",
"Overrides the transaction behavior of migrations, so that all migrations to be executed will run in one transaction.",
v => { TransactionPerSession = v != null; }
},
{
"allow-breaking-changes|abc",
"Allows execution of migrations marked as breaking changes.",
v => { AllowBreakingChange = v != null; }
},
{
"default-schema-name=",
"Set default schema name for the VersionInfo table and the migrations.",
v => { DefaultSchemaName = v; }
},
};
try
{
optionSet.Parse(args);
}
catch (OptionException e)
{
AsError(() => System.Console.Error.WriteException(e));
System.Console.WriteLine(@"Try 'migrate --help' for more information.");
return 2;
}
if (string.IsNullOrEmpty(Task))
{
Task = "migrate";
}
if (!ValidateArguments(optionSet))
{
return 1;
}
if (ShowHelp)
{
DisplayHelp(optionSet);
return 0;
}
return ExecuteMigrations();
}
catch (MissingMigrationsException ex)
{
AsError(() => System.Console.Error.WriteException(ex));
return 6;
}
catch (RunnerException ex)
{
AsError(() => System.Console.Error.WriteException(ex));
return 5;
}
catch (FluentMigratorException ex)
{
AsError(() => System.Console.Error.WriteException(ex));
return 4;
}
catch (Exception ex)
{
AsError(() => System.Console.Error.WriteException(ex));
return 3;
}
}
private bool ValidateArguments(OptionSet optionSet)
{
if (string.IsNullOrEmpty(TargetAssembly))
{
DisplayHelp(optionSet, "Please enter the path of the assembly containing migrations you want to execute.");
return false;
}
if (string.IsNullOrEmpty(ProcessorType))
{
DisplayHelp(optionSet, "Please enter the kind of database you are migrating against.");
return false;
}
return true;
}
private void DisplayHelp(OptionSet optionSet, string validationErrorMessage)
{
System.Console.ForegroundColor = ConsoleColor.Yellow;
System.Console.WriteLine(validationErrorMessage);
System.Console.ResetColor();
DisplayHelp(optionSet);
}
private void DisplayHelp(OptionSet p)
{
System.Console.WriteLine(@"Usage:");
System.Console.WriteLine(@" migrate [OPTIONS]");
System.Console.WriteLine(@"Example:");
System.Console.WriteLine(@" migrate -a bin\debug\MyMigrations.dll -db SqlServer2008 -conn ""SEE_BELOW"" -profile ""Debug""");
System.Console.WriteLine(@" ");
System.Console.WriteLine(@"Boolean options/flags (those without '=' or ':' in the option format string)");
System.Console.WriteLine(@"are explicitly enabled if they are followed with '+', and explicitly");
System.Console.WriteLine(@"disabled if they are followed with '-'.");
System.Console.Out.WriteHorizontalRuler();
System.Console.WriteLine(@"Example Connection Strings:");
System.Console.WriteLine(@" MySql: Data Source=172.0.0.1;Database=Foo;User Id=USERNAME;Password=BLAH");
System.Console.WriteLine(@" Oracle: Server=172.0.0.1;Database=Foo;Uid=USERNAME;Pwd=BLAH");
System.Console.WriteLine(@" SqlLite: Data Source=:memory:");
System.Console.WriteLine(@" SqlServer: server=127.0.0.1;database=Foo;user id=USERNAME;password=BLAH");
System.Console.WriteLine(@" server=.\SQLExpress;database=Foo;trusted_connection=true");
System.Console.WriteLine(@" ");
System.Console.WriteLine(@"OR use a named connection string from the machine.config:");
System.Console.WriteLine(@" migrate -a bin\debug\MyMigrations.dll -db SqlServer2008 -conn ""namedConnection"" -profile ""Debug""");
System.Console.Out.WriteHorizontalRuler();
System.Console.WriteLine(@"Options:");
p.WriteOptionDescriptions(System.Console.Out);
}
private bool ExecutingAgainstMsSql => ProcessorType.StartsWith("SqlServer", StringComparison.InvariantCultureIgnoreCase);
private int ExecuteMigrations()
{
var conventionSet = new DefaultConventionSet(DefaultSchemaName, WorkingDirectory);
var services = CreateCoreServices()
.Configure<FluentMigratorLoggerOptions>(
opt =>
{
opt.ShowElapsedTime = Verbose;
opt.ShowSql = Verbose;
})
.AddSingleton<IConventionSet>(conventionSet)
.Configure<SelectingProcessorAccessorOptions>(opt => opt.ProcessorId = ProcessorType)
.Configure<AssemblySourceOptions>(opt => opt.AssemblyNames = new[] { TargetAssembly })
#pragma warning disable 612
.Configure<AppConfigConnectionStringAccessorOptions>(
opt => opt.ConnectionStringConfigPath = ConnectionStringConfigPath)
#pragma warning restore 612
.Configure<TypeFilterOptions>(
opt =>
{
opt.Namespace = Namespace;
opt.NestedNamespaces = NestedNamespaces;
})
.Configure<RunnerOptions>(
opt =>
{
opt.Task = Task;
opt.Version = Version;
opt.StartVersion = StartVersion;
opt.NoConnection = NoConnection;
opt.Steps = Steps;
opt.Profile = Profile;
opt.Tags = Tags.ToArray();
#pragma warning disable 612
opt.ApplicationContext = ApplicationContext;
#pragma warning restore 612
opt.TransactionPerSession = TransactionPerSession;
opt.AllowBreakingChange = AllowBreakingChange;
opt.IncludeUntaggedMaintenances = IncludeUntaggedMaintenances;
opt.IncludeUntaggedMigrations = IncludeUntaggedMigrations;
})
.Configure<ProcessorOptions>(
opt =>
{
opt.ConnectionString = Connection;
opt.PreviewOnly = PreviewOnly;
opt.ProviderSwitches = ProviderSwitches;
opt.StripComments = StripComments;
opt.Timeout = Timeout == null ? null : (TimeSpan?) TimeSpan.FromSeconds(Timeout.Value);
});
if (StopOnError)
{
services
.AddSingleton<ILoggerProvider, StopOnErrorLoggerProvider>();
}
else
{
services
.AddSingleton<ILoggerProvider, FluentMigratorConsoleLoggerProvider>();
}
if (Output)
{
services
.Configure<LogFileFluentMigratorLoggerOptions>(
opt =>
{
opt.ShowSql = true;
opt.OutputFileName = OutputFilename;
opt.OutputGoBetweenStatements = ExecutingAgainstMsSql;
opt.OutputSemicolonDelimiter = OutputSemicolonDelimiter;
})
.AddSingleton<ILoggerProvider, LogFileFluentMigratorLoggerProvider>();
}
using (var serviceProvider = services.BuildServiceProvider(validateScopes: false))
{
var executor = serviceProvider.GetRequiredService<TaskExecutor>();
executor.Execute();
}
return 0;
}
private static IServiceCollection CreateCoreServices()
{
var services = new ServiceCollection()
.AddFluentMigratorCore()
.ConfigureRunner(
builder => builder
.AddDb2()
.AddDb2ISeries()
.AddDotConnectOracle()
.AddDotConnectOracle12C()
.AddFirebird()
.AddHana()
.AddMySql4()
.AddMySql5()
.AddOracle()
.AddOracle12C()
.AddOracleManaged()
.AddOracle12CManaged()
.AddPostgres()
.AddPostgres92()
.AddRedshift()
.AddSqlAnywhere()
.AddSQLite()
.AddSqlServer()
.AddSqlServer2000()
.AddSqlServer2005()
.AddSqlServer2008()
.AddSqlServer2012()
.AddSqlServer2014()
.AddSqlServer2016()
.AddSqlServerCe());
return services;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace RocketFireWeb.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
namespace Bridge.Html5
{
/// <summary>
/// HTML Colors
/// </summary>
[External]
public static class HTMLColor
{
/// <summary>
/// rgb( 0, 0, 0)
/// </summary>
[InlineConst]
public const string Black = "black";
/// <summary>
/// rgb(192, 192, 192)
/// </summary>
[InlineConst]
public const string Silver = "silver";
/// <summary>
/// rgb(128, 128, 128)
/// </summary>
[InlineConst]
public const string Gray = "gray";
/// <summary>
/// rgb(255, 255, 255)
/// </summary>
[InlineConst]
public const string White = "white";
/// <summary>
/// rgb(128, 0, 0)
/// </summary>
[InlineConst]
public const string Maroon = "maroon";
/// <summary>
/// rgb(255, 0, 0)
/// </summary>
[InlineConst]
public const string Red = "red";
/// <summary>
/// rgb(128, 0, 128)
/// </summary>
[InlineConst]
public const string Purple = "purple";
/// <summary>
/// rgb(102, 51, 153)
/// </summary>
[InlineConst]
public const string RebeccaPurple = "rebeccapurple";
/// <summary>
/// rgb(255, 0, 255)
/// </summary>
[InlineConst]
public const string Fuchsia = "fuchsia";
/// <summary>
/// rgb( 0, 128, 0)
/// </summary>
[InlineConst]
public const string Green = "green";
/// <summary>
/// rgb( 0, 255, 0)
/// </summary>
[InlineConst]
public const string Lime = "lime";
/// <summary>
/// rgb(128, 128, 0)
/// </summary>
[InlineConst]
public const string Olive = "olive";
/// <summary>
/// rgb(255, 255, 0)
/// </summary>
[InlineConst]
public const string Yellow = "yellow";
/// <summary>
/// rgb( 0, 0, 128)
/// </summary>
[InlineConst]
public const string Navy = "navy";
/// <summary>
/// rgb( 0, 0, 255)
/// </summary>
[InlineConst]
public const string Blue = "blue";
/// <summary>
/// rgb( 0, 128, 128)
/// </summary>
[InlineConst]
public const string Teal = "teal";
/// <summary>
/// rgb( 0, 255, 255)
/// </summary>
[InlineConst]
public const string Aqua = "aqua";
/// <summary>
/// rgb(255, 165, 0)
/// </summary>
[InlineConst]
public const string Orange = "orange";
/// <summary>
/// rgb(240, 248, 255)
/// </summary>
[InlineConst]
public const string AliceBlue = "aliceblue";
/// <summary>
/// rgb(250, 235, 215)
/// </summary>
[InlineConst]
public const string AntiqueWhite = "antiquewhite";
/// <summary>
/// rgb(127, 255, 212)
/// </summary>
[InlineConst]
public const string Aquamarine = "aquamarine";
/// <summary>
/// rgb(240, 255, 255)
/// </summary>
[InlineConst]
public const string Azure = "azure";
/// <summary>
/// rgb(245, 245, 220)
/// </summary>
[InlineConst]
public const string Beige = "beige";
/// <summary>
/// rgb(255, 228, 196)
/// </summary>
[InlineConst]
public const string Bisque = "bisque";
/// <summary>
/// rgb(255, 235, 205)
/// </summary>
[InlineConst]
public const string BlanchedAlmond = "blanchedalmond";
/// <summary>
/// rgb(138, 43, 226)
/// </summary>
[InlineConst]
public const string BlueViolet = "blueviolet";
/// <summary>
/// rgb(165, 42, 42)
/// </summary>
[InlineConst]
public const string Brown = "brown";
/// <summary>
/// rgb(222, 184, 135)
/// </summary>
[InlineConst]
public const string BurlyWood = "burlywood";
/// <summary>
/// rgb( 95, 158, 160)
/// </summary>
[InlineConst]
public const string CadetBlue = "cadetblue";
/// <summary>
/// rgb(127, 255, 0)
/// </summary>
[InlineConst]
public const string Chartreuse = "chartreuse";
/// <summary>
/// rgb(210, 105, 30)
/// </summary>
[InlineConst]
public const string Chocolate = "chocolate";
/// <summary>
/// rgb(255, 127, 80)
/// </summary>
[InlineConst]
public const string Coral = "coral";
/// <summary>
/// rgb(100, 149, 237)
/// </summary>
[InlineConst]
public const string CornflowerBlue = "cornflowerblue";
/// <summary>
/// rgb(255, 248, 220)
/// </summary>
[InlineConst]
public const string Cornsilk = "cornsilk";
/// <summary>
/// rgb(220, 20, 60)
/// </summary>
[InlineConst]
public const string Crimson = "crimson";
/// <summary>
/// rgb(0, 255, 255)
/// </summary>
[InlineConst]
public const string Cyan = "cyan";
/// <summary>
/// rgb( 0, 0, 139)
/// </summary>
[InlineConst]
public const string DarkBlue = "darkblue";
/// <summary>
/// rgb( 0, 139, 139)
/// </summary>
[InlineConst]
public const string DarkCyan = "darkcyan";
/// <summary>
/// rgb(184, 134, 11)
/// </summary>
[InlineConst]
public const string DarkGoldenRod = "darkgoldenrod";
/// <summary>
/// rgb(169, 169, 169)
/// </summary>
[InlineConst]
public const string DarkGray = "darkgray";
/// <summary>
/// rgb( 0, 100, 0)
/// </summary>
[InlineConst]
public const string DarkGreen = "darkgreen";
/// <summary>
/// rgb(169, 169, 169)
/// </summary>
[InlineConst]
public const string DarkGrey = "darkgrey";
/// <summary>
/// rgb(189, 183, 107)
/// </summary>
[InlineConst]
public const string DarkKhaki = "darkkhaki";
/// <summary>
/// rgb(139, 0, 139)
/// </summary>
[InlineConst]
public const string DarkMagenta = "darkmagenta";
/// <summary>
/// rgb( 85, 107, 47)
/// </summary>
[InlineConst]
public const string DarkOliveGreen = "darkolivegreen";
/// <summary>
/// rgb(255, 140, 0)
/// </summary>
[InlineConst]
public const string DarkOrange = "darkorange";
/// <summary>
/// rgb(153, 50, 204)
/// </summary>
[InlineConst]
public const string DarkOrchid = "darkorchid";
/// <summary>
/// rgb(139, 0, 0)
/// </summary>
[InlineConst]
public const string DarkRed = "darkred";
/// <summary>
/// rgb(233, 150, 122)
/// </summary>
[InlineConst]
public const string DarkSalmon = "darksalmon";
/// <summary>
/// rgb(143, 188, 143)
/// </summary>
[InlineConst]
public const string DarkSeaGreen = "darkseagreen";
/// <summary>
/// rgb( 72, 61, 139)
/// </summary>
[InlineConst]
public const string DarkSlateBlue = "darkslateblue";
/// <summary>
/// rgb( 47, 79, 79)
/// </summary>
[InlineConst]
public const string DarkSlateGray = "darkslategray";
/// <summary>
/// rgb( 47, 79, 79)
/// </summary>
[InlineConst]
public const string DarkSlateGrey = "darkslategrey";
/// <summary>
/// rgb( 0, 206, 209)
/// </summary>
[InlineConst]
public const string DarkTurquoise = "darkturquoise";
/// <summary>
/// rgb(148, 0, 211)
/// </summary>
[InlineConst]
public const string DarkViolet = "darkviolet";
/// <summary>
/// rgb(255, 20, 147)
/// </summary>
[InlineConst]
public const string DeepPink = "deeppink";
/// <summary>
/// rgb( 0, 191, 255)
/// </summary>
[InlineConst]
public const string DeepSkyBlue = "deepskyblue";
/// <summary>
/// rgb(105, 105, 105)
/// </summary>
[InlineConst]
public const string DimGray = "dimgray";
/// <summary>
/// rgb(105, 105, 105)
/// </summary>
[InlineConst]
public const string DimGrey = "dimgrey";
/// <summary>
/// rgb( 30, 144, 255)
/// </summary>
[InlineConst]
public const string DodgerBlue = "dodgerblue";
/// <summary>
/// rgb(178, 34, 34)
/// </summary>
[InlineConst]
public const string FireBrick = "firebrick";
/// <summary>
/// rgb(255, 250, 240)
/// </summary>
[InlineConst]
public const string FloralWhite = "floralwhite";
/// <summary>
/// rgb( 34, 139, 34)
/// </summary>
[InlineConst]
public const string ForestGreen = "forestgreen";
/// <summary>
/// rgb(220, 220, 220)
/// </summary>
[InlineConst]
public const string Gainsboro = "gainsboro";
/// <summary>
/// rgb(248, 248, 255)
/// </summary>
[InlineConst]
public const string GhostWhite = "ghostwhite";
/// <summary>
/// rgb(255, 215, 0)
/// </summary>
[InlineConst]
public const string Gold = "gold";
/// <summary>
/// rgb(218, 165, 32)
/// </summary>
[InlineConst]
public const string GoldenRod = "goldenrod";
/// <summary>
/// rgb(173, 255, 47)
/// </summary>
[InlineConst]
public const string GreenYellow = "greenyellow";
/// <summary>
/// rgb(128, 128, 128)
/// </summary>
[InlineConst]
public const string Grey = "grey";
/// <summary>
/// rgb(240, 255, 240)
/// </summary>
[InlineConst]
public const string HoneyDew = "honeydew";
/// <summary>
/// rgb(255, 105, 180)
/// </summary>
[InlineConst]
public const string HotPink = "hotpink";
/// <summary>
/// rgb(205, 92, 92)
/// </summary>
[InlineConst]
public const string IndianRed = "indianred";
/// <summary>
/// rgb( 75, 0, 130)
/// </summary>
[InlineConst]
public const string Indigo = "indigo";
/// <summary>
/// rgb(255, 255, 240)
/// </summary>
[InlineConst]
public const string Ivory = "ivory";
/// <summary>
/// rgb(240, 230, 140)
/// </summary>
[InlineConst]
public const string Khaki = "khaki";
/// <summary>
/// rgb(230, 230, 250)
/// </summary>
[InlineConst]
public const string Lavender = "lavender";
/// <summary>
/// rgb(255, 240, 245)
/// </summary>
[InlineConst]
public const string LavenderBlush = "lavenderblush";
/// <summary>
/// rgb(124, 252, 0)
/// </summary>
[InlineConst]
public const string LawnGreen = "lawngreen";
/// <summary>
/// rgb(255, 250, 205)
/// </summary>
[InlineConst]
public const string LemonChiffon = "lemonchiffon";
/// <summary>
/// rgb(173, 216, 230)
/// </summary>
[InlineConst]
public const string LightBlue = "lightblue";
/// <summary>
/// rgb(240, 128, 128)
/// </summary>
[InlineConst]
public const string LightCoral = "lightcoral";
/// <summary>
/// rgb(224, 255, 255)
/// </summary>
[InlineConst]
public const string LightCyan = "lightcyan";
/// <summary>
/// rgb(250, 250, 210)
/// </summary>
[InlineConst]
public const string LightGoldenRodYellow = "lightgoldenrodyellow";
/// <summary>
/// rgb(211, 211, 211)
/// </summary>
[InlineConst]
public const string LightGray = "lightgray";
/// <summary>
/// rgb(211, 211, 211)
/// </summary>
[InlineConst]
public const string LightGrey = "lightgrey";
/// <summary>
/// rgb(144, 238, 144)
/// </summary>
[InlineConst]
public const string LightGreen = "lightgreen";
/// <summary>
/// rgb(255, 182, 193)
/// </summary>
[InlineConst]
public const string LightPink = "lightpink";
/// <summary>
/// rgb(255, 160, 122)
/// </summary>
[InlineConst]
public const string LightSalmon = "lightsalmon";
/// <summary>
/// rgb( 32, 178, 170)
/// </summary>
[InlineConst]
public const string LightSeaGreen = "lightseagreen";
/// <summary>
/// rgb(135, 206, 250)
/// </summary>
[InlineConst]
public const string LightSkyBlue = "lightskyblue";
/// <summary>
/// rgb(119, 136, 153)
/// </summary>
[InlineConst]
public const string LightSlateGray = "lightslategray";
/// <summary>
/// rgb(119, 136, 153)
/// </summary>
[InlineConst]
public const string LightSlateGrey = "lightslategrey";
/// <summary>
/// rgb(176, 196, 222)
/// </summary>
[InlineConst]
public const string LightSteelBlue = "lightsteelblue";
/// <summary>
/// rgb(255, 255, 224)
/// </summary>
[InlineConst]
public const string LightYellow = "lightyellow";
/// <summary>
/// rgb( 50, 205, 50)
/// </summary>
[InlineConst]
public const string LimeGreen = "limegreen";
/// <summary>
/// rgb(250, 240, 230)
/// </summary>
[InlineConst]
public const string Linen = "linen";
/// <summary>
/// rgb(255, 0, 255)
/// </summary>
[InlineConst]
public const string Magenta = "magenta";
/// <summary>
/// rgb(102, 205, 170)
/// </summary>
[InlineConst]
public const string MediumAquamarine = "mediumaquamarine";
/// <summary>
/// rgb( 0, 0, 205)
/// </summary>
[InlineConst]
public const string MediumBlue = "mediumblue";
/// <summary>
/// rgb(186, 85, 211)
/// </summary>
[InlineConst]
public const string MediumOrchid = "mediumorchid";
/// <summary>
/// rgb(147, 112, 219)
/// </summary>
[InlineConst]
public const string MediumPurple = "mediumpurple";
/// <summary>
/// rgb( 60, 179, 113)
/// </summary>
[InlineConst]
public const string MediumSeaGreen = "mediumseagreen";
/// <summary>
/// rgb(123, 104, 238)
/// </summary>
[InlineConst]
public const string MediumSlateBlue = "mediumslateblue";
/// <summary>
/// rgb( 0, 250, 154)
/// </summary>
[InlineConst]
public const string MediumSpringGreen = "mediumspringgreen";
/// <summary>
/// rgb( 72, 209, 204)
/// </summary>
[InlineConst]
public const string MediumTurquoise = "mediumturquoise";
/// <summary>
/// rgb(199, 21, 133)
/// </summary>
[InlineConst]
public const string MediumVioletRed = "mediumvioletred";
/// <summary>
/// rgb( 25, 25, 112)
/// </summary>
[InlineConst]
public const string MidnightBlue = "midnightblue";
/// <summary>
/// rgb(245, 255, 250)
/// </summary>
[InlineConst]
public const string MintCream = "mintcream";
/// <summary>
/// rgb(255, 228, 225)
/// </summary>
[InlineConst]
public const string MistyRose = "mistyrose";
/// <summary>
/// rgb(255, 228, 181)
/// </summary>
[InlineConst]
public const string Moccasin = "moccasin";
/// <summary>
/// rgb(255, 222, 173)
/// </summary>
[InlineConst]
public const string NavajoWhite = "navajowhite";
/// <summary>
/// rgb(253, 245, 230)
/// </summary>
[InlineConst]
public const string OldLace = "oldlace";
/// <summary>
/// rgb(107, 142, 35)
/// </summary>
[InlineConst]
public const string OliveDrab = "olivedrab";
/// <summary>
/// rgb(255, 69, 0)
/// </summary>
[InlineConst]
public const string OrangeRed = "orangered";
/// <summary>
/// rgb(218, 112, 214)
/// </summary>
[InlineConst]
public const string Orchid = "orchid";
/// <summary>
/// rgb(238, 232, 170)
/// </summary>
[InlineConst]
public const string PaleGoldenRod = "palegoldenrod";
/// <summary>
/// rgb(152, 251, 152)
/// </summary>
[InlineConst]
public const string PaleGreen = "palegreen";
/// <summary>
/// rgb(175, 238, 238)
/// </summary>
[InlineConst]
public const string PaleTurquoise = "paleturquoise";
/// <summary>
/// rgb(219, 112, 147)
/// </summary>
[InlineConst]
public const string PaleVioletRed = "palevioletred";
/// <summary>
/// rgb(255, 239, 213)
/// </summary>
[InlineConst]
public const string PapayaWhip = "papayawhip";
/// <summary>
/// rgb(255, 218, 185)
/// </summary>
[InlineConst]
public const string PeachPuff = "peachpuff";
/// <summary>
/// rgb(205, 133, 63)
/// </summary>
[InlineConst]
public const string Peru = "peru";
/// <summary>
/// rgb(255, 192, 203)
/// </summary>
[InlineConst]
public const string Pink = "pink";
/// <summary>
/// rgb(221, 160, 221)
/// </summary>
[InlineConst]
public const string Plum = "plum";
/// <summary>
/// rgb(176, 224, 230)
/// </summary>
[InlineConst]
public const string PowderBlue = "powderblue";
/// <summary>
/// rgb(188, 143, 143)
/// </summary>
[InlineConst]
public const string RosyBrown = "rosybrown";
/// <summary>
/// rgb( 65, 105, 225)
/// </summary>
[InlineConst]
public const string RoyalBlue = "royalblue";
/// <summary>
/// rgb(139, 69, 19)
/// </summary>
[InlineConst]
public const string SaddleBrown = "saddlebrown";
/// <summary>
/// rgb(250, 128, 114)
/// </summary>
[InlineConst]
public const string Salmon = "salmon";
/// <summary>
/// rgb(244, 164, 96)
/// </summary>
[InlineConst]
public const string SandyBrown = "sandybrown";
/// <summary>
/// rgb( 46, 139, 87)
/// </summary>
[InlineConst]
public const string SeaGreen = "seagreen";
/// <summary>
/// rgb(255, 245, 238)
/// </summary>
[InlineConst]
public const string SeaShell = "seashell";
/// <summary>
/// rgb(160, 82, 45)
/// </summary>
[InlineConst]
public const string Sienna = "sienna";
/// <summary>
/// rgb(135, 206, 235)
/// </summary>
[InlineConst]
public const string Skyblue = "skyblue";
/// <summary>
/// rgb(106, 90, 205)
/// </summary>
[InlineConst]
public const string SlateBlue = "slateblue";
/// <summary>
/// rgb(112, 128, 144)
/// </summary>
[InlineConst]
public const string SlateGray = "slategray";
/// <summary>
/// rgb(112, 128, 144)
/// </summary>
[InlineConst]
public const string SlateGrey = "slategrey";
/// <summary>
/// rgb(255, 250, 250)
/// </summary>
[InlineConst]
public const string Snow = "snow";
/// <summary>
/// rgb( 0, 255, 127)
/// </summary>
[InlineConst]
public const string SpringGreen = "springgreen";
/// <summary>
/// rgb( 70, 130, 180)
/// </summary>
[InlineConst]
public const string SteelBlue = "steelblue";
/// <summary>
/// rgb(210, 180, 140)
/// </summary>
[InlineConst]
public const string Tan = "tan";
/// <summary>
/// rgb(216, 191, 216)
/// </summary>
[InlineConst]
public const string Thistle = "thistle";
/// <summary>
/// rgb(255, 99, 71)
/// </summary>
[InlineConst]
public const string Tomato = "tomato";
/// <summary>
/// rgb( 64, 224, 208)
/// </summary>
[InlineConst]
public const string Turquoise = "turquoise";
/// <summary>
/// rgb(238, 130, 238)
/// </summary>
[InlineConst]
public const string Violet = "violet";
/// <summary>
/// rgb(245, 222, 179)
/// </summary>
[InlineConst]
public const string Wheat = "wheat";
/// <summary>
/// rgb(245, 245, 245)
/// </summary>
[InlineConst]
public const string WhiteSmoke = "whitesmoke";
/// <summary>
/// rgb(154, 205, 50)
/// </summary>
[InlineConst]
public const string YellowGreen = "yellowgreen";
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// (C) Copyright 2002 Franklin Wise
// (C) Copyright 2002 Rodrigo Moya
// (C) Copyright 2003 Daniel Morgan
// (C) Copyright 2003 Martin Willemoes Hansen
// (C) Copyright 2011 Xamarin Inc
//
// Copyright 2011 Xamarin Inc (http://www.xamarin.com)
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.ComponentModel;
using System.Data.SqlTypes;
using Xunit;
namespace System.Data.Tests
{
public class DataColumnTest
{
private DataTable _tbl;
public DataColumnTest()
{
_tbl = new DataTable();
}
[Fact]
public void Ctor()
{
string colName = "ColName";
DataColumn col = new DataColumn();
//These should all ctor without an exception
col = new DataColumn(colName);
col = new DataColumn(colName, typeof(int));
col = new DataColumn(colName, typeof(int), null);
col = new DataColumn(colName, typeof(int), null, MappingType.Attribute);
}
[Fact]
public void Constructor3_DataType_Null()
{
try
{
new DataColumn("ColName", null);
Assert.False(true);
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
// Never premise English.
// Assert.NotNull (ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("dataType", ex.ParamName);
}
}
[Fact]
public void AllowDBNull()
{
DataColumn col = new DataColumn("NullCheck", typeof(int));
_tbl.Columns.Add(col);
col.AllowDBNull = true;
_tbl.Rows.Add(_tbl.NewRow());
_tbl.Rows[0]["NullCheck"] = DBNull.Value;
try
{
col.AllowDBNull = false;
Assert.False(true);
}
catch (DataException)
{
}
}
[Fact]
public void AllowDBNull1()
{
DataTable tbl = _tbl;
tbl.Columns.Add("id", typeof(int));
tbl.Columns.Add("name", typeof(string));
tbl.PrimaryKey = new DataColumn[] { tbl.Columns["id"] };
tbl.Rows.Add(new object[] { 1, "RowState 1" });
tbl.Rows.Add(new object[] { 2, "RowState 2" });
tbl.Rows.Add(new object[] { 3, "RowState 3" });
tbl.AcceptChanges();
// Update Table with following changes: Row0 unmodified,
// Row1 modified, Row2 deleted, Row3 added, Row4 not-present.
tbl.Rows[1]["name"] = "Modify 2";
tbl.Rows[2].Delete();
DataColumn col = tbl.Columns["name"];
col.AllowDBNull = true;
col.AllowDBNull = false;
Assert.False(col.AllowDBNull);
}
[Fact]
public void AutoIncrement()
{
DataColumn col = new DataColumn("Auto", typeof(string));
col.AutoIncrement = true;
//Check for Correct Default Values
Assert.Equal(0L, col.AutoIncrementSeed);
Assert.Equal(1L, col.AutoIncrementStep);
//Check for auto type convert
Assert.Equal(typeof(int), col.DataType);
}
[Fact]
public void AutoIncrementExceptions()
{
DataColumn col = new DataColumn();
col.Expression = "SomeExpression";
//if computed column exception is thrown
try
{
col.AutoIncrement = true;
Assert.False(true);
}
catch (ArgumentException)
{
}
}
[Fact]
public void Caption()
{
DataColumn col = new DataColumn("ColName");
//Caption not set at this point
Assert.Equal(col.ColumnName, col.Caption);
//Set caption
col.Caption = "MyCaption";
Assert.Equal("MyCaption", col.Caption);
//Clear caption
col.Caption = null;
Assert.Equal(string.Empty, col.Caption);
}
[Fact]
public void DateTimeMode_Valid()
{
DataColumn col = new DataColumn("birthdate", typeof(DateTime));
col.DateTimeMode = DataSetDateTime.Local;
Assert.Equal(DataSetDateTime.Local, col.DateTimeMode);
col.DateTimeMode = DataSetDateTime.Unspecified;
Assert.Equal(DataSetDateTime.Unspecified, col.DateTimeMode);
col.DateTimeMode = DataSetDateTime.Utc;
Assert.Equal(DataSetDateTime.Utc, col.DateTimeMode);
}
[Fact]
public void DateTime_DataType_Invalid()
{
DataColumn col = new DataColumn("birthdate", typeof(int));
try
{
col.DateTimeMode = DataSetDateTime.Local;
Assert.False(true);
}
catch (InvalidOperationException ex)
{
// The DateTimeMode can be set only on DataColumns
// of type DateTime
Assert.Equal(typeof(InvalidOperationException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.True(ex.Message.IndexOf("DateTimeMode") != -1);
Assert.True(ex.Message.IndexOf("DateTime") != -1);
}
}
[Fact]
public void DateTimeMode_Invalid()
{
DataColumn col = new DataColumn("birthdate", typeof(DateTime));
try
{
col.DateTimeMode = (DataSetDateTime)666;
Assert.False(true);
}
catch (InvalidEnumArgumentException ex)
{
// The DataSetDateTime enumeration value, 666, is invalid
Assert.Equal(typeof(InvalidEnumArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.True(ex.Message.IndexOf("DataSetDateTime") != -1);
Assert.True(ex.Message.IndexOf("666") != -1);
Assert.Null(ex.ParamName);
}
}
[Fact]
public void ForColumnNameException()
{
DataColumn col = new DataColumn();
DataColumn col2 = new DataColumn();
DataColumn col3 = new DataColumn();
DataColumn col4 = new DataColumn();
col.ColumnName = "abc";
Assert.Equal("abc", col.ColumnName);
_tbl.Columns.Add(col);
//Duplicate name exception
try
{
col2.ColumnName = "abc";
_tbl.Columns.Add(col2);
Assert.Equal("abc", col2.ColumnName);
Assert.False(true);
}
catch (DuplicateNameException)
{
}
// Make sure case matters in duplicate checks
col3.ColumnName = "ABC";
_tbl.Columns.Add(col3);
}
[Fact]
public void DefaultValue()
{
DataTable tbl = new DataTable();
tbl.Columns.Add("MyCol", typeof(int));
//Set default Value if Autoincrement is true
tbl.Columns[0].AutoIncrement = true;
try
{
tbl.Columns[0].DefaultValue = 2;
Assert.False(true);
}
catch (ArgumentException)
{
}
tbl.Columns[0].AutoIncrement = false;
//Set default value to an incompatible datatype
try
{
tbl.Columns[0].DefaultValue = "hello";
Assert.False(true);
}
catch (FormatException)
{
}
}
[Fact]
public void Defaults1()
{
//Check for defaults - ColumnName not set at the beginning
DataTable table = new DataTable();
DataColumn column = new DataColumn();
Assert.Equal(string.Empty, column.ColumnName);
Assert.Equal(typeof(string), column.DataType);
table.Columns.Add(column);
Assert.Equal("Column1", table.Columns[0].ColumnName);
Assert.Equal(typeof(string), table.Columns[0].DataType);
DataRow row = table.NewRow();
table.Rows.Add(row);
DataRow dataRow = table.Rows[0];
object v = dataRow.ItemArray[0];
Assert.Equal(typeof(DBNull), v.GetType());
Assert.Equal(DBNull.Value, v);
}
[Fact]
public void Defaults2()
{
//Check for defaults - ColumnName set at the beginning
string blah = "Blah";
//Check for defaults - ColumnName not set at the beginning
DataTable table = new DataTable();
DataColumn column = new DataColumn(blah);
Assert.Equal(blah, column.ColumnName);
Assert.Equal(typeof(string), column.DataType);
table.Columns.Add(column);
Assert.Equal(blah, table.Columns[0].ColumnName);
Assert.Equal(typeof(string), table.Columns[0].DataType);
DataRow row = table.NewRow();
table.Rows.Add(row);
DataRow dataRow = table.Rows[0];
object v = dataRow.ItemArray[0];
Assert.Equal(typeof(DBNull), v.GetType());
Assert.Equal(DBNull.Value, v);
}
[Fact]
public void Defaults3()
{
DataColumn col = new DataColumn("foo", typeof(SqlBoolean));
Assert.Equal(SqlBoolean.Null, col.DefaultValue);
col.DefaultValue = SqlBoolean.True;
// FIXME: not working yet
//col.DefaultValue = true;
//Assert.Equal (SqlBoolean.True, col.DefaultValue);
col.DefaultValue = DBNull.Value;
Assert.Equal(SqlBoolean.Null, col.DefaultValue);
}
[Fact]
public void ChangeTypeAfterSettingDefaultValue()
{
Assert.Throws<DataException>(() =>
{
DataColumn col = new DataColumn("foo", typeof(SqlBoolean));
col.DefaultValue = true;
col.DataType = typeof(int);
});
}
[Fact]
public void ExpressionSubstringlimits()
{
DataTable t = new DataTable();
t.Columns.Add("aaa");
t.Rows.Add(new object[] { "xxx" });
DataColumn c = t.Columns.Add("bbb");
try
{
c.Expression = "SUBSTRING(aaa, 6000000000000000, 2)";
Assert.False(true);
}
catch (OverflowException)
{
}
}
[Fact]
public void ExpressionFunctions()
{
DataTable T = new DataTable("test");
DataColumn C = new DataColumn("name");
T.Columns.Add(C);
C = new DataColumn("age");
C.DataType = typeof(int);
T.Columns.Add(C);
C = new DataColumn("id");
C.Expression = "substring (name, 1, 3) + len (name) + age";
T.Columns.Add(C);
DataSet Set = new DataSet("TestSet");
Set.Tables.Add(T);
DataRow Row = null;
for (int i = 0; i < 100; i++)
{
Row = T.NewRow();
Row[0] = "human" + i;
Row[1] = i;
T.Rows.Add(Row);
}
Row = T.NewRow();
Row[0] = "h*an";
Row[1] = DBNull.Value;
T.Rows.Add(Row);
Assert.Equal("hum710", T.Rows[10][2]);
Assert.Equal("hum64", T.Rows[4][2]);
C = T.Columns[2];
C.Expression = "isnull (age, 'succ[[]]ess')";
Assert.Equal("succ[[]]ess", T.Rows[100][2]);
C.Expression = "iif (age = 24, 'hurrey', 'boo')";
Assert.Equal("boo", T.Rows[50][2]);
Assert.Equal("hurrey", T.Rows[24][2]);
C.Expression = "convert (age, 'System.Boolean')";
Assert.Equal(bool.TrueString, T.Rows[50][2]);
Assert.Equal(bool.FalseString, T.Rows[0][2]);
//
// Exceptions
//
try
{
// The expression contains undefined function call iff().
C.Expression = "iff (age = 24, 'hurrey', 'boo')";
Assert.False(true);
}
catch (EvaluateException)
{
}
catch (SyntaxErrorException)
{
}
//The following two cases fail on mono. MS.net evaluates the expression
//immediatly upon assignment. We don't do this yet hence we don't throw
//an exception at this point.
try
{
C.Expression = "iif (nimi = 24, 'hurrey', 'boo')";
Assert.False(true);
}
catch (EvaluateException e)
{
Assert.Equal(typeof(EvaluateException), e.GetType());
// Never premise English.
//Assert.Equal ("Cannot find column [nimi].", e.Message);
}
try
{
C.Expression = "iif (name = 24, 'hurrey', 'boo')";
Assert.False(true);
}
catch (EvaluateException e)
{
Assert.Equal(typeof(EvaluateException), e.GetType());
//AssertEquals ("DC41", "Cannot perform '=' operation on System.String and System.Int32.", e.Message);
}
try
{
C.Expression = "convert (age, Boolean)";
Assert.False(true);
}
catch (EvaluateException e)
{
Assert.Equal(typeof(EvaluateException), e.GetType());
// Never premise English.
//Assert.Equal ("Invalid type name 'Boolean'.", e.Message);
}
}
[Fact]
public void ExpressionAggregates()
{
DataTable T = new DataTable("test");
DataTable T2 = new DataTable("test2");
DataColumn C = new DataColumn("name");
T.Columns.Add(C);
C = new DataColumn("age");
C.DataType = typeof(int);
T.Columns.Add(C);
C = new DataColumn("childname");
T.Columns.Add(C);
C = new DataColumn("expression");
T.Columns.Add(C);
DataSet Set = new DataSet("TestSet");
Set.Tables.Add(T);
Set.Tables.Add(T2);
DataRow Row = null;
for (int i = 0; i < 100; i++)
{
Row = T.NewRow();
Row[0] = "human" + i;
Row[1] = i;
Row[2] = "child" + i;
T.Rows.Add(Row);
}
Row = T.NewRow();
Row[0] = "h*an";
Row[1] = DBNull.Value;
T.Rows.Add(Row);
C = new DataColumn("name");
T2.Columns.Add(C);
C = new DataColumn("age");
C.DataType = typeof(int);
T2.Columns.Add(C);
for (int i = 0; i < 100; i++)
{
Row = T2.NewRow();
Row[0] = "child" + i;
Row[1] = i;
T2.Rows.Add(Row);
Row = T2.NewRow();
Row[0] = "child" + i;
Row[1] = i - 2;
T2.Rows.Add(Row);
}
DataRelation Rel = new DataRelation("Rel", T.Columns[2], T2.Columns[0]);
Set.Relations.Add(Rel);
C = T.Columns[3];
C.Expression = "Sum (Child.age)";
Assert.Equal("-2", T.Rows[0][3]);
Assert.Equal("98", T.Rows[50][3]);
C.Expression = "Count (Child.age)";
Assert.Equal("2", T.Rows[0][3]);
Assert.Equal("2", T.Rows[60][3]);
C.Expression = "Avg (Child.age)";
Assert.Equal("-1", T.Rows[0][3]);
Assert.Equal("59", T.Rows[60][3]);
C.Expression = "Min (Child.age)";
Assert.Equal("-2", T.Rows[0][3]);
Assert.Equal("58", T.Rows[60][3]);
C.Expression = "Max (Child.age)";
Assert.Equal("0", T.Rows[0][3]);
Assert.Equal("60", T.Rows[60][3]);
C.Expression = "stdev (Child.age)";
Assert.Equal((1.4142135623731).ToString(T.Locale), T.Rows[0][3]);
Assert.Equal((1.4142135623731).ToString(T.Locale), T.Rows[60][3]);
C.Expression = "var (Child.age)";
Assert.Equal("2", T.Rows[0][3]);
Assert.Equal("2", T.Rows[60][3]);
}
[Fact]
public void ExpressionOperator()
{
DataTable T = new DataTable("test");
DataColumn C = new DataColumn("name");
T.Columns.Add(C);
C = new DataColumn("age");
C.DataType = typeof(int);
T.Columns.Add(C);
C = new DataColumn("id");
C.Expression = "substring (name, 1, 3) + len (name) + age";
T.Columns.Add(C);
DataSet Set = new DataSet("TestSet");
Set.Tables.Add(T);
DataRow Row = null;
for (int i = 0; i < 100; i++)
{
Row = T.NewRow();
Row[0] = "human" + i;
Row[1] = i;
T.Rows.Add(Row);
}
Row = T.NewRow();
Row[0] = "h*an";
Row[1] = DBNull.Value;
T.Rows.Add(Row);
C = T.Columns[2];
C.Expression = "age + 4";
Assert.Equal("68", T.Rows[64][2]);
C.Expression = "age - 4";
Assert.Equal("60", T.Rows[64][2]);
C.Expression = "age * 4";
Assert.Equal("256", T.Rows[64][2]);
C.Expression = "age / 4";
Assert.Equal("16", T.Rows[64][2]);
C.Expression = "age % 5";
Assert.Equal("4", T.Rows[64][2]);
C.Expression = "age in (5, 10, 15, 20, 25)";
Assert.Equal("False", T.Rows[64][2]);
Assert.Equal("True", T.Rows[25][2]);
C.Expression = "name like 'human1%'";
Assert.Equal("True", T.Rows[1][2]);
Assert.Equal("False", T.Rows[25][2]);
C.Expression = "age < 4";
Assert.Equal("False", T.Rows[4][2]);
Assert.Equal("True", T.Rows[3][2]);
C.Expression = "age <= 4";
Assert.Equal("True", T.Rows[4][2]);
Assert.Equal("False", T.Rows[5][2]);
C.Expression = "age > 4";
Assert.Equal("False", T.Rows[4][2]);
Assert.Equal("True", T.Rows[5][2]);
C.Expression = "age >= 4";
Assert.Equal("True", T.Rows[4][2]);
Assert.Equal("False", T.Rows[1][2]);
C.Expression = "age = 4";
Assert.Equal("True", T.Rows[4][2]);
Assert.Equal("False", T.Rows[1][2]);
C.Expression = "age <> 4";
Assert.Equal("False", T.Rows[4][2]);
Assert.Equal("True", T.Rows[1][2]);
}
[Fact]
public void SetMaxLengthException()
{
// Setting MaxLength on SimpleContent -> exception
DataSet ds = new DataSet("Example");
ds.Tables.Add("MyType");
ds.Tables["MyType"].Columns.Add(new DataColumn("Desc",
typeof(string), "", MappingType.SimpleContent));
try
{
ds.Tables["MyType"].Columns["Desc"].MaxLength = 32;
Assert.False(true);
}
catch (ArgumentException)
{
}
}
[Fact]
public void SetMaxLengthNegativeValue()
{
// however setting MaxLength on SimpleContent is OK
DataSet ds = new DataSet("Example");
ds.Tables.Add("MyType");
ds.Tables["MyType"].Columns.Add(
new DataColumn("Desc", typeof(string), "", MappingType.SimpleContent));
ds.Tables["MyType"].Columns["Desc"].MaxLength = -1;
}
[Fact]
public void AdditionToConstraintCollectionTest()
{
DataTable myTable = new DataTable("myTable");
DataColumn idCol = new DataColumn("id", typeof(int));
idCol.Unique = true;
myTable.Columns.Add(idCol);
ConstraintCollection cc = myTable.Constraints;
//cc just contains a single UniqueConstraint object.
UniqueConstraint uc = cc[0] as UniqueConstraint;
Assert.Equal("id", uc.Columns[0].ColumnName);
}
[Fact]
public void CalcStatisticalFunction_SingleElement()
{
DataTable table = new DataTable();
table.Columns.Add("test", typeof(int));
table.Rows.Add(new object[] { 0 });
table.Columns.Add("result_var", typeof(double), "var(test)");
table.Columns.Add("result_stdev", typeof(double), "stdev(test)");
// Check DBNull.Value is set as the result
Assert.Equal(typeof(DBNull), (table.Rows[0]["result_var"]).GetType());
Assert.Equal(typeof(DBNull), (table.Rows[0]["result_stdev"]).GetType());
}
[Fact]
public void Aggregation_CheckIfChangesDynamically()
{
DataTable table = new DataTable();
table.Columns.Add("test", typeof(int));
table.Columns.Add("result_count", typeof(int), "count(test)");
table.Columns.Add("result_sum", typeof(int), "sum(test)");
table.Columns.Add("result_avg", typeof(int), "avg(test)");
table.Columns.Add("result_max", typeof(int), "max(test)");
table.Columns.Add("result_min", typeof(int), "min(test)");
table.Columns.Add("result_var", typeof(double), "var(test)");
table.Columns.Add("result_stdev", typeof(double), "stdev(test)");
// Adding the rows after all the expression columns are added
table.Rows.Add(new object[] { 0 });
Assert.Equal(1, table.Rows[0]["result_count"]);
Assert.Equal(0, table.Rows[0]["result_sum"]);
Assert.Equal(0, table.Rows[0]["result_avg"]);
Assert.Equal(0, table.Rows[0]["result_max"]);
Assert.Equal(0, table.Rows[0]["result_min"]);
Assert.Equal(DBNull.Value, table.Rows[0]["result_var"]);
Assert.Equal(DBNull.Value, table.Rows[0]["result_stdev"]);
table.Rows.Add(new object[] { 1 });
table.Rows.Add(new object[] { -2 });
// Check if the aggregate columns are updated correctly
Assert.Equal(3, table.Rows[0]["result_count"]);
Assert.Equal(-1, table.Rows[0]["result_sum"]);
Assert.Equal(0, table.Rows[0]["result_avg"]);
Assert.Equal(1, table.Rows[0]["result_max"]);
Assert.Equal(-2, table.Rows[0]["result_min"]);
Assert.Equal((7.0 / 3), table.Rows[0]["result_var"]);
Assert.Equal(Math.Sqrt(7.0 / 3), table.Rows[0]["result_stdev"]);
}
[Fact]
public void Aggregation_CheckIfChangesDynamically_ChildTable()
{
DataSet ds = new DataSet();
DataTable table = new DataTable();
DataTable table2 = new DataTable();
ds.Tables.Add(table);
ds.Tables.Add(table2);
table.Columns.Add("test", typeof(int));
table2.Columns.Add("test", typeof(int));
table2.Columns.Add("val", typeof(int));
DataRelation rel = new DataRelation("rel", table.Columns[0], table2.Columns[0]);
ds.Relations.Add(rel);
table.Columns.Add("result_count", typeof(int), "count(child.test)");
table.Columns.Add("result_sum", typeof(int), "sum(child.test)");
table.Columns.Add("result_avg", typeof(int), "avg(child.test)");
table.Columns.Add("result_max", typeof(int), "max(child.test)");
table.Columns.Add("result_min", typeof(int), "min(child.test)");
table.Columns.Add("result_var", typeof(double), "var(child.test)");
table.Columns.Add("result_stdev", typeof(double), "stdev(child.test)");
table.Rows.Add(new object[] { 1 });
table.Rows.Add(new object[] { 2 });
// Add rows to the child table
for (int j = 0; j < 10; j++)
table2.Rows.Add(new object[] { 1, j });
// Check the values for the expression columns in parent table
Assert.Equal(10, table.Rows[0]["result_count"]);
Assert.Equal(0, table.Rows[1]["result_count"]);
Assert.Equal(10, table.Rows[0]["result_sum"]);
Assert.Equal(DBNull.Value, table.Rows[1]["result_sum"]);
Assert.Equal(1, table.Rows[0]["result_avg"]);
Assert.Equal(DBNull.Value, table.Rows[1]["result_avg"]);
Assert.Equal(1, table.Rows[0]["result_max"]);
Assert.Equal(DBNull.Value, table.Rows[1]["result_max"]);
Assert.Equal(1, table.Rows[0]["result_min"]);
Assert.Equal(DBNull.Value, table.Rows[1]["result_min"]);
Assert.Equal(0.0, table.Rows[0]["result_var"]);
Assert.Equal(DBNull.Value, table.Rows[1]["result_var"]);
Assert.Equal(0.0, table.Rows[0]["result_stdev"]);
Assert.Equal(DBNull.Value, table.Rows[1]["result_stdev"]);
}
[Fact]
public void Aggregation_TestForSyntaxErrors()
{
string error = "Aggregation functions cannot be called on Singular(Parent) Columns";
DataSet ds = new DataSet();
DataTable table1 = new DataTable();
DataTable table2 = new DataTable();
DataTable table3 = new DataTable();
table1.Columns.Add("test", typeof(int));
table2.Columns.Add("test", typeof(int));
table3.Columns.Add("test", typeof(int));
ds.Tables.Add(table1);
ds.Tables.Add(table2);
ds.Tables.Add(table3);
DataRelation rel1 = new DataRelation("rel1", table1.Columns[0], table2.Columns[0]);
DataRelation rel2 = new DataRelation("rel2", table2.Columns[0], table3.Columns[0]);
ds.Relations.Add(rel1);
ds.Relations.Add(rel2);
error = "Aggregation Functions cannot be called on Columns Returning Single Row (Parent Column)";
try
{
table2.Columns.Add("result", typeof(int), "count(parent.test)");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
error = "Numerical or Functions cannot be called on Columns Returning Multiple Rows (Child Column)";
// Check arithematic operator
try
{
table2.Columns.Add("result", typeof(int), "10*(child.test)");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
// Check rel operator
try
{
table2.Columns.Add("result", typeof(int), "(child.test) > 10");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
// Check predicates
try
{
table2.Columns.Add("result", typeof(int), "(child.test) IN (1,2,3)");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
try
{
table2.Columns.Add("result", typeof(int), "(child.test) LIKE 1");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
try
{
table2.Columns.Add("result", typeof(int), "(child.test) IS null");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
// Check Calc Functions
try
{
table2.Columns.Add("result", typeof(int), "isnull(child.test,10)");
Assert.False(true);
}
catch (SyntaxErrorException)
{
}
}
[Fact]
public void CheckValuesAfterRemovedFromCollection()
{
DataTable table = new DataTable("table1");
DataColumn col1 = new DataColumn("col1", typeof(int));
DataColumn col2 = new DataColumn("col2", typeof(int));
Assert.Equal(-1, col1.Ordinal);
Assert.Null(col1.Table);
table.Columns.Add(col1);
table.Columns.Add(col2);
Assert.Equal(0, col1.Ordinal);
Assert.Equal(table, col1.Table);
table.Columns.RemoveAt(0);
Assert.Equal(-1, col1.Ordinal);
Assert.Null(col1.Table);
table.Columns.Clear();
Assert.Equal(-1, col2.Ordinal);
Assert.Null(col2.Table);
}
[Fact]
public void B565616_NonIConvertibleTypeTest()
{
try
{
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
dt.Columns.Add("ID", typeof(string));
DataRow row = dt.NewRow();
row["ID"] = id;
Assert.Equal(id.ToString(), row["ID"]);
}
catch (InvalidCastException ex)
{
Assert.False(true);
}
}
[Fact]
public void B623451_SetOrdinalTest()
{
try
{
DataTable t = new DataTable();
t.Columns.Add("one");
t.Columns.Add("two");
t.Columns.Add("three");
Assert.Equal("one", t.Columns[0].ColumnName);
Assert.Equal("two", t.Columns[1].ColumnName);
Assert.Equal("three", t.Columns[2].ColumnName);
t.Columns["three"].SetOrdinal(0);
Assert.Equal("three", t.Columns[0].ColumnName);
Assert.Equal("one", t.Columns[1].ColumnName);
Assert.Equal("two", t.Columns[2].ColumnName);
t.Columns["three"].SetOrdinal(1);
Assert.Equal("one", t.Columns[0].ColumnName);
Assert.Equal("three", t.Columns[1].ColumnName);
Assert.Equal("two", t.Columns[2].ColumnName);
}
catch (ArgumentOutOfRangeException ex)
{
Assert.False(true);
}
}
[Fact]
public void Xamarin665()
{
var t = new DataTable();
var c1 = t.Columns.Add("c1");
var c2 = t.Columns.Add("c2");
c2.Expression = "TRIM(ISNULL(c1,' '))";
c2.Expression = "SUBSTRING(ISNULL(c1,' '), 1, 10)";
}
private DataColumn MakeColumn(string col, string test)
{
return new DataColumn()
{
ColumnName = col,
Expression = test
};
}
#if false
// Check Windows output for the row [0] value
[Fact]
public void NullStrings ()
{
var a = MakeColumn ("nullbar", "null+'bar'");
var b = MakeColumn ("barnull", "'bar'+null");
var c = MakeColumn ("foobar", "'foo'+'bar'");
var table = new DataTable();
table.Columns.Add(a);
table.Columns.Add(b);
table.Columns.Add(c);
var row = table.NewRow();
table.Rows.Add(row);
Assert.Equal (row [0], DBNull.Value);
Assert.Equal (row [1], DBNull.Value);
Assert.Equal (row [2], "foobar");
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Core;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Storage;
using Orleans.Streams.Core;
namespace Orleans.Streams
{
internal class PubSubGrainStateStorageFactory
{
private readonly IServiceProvider _serviceProvider;
private readonly ILoggerFactory _loggerFactory;
public PubSubGrainStateStorageFactory(IServiceProvider serviceProvider, ILoggerFactory loggerFactory)
{
_serviceProvider = serviceProvider;
_loggerFactory = loggerFactory;
}
public IStorage<PubSubGrainState> GetStorage(PubSubRendezvousGrain grain)
{
var logger = _loggerFactory.CreateLogger<PubSubGrainStateStorageFactory>();
var streamId = InternalStreamId.Parse(grain.GetGrainId().Key.ToString());
if (logger.IsEnabled(LogLevel.Debug))
logger.LogDebug($"Trying to find storage provider {streamId.ProviderName}");
var storage = _serviceProvider.GetServiceByName<IGrainStorage>(streamId.ProviderName);
if (storage == null)
{
if (logger.IsEnabled(LogLevel.Debug))
logger.LogDebug($"Fallback to storage provider {ProviderConstants.DEFAULT_PUBSUB_PROVIDER_NAME}");
storage = _serviceProvider.GetRequiredServiceByName<IGrainStorage>(ProviderConstants.DEFAULT_PUBSUB_PROVIDER_NAME);
}
return new StateStorageBridge<PubSubGrainState>(typeof(PubSubRendezvousGrain).FullName, grain.GrainReference, storage, _loggerFactory);
}
}
[Serializable]
[GenerateSerializer]
internal class PubSubGrainState
{
[Id(1)]
public HashSet<PubSubPublisherState> Producers { get; set; } = new HashSet<PubSubPublisherState>();
[Id(2)]
public HashSet<PubSubSubscriptionState> Consumers { get; set; } = new HashSet<PubSubSubscriptionState>();
}
[GrainType("pubsubrendezvous")]
internal class PubSubRendezvousGrain : Grain, IPubSubRendezvousGrain
{
private readonly ILogger logger;
private const bool DEBUG_PUB_SUB = false;
private static readonly CounterStatistic counterProducersAdded;
private static readonly CounterStatistic counterProducersRemoved;
private static readonly CounterStatistic counterProducersTotal;
private static readonly CounterStatistic counterConsumersAdded;
private static readonly CounterStatistic counterConsumersRemoved;
private static readonly CounterStatistic counterConsumersTotal;
private readonly PubSubGrainStateStorageFactory _storageFactory;
private IStorage<PubSubGrainState> _storage;
private PubSubGrainState State => _storage.State;
static PubSubRendezvousGrain()
{
counterProducersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_ADDED);
counterProducersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_REMOVED);
counterProducersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_TOTAL);
counterConsumersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_ADDED);
counterConsumersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_REMOVED);
counterConsumersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_TOTAL);
}
public PubSubRendezvousGrain(PubSubGrainStateStorageFactory storageFactory, ILogger<PubSubRendezvousGrain> logger)
{
_storageFactory = storageFactory;
this.logger = logger;
}
public override async Task OnActivateAsync(CancellationToken cancellationToken)
{
LogPubSubCounts("OnActivateAsync");
_storage = _storageFactory.GetStorage(this);
await ReadStateAsync();
}
public override Task OnDeactivateAsync(DeactivationReason reason, CancellationToken cancellationToken)
{
LogPubSubCounts("OnDeactivateAsync");
return Task.CompletedTask;
}
public async Task<ISet<PubSubSubscriptionState>> RegisterProducer(InternalStreamId streamId, IStreamProducerExtension streamProducer)
{
counterProducersAdded.Increment();
try
{
var publisherState = new PubSubPublisherState(streamId, streamProducer);
State.Producers.Add(publisherState);
LogPubSubCounts("RegisterProducer {0}", streamProducer);
await WriteStateAsync();
counterProducersTotal.Increment();
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_RegisterProducerFailed, $"Failed to register a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
return State.Consumers.Where(c => !c.IsFaulted).ToSet();
}
public async Task UnregisterProducer(InternalStreamId streamId, IStreamProducerExtension streamProducer)
{
counterProducersRemoved.Increment();
try
{
int numRemoved = State.Producers.RemoveWhere(s => s.Equals(streamId, streamProducer));
LogPubSubCounts("UnregisterProducer {0} NumRemoved={1}", streamProducer, numRemoved);
if (numRemoved > 0)
{
Task updateStorageTask = State.Producers.Count == 0 && State.Consumers.Count == 0
? ClearStateAsync() //State contains no producers or consumers, remove it from storage
: WriteStateAsync();
await updateStorageTask;
}
counterProducersTotal.DecrementBy(numRemoved);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_UnegisterProducerFailed,
$"Failed to unregister a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
if (State.Producers.Count == 0 && State.Consumers.Count == 0)
{
DeactivateOnIdle(); // No producers or consumers left now, so flag ourselves to expedite Deactivation
}
}
public async Task RegisterConsumer(
GuidId subscriptionId,
InternalStreamId streamId,
IStreamConsumerExtension streamConsumer,
string filterData)
{
counterConsumersAdded.Increment();
PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId));
if (pubSubState != null && pubSubState.IsFaulted)
throw new FaultedSubscriptionException(subscriptionId, streamId);
try
{
if (pubSubState == null)
{
pubSubState = new PubSubSubscriptionState(subscriptionId, streamId, streamConsumer);
State.Consumers.Add(pubSubState);
}
if (!string.IsNullOrWhiteSpace(filterData))
pubSubState.AddFilter(filterData);
LogPubSubCounts("RegisterConsumer {0}", streamConsumer);
await WriteStateAsync();
counterConsumersTotal.Increment();
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_RegisterConsumerFailed,
$"Failed to register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
int numProducers = State.Producers.Count;
if (numProducers <= 0)
return;
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug("Notifying {0} existing producer(s) about new consumer {1}. Producers={2}",
numProducers, streamConsumer, Utils.EnumerableToString(State.Producers));
// Notify producers about a new streamConsumer.
var tasks = new List<Task>();
var producers = State.Producers.ToList();
int initialProducerCount = producers.Count;
try
{
foreach (PubSubPublisherState producerState in producers)
{
tasks.Add(ExecuteProducerTask(producerState, producerState.Producer.AddSubscriber(subscriptionId, streamId, streamConsumer, filterData)));
}
Exception exception = null;
try
{
await Task.WhenAll(tasks);
}
catch (Exception exc)
{
exception = exc;
}
// if the number of producers has been changed, resave state.
if (State.Producers.Count != initialProducerCount)
{
await WriteStateAsync();
counterConsumersTotal.DecrementBy(initialProducerCount - State.Producers.Count);
}
if (exception != null)
{
throw exception;
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_RegisterConsumerFailed,
$"Failed to update producers while register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
}
private void RemoveProducer(PubSubPublisherState producer)
{
logger.Warn(ErrorCode.Stream_ProducerIsDead,
"Producer {0} on stream {1} is no longer active - permanently removing producer.",
producer, producer.Stream);
State.Producers.Remove(producer);
}
public async Task UnregisterConsumer(GuidId subscriptionId, InternalStreamId streamId)
{
counterConsumersRemoved.Increment();
try
{
int numRemoved = State.Consumers.RemoveWhere(c => c.Equals(subscriptionId));
LogPubSubCounts("UnregisterSubscription {0} NumRemoved={1}", subscriptionId, numRemoved);
if (await TryClearState())
{
// If state was cleared expedite Deactivation
DeactivateOnIdle();
}
else
{
if (numRemoved != 0)
{
await WriteStateAsync();
}
await NotifyProducersOfRemovedSubscription(subscriptionId, streamId);
}
counterConsumersTotal.DecrementBy(numRemoved);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_UnregisterConsumerFailed,
$"Failed to unregister a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
}
public Task<int> ProducerCount(InternalStreamId streamId)
{
return Task.FromResult(State.Producers.Count);
}
public Task<int> ConsumerCount(InternalStreamId streamId)
{
return Task.FromResult(GetConsumersForStream(streamId).Length);
}
public Task<PubSubSubscriptionState[]> DiagGetConsumers(InternalStreamId streamId)
{
return Task.FromResult(GetConsumersForStream(streamId));
}
private PubSubSubscriptionState[] GetConsumersForStream(InternalStreamId streamId)
{
return State.Consumers.Where(c => !c.IsFaulted && c.Stream.Equals(streamId)).ToArray();
}
private void LogPubSubCounts(string fmt, params object[] args)
{
if (logger.IsEnabled(LogLevel.Debug) || DEBUG_PUB_SUB)
{
int numProducers = 0;
int numConsumers = 0;
if (State?.Producers != null)
numProducers = State.Producers.Count;
if (State?.Consumers != null)
numConsumers = State.Consumers.Count;
string when = args != null && args.Length != 0 ? string.Format(fmt, args) : fmt;
logger.Info("{0}. Now have total of {1} producers and {2} consumers. All Consumers = {3}, All Producers = {4}",
when, numProducers, numConsumers, Utils.EnumerableToString(State?.Consumers), Utils.EnumerableToString(State?.Producers));
}
}
// Check that what we have cached locally matches what is in the persistent table.
public async Task Validate()
{
var captureProducers = State.Producers;
var captureConsumers = State.Consumers;
await ReadStateAsync();
if (captureProducers.Count != State.Producers.Count)
{
throw new OrleansException(
$"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers.Count={captureProducers.Count}, State.Producers.Count={State.Producers.Count}");
}
if (captureProducers.Any(producer => !State.Producers.Contains(producer)))
{
throw new OrleansException(
$"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers={Utils.EnumerableToString(captureProducers)}, State.Producers={Utils.EnumerableToString(State.Producers)}");
}
if (captureConsumers.Count != State.Consumers.Count)
{
LogPubSubCounts("Validate: Consumer count mismatch");
throw new OrleansException(
$"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers.Count={captureConsumers.Count}, State.Consumers.Count={State.Consumers.Count}");
}
if (captureConsumers.Any(consumer => !State.Consumers.Contains(consumer)))
{
throw new OrleansException(
$"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers={Utils.EnumerableToString(captureConsumers)}, State.Consumers={Utils.EnumerableToString(State.Consumers)}");
}
}
public Task<List<StreamSubscription>> GetAllSubscriptions(InternalStreamId streamId, IStreamConsumerExtension streamConsumer)
{
var grainRef = streamConsumer as GrainReference;
if (grainRef != null)
{
List<StreamSubscription> subscriptions =
State.Consumers.Where(c => !c.IsFaulted && c.Consumer.Equals(streamConsumer))
.Select(
c =>
new StreamSubscription(c.SubscriptionId.Guid, streamId.ProviderName, streamId,
grainRef.GrainId)).ToList();
return Task.FromResult(subscriptions);
}
else
{
List<StreamSubscription> subscriptions =
State.Consumers.Where(c => !c.IsFaulted)
.Select(
c =>
new StreamSubscription(c.SubscriptionId.Guid, streamId.ProviderName, streamId,
c.consumerReference.GrainId)).ToList();
return Task.FromResult(subscriptions);
}
}
public async Task FaultSubscription(GuidId subscriptionId)
{
PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId));
if (pubSubState == null)
{
return;
}
try
{
pubSubState.Fault();
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Setting subscription {0} to a faulted state.", subscriptionId.Guid);
await WriteStateAsync();
await NotifyProducersOfRemovedSubscription(pubSubState.SubscriptionId, pubSubState.Stream);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_SetSubscriptionToFaultedFailed,
$"Failed to set subscription state to faulted. SubscriptionId {subscriptionId}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
}
private async Task NotifyProducersOfRemovedSubscription(GuidId subscriptionId, InternalStreamId streamId)
{
int numProducersBeforeNotify = State.Producers.Count;
if (numProducersBeforeNotify > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Notifying {0} existing producers about unregistered consumer.", numProducersBeforeNotify);
// Notify producers about unregistered consumer.
List<Task> tasks = State.Producers
.Select(producerState => ExecuteProducerTask(producerState, producerState.Producer.RemoveSubscriber(subscriptionId, streamId)))
.ToList();
await Task.WhenAll(tasks);
//if producers got removed
if (State.Producers.Count < numProducersBeforeNotify)
await this.WriteStateAsync();
}
}
/// <summary>
/// Try clear state will only clear the state if there are no producers or consumers.
/// </summary>
/// <returns></returns>
private async Task<bool> TryClearState()
{
if (State.Producers.Count == 0 && State.Consumers.Count == 0) // + we already know that numProducers == 0 from previous if-clause
{
await ClearStateAsync(); //State contains no producers or consumers, remove it from storage
return true;
}
return false;
}
private async Task ExecuteProducerTask(PubSubPublisherState producer, Task producerTask)
{
try
{
await producerTask;
}
catch (GrainExtensionNotInstalledException)
{
RemoveProducer(producer);
}
catch (ClientNotAvailableException)
{
RemoveProducer(producer);
}
catch (OrleansMessageRejectionException)
{
var grainRef = producer.Producer as GrainReference;
// if producer is a system target on and unavailable silo, remove it.
if (grainRef == null || grainRef.GrainId.IsSystemTarget())
{
RemoveProducer(producer);
}
else // otherwise, throw
{
throw;
}
}
}
private Task ReadStateAsync() => _storage.ReadStateAsync();
private Task WriteStateAsync() => _storage.WriteStateAsync();
private Task ClearStateAsync() => _storage.ClearStateAsync();
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Moq;
using Xunit;
namespace Microsoft.Diagnostics.EventFlow.ServiceFabric.Tests
{
public class ServiceFabricTests
{
[Fact]
public void ConfigurationIsNotChangedIfNoValueReferencesExist()
{
var healthReporterMock = new Mock<IHealthReporter>();
var configurationSource = new Dictionary<string, string>()
{
["alpha"] = "Alpha",
["bravo:charlie"] = "BravoCharlie"
};
IConfigurationRoot configuration = (new ConfigurationBuilder()).AddInMemoryCollection(configurationSource).Build();
ServiceFabricDiagnosticPipelineFactory.ApplyFabricConfigurationOverrides(configuration, "unused-configuration-package-path", healthReporterMock.Object);
string verificationError;
bool isOK = VerifyConfguration(configuration.AsEnumerable(), configurationSource, out verificationError);
Assert.True(isOK, verificationError);
healthReporterMock.Verify(o => o.ReportProblem(It.IsAny<string>(), It.IsAny<string>()), Times.Never());
healthReporterMock.Verify(o => o.ReportWarning(It.IsAny<string>(), It.IsAny<string>()), Times.Never());
}
[Fact]
public void ConfigurationIsNotChangedIfValueReferenceNotResolved()
{
var healthReporterMock = new Mock<IHealthReporter>();
var configurationSource = new Dictionary<string, string>()
{
["alpha"] = "Alpha",
["bravo:charlie"] = "BravoCharlie",
["delta"] = "servicefabric:/bravo/foxtrot"
};
IConfigurationRoot configuration = (new ConfigurationBuilder()).AddInMemoryCollection(configurationSource).Build();
ServiceFabricDiagnosticPipelineFactory.ApplyFabricConfigurationOverrides(configuration, "unused-configuration-package-path", healthReporterMock.Object);
string verificationError;
bool isOK = VerifyConfguration(configuration.AsEnumerable(), configurationSource, out verificationError);
Assert.True(isOK, verificationError);
healthReporterMock.Verify(o => o.ReportWarning(
It.Is<string>(s => s.Contains("no corresponding configuration value was found")),
It.Is<string>(s => s == EventFlowContextIdentifiers.Configuration)),
Times.Exactly(1));
}
[Fact]
public void ConfigurationUpdatedWithValueReferences()
{
var healthReporterMock = new Mock<IHealthReporter>();
var configurationSource = new Dictionary<string, string>()
{
["alpha"] = "Alpha",
["bravo:charlie"] = "BravoCharlie",
["delta"] = "servicefabric:/bravo/charlie"
};
IConfigurationRoot configuration = (new ConfigurationBuilder()).AddInMemoryCollection(configurationSource).Build();
ServiceFabricDiagnosticPipelineFactory.ApplyFabricConfigurationOverrides(configuration, "unused-configuration-package-path", healthReporterMock.Object);
healthReporterMock.Verify(o => o.ReportProblem(It.IsAny<string>(), It.IsAny<string>()), Times.Never());
healthReporterMock.Verify(o => o.ReportWarning(It.IsAny<string>(), It.IsAny<string>()), Times.Never());
string verificationError;
bool isOK = VerifyConfguration(configuration.AsEnumerable(), configurationSource, out verificationError);
Assert.False(isOK, verificationError);
configurationSource["delta"] = "BravoCharlie";
isOK = VerifyConfguration(configuration.AsEnumerable(), configurationSource, out verificationError);
Assert.True(isOK, verificationError);
}
[Theory]
[InlineData("charlie.delta")]
[InlineData("charlie-delta")]
[InlineData("charlie_delta")]
[InlineData("charlie:delta")]
[InlineData("charlie/delta")]
[InlineData("charlie#delta")]
public void ReferencedKeyCanContainComplexKey(string complexKey)
{
var healthReporterMock = new Mock<IHealthReporter>();
var configurationSource = new Dictionary<string, string>()
{
["alpha"] = "Alpha",
[$"bravo:{complexKey}"] = "Delta",
["delta"] = $"servicefabric:/bravo/{complexKey}"
};
IConfigurationRoot configuration = (new ConfigurationBuilder()).AddInMemoryCollection(configurationSource).Build();
ServiceFabricDiagnosticPipelineFactory.ApplyFabricConfigurationOverrides(configuration, "unused-configuration-package-path", healthReporterMock.Object);
healthReporterMock.Verify(o => o.ReportProblem(It.IsAny<string>(), It.IsAny<string>()), Times.Never());
healthReporterMock.Verify(o => o.ReportWarning(It.IsAny<string>(), It.IsAny<string>()), Times.Never());
string verificationError;
bool isOK = VerifyConfguration(configuration.AsEnumerable(), configurationSource, out verificationError);
Assert.False(isOK, verificationError);
configurationSource["delta"] = "Delta";
isOK = VerifyConfguration(configuration.AsEnumerable(), configurationSource, out verificationError);
Assert.True(isOK, verificationError);
}
[Fact]
public void ReferencedValueCanBeEmpty()
{
var healthReporterMock = new Mock<IHealthReporter>();
var configurationSource = new Dictionary<string, string>()
{
["alpha"] = "Alpha",
["bravo:charlie"] = "",
["delta"] = "servicefabric:/bravo/charlie"
};
IConfigurationRoot configuration = (new ConfigurationBuilder()).AddInMemoryCollection(configurationSource).Build();
ServiceFabricDiagnosticPipelineFactory.ApplyFabricConfigurationOverrides(configuration, "unused-configuration-package-path", healthReporterMock.Object);
healthReporterMock.Verify(o => o.ReportProblem(It.IsAny<string>(), It.IsAny<string>()), Times.Never());
healthReporterMock.Verify(o => o.ReportWarning(It.IsAny<string>(), It.IsAny<string>()), Times.Never());
string verificationError;
bool isOK = VerifyConfguration(configuration.AsEnumerable(), configurationSource, out verificationError);
Assert.False(isOK, verificationError);
configurationSource["delta"] = "";
isOK = VerifyConfguration(configuration.AsEnumerable(), configurationSource, out verificationError);
Assert.True(isOK, verificationError);
}
[Fact]
public void ConfigurationIsNotChangedIfFileReferenceIsEmpty()
{
var healthReporterMock = new Mock<IHealthReporter>();
var configurationSource = new Dictionary<string, string>()
{
["alpha"] = "Alpha",
["bravo:charlie"] = "BravoCharlie",
["delta"] = "servicefabricfile:/ "
};
IConfigurationRoot configuration = (new ConfigurationBuilder()).AddInMemoryCollection(configurationSource).Build();
ServiceFabricDiagnosticPipelineFactory.ApplyFabricConfigurationOverrides(configuration, "unused-configuration-package-path", healthReporterMock.Object);
string verificationError;
bool isOK = VerifyConfguration(configuration.AsEnumerable(), configurationSource, out verificationError);
Assert.True(isOK, verificationError);
healthReporterMock.Verify(o => o.ReportWarning(
It.Is<string>(s => s.Contains("but the file name part is missing")),
It.Is<string>(s => s == EventFlowContextIdentifiers.Configuration)),
Times.Exactly(1));
}
[Fact]
public void ConfigurationUpdatedWithFileReferences()
{
var healthReporterMock = new Mock<IHealthReporter>();
var configurationSource = new Dictionary<string, string>()
{
["alpha"] = "Alpha",
["bravo:charlie"] = "BravoCharlie",
["delta"] = "servicefabricfile:/ApplicationInsights.config"
};
IConfigurationRoot configuration = (new ConfigurationBuilder()).AddInMemoryCollection(configurationSource).Build();
ServiceFabricDiagnosticPipelineFactory.ApplyFabricConfigurationOverrides(configuration, @"C:\FabricCluster\work\Config\AppInstance00", healthReporterMock.Object);
healthReporterMock.Verify(o => o.ReportProblem(It.IsAny<string>(), It.IsAny<string>()), Times.Never());
healthReporterMock.Verify(o => o.ReportWarning(It.IsAny<string>(), It.IsAny<string>()), Times.Never());
string verificationError;
bool isOK = VerifyConfguration(configuration.AsEnumerable(), configurationSource, out verificationError);
Assert.False(isOK, verificationError);
configurationSource["delta"] = @"C:\FabricCluster\work\Config\AppInstance00\ApplicationInsights.config";
isOK = VerifyConfguration(configuration.AsEnumerable(), configurationSource, out verificationError);
Assert.True(isOK, verificationError);
}
private bool VerifyConfguration<TKey, TValue>(
IEnumerable<KeyValuePair<TKey, TValue>> configuration,
IDictionary<TKey, TValue> expected,
out string verificationError,
IEqualityComparer<TValue> valueComparer = null)
{
verificationError = string.Empty;
var keyComparer = EqualityComparer<TKey>.Default;
valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
foreach (var kvp in expected)
{
KeyValuePair<TKey, TValue>? correspondingPair = configuration.Where(otherKvp => keyComparer.Equals(otherKvp.Key, kvp.Key))
.Cast<KeyValuePair<TKey, TValue>?>()
.FirstOrDefault();
if (correspondingPair == null)
{
verificationError = $"Configuration is missing expected key '{kvp.Key}'";
return false;
}
if (!valueComparer.Equals(kvp.Value, correspondingPair.Value.Value))
{
verificationError = $"The value for key '{kvp.Key}' was expected to be '{kvp.Value}' but instead it is '{correspondingPair.Value.Value}'";
return false;
}
}
return true;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IdentityModel.Claims;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Xml;
class PeerSecurityManager
{
PeerAuthenticationMode authenticationMode;
bool enableSigning;
internal string password;
DuplexSecurityProtocolFactory securityProtocolFactory;
// Double-checked locking pattern requires volatile for read/write synchronization
volatile byte[] authenticatorHash;
object thisLock;
//public EventHandler OnNeighborOpened;
public EventHandler OnNeighborAuthenticated;
string meshId = String.Empty;
ChannelProtectionRequirements protection;
PeerSecurityCredentialsManager credManager;
SecurityTokenManager tokenManager;
// Double-checked locking pattern requires volatile for read/write synchronization
volatile SelfSignedCertificate ssc;
XmlDictionaryReaderQuotas readerQuotas;
// Audit
ServiceSecurityAuditBehavior auditBehavior;
PeerSecurityManager(PeerAuthenticationMode authMode, bool signing)
{
this.authenticationMode = authMode;
this.enableSigning = signing;
thisLock = new object();
}
public PeerAuthenticationMode AuthenticationMode
{
get
{
return authenticationMode;
}
}
public string Password
{
get
{
return password;
}
}
public X509Certificate2 SelfCert
{
get
{
return credManager.Certificate;
}
}
public bool MessageAuthentication
{
get
{
return this.enableSigning;
}
}
internal string MeshId
{
get
{
return this.meshId;
}
set
{
this.meshId = value;
}
}
internal SelfSignedCertificate GetCertificate()
{
if (this.ssc == null)
{
lock (ThisLock)
{
if (ssc == null)
ssc = SelfSignedCertificate.Create("CN=" + Guid.NewGuid().ToString(), this.Password);
}
}
return ssc;
}
object ThisLock
{
get { return thisLock; }
}
static PeerSecurityCredentialsManager GetCredentialsManager(PeerAuthenticationMode mode, bool signing, BindingContext context)
{
if (mode == PeerAuthenticationMode.None && !signing)
return null;
ClientCredentials clientCredentials = context.BindingParameters.Find<ClientCredentials>();
if (clientCredentials != null)
{
return new PeerSecurityCredentialsManager(clientCredentials.Peer, mode, signing);
}
ServiceCredentials serviceCredentials = context.BindingParameters.Find<ServiceCredentials>();
if (serviceCredentials != null)
{
return new PeerSecurityCredentialsManager(serviceCredentials.Peer, mode, signing);
}
SecurityCredentialsManager credman = context.BindingParameters.Find<SecurityCredentialsManager>();
if (credman == null)
{
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Credentials);
}
return new PeerSecurityCredentialsManager(credman.CreateSecurityTokenManager(), mode, signing);
}
static void Convert(PeerSecuritySettings security, out PeerAuthenticationMode authMode, out bool signing)
{
authMode = PeerAuthenticationMode.None;
signing = false;
if (security.Mode == SecurityMode.Transport || security.Mode == SecurityMode.TransportWithMessageCredential)
{
switch (security.Transport.CredentialType)
{
case PeerTransportCredentialType.Password:
authMode = PeerAuthenticationMode.Password;
break;
case PeerTransportCredentialType.Certificate:
authMode = PeerAuthenticationMode.MutualCertificate;
break;
}
}
if (security.Mode == SecurityMode.Message || security.Mode == SecurityMode.TransportWithMessageCredential)
{
signing = true;
}
}
static public PeerSecurityManager Create(PeerSecuritySettings security, BindingContext context, XmlDictionaryReaderQuotas readerQuotas)
{
PeerAuthenticationMode authMode = PeerAuthenticationMode.None;
bool signing = false;
Convert(security, out authMode, out signing);
return Create(authMode, signing, context, readerQuotas);
}
static public PeerSecurityManager Create(PeerAuthenticationMode authenticationMode, bool signMessages, BindingContext context, XmlDictionaryReaderQuotas readerQuotas)
{
if (authenticationMode == PeerAuthenticationMode.None && !signMessages)
return CreateDummy();
// test FIPS mode
if (authenticationMode == PeerAuthenticationMode.Password)
{
try
{
using (HMACSHA256 algo = new HMACSHA256())
{
using (SHA256Managed sha = new SHA256Managed()) { }
}
}
catch (InvalidOperationException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
PeerExceptionHelper.ThrowInvalidOperation_InsufficientCryptoSupport(e);
}
}
ChannelProtectionRequirements reqs = context.BindingParameters.Find<ChannelProtectionRequirements>();
PeerSecurityCredentialsManager credman = GetCredentialsManager(authenticationMode, signMessages, context);
if (credman.Credential != null)
{
//for compatibility with existing code:
ValidateCredentialSettings(authenticationMode, signMessages, credman.Credential);
}
PeerSecurityManager manager = Create(authenticationMode, signMessages, credman, reqs, readerQuotas);
credman.Parent = manager;
manager.ApplyAuditBehaviorSettings(context);
return manager;
}
static void ValidateCredentialSettings(PeerAuthenticationMode authenticationMode, bool signMessages, PeerCredential credential)
{
X509CertificateValidator validator;
if (authenticationMode == PeerAuthenticationMode.None && !signMessages)
return;
switch (authenticationMode)
{
case PeerAuthenticationMode.Password:
{
if (String.IsNullOrEmpty(credential.MeshPassword))
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Password);
}
break;
case PeerAuthenticationMode.MutualCertificate:
{
if (credential.Certificate == null)
{
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Certificate);
}
if (!credential.PeerAuthentication.TryGetCertificateValidator(out validator))
{
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.PeerAuthentication);
}
}
break;
}
if (signMessages)
{
if (!credential.MessageSenderAuthentication.TryGetCertificateValidator(out validator))
{
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication);
}
}
}
void ApplyAuditBehaviorSettings(BindingContext context)
{
ServiceSecurityAuditBehavior auditBehavior = context.BindingParameters.Find<ServiceSecurityAuditBehavior>();
if (auditBehavior != null)
{
this.auditBehavior = auditBehavior.Clone();
}
else
{
this.auditBehavior = new ServiceSecurityAuditBehavior();
}
}
public void ApplyServiceSecurity(ServiceDescription description)
{
if (this.AuthenticationMode == PeerAuthenticationMode.None)
return;
description.Behaviors.Add(credManager.CloneForTransport());
}
internal static PeerSecurityManager CreateDummy()
{
PeerSecurityManager manager = new PeerSecurityManager(PeerAuthenticationMode.None, false);
return manager;
}
static public PeerSecurityManager Create(PeerAuthenticationMode authenticationMode, bool messageAuthentication, PeerSecurityCredentialsManager credman, ChannelProtectionRequirements reqs, XmlDictionaryReaderQuotas readerQuotas)
{
PeerSecurityManager manager = null;
X509CertificateValidator connectionValidator = null;
X509CertificateValidator messageValidator = null;
PeerCredential credential = credman.Credential;
if (null == credential && credman == null)
{
if (authenticationMode != PeerAuthenticationMode.None || messageAuthentication)
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Credentials);
//create one that doesnt have any credentials in it.
return CreateDummy();
}
manager = new PeerSecurityManager(authenticationMode, messageAuthentication);
manager.credManager = credman;
manager.password = credman.Password;
manager.readerQuotas = readerQuotas;
if (reqs != null)
{
manager.protection = new ChannelProtectionRequirements(reqs);
}
manager.tokenManager = credman.CreateSecurityTokenManager();
if (credential == null)
return manager;
switch (authenticationMode)
{
case PeerAuthenticationMode.None:
break;
case PeerAuthenticationMode.Password:
{
manager.password = credential.MeshPassword;
if (String.IsNullOrEmpty(manager.credManager.Password))
{
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Password);
}
connectionValidator = X509CertificateValidator.None;
}
break;
case PeerAuthenticationMode.MutualCertificate:
{
if (manager.credManager.Certificate == null)
{
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Certificate);
}
if (!credential.PeerAuthentication.TryGetCertificateValidator(out connectionValidator))
{
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.PeerAuthentication);
}
}
break;
}
if (messageAuthentication)
{
if (credential.MessageSenderAuthentication != null)
{
if (!credential.MessageSenderAuthentication.TryGetCertificateValidator(out messageValidator))
{
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication);
}
}
else
{
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication);
}
}
return manager;
}
void ApplySigningRequirements(ScopedMessagePartSpecification spec)
{
//following are the headers that we add and want signed.
MessagePartSpecification partSpec = new MessagePartSpecification(
new XmlQualifiedName(PeerStrings.Via, PeerStrings.Namespace),
new XmlQualifiedName(PeerOperationNames.Flood, PeerStrings.Namespace),
new XmlQualifiedName(PeerOperationNames.PeerTo, PeerStrings.Namespace),
new XmlQualifiedName(PeerStrings.MessageId, PeerStrings.Namespace));
foreach (string action in spec.Actions)
{
spec.AddParts(partSpec, action);
}
spec.AddParts(partSpec, MessageHeaders.WildcardAction);
}
public void Open()
{
CreateSecurityProtocolFactory();
}
void CreateSecurityProtocolFactory()
{
SecurityProtocolFactory incomingProtocolFactory;
SecurityProtocolFactory outgoingProtocolFactory;
ChannelProtectionRequirements protectionRequirements;
lock (ThisLock)
{
if (null != securityProtocolFactory)
return;
TimeoutHelper timeoutHelper = new TimeoutHelper(ServiceDefaults.SendTimeout);
if (!enableSigning)
{
outgoingProtocolFactory = new PeerDoNothingSecurityProtocolFactory();
incomingProtocolFactory = new PeerDoNothingSecurityProtocolFactory();
}
else
{
X509Certificate2 cert = credManager.Certificate;
if (cert != null)
{
SecurityBindingElement securityBindingElement = SecurityBindingElement.CreateCertificateSignatureBindingElement();
securityBindingElement.ReaderQuotas = this.readerQuotas;
BindingParameterCollection bpc = new BindingParameterCollection();
if (protection == null)
{
protectionRequirements = new ChannelProtectionRequirements();
}
else
{
protectionRequirements = new ChannelProtectionRequirements(protection);
}
ApplySigningRequirements(protectionRequirements.IncomingSignatureParts);
ApplySigningRequirements(protectionRequirements.OutgoingSignatureParts);
bpc.Add(protectionRequirements);
bpc.Add(this.auditBehavior);
bpc.Add(credManager);
BindingContext context = new BindingContext(new CustomBinding(securityBindingElement), bpc);
outgoingProtocolFactory = securityBindingElement.CreateSecurityProtocolFactory<IOutputChannel>(context, credManager, false, null);
}
else
{
outgoingProtocolFactory = new PeerDoNothingSecurityProtocolFactory();
}
SecurityTokenResolver resolver;
X509SecurityTokenAuthenticator auth = tokenManager.CreateSecurityTokenAuthenticator(PeerSecurityCredentialsManager.PeerClientSecurityTokenManager.CreateRequirement(SecurityTokenTypes.X509Certificate, true), out resolver) as X509SecurityTokenAuthenticator;
if (auth != null)
{
SecurityBindingElement securityBindingElement = SecurityBindingElement.CreateCertificateSignatureBindingElement();
securityBindingElement.ReaderQuotas = this.readerQuotas;
BindingParameterCollection bpc = new BindingParameterCollection();
if (protection == null)
{
protectionRequirements = new ChannelProtectionRequirements();
}
else
{
protectionRequirements = new ChannelProtectionRequirements(protection);
}
ApplySigningRequirements(protectionRequirements.IncomingSignatureParts);
ApplySigningRequirements(protectionRequirements.OutgoingSignatureParts);
bpc.Add(protectionRequirements);
bpc.Add(this.auditBehavior);
bpc.Add(credManager);
BindingContext context = new BindingContext(new CustomBinding(securityBindingElement), bpc);
incomingProtocolFactory = securityBindingElement.CreateSecurityProtocolFactory<IOutputChannel>(context, credManager, true, null);
}
else
{
incomingProtocolFactory = new PeerDoNothingSecurityProtocolFactory();
}
}
DuplexSecurityProtocolFactory tempFactory = new DuplexSecurityProtocolFactory(outgoingProtocolFactory, incomingProtocolFactory);
tempFactory.Open(true, timeoutHelper.RemainingTime());
securityProtocolFactory = tempFactory;
}
}
public SecurityProtocolFactory GetProtocolFactory<TChannel>()
{
if (securityProtocolFactory == null)
{
CreateSecurityProtocolFactory();
}
if (typeof(TChannel) == typeof(IOutputChannel))
{
if (enableSigning && securityProtocolFactory.ForwardProtocolFactory is PeerDoNothingSecurityProtocolFactory)
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication);
return securityProtocolFactory.ForwardProtocolFactory;
}
else if (typeof(TChannel) == typeof(IInputChannel))
{
if (enableSigning && securityProtocolFactory.ReverseProtocolFactory is PeerDoNothingSecurityProtocolFactory)
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication);
return securityProtocolFactory.ReverseProtocolFactory;
}
else
{
if (enableSigning && ((securityProtocolFactory.ReverseProtocolFactory is PeerDoNothingSecurityProtocolFactory)
|| (securityProtocolFactory.ForwardProtocolFactory is PeerDoNothingSecurityProtocolFactory)))
PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication);
return securityProtocolFactory;
}
}
public SecurityProtocol CreateSecurityProtocol<TChannel>(EndpointAddress target, TimeSpan timespan)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timespan);
SecurityProtocolFactory factory = GetProtocolFactory<TChannel>();
Fx.Assert(factory != null, "SecurityProtocolFactory is NULL!");
SecurityProtocol instance = factory.CreateSecurityProtocol(target, null, /*listenerSecurityState*/null, /*isReturnLegSecurityRequired*/false, timeoutHelper.RemainingTime());
if (instance != null)
instance.Open(timeoutHelper.RemainingTime());
return instance;
}
public void CheckIfCompatibleNodeSettings(object other)
{
string mismatch = null;
PeerSecurityManager that = other as PeerSecurityManager;
if (that == null)
mismatch = PeerBindingPropertyNames.Security;
else if (this.authenticationMode != that.authenticationMode)
mismatch = PeerBindingPropertyNames.SecurityDotMode;
else if (this.authenticationMode == PeerAuthenticationMode.None)
return;
else if (!this.tokenManager.Equals(that.tokenManager))
{
if (this.credManager != null)
this.credManager.CheckIfCompatible(that.credManager);
else
{
Fx.Assert(typeof(PeerSecurityCredentialsManager.PeerClientSecurityTokenManager).IsAssignableFrom(tokenManager.GetType()), "");
mismatch = PeerBindingPropertyNames.Credentials;
}
}
if (mismatch != null)
PeerExceptionHelper.ThrowInvalidOperation_PeerConflictingPeerNodeSettings(mismatch);
}
public bool HasCompatibleMessageSecurity(PeerSecurityManager that)
{
return (this.MessageAuthentication == that.MessageAuthentication);
}
public byte[] GetAuthenticator()
{
if (authenticationMode != PeerAuthenticationMode.Password)
return null;
if (authenticatorHash == null)
{
lock (ThisLock)
{
if (authenticatorHash == null)
{
authenticatorHash = PeerSecurityHelpers.ComputeHash(credManager.Certificate, credManager.Password);
}
}
}
return authenticatorHash;
}
public bool Authenticate(ServiceSecurityContext context, byte[] message)
{
Claim claim = null;
if (context == null)
{
return (authenticationMode == PeerAuthenticationMode.None);
}
if (authenticationMode == PeerAuthenticationMode.Password)
{
if (!(context != null))
{
throw Fx.AssertAndThrow("No SecurityContext attached in security mode!");
}
claim = FindClaim(context);
return PeerSecurityHelpers.Authenticate(claim, this.credManager.Password, message);
}
else
{
if (message != null)
{
PeerExceptionHelper.ThrowInvalidOperation_UnexpectedSecurityTokensDuringHandshake();
}
return true;
}
}
public static Claim FindClaim(ServiceSecurityContext context)
{
Claim result = null;
Fx.Assert(context != null, "ServiceSecurityContext is null!");
for (int i = 0; i < context.AuthorizationContext.ClaimSets.Count; ++i)
{
ClaimSet claimSet = context.AuthorizationContext.ClaimSets[i];
IEnumerator<Claim> claims = claimSet.FindClaims(ClaimTypes.Rsa, null).GetEnumerator();
if (claims.MoveNext())
{
result = claims.Current;
break;
}
}
return result;
}
public void ApplyClientSecurity(ChannelFactory<IPeerProxy> factory)
{
factory.Endpoint.Behaviors.Remove<ClientCredentials>();
if (authenticationMode != PeerAuthenticationMode.None)
{
factory.Endpoint.Behaviors.Add(this.credManager.CloneForTransport());
}
}
public BindingElement GetSecurityBindingElement()
{
SslStreamSecurityBindingElement security = null;
if (this.AuthenticationMode != PeerAuthenticationMode.None)
{
security = new SslStreamSecurityBindingElement();
security.IdentityVerifier = new PeerIdentityVerifier();
security.RequireClientCertificate = true;
}
return security;
}
public PeerHashToken GetSelfToken()
{
if (!(this.authenticationMode == PeerAuthenticationMode.Password))
{
throw Fx.AssertAndThrow("unexpected call to GetSelfToken");
}
return new PeerHashToken(this.credManager.Certificate, this.credManager.Password);
}
public PeerHashToken GetExpectedTokenForClaim(Claim claim)
{
return new PeerHashToken(claim, this.password);
}
public void OnNeighborOpened(object sender, EventArgs args)
{
IPeerNeighbor neighbor = sender as IPeerNeighbor;
EventHandler handler = this.OnNeighborAuthenticated;
if (handler == null)
{
neighbor.Abort(PeerCloseReason.LeavingMesh, PeerCloseInitiator.LocalNode);
return;
}
if (this.authenticationMode == PeerAuthenticationMode.Password)
{
if (!(neighbor.Extensions.Find<PeerChannelAuthenticatorExtension>() == null))
{
throw Fx.AssertAndThrow("extension already exists!");
}
PeerChannelAuthenticatorExtension extension = new PeerChannelAuthenticatorExtension(this, handler, args, this.MeshId);
neighbor.Extensions.Add(extension);
if (neighbor.IsInitiator)
extension.InitiateHandShake();
}
else
{
neighbor.TrySetState(PeerNeighborState.Authenticated);
handler(sender, args);
}
}
public Message ProcessRequest(IPeerNeighbor neighbor, Message request)
{
if (this.authenticationMode != PeerAuthenticationMode.Password || request == null)
{
Abort(neighbor);
return null;
}
PeerChannelAuthenticatorExtension extension = neighbor.Extensions.Find<PeerChannelAuthenticatorExtension>();
Claim claim = FindClaim(ServiceSecurityContext.Current);
if (!(extension != null && claim != null))
{
throw Fx.AssertAndThrow("No suitable claim found in the context to do security negotiation!");
}
return extension.ProcessRst(request, claim);
}
void Abort(IPeerNeighbor neighbor)
{
neighbor.Abort(PeerCloseReason.AuthenticationFailure, PeerCloseInitiator.LocalNode);
}
}
class PeerSecurityCredentialsManager : SecurityCredentialsManager, IEndpointBehavior, IServiceBehavior
{
SecurityTokenManager manager;
PeerCredential credential;
bool messageAuth;
PeerAuthenticationMode mode = PeerAuthenticationMode.Password;
SelfSignedCertificate ssl;
PeerSecurityManager parent;
public PeerSecurityCredentialsManager(SecurityTokenManager manager, PeerAuthenticationMode mode, bool messageAuth)
: base()
{
this.manager = manager;
this.mode = mode;
this.messageAuth = messageAuth;
}
public PeerSecurityCredentialsManager(PeerCredential credential, PeerAuthenticationMode mode, bool messageAuth)
: base()
{
this.credential = credential;
this.mode = mode;
this.messageAuth = messageAuth;
}
public PeerSecurityManager Parent
{
get
{
return this.parent;
}
set
{
parent = value;
}
}
public override SecurityTokenManager CreateSecurityTokenManager()
{
if (manager != null)
return new PeerClientSecurityTokenManager(this.parent, manager, mode, messageAuth);
else
return new PeerClientSecurityTokenManager(this.parent, credential, mode, messageAuth);
}
public PeerSecurityCredentialsManager() : base() { }
public PeerSecurityCredentialsManager CloneForTransport()
{
PeerSecurityCredentialsManager cloner = new PeerSecurityCredentialsManager();
if (this.credential != null)
cloner.credential = new PeerCredential(this.credential);
cloner.mode = this.mode;
cloner.messageAuth = this.messageAuth;
cloner.manager = this.manager;
cloner.parent = parent;
return cloner;
}
internal PeerCredential Credential
{
get
{
return this.credential;
}
}
internal string Password
{
get
{
if (this.credential != null)
return credential.MeshPassword;
ServiceModelSecurityTokenRequirement req = PeerClientSecurityTokenManager.CreateRequirement(SecurityTokenTypes.UserName);
UserNameSecurityTokenProvider tokenProvider = this.manager.CreateSecurityTokenProvider(req) as UserNameSecurityTokenProvider;
if (tokenProvider == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TokenProvider");
UserNameSecurityToken token = tokenProvider.GetToken(ServiceDefaults.SendTimeout) as UserNameSecurityToken;
if (token == null || String.IsNullOrEmpty(token.Password))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("password");
return token.Password;
}
}
internal X509Certificate2 Certificate
{
get
{
X509Certificate2 result = null;
if (mode == PeerAuthenticationMode.Password)
{
if (ssl != null)
result = ssl.GetX509Certificate();
}
if (this.credential != null)
{
result = credential.Certificate;
}
else
{
ServiceModelSecurityTokenRequirement req = PeerClientSecurityTokenManager.CreateRequirement(SecurityTokenTypes.X509Certificate);
X509SecurityTokenProvider tokenProvider = this.manager.CreateSecurityTokenProvider(req) as X509SecurityTokenProvider;
if (tokenProvider == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TokenProvider");
X509SecurityToken token = tokenProvider.GetToken(ServiceDefaults.SendTimeout) as X509SecurityToken;
if (token == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("token");
result = token.Certificate;
}
if (result == null && mode == PeerAuthenticationMode.Password)
{
ssl = this.parent.GetCertificate();
result = ssl.GetX509Certificate();
}
return result;
}
}
void IEndpointBehavior.Validate(ServiceEndpoint serviceEndpoint)
{
}
void IEndpointBehavior.AddBindingParameters(ServiceEndpoint serviceEndpoint, BindingParameterCollection bindingParameters)
{
if (bindingParameters != null)
bindingParameters.Add(this);
}
void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher)
{
}
void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime behavior)
{
}
void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
}
void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
{
if (parameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
}
parameters.Add(this);
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
}
public override bool Equals(object other)
{
PeerSecurityCredentialsManager that = other as PeerSecurityCredentialsManager;
if (that == null)
return false;
if (this.credential != null)
{
return this.credential.Equals(that.credential, mode, messageAuth);
}
else
{
return this.manager.Equals(that.manager);
}
}
public void CheckIfCompatible(PeerSecurityCredentialsManager that)
{
if (that == null)
PeerExceptionHelper.ThrowInvalidOperation_PeerConflictingPeerNodeSettings(PeerBindingPropertyNames.Credentials);
if (this.mode == PeerAuthenticationMode.None)
return;
if (this.mode == PeerAuthenticationMode.Password)
{
if (this.Password != that.Password)
PeerExceptionHelper.ThrowInvalidOperation_PeerConflictingPeerNodeSettings(PeerBindingPropertyNames.Password);
}
if (!this.Certificate.Equals(that.Certificate))
PeerExceptionHelper.ThrowInvalidOperation_PeerConflictingPeerNodeSettings(PeerBindingPropertyNames.Certificate);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public class PeerClientSecurityTokenManager : SecurityTokenManager
{
SecurityTokenManager delegateManager;
PeerCredential credential;
PeerAuthenticationMode mode;
bool messageAuth;
SelfSignedCertificate ssc;
PeerSecurityManager parent;
public PeerClientSecurityTokenManager(PeerSecurityManager parent, PeerCredential credential, PeerAuthenticationMode mode, bool messageAuth)
{
this.credential = credential;
this.mode = mode;
this.messageAuth = messageAuth;
this.parent = parent;
}
public PeerClientSecurityTokenManager(PeerSecurityManager parent, SecurityTokenManager manager, PeerAuthenticationMode mode, bool messageAuth)
{
this.delegateManager = manager;
this.mode = mode;
this.messageAuth = messageAuth;
this.parent = parent;
}
internal static ServiceModelSecurityTokenRequirement CreateRequirement(string tokenType)
{
return CreateRequirement(tokenType, false);
}
internal static ServiceModelSecurityTokenRequirement CreateRequirement(string tokenType, bool forMessageValidation)
{
InitiatorServiceModelSecurityTokenRequirement requirement = new InitiatorServiceModelSecurityTokenRequirement();
requirement.TokenType = tokenType;
requirement.TransportScheme = PeerStrings.Scheme;
if (forMessageValidation)
requirement.Properties[SecurityTokenRequirement.PeerAuthenticationMode] = SecurityMode.Message;
else
requirement.Properties[SecurityTokenRequirement.PeerAuthenticationMode] = SecurityMode.Transport;
return requirement;
}
UserNameSecurityTokenProvider GetPasswordTokenProvider()
{
if (delegateManager != null)
{
ServiceModelSecurityTokenRequirement requirement = CreateRequirement(SecurityTokenTypes.UserName);
UserNameSecurityTokenProvider tokenProvider = delegateManager.CreateSecurityTokenProvider(requirement) as UserNameSecurityTokenProvider;
if (tokenProvider == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenManagerCannotCreateProviderForRequirement, requirement)));
return tokenProvider;
}
else
return new UserNameSecurityTokenProvider(string.Empty, credential.MeshPassword);
}
public override SecurityTokenSerializer CreateSecurityTokenSerializer(SecurityTokenVersion version)
{
if (delegateManager != null)
return delegateManager.CreateSecurityTokenSerializer(version);
else
{
MessageSecurityTokenVersion wsVersion = version as MessageSecurityTokenVersion;
if (wsVersion != null)
{
return new WSSecurityTokenSerializer(wsVersion.SecurityVersion, wsVersion.TrustVersion, wsVersion.SecureConversationVersion, wsVersion.EmitBspRequiredAttributes, null, null, null);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenManagerCannotCreateSerializerForVersion, version)));
}
}
}
public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement)
{
ServiceModelSecurityTokenRequirement requirement = tokenRequirement as ServiceModelSecurityTokenRequirement;
if (requirement != null)
{
if (IsX509TokenRequirement(requirement))
{
if (IsForConnectionValidator(requirement))
{
SecurityTokenProvider result = null;
if (this.ssc != null)
{
result = new X509SecurityTokenProvider(this.ssc.GetX509Certificate());
}
else
{
if (this.delegateManager != null)
{
requirement.Properties[SecurityTokenRequirement.PeerAuthenticationMode] = SecurityMode.Transport;
requirement.TransportScheme = PeerStrings.Scheme;
result = delegateManager.CreateSecurityTokenProvider(tokenRequirement);
}
else
{
if (this.credential.Certificate != null)
result = new X509SecurityTokenProvider(this.credential.Certificate);
}
}
if (result == null && mode == PeerAuthenticationMode.Password)
{
this.ssc = parent.GetCertificate();
result = new X509SecurityTokenProvider(this.ssc.GetX509Certificate());
}
return result;
}
else
{
X509CertificateValidator validator;
if (this.delegateManager != null)
{
requirement.TransportScheme = PeerStrings.Scheme;
requirement.Properties[SecurityTokenRequirement.PeerAuthenticationMode] = SecurityMode.Message;
return delegateManager.CreateSecurityTokenProvider(tokenRequirement);
}
if (!this.credential.MessageSenderAuthentication.TryGetCertificateValidator(out validator))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("TokenType");
return new PeerX509TokenProvider(validator, this.credential.Certificate);
}
}
else if (IsPasswordTokenRequirement(requirement))
{
return GetPasswordTokenProvider();
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("TokenType");
}
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement");
}
}
bool IsPasswordTokenRequirement(ServiceModelSecurityTokenRequirement requirement)
{
return ((requirement != null) && (requirement.TokenType == SecurityTokenTypes.UserName));
}
bool IsX509TokenRequirement(ServiceModelSecurityTokenRequirement requirement)
{
return (requirement != null && requirement.TokenType == SecurityTokenTypes.X509Certificate);
}
bool IsForConnectionValidator(ServiceModelSecurityTokenRequirement requirement)
{
return (requirement.TransportScheme == "net.tcp" && requirement.SecurityBindingElement == null && requirement.MessageSecurityVersion == null);
}
public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver)
{
ServiceModelSecurityTokenRequirement requirement = tokenRequirement as ServiceModelSecurityTokenRequirement;
outOfBandTokenResolver = null;
if (requirement != null)
{
if (IsX509TokenRequirement(requirement))
{
if (mode == PeerAuthenticationMode.Password && IsForConnectionValidator(requirement))
{
return new X509SecurityTokenAuthenticator(X509CertificateValidator.None);
}
if (delegateManager != null)
{
if (IsForConnectionValidator(requirement))
{
requirement.TransportScheme = PeerStrings.Scheme;
requirement.Properties[SecurityTokenRequirement.PeerAuthenticationMode] = SecurityMode.Transport;
}
else
{
requirement.TransportScheme = PeerStrings.Scheme;
requirement.Properties[SecurityTokenRequirement.PeerAuthenticationMode] = SecurityMode.Message;
}
return delegateManager.CreateSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver);
}
else
{
X509CertificateValidator validator = null;
if (IsForConnectionValidator(requirement))
{
if (this.mode == PeerAuthenticationMode.MutualCertificate)
{
if (!this.credential.PeerAuthentication.TryGetCertificateValidator(out validator))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenManagerCannotCreateProviderForRequirement, requirement)));
}
else
validator = X509CertificateValidator.None;
}
else
{
if (!this.credential.MessageSenderAuthentication.TryGetCertificateValidator(out validator))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenManagerCannotCreateProviderForRequirement, requirement)));
}
return new X509SecurityTokenAuthenticator(validator);
}
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("tokenRequirement");
}
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement");
}
}
public override bool Equals(object other)
{
PeerClientSecurityTokenManager that = other as PeerClientSecurityTokenManager;
if (that == null)
return false;
if (this.credential != null)
{
if (that.credential == null || !this.credential.Equals(that.credential, this.mode, this.messageAuth))
return false;
return true;
}
else
{
return this.delegateManager.Equals(that.delegateManager);
}
}
internal bool HasCompatibleMessageSecuritySettings(PeerClientSecurityTokenManager that)
{
if (this.credential != null)
return (that.credential != null && this.credential.Equals(that.credential));
else
return this.delegateManager.Equals(that.delegateManager);
}
public override int GetHashCode()
{
if (credential != null)
return credential.GetHashCode();
else if (delegateManager != null)
return delegateManager.GetHashCode();
else
return 0;
}
}
}
}
| |
// 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.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
namespace System.Net.Security
{
internal static class SslStreamPal
{
private const string SecurityPackage = "Microsoft Unified Security Protocol Provider";
private const Interop.SspiCli.ContextFlags RequiredFlags =
Interop.SspiCli.ContextFlags.ReplayDetect |
Interop.SspiCli.ContextFlags.SequenceDetect |
Interop.SspiCli.ContextFlags.Confidentiality |
Interop.SspiCli.ContextFlags.AllocateMemory;
private const Interop.SspiCli.ContextFlags ServerRequiredFlags =
RequiredFlags | Interop.SspiCli.ContextFlags.AcceptStream;
public static Exception GetException(SecurityStatusPal status)
{
int win32Code = (int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(status);
return new Win32Exception(win32Code);
}
internal const bool StartMutualAuthAsAnonymous = true;
internal const bool CanEncryptEmptyMessage = true;
public static void VerifyPackageInfo()
{
SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPISecureChannel, SecurityPackage, true);
}
public static byte[] ConvertAlpnProtocolListToByteArray(List<SslApplicationProtocol> protocols)
{
return Interop.Sec_Application_Protocols.ToByteArray(protocols);
}
public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, ArraySegment<byte> input, ref byte[] outputBuffer, SslAuthenticationOptions sslAuthenticationOptions)
{
Interop.SspiCli.ContextFlags unusedAttributes = default;
ThreeSecurityBuffers threeSecurityBuffers = default;
SecurityBuffer? incomingSecurity = input.Array != null ?
new SecurityBuffer(input.Array, input.Offset, input.Count, SecurityBufferType.SECBUFFER_TOKEN) :
(SecurityBuffer?)null;
Span<SecurityBuffer> inputBuffers = MemoryMarshal.CreateSpan(ref threeSecurityBuffers._item0, 3);
GetIncomingSecurityBuffers(sslAuthenticationOptions, in incomingSecurity, ref inputBuffers);
var resultBuffer = new SecurityBuffer(outputBuffer, SecurityBufferType.SECBUFFER_TOKEN);
int errorCode = SSPIWrapper.AcceptSecurityContext(
GlobalSSPI.SSPISecureChannel,
credentialsHandle,
ref context,
ServerRequiredFlags | (sslAuthenticationOptions.RemoteCertRequired ? Interop.SspiCli.ContextFlags.MutualAuth : Interop.SspiCli.ContextFlags.Zero),
Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP,
inputBuffers,
ref resultBuffer,
ref unusedAttributes);
outputBuffer = resultBuffer.token;
return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode);
}
public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, ArraySegment<byte> input, ref byte[] outputBuffer, SslAuthenticationOptions sslAuthenticationOptions)
{
Interop.SspiCli.ContextFlags unusedAttributes = default;
ThreeSecurityBuffers threeSecurityBuffers = default;
SecurityBuffer? incomingSecurity = input.Array != null ?
new SecurityBuffer(input.Array, input.Offset, input.Count, SecurityBufferType.SECBUFFER_TOKEN) :
(SecurityBuffer?)null;
Span<SecurityBuffer> inputBuffers = MemoryMarshal.CreateSpan(ref threeSecurityBuffers._item0, 3);
GetIncomingSecurityBuffers(sslAuthenticationOptions, in incomingSecurity, ref inputBuffers);
var resultBuffer = new SecurityBuffer(outputBuffer, SecurityBufferType.SECBUFFER_TOKEN);
int errorCode = SSPIWrapper.InitializeSecurityContext(
GlobalSSPI.SSPISecureChannel,
ref credentialsHandle,
ref context,
targetName,
RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation,
Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP,
inputBuffers,
ref resultBuffer,
ref unusedAttributes);
outputBuffer = resultBuffer.token;
return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode);
}
private static void GetIncomingSecurityBuffers(SslAuthenticationOptions options, in SecurityBuffer? incomingSecurity, ref Span<SecurityBuffer> incomingSecurityBuffers)
{
SecurityBuffer? alpnBuffer = null;
if (options.ApplicationProtocols != null && options.ApplicationProtocols.Count != 0)
{
byte[] alpnBytes = ConvertAlpnProtocolListToByteArray(options.ApplicationProtocols);
alpnBuffer = new SecurityBuffer(alpnBytes, 0, alpnBytes.Length, SecurityBufferType.SECBUFFER_APPLICATION_PROTOCOLS);
}
if (incomingSecurity != null)
{
if (alpnBuffer != null)
{
Debug.Assert(incomingSecurityBuffers.Length >= 3);
incomingSecurityBuffers[0] = incomingSecurity.GetValueOrDefault();
incomingSecurityBuffers[1] = new SecurityBuffer(null, 0, 0, SecurityBufferType.SECBUFFER_EMPTY);
incomingSecurityBuffers[2] = alpnBuffer.GetValueOrDefault();
incomingSecurityBuffers = incomingSecurityBuffers.Slice(0, 3);
}
else
{
Debug.Assert(incomingSecurityBuffers.Length >= 2);
incomingSecurityBuffers[0] = incomingSecurity.GetValueOrDefault();
incomingSecurityBuffers[1] = new SecurityBuffer(null, 0, 0, SecurityBufferType.SECBUFFER_EMPTY);
incomingSecurityBuffers = incomingSecurityBuffers.Slice(0, 2);
}
}
else if (alpnBuffer != null)
{
incomingSecurityBuffers[0] = alpnBuffer.GetValueOrDefault();
incomingSecurityBuffers = incomingSecurityBuffers.Slice(0, 1);
}
else
{
incomingSecurityBuffers = default;
}
}
public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy, bool isServer)
{
int protocolFlags = GetProtocolFlagsFromSslProtocols(protocols, isServer);
Interop.SspiCli.SCHANNEL_CRED.Flags flags;
Interop.SspiCli.CredentialUse direction;
if (!isServer)
{
direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND;
flags =
Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_MANUAL_CRED_VALIDATION |
Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_NO_DEFAULT_CREDS |
Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_SEND_AUX_RECORD;
// CoreFX: always opt-in SCH_USE_STRONG_CRYPTO for TLS.
if (((protocolFlags == 0) ||
(protocolFlags & ~(Interop.SChannel.SP_PROT_SSL2 | Interop.SChannel.SP_PROT_SSL3)) != 0)
&& (policy != EncryptionPolicy.AllowNoEncryption) && (policy != EncryptionPolicy.NoEncryption))
{
flags |= Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_USE_STRONG_CRYPTO;
}
}
else
{
direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND;
flags = Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_SEND_AUX_RECORD;
}
if (NetEventSource.IsEnabled) NetEventSource.Info($"flags=({flags}), ProtocolFlags=({protocolFlags}), EncryptionPolicy={policy}");
Interop.SspiCli.SCHANNEL_CRED secureCredential = CreateSecureCredential(
Interop.SspiCli.SCHANNEL_CRED.CurrentVersion,
certificate,
flags,
protocolFlags,
policy);
return AcquireCredentialsHandle(direction, secureCredential);
}
internal static byte[] GetNegotiatedApplicationProtocol(SafeDeleteContext context)
{
Interop.SecPkgContext_ApplicationProtocol alpnContext = default;
bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, context, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_APPLICATION_PROTOCOL, ref alpnContext);
// Check if the context returned is alpn data, with successful negotiation.
if (success &&
alpnContext.ProtoNegoExt == Interop.ApplicationProtocolNegotiationExt.ALPN &&
alpnContext.ProtoNegoStatus == Interop.ApplicationProtocolNegotiationStatus.Success)
{
return alpnContext.Protocol;
}
return null;
}
public static unsafe SecurityStatusPal EncryptMessage(SafeDeleteContext securityContext, ReadOnlyMemory<byte> input, int headerSize, int trailerSize, ref byte[] output, out int resultSize)
{
// Ensure that there is sufficient space for the message output.
int bufferSizeNeeded;
try
{
bufferSizeNeeded = checked(input.Length + headerSize + trailerSize);
}
catch
{
NetEventSource.Fail(securityContext, "Arguments out of range");
throw;
}
if (output == null || output.Length < bufferSizeNeeded)
{
output = new byte[bufferSizeNeeded];
}
// Copy the input into the output buffer to prepare for SCHANNEL's expectations
input.Span.CopyTo(new Span<byte>(output, headerSize, input.Length));
const int NumSecBuffers = 4; // header + data + trailer + empty
var unmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[NumSecBuffers];
var sdcInOut = new Interop.SspiCli.SecBufferDesc(NumSecBuffers);
sdcInOut.pBuffers = unmanagedBuffer;
fixed (byte* outputPtr = output)
{
Interop.SspiCli.SecBuffer* headerSecBuffer = &unmanagedBuffer[0];
headerSecBuffer->BufferType = SecurityBufferType.SECBUFFER_STREAM_HEADER;
headerSecBuffer->pvBuffer = (IntPtr)outputPtr;
headerSecBuffer->cbBuffer = headerSize;
Interop.SspiCli.SecBuffer* dataSecBuffer = &unmanagedBuffer[1];
dataSecBuffer->BufferType = SecurityBufferType.SECBUFFER_DATA;
dataSecBuffer->pvBuffer = (IntPtr)(outputPtr + headerSize);
dataSecBuffer->cbBuffer = input.Length;
Interop.SspiCli.SecBuffer* trailerSecBuffer = &unmanagedBuffer[2];
trailerSecBuffer->BufferType = SecurityBufferType.SECBUFFER_STREAM_TRAILER;
trailerSecBuffer->pvBuffer = (IntPtr)(outputPtr + headerSize + input.Length);
trailerSecBuffer->cbBuffer = trailerSize;
Interop.SspiCli.SecBuffer* emptySecBuffer = &unmanagedBuffer[3];
emptySecBuffer->BufferType = SecurityBufferType.SECBUFFER_EMPTY;
emptySecBuffer->cbBuffer = 0;
emptySecBuffer->pvBuffer = IntPtr.Zero;
int errorCode = GlobalSSPI.SSPISecureChannel.EncryptMessage(securityContext, ref sdcInOut, 0);
if (errorCode != 0)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(securityContext, $"Encrypt ERROR {errorCode:X}");
resultSize = 0;
return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode);
}
Debug.Assert(headerSecBuffer->cbBuffer >= 0 && dataSecBuffer->cbBuffer >= 0 && trailerSecBuffer->cbBuffer >= 0);
Debug.Assert(checked(headerSecBuffer->cbBuffer + dataSecBuffer->cbBuffer + trailerSecBuffer->cbBuffer) <= output.Length);
resultSize = checked(headerSecBuffer->cbBuffer + dataSecBuffer->cbBuffer + trailerSecBuffer->cbBuffer);
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
}
public static unsafe SecurityStatusPal DecryptMessage(SafeDeleteContext securityContext, byte[] buffer, ref int offset, ref int count)
{
const int NumSecBuffers = 4; // data + empty + empty + empty
var unmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[NumSecBuffers];
var sdcInOut = new Interop.SspiCli.SecBufferDesc(NumSecBuffers);
sdcInOut.pBuffers = unmanagedBuffer;
fixed (byte* bufferPtr = buffer)
{
Interop.SspiCli.SecBuffer* dataBuffer = &unmanagedBuffer[0];
dataBuffer->BufferType = SecurityBufferType.SECBUFFER_DATA;
dataBuffer->pvBuffer = (IntPtr)bufferPtr + offset;
dataBuffer->cbBuffer = count;
for (int i = 1; i < NumSecBuffers; i++)
{
Interop.SspiCli.SecBuffer* emptyBuffer = &unmanagedBuffer[i];
emptyBuffer->BufferType = SecurityBufferType.SECBUFFER_EMPTY;
emptyBuffer->pvBuffer = IntPtr.Zero;
emptyBuffer->cbBuffer = 0;
}
Interop.SECURITY_STATUS errorCode = (Interop.SECURITY_STATUS)GlobalSSPI.SSPISecureChannel.DecryptMessage(securityContext, ref sdcInOut, 0);
// Decrypt may repopulate the sec buffers, likely with header + data + trailer + empty.
// We need to find the data.
count = 0;
for (int i = 0; i < NumSecBuffers; i++)
{
// Successfully decoded data and placed it at the following position in the buffer,
if ((errorCode == Interop.SECURITY_STATUS.OK && unmanagedBuffer[i].BufferType == SecurityBufferType.SECBUFFER_DATA)
// or we failed to decode the data, here is the encoded data.
|| (errorCode != Interop.SECURITY_STATUS.OK && unmanagedBuffer[i].BufferType == SecurityBufferType.SECBUFFER_EXTRA))
{
offset = (int)((byte*)unmanagedBuffer[i].pvBuffer - bufferPtr);
count = unmanagedBuffer[i].cbBuffer;
Debug.Assert(offset >= 0 && count >= 0, $"Expected offset and count greater than 0, got {offset} and {count}");
Debug.Assert(checked(offset + count) <= buffer.Length, $"Expected offset+count <= buffer.Length, got {offset}+{count}>={buffer.Length}");
break;
}
}
return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode);
}
}
public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage)
{
var alertToken = new Interop.SChannel.SCHANNEL_ALERT_TOKEN
{
dwTokenType = Interop.SChannel.SCHANNEL_ALERT,
dwAlertType = (uint)alertType,
dwAlertNumber = (uint)alertMessage
};
byte[] buffer = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref alertToken, 1)).ToArray();
var securityBuffer = new SecurityBuffer(buffer, SecurityBufferType.SECBUFFER_TOKEN);
var errorCode = (Interop.SECURITY_STATUS)SSPIWrapper.ApplyControlToken(
GlobalSSPI.SSPISecureChannel,
ref securityContext,
in securityBuffer);
return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException: true);
}
private static readonly byte[] s_schannelShutdownBytes = BitConverter.GetBytes(Interop.SChannel.SCHANNEL_SHUTDOWN);
public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext)
{
var securityBuffer = new SecurityBuffer(s_schannelShutdownBytes, SecurityBufferType.SECBUFFER_TOKEN);
var errorCode = (Interop.SECURITY_STATUS)SSPIWrapper.ApplyControlToken(
GlobalSSPI.SSPISecureChannel,
ref securityContext,
in securityBuffer);
return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException: true);
}
public static unsafe SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute)
{
return SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.SspiCli.ContextAttribute)attribute);
}
public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes)
{
SecPkgContext_StreamSizes interopStreamSizes = default;
bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_STREAM_SIZES, ref interopStreamSizes);
Debug.Assert(success);
streamSizes = new StreamSizes(interopStreamSizes);
}
public static void QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo)
{
SecPkgContext_ConnectionInfo interopConnectionInfo = default;
bool success = SSPIWrapper.QueryBlittableContextAttributes(
GlobalSSPI.SSPISecureChannel,
securityContext,
Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CONNECTION_INFO,
ref interopConnectionInfo);
Debug.Assert(success);
TlsCipherSuite cipherSuite = default;
SecPkgContext_CipherInfo cipherInfo = default;
success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CIPHER_INFO, ref cipherInfo);
if (success)
{
cipherSuite = (TlsCipherSuite)cipherInfo.dwCipherSuite;
}
connectionInfo = new SslConnectionInfo(interopConnectionInfo, cipherSuite);
}
private static int GetProtocolFlagsFromSslProtocols(SslProtocols protocols, bool isServer)
{
int protocolFlags = (int)protocols;
if (isServer)
{
protocolFlags &= Interop.SChannel.ServerProtocolMask;
}
else
{
protocolFlags &= Interop.SChannel.ClientProtocolMask;
}
return protocolFlags;
}
private static Interop.SspiCli.SCHANNEL_CRED CreateSecureCredential(
int version,
X509Certificate certificate,
Interop.SspiCli.SCHANNEL_CRED.Flags flags,
int protocols, EncryptionPolicy policy)
{
var credential = new Interop.SspiCli.SCHANNEL_CRED()
{
hRootStore = IntPtr.Zero,
aphMappers = IntPtr.Zero,
palgSupportedAlgs = IntPtr.Zero,
paCred = IntPtr.Zero,
cCreds = 0,
cMappers = 0,
cSupportedAlgs = 0,
dwSessionLifespan = 0,
reserved = 0
};
if (policy == EncryptionPolicy.RequireEncryption)
{
// Prohibit null encryption cipher.
credential.dwMinimumCipherStrength = 0;
credential.dwMaximumCipherStrength = 0;
}
else if (policy == EncryptionPolicy.AllowNoEncryption)
{
// Allow null encryption cipher in addition to other ciphers.
credential.dwMinimumCipherStrength = -1;
credential.dwMaximumCipherStrength = 0;
}
else if (policy == EncryptionPolicy.NoEncryption)
{
// Suppress all encryption and require null encryption cipher only
credential.dwMinimumCipherStrength = -1;
credential.dwMaximumCipherStrength = -1;
}
else
{
throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(policy));
}
credential.dwVersion = version;
credential.dwFlags = flags;
credential.grbitEnabledProtocols = protocols;
if (certificate != null)
{
credential.paCred = certificate.Handle;
credential.cCreds = 1;
}
return credential;
}
//
// Security: we temporarily reset thread token to open the handle under process account.
//
private static SafeFreeCredentials AcquireCredentialsHandle(Interop.SspiCli.CredentialUse credUsage, Interop.SspiCli.SCHANNEL_CRED secureCredential)
{
// First try without impersonation, if it fails, then try the process account.
// I.E. We don't know which account the certificate context was created under.
try
{
//
// For app-compat we want to ensure the credential are accessed under >>process<< account.
//
return WindowsIdentity.RunImpersonated<SafeFreeCredentials>(SafeAccessTokenHandle.InvalidHandle, () =>
{
return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential);
});
}
catch
{
return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using BTDB.Collections;
namespace BTDB.IL.Caching
{
class CachingILDynamicType : IILDynamicType
{
readonly CachingILBuilder _cachingIlBuilder;
readonly string _name;
readonly Type _baseType;
readonly Type[] _interfaces;
StructList<IReplay> _instructions;
Type? TrueContent { get; set; }
interface IReplay
{
void ReplayTo(IILDynamicType target);
void FinishReplay(IILDynamicType target);
void FreeTemps();
bool Equals(IReplay? other);
object TrueContent();
}
public CachingILDynamicType(CachingILBuilder cachingIlBuilder, string name, Type baseType, Type[] interfaces)
{
_cachingIlBuilder = cachingIlBuilder;
_name = name;
_baseType = baseType;
_interfaces = interfaces;
}
public IILMethod DefineMethod(string name, Type returns, Type[] parameters,
MethodAttributes methodAttributes = MethodAttributes.Public)
{
var res = new Method((int)_instructions.Count, name, returns, parameters, methodAttributes);
_instructions.Add(res);
return res;
}
class Method : IReplay, IILMethodPrivate
{
readonly int _id;
readonly string _name;
readonly Type _returns;
readonly Type[] _parameters;
readonly MethodAttributes _methodAttributes;
readonly CachingILGen _ilGen = new CachingILGen();
int _expectedLength = -1;
IILMethodPrivate? _trueContent;
public Method(int id, string name, Type returns, Type[] parameters, MethodAttributes methodAttributes)
{
_id = id;
_name = name;
_returns = returns;
_parameters = parameters;
_methodAttributes = methodAttributes;
}
public void ReplayTo(IILDynamicType target)
{
_trueContent = (IILMethodPrivate) target.DefineMethod(_name, _returns, _parameters, _methodAttributes);
if (_expectedLength >= 0) _trueContent.ExpectedLength(_expectedLength);
}
public void FinishReplay(IILDynamicType target)
{
_ilGen.ReplayTo(_trueContent!.Generator);
}
public void FreeTemps()
{
_trueContent = null;
_ilGen.FreeTemps();
}
public bool Equals(IReplay? other)
{
if (!(other is Method v)) return false;
return _id == v._id
&& _name == v._name
&& _returns == v._returns
&& _methodAttributes == v._methodAttributes
&& _parameters.SequenceEqual(v._parameters)
&& _ilGen.Equals(v._ilGen);
}
public override bool Equals(object obj)
{
return Equals(obj as IReplay);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = _id;
hashCode = (hashCode * 397) ^ _name.GetHashCode();
hashCode = (hashCode * 397) ^ _returns.GetHashCode();
return hashCode;
}
}
public object TrueContent()
{
return _trueContent!;
}
public void ExpectedLength(int length)
{
_expectedLength = length;
}
public IILGen Generator => _ilGen;
public MethodInfo TrueMethodInfo => _trueContent!.TrueMethodInfo;
public Type ReturnType => _returns;
public Type[] Parameters => _parameters;
}
public IILField DefineField(string name, Type type, FieldAttributes fieldAttributes)
{
var res = new Field((int)_instructions.Count, name, type, fieldAttributes);
_instructions.Add(res);
return res;
}
class Field : IReplay, IILFieldPrivate
{
readonly int _id;
readonly string _name;
readonly Type _type;
readonly FieldAttributes _fieldAttributes;
IILFieldPrivate? _trueContent;
public Field(int id, string name, Type type, FieldAttributes fieldAttributes)
{
_id = id;
_name = name;
_type = type;
_fieldAttributes = fieldAttributes;
}
public void ReplayTo(IILDynamicType target)
{
_trueContent = (IILFieldPrivate) target.DefineField(_name, _type, _fieldAttributes);
}
public void FreeTemps()
{
_trueContent = null;
}
public bool Equals(IReplay? other)
{
if (!(other is Field v)) return false;
return _id == v._id && _name == v._name && _type == v._type && _fieldAttributes == v._fieldAttributes;
}
public override bool Equals(object obj)
{
return Equals(obj as IReplay);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = _id;
hashCode = (hashCode * 397) ^ _name.GetHashCode();
hashCode = (hashCode * 397) ^ _type.GetHashCode();
return hashCode;
}
}
public object TrueContent()
{
return _trueContent!;
}
public Type FieldType => _type;
public string Name => _name;
public void FinishReplay(IILDynamicType target)
{
}
public FieldBuilder TrueField => _trueContent!.TrueField;
}
public IILEvent DefineEvent(string name, EventAttributes eventAttributes, Type type)
{
var res = new Event((int)_instructions.Count, name, eventAttributes, type);
_instructions.Add(res);
return res;
}
class Event : IReplay, IILEvent
{
readonly int _id;
readonly string _name;
readonly EventAttributes _eventAttributes;
readonly Type _type;
IILEvent? _trueContent;
IReplay? _addOnMethod;
IReplay? _removeOnMethod;
public Event(int id, string name, EventAttributes eventAttributes, Type type)
{
_id = id;
_name = name;
_eventAttributes = eventAttributes;
_type = type;
}
public void ReplayTo(IILDynamicType target)
{
_trueContent = target.DefineEvent(_name, _eventAttributes, _type);
}
public void FreeTemps()
{
_trueContent = null;
}
public bool Equals(IReplay? other)
{
if (!(other is Event v)) return false;
return _id == v._id && _name == v._name && _eventAttributes == v._eventAttributes && _type == v._type;
}
public override bool Equals(object obj)
{
return Equals(obj as IReplay);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = _id;
hashCode = (hashCode * 397) ^ _name.GetHashCode();
hashCode = (hashCode * 397) ^ _type.GetHashCode();
return hashCode;
}
}
public object TrueContent()
{
return _trueContent!;
}
public void SetAddOnMethod(IILMethod method)
{
_addOnMethod = (IReplay)method;
}
public void SetRemoveOnMethod(IILMethod method)
{
_removeOnMethod = (IReplay)method;
}
public void FinishReplay(IILDynamicType target)
{
_trueContent!.SetAddOnMethod((IILMethod)_addOnMethod!.TrueContent());
_trueContent.SetRemoveOnMethod((IILMethod)_removeOnMethod!.TrueContent());
}
}
public IILMethod DefineConstructor(Type[] parameters)
{
var res = new Constructor((int)_instructions.Count, parameters);
_instructions.Add(res);
return res;
}
class Constructor : IReplay, IILMethod
{
readonly int _id;
readonly Type[] _parameters;
readonly CachingILGen _ilGen = new CachingILGen();
int _expectedLength = -1;
IILMethod? _trueContent;
public Constructor(int id, Type[] parameters)
{
_id = id;
_parameters = parameters;
}
public void ReplayTo(IILDynamicType target)
{
_trueContent = target.DefineConstructor(_parameters);
if (_expectedLength >= 0) _trueContent.ExpectedLength(_expectedLength);
}
public void FinishReplay(IILDynamicType target)
{
_ilGen.ReplayTo(_trueContent!.Generator);
}
public void FreeTemps()
{
_trueContent = null;
_ilGen.FreeTemps();
}
public bool Equals(IReplay? other)
{
if (!(other is Constructor v)) return false;
return _id == v._id && _parameters.SequenceEqual(v._parameters) && _ilGen.Equals(v._ilGen);
}
public override bool Equals(object obj)
{
return Equals(obj as IReplay);
}
public override int GetHashCode()
{
return _id;
}
public object TrueContent()
{
return _trueContent!;
}
public void ExpectedLength(int length)
{
_expectedLength = length;
}
public IILGen Generator => _ilGen;
}
public void DefineMethodOverride(IILMethod methodBuilder, MethodInfo baseMethod)
{
_instructions.Add(new MethodOverride((int)_instructions.Count, methodBuilder, baseMethod));
}
class MethodOverride : IReplay
{
readonly int _id;
readonly IReplay _methodBuilder;
readonly MethodInfo _baseMethod;
public MethodOverride(int id, IILMethod methodBuilder, MethodInfo baseMethod)
{
_id = id;
_methodBuilder = (IReplay)methodBuilder;
_baseMethod = baseMethod;
}
public void ReplayTo(IILDynamicType target)
{
}
public void FinishReplay(IILDynamicType target)
{
target.DefineMethodOverride((IILMethod)_methodBuilder.TrueContent(), _baseMethod);
}
public void FreeTemps()
{
}
public bool Equals(IReplay? other)
{
if (!(other is MethodOverride v)) return false;
return _id == v._id && _methodBuilder.Equals(v._methodBuilder) && _baseMethod == v._baseMethod;
}
public override bool Equals(object obj)
{
return Equals(obj as IReplay);
}
public override int GetHashCode()
{
return _id;
}
public object TrueContent()
{
throw new InvalidOperationException();
}
}
public Type CreateType()
{
lock (_cachingIlBuilder.Lock)
{
var item = (CachingILDynamicType)_cachingIlBuilder.FindInCache(this);
if (item.TrueContent == null)
{
var typeGen = _cachingIlBuilder.Wrapping.NewType(_name, _baseType, _interfaces);
foreach (var replay in _instructions)
{
replay.ReplayTo(typeGen);
}
foreach (var replay in _instructions)
{
replay.FinishReplay(typeGen);
}
foreach (var replay in _instructions)
{
replay.FreeTemps();
}
item.TrueContent = typeGen.CreateType();
}
return item.TrueContent;
}
}
public override int GetHashCode()
{
// ReSharper disable once NonReadonlyMemberInGetHashCode
return _name.GetHashCode() * 33 + (int)_instructions.Count;
}
public override bool Equals(object obj)
{
if (!(obj is CachingILDynamicType v)) return false;
return _name == v._name && _baseType == v._baseType && _interfaces.SequenceEqual(v._interfaces) &&
_instructions.SequenceEqual(v._instructions, ReplayComparer.Instance);
}
class ReplayComparer : IEqualityComparer<IReplay>
{
internal static readonly ReplayComparer Instance = new ReplayComparer();
public bool Equals(IReplay? x, IReplay? y)
{
if (ReferenceEquals(x, y)) return true;
return x != null && x.Equals(y);
}
public int GetHashCode(IReplay obj)
{
return 0;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Web;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
namespace Umbraco.Web
{
/// <summary>
/// Class that encapsulates Umbraco information of a specific HTTP request
/// </summary>
public class UmbracoContext : DisposableObjectSlim, IDisposeOnRequestEnd
{
private readonly IGlobalSettings _globalSettings;
private readonly Lazy<IPublishedSnapshot> _publishedSnapshot;
private string _previewToken;
private bool? _previewing;
// initializes a new instance of the UmbracoContext class
// internal for unit tests
// otherwise it's used by EnsureContext above
// warn: does *not* manage setting any IUmbracoContextAccessor
internal UmbracoContext(HttpContextBase httpContext,
IPublishedSnapshotService publishedSnapshotService,
WebSecurity webSecurity,
IUmbracoSettingsSection umbracoSettings,
IEnumerable<IUrlProvider> urlProviders,
IEnumerable<IMediaUrlProvider> mediaUrlProviders,
IGlobalSettings globalSettings,
IVariationContextAccessor variationContextAccessor)
{
if (httpContext == null) throw new ArgumentNullException(nameof(httpContext));
if (publishedSnapshotService == null) throw new ArgumentNullException(nameof(publishedSnapshotService));
if (webSecurity == null) throw new ArgumentNullException(nameof(webSecurity));
if (umbracoSettings == null) throw new ArgumentNullException(nameof(umbracoSettings));
if (urlProviders == null) throw new ArgumentNullException(nameof(urlProviders));
if (mediaUrlProviders == null) throw new ArgumentNullException(nameof(mediaUrlProviders));
VariationContextAccessor = variationContextAccessor ?? throw new ArgumentNullException(nameof(variationContextAccessor));
_globalSettings = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings));
// ensure that this instance is disposed when the request terminates, though we *also* ensure
// this happens in the Umbraco module since the UmbracoCOntext is added to the HttpContext items.
//
// also, it *can* be returned by the container with a PerRequest lifetime, meaning that the
// container *could* also try to dispose it.
//
// all in all, this context may be disposed more than once, but DisposableObject ensures that
// it is ok and it will be actually disposed only once.
httpContext.DisposeOnPipelineCompleted(this);
ObjectCreated = DateTime.Now;
UmbracoRequestId = Guid.NewGuid();
HttpContext = httpContext;
Security = webSecurity;
// beware - we cannot expect a current user here, so detecting preview mode must be a lazy thing
_publishedSnapshot = new Lazy<IPublishedSnapshot>(() => publishedSnapshotService.CreatePublishedSnapshot(PreviewToken));
// set the urls...
// NOTE: The request will not be available during app startup so we can only set this to an absolute URL of localhost, this
// is a work around to being able to access the UmbracoContext during application startup and this will also ensure that people
// 'could' still generate URLs during startup BUT any domain driven URL generation will not work because it is NOT possible to get
// the current domain during application startup.
// see: http://issues.umbraco.org/issue/U4-1890
//
OriginalRequestUrl = GetRequestFromContext()?.Url ?? new Uri("http://localhost");
CleanedUmbracoUrl = UriUtility.UriToUmbraco(OriginalRequestUrl);
UrlProvider = new UrlProvider(this, umbracoSettings.WebRouting, urlProviders, mediaUrlProviders, variationContextAccessor);
}
/// <summary>
/// This is used internally for performance calculations, the ObjectCreated DateTime is set as soon as this
/// object is instantiated which in the web site is created during the BeginRequest phase.
/// We can then determine complete rendering time from that.
/// </summary>
internal DateTime ObjectCreated { get; }
/// <summary>
/// This is used internally for debugging and also used to define anything required to distinguish this request from another.
/// </summary>
internal Guid UmbracoRequestId { get; }
/// <summary>
/// Gets the WebSecurity class
/// </summary>
public WebSecurity Security { get; }
/// <summary>
/// Gets the uri that is handled by ASP.NET after server-side rewriting took place.
/// </summary>
internal Uri OriginalRequestUrl { get; }
/// <summary>
/// Gets the cleaned up url that is handled by Umbraco.
/// </summary>
/// <remarks>That is, lowercase, no trailing slash after path, no .aspx...</remarks>
internal Uri CleanedUmbracoUrl { get; }
/// <summary>
/// Gets the published snapshot.
/// </summary>
public IPublishedSnapshot PublishedSnapshot => _publishedSnapshot.Value;
/// <summary>
/// Gets the published content cache.
/// </summary>
[Obsolete("Use the Content property.")]
public IPublishedContentCache ContentCache => PublishedSnapshot.Content;
/// <summary>
/// Gets the published content cache.
/// </summary>
public IPublishedContentCache Content => PublishedSnapshot.Content;
/// <summary>
/// Gets the published media cache.
/// </summary>
[Obsolete("Use the Media property.")]
public IPublishedMediaCache MediaCache => PublishedSnapshot.Media;
/// <summary>
/// Gets the published media cache.
/// </summary>
public IPublishedMediaCache Media => PublishedSnapshot.Media;
/// <summary>
/// Gets the domains cache.
/// </summary>
public IDomainCache Domains => PublishedSnapshot.Domains;
/// <summary>
/// Boolean value indicating whether the current request is a front-end umbraco request
/// </summary>
public bool IsFrontEndUmbracoRequest => PublishedRequest != null;
/// <summary>
/// Gets the url provider.
/// </summary>
public UrlProvider UrlProvider { get; }
/// <summary>
/// Gets/sets the PublishedRequest object
/// </summary>
public PublishedRequest PublishedRequest { get; set; }
/// <summary>
/// Exposes the HttpContext for the current request
/// </summary>
public HttpContextBase HttpContext { get; }
/// <summary>
/// Gets the variation context accessor.
/// </summary>
public IVariationContextAccessor VariationContextAccessor { get; }
/// <summary>
/// Gets a value indicating whether the request has debugging enabled
/// </summary>
/// <value><c>true</c> if this instance is debug; otherwise, <c>false</c>.</value>
public bool IsDebug
{
get
{
var request = GetRequestFromContext();
//NOTE: the request can be null during app startup!
return GlobalSettings.DebugMode
&& request != null
&& (string.IsNullOrEmpty(request["umbdebugshowtrace"]) == false
|| string.IsNullOrEmpty(request["umbdebug"]) == false
|| string.IsNullOrEmpty(request.Cookies["UMB-DEBUG"]?.Value) == false);
}
}
/// <summary>
/// Determines whether the current user is in a preview mode and browsing the site (ie. not in the admin UI)
/// </summary>
public bool InPreviewMode
{
get
{
if (_previewing.HasValue == false) DetectPreviewMode();
return _previewing ?? false;
}
private set => _previewing = value;
}
#region Urls
/// <summary>
/// Gets the url of a content identified by its identifier.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <param name="culture"></param>
/// <returns>The url for the content.</returns>
public string Url(int contentId, string culture = null)
{
return UrlProvider.GetUrl(contentId, culture: culture);
}
/// <summary>
/// Gets the url of a content identified by its identifier.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <param name="culture"></param>
/// <returns>The url for the content.</returns>
public string Url(Guid contentId, string culture = null)
{
return UrlProvider.GetUrl(contentId, culture: culture);
}
/// <summary>
/// Gets the url of a content identified by its identifier, in a specified mode.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <param name="mode">The mode.</param>
/// <param name="culture"></param>
/// <returns>The url for the content.</returns>
public string Url(int contentId, UrlMode mode, string culture = null)
{
return UrlProvider.GetUrl(contentId, mode, culture);
}
/// <summary>
/// Gets the url of a content identified by its identifier, in a specified mode.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <param name="mode">The mode.</param>
/// <param name="culture"></param>
/// <returns>The url for the content.</returns>
public string Url(Guid contentId, UrlMode mode, string culture = null)
{
return UrlProvider.GetUrl(contentId, mode, culture);
}
/// <summary>
/// Gets the absolute url of a content identified by its identifier.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <param name="culture"></param>
/// <returns>The absolute url for the content.</returns>
[Obsolete("Use the Url() method with UrlMode.Absolute.")]
public string UrlAbsolute(int contentId, string culture = null)
{
return UrlProvider.GetUrl(contentId, UrlMode.Absolute, culture);
}
/// <summary>
/// Gets the absolute url of a content identified by its identifier.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <param name="culture"></param>
/// <returns>The absolute url for the content.</returns>
[Obsolete("Use the Url() method with UrlMode.Absolute.")]
public string UrlAbsolute(Guid contentId, string culture = null)
{
return UrlProvider.GetUrl(contentId, UrlMode.Absolute, culture);
}
#endregion
private string PreviewToken
{
get
{
if (_previewing.HasValue == false) DetectPreviewMode();
return _previewToken;
}
}
private void DetectPreviewMode()
{
var request = GetRequestFromContext();
if (request?.Url != null
&& request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, _globalSettings) == false
&& Security.CurrentUser != null)
{
var previewToken = request.GetPreviewCookieValue(); // may be null or empty
_previewToken = previewToken.IsNullOrWhiteSpace() ? null : previewToken;
}
_previewing = _previewToken.IsNullOrWhiteSpace() == false;
}
// say we render a macro or RTE in a give 'preview' mode that might not be the 'current' one,
// then due to the way it all works at the moment, the 'current' published snapshot need to be in the proper
// default 'preview' mode - somehow we have to force it. and that could be recursive.
internal IDisposable ForcedPreview(bool preview)
{
InPreviewMode = preview;
return PublishedSnapshot.ForcedPreview(preview, orig => InPreviewMode = orig);
}
private HttpRequestBase GetRequestFromContext()
{
try
{
return HttpContext.Request;
}
catch (HttpException)
{
return null;
}
}
protected override void DisposeResources()
{
// DisposableObject ensures that this runs only once
Security.DisposeIfDisposable();
// help caches release resources
// (but don't create caches just to dispose them)
// context is not multi-threaded
if (_publishedSnapshot.IsValueCreated)
_publishedSnapshot.Value.Dispose();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Compute.Fluent
{
using Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Definition;
using Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// The implementation for GalleryImage and its create and update interfaces.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uR2FsbGVyeUltYWdlSW1wbA==
internal partial class GalleryImageImpl :
CreatableUpdatable<Microsoft.Azure.Management.Compute.Fluent.IGalleryImage,
Models.GalleryImageInner,
Microsoft.Azure.Management.Compute.Fluent.GalleryImageImpl,
IHasId,
IUpdate>,
IGalleryImage,
IDefinition,
IUpdate
{
private string galleryImageName;
private string galleryName;
private IComputeManager computeManager;
private string resourceGroupName;
///GENMHASH:27AE3C88D6A0823E2356C59DA4236D18:666F587DB54BEB717C40C0642603C57C
internal GalleryImageImpl(string name, IComputeManager computeManager) : base(name, new GalleryImageInner())
{
this.computeManager = computeManager;
// Set resource name
this.galleryImageName = name;
}
///GENMHASH:7085203F0E54D9143441675F515A5350:8187A0188F5A617E219748998105A41C
internal GalleryImageImpl(GalleryImageInner inner, IComputeManager computeManager) : base(inner.Name, inner)
{
this.computeManager = computeManager;
// Set resource name
this.galleryImageName = inner.Name;
// resource ancestor names
this.resourceGroupName = GetValueFromIdByName(inner.Id, "resourceGroups");
this.galleryName = GetValueFromIdByName(inner.Id, "galleries");
this.galleryImageName = GetValueFromIdByName(inner.Id, "images");
}
///GENMHASH:7B3CA3D467253D93C6FF7587C3C0D0B7:F5293CC540B22E551BB92F6FCE17DE2C
public string Description()
{
return this.Inner.Description;
}
///GENMHASH:9A64142FBBAA15A12F245837F69E96FC:C0D602DEFC3F98CE1F6CCC5F0E7012C8
public Disallowed Disallowed()
{
return this.Inner.Disallowed;
}
///GENMHASH:E6D1DF89668E0AD4124D23BB98631AC0:253C5A8AA0CBC938019059050302255C
public DateTime? EndOfLifeDate()
{
return this.Inner.EndOfLifeDate;
}
///GENMHASH:638FC117F6C00F9473BA079A3C081D9C:9353C175CA560A336F913CAF055AF981
public string Eula()
{
return this.Inner.Eula;
}
///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:899F2B088BBBD76CCBC31221756265BC
public string Id()
{
return this.Inner.Id;
}
///GENMHASH:4D478BD54577C4E8EA7106DF1AB25435:694E5498526F78972B783CD90E235C66
public GalleryImageIdentifier Identifier()
{
return this.Inner.Identifier;
}
///GENMHASH:A85BBC58BA3B783F90EB92B75BD97D51:3054A3D10ED7865B89395E7C007419C9
public string Location()
{
return this.Inner.Location;
}
///GENMHASH:B6961E0C7CB3A9659DE0E1489F44A936:168EFDB95EECDB98D4BDFCCA32101AC1
public IComputeManager Manager()
{
return this.computeManager;
}
///GENMHASH:3E38805ED0E7BA3CAEE31311D032A21C:61C1065B307679F3800C701AE0D87070
public override string Name
{
get
{
if (base.Name == null)
{
return this.Inner.Name;
}
else
{
return base.Name;
}
}
}
string IHasId.Id
{
get
{
return this.Id();
}
}
///GENMHASH:C8DCA7493B3D93CC58B7F779B4A3944C:A3BA84BA84AB2202398D3A6E65C5F76A
public OperatingSystemStateTypes? OSState()
{
return this.Inner.OsState;
}
///GENMHASH:1BAF4F1B601F89251ABCFE6CC4867026:F71645491B82E137E4D1786750E7ADF0
public OperatingSystemTypes? OSType()
{
return this.Inner.OsType;
}
///GENMHASH:B36E92D071C2D2632B90A6792DC9FAAF:9DCD82DEC86B01C07765B045E56BAB5F
public string PrivacyStatementUri()
{
return this.Inner.PrivacyStatementUri;
}
///GENMHASH:99D5BF64EA8AA0E287C9B6F77AAD6FC4:220D4662AAC7DF3BEFAF2B253278E85C
public ProvisioningState ProvisioningState()
{
return this.Inner.ProvisioningState;
}
///GENMHASH:7BF8931EF46F2FF0CF8FAD2663BC8F23:C3F84D08346618993E076B02237B84D9
public ImagePurchasePlan PurchasePlan()
{
return this.Inner.PurchasePlan;
}
///GENMHASH:6C30DC9FBD3D6CDF3BBB75B625DA990E:FC00F099BFC148181C0F3BD72E4B1BB4
public RecommendedMachineConfiguration RecommendedVirtualMachineConfiguration()
{
return this.Inner.Recommended;
}
///GENMHASH:45CB5EDC146E59116E681E4FA893DA9D:1847D4773368CE9C950D03D06E70E1A0
public string ReleaseNoteUri()
{
return this.Inner.ReleaseNoteUri;
}
///GENMHASH:4B19A5F1B35CA91D20F63FBB66E86252:3E9F81F446FDF2A19095DC13C7608416
public IReadOnlyDictionary<string, string> Tags()
{
if (this.Inner.Tags == null)
{
return new Dictionary<string, string>();
}
else
{
return this.Inner.Tags.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
}
///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:23EC4B61BB9F1DFE8F251827F8E66FF4
protected override async Task<Models.GalleryImageInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var client = this.computeManager.Inner.GalleryImages;
return await client.GetAsync(this.resourceGroupName, this.galleryName, this.galleryImageName, cancellationToken);
}
///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:3EE578C74AE5F7B41F5C490A1DC7D638
public override async Task<Microsoft.Azure.Management.Compute.Fluent.IGalleryImage> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var client = this.computeManager.Inner.GalleryImages;
var inner = await client.CreateOrUpdateAsync(this.resourceGroupName, this.galleryName, this.galleryImageName, this.Inner, cancellationToken);
this.SetInner(inner);
return this;
}
///GENMHASH:4A32A0416E219F53BE84CDA28E1A7FD1:1A75F5D887CCA16C68B3E18528A673E1
public IGalleryImageVersion GetVersion(string versionName)
{
return this.computeManager.GalleryImageVersions.GetByGalleryImage(this.resourceGroupName, this.galleryName, this.galleryImageName, versionName);
}
///GENMHASH:7F002133997D7216F18BB8D21CF034D2:BE28E3F7E873613CF430C710146DC5B3
public async Task<Microsoft.Azure.Management.Compute.Fluent.IGalleryImageVersion> GetVersionAsync(string versionName, CancellationToken cancellationToken = default(CancellationToken))
{
return await this.computeManager.GalleryImageVersions.GetByGalleryImageAsync(this.resourceGroupName, this.galleryName, this.galleryImageName, versionName, cancellationToken);
}
///GENMHASH:37F76E5729DFBD562C6418F2290EBC6E:86927F304FB8C992B92BE20600A9354A
public IEnumerable<Microsoft.Azure.Management.Compute.Fluent.IGalleryImageVersion> ListVersions()
{
return this.computeManager.GalleryImageVersions.ListByGalleryImage(this.resourceGroupName, this.galleryName, this.galleryImageName);
}
///GENMHASH:D4A7A02E673639C444C53A8D52EFA5E3:6BDB02D858015991B4568658D3E9ADC2
public async Task<IPagedCollection<Microsoft.Azure.Management.Compute.Fluent.IGalleryImageVersion>> ListVersionsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await this.computeManager.GalleryImageVersions.ListByGalleryImageAsync(this.resourceGroupName, this.galleryName, this.galleryImageName, cancellationToken);
}
///GENMHASH:8442F1C1132907DE46B62B277F4EE9B7:605B8FC69F180AFC7CE18C754024B46C
public string Type()
{
return this.Inner.Type;
}
///GENMHASH:46AD705474F82EB01989BDC537143CDA:E24CCAC647CB1E84A09989E367AC3866
public IReadOnlyList<Models.DiskSkuTypes> UnsupportedDiskTypes()
{
if (this.Inner.Disallowed == null || this.Inner.Disallowed.DiskTypes == null)
{
return new List<Models.DiskSkuTypes>();
}
else
{
List<DiskSkuTypes> diskTypes = new List<DiskSkuTypes>();
foreach(var diskTypeStr in this.Inner.Disallowed.DiskTypes)
{
diskTypes.Add(DiskSkuTypes.FromStorageAccountType(StorageAccountTypes.Parse(diskTypeStr)));
}
return diskTypes;
}
}
///GENMHASH:016764F09D1966D691B5DE3A7FD47AC9:5D67BF1D9DA1008F878F13C112FF5F35
public GalleryImageImpl WithDescription(string description)
{
this.Inner.Description = description;
return this;
}
///GENMHASH:07B06D37077546C0B927329D67C53A81:79C20DF0A1E7505EA0686D15E34FECA3
public GalleryImageImpl WithDisallowed(Disallowed disallowed)
{
this.Inner.Disallowed = disallowed;
return this;
}
///GENMHASH:6E6C9FDCE928A4707B0B6A71AD136F25:0D8FEF56B96316FB8667DA78C5C84F07
public GalleryImageImpl WithEndOfLifeDate(DateTime endOfLifeDate)
{
this.Inner.EndOfLifeDate = endOfLifeDate;
return this;
}
///GENMHASH:3E2F10CC43558B774476B4098C4B5AAB:5EAED4443132B650A90DAC7E22166BA5
public GalleryImageImpl WithEula(string eula)
{
this.Inner.Eula = eula;
return this;
}
///GENMHASH:A665BD8151EF9002B07A6E1C8B87CDB8:6698608EA6DD6C61B2F2C8FA3AE030C8
public GalleryImageImpl WithExistingGallery(string resourceGroupName, string galleryName)
{
this.resourceGroupName = resourceGroupName;
this.galleryName = galleryName;
return this;
}
///GENMHASH:122D20BE545BE3A9BA66426AA6D8F239:63AE95F215B8467877CE9E7DFD592E08
public GalleryImageImpl WithExistingGallery(IGallery gallery)
{
this.resourceGroupName = gallery.ResourceGroupName;
this.galleryName = gallery.Name;
return this;
}
///GENMHASH:1EECE36B662887AA5C7C35565C99004E:00986057020BA21F25DC9703C93425B5
public GalleryImageImpl WithGeneralizedLinux()
{
return this.WithLinux(OperatingSystemStateTypes.Generalized);
}
///GENMHASH:71FAF9C45070E7CFF3E5C7BEDBD9DC0C:A57DB503FD70A521A97595B8FEF4B6AB
public GalleryImageImpl WithGeneralizedWindows()
{
return this.WithWindows(OperatingSystemStateTypes.Generalized);
}
///GENMHASH:4FF261989C984084E4F237BBB3F3166D:C1387D5805B738EDA65329EFF9CEDD95
public GalleryImageImpl WithIdentifier(GalleryImageIdentifier identifier)
{
this.Inner.Identifier = identifier;
return this;
}
///GENMHASH:D2D95F5FA658E1ECA4DB864407B55C44:989E2C520E5575DC9C7E40E25FF2D269
public GalleryImageImpl WithIdentifier(string publisher, string offer, string sku)
{
this.Inner.Identifier = new GalleryImageIdentifier()
{
Publisher = publisher,
Offer = offer,
Sku = sku
};
return this;
}
///GENMHASH:3472074D1AB5FCC22AE56AFE70FDA2F8:E55B773D65A05FA8865303A9358A98E3
public GalleryImageImpl WithLinux(OperatingSystemStateTypes osState)
{
this.Inner.OsType = OperatingSystemTypes.Linux;
this.Inner.OsState = osState;
return this;
}
///GENMHASH:C8421133DBC453BD76FCC9BC29C80FA1:E4BC2D6403FDE9DB36572C1A7DC24543
public GalleryImageImpl WithLocation(string location)
{
this.Inner.Location = location;
return this;
}
///GENMHASH:3E6A2E1842CF7045A3B0CF12AF9A85DA:8631322721E2C0858A3ABA04A72303A3
public GalleryImageImpl WithLocation(Region location)
{
this.Inner.Location = location.ToString();
return this;
}
///GENMHASH:B193C7EB04D97343DA56B771815DD347:058990A9D00E548A58C7CAB261EFDC30
public GalleryImageImpl WithOsState(OperatingSystemStateTypes osState)
{
this.Inner.OsState = osState;
return this;
}
///GENMHASH:327CBF262F4C69D4F67206A8BC678FD6:6E1EBADD62B789305803912915AD8226
public GalleryImageImpl WithoutUnsupportedDiskType(DiskSkuTypes diskType)
{
if (this.Inner.Disallowed != null && this.Inner.Disallowed.DiskTypes != null)
{
int foundIndex = -1;
int i = 0;
string diskTypeToRemove = diskType.ToString();
foreach(var diskTypeStr in this.Inner.Disallowed.DiskTypes)
{
if (diskTypeStr.Equals(diskTypeToRemove, StringComparison.OrdinalIgnoreCase))
{
foundIndex = i;
break;
}
i++;
}
if (foundIndex != -1)
{
this.Inner.Disallowed.DiskTypes.RemoveAt(foundIndex);
}
}
return this;
}
///GENMHASH:542B4A501337E966839DDFF5B784C5A4:956B22DE0183A9B1B40E11CB72457E23
public GalleryImageImpl WithPrivacyStatementUri(string privacyStatementUri)
{
this.Inner.PrivacyStatementUri = privacyStatementUri;
return this;
}
///GENMHASH:77CF9954FB80D58565A3BDE78A132F2F:4738D18AB791EDFE3036C5D639ECDCBC
public GalleryImageImpl WithPurchasePlan(string name, string publisher, string product)
{
return this.WithPurchasePlan(new ImagePurchasePlan()
{
Name = name,
Publisher = publisher,
Product = product
});
}
///GENMHASH:BD26D6DAB7F06580CA699479A1DBE779:2D7E0C7182D588C854835401FBDB12AD
public GalleryImageImpl WithPurchasePlan(ImagePurchasePlan purchasePlan)
{
this.Inner.PurchasePlan = purchasePlan;
return this;
}
///GENMHASH:BB6C17CE4E2C9A3D847511D22875485F:EA7F351EB07905E692E2BECFD19BC27B
public GalleryImageImpl WithRecommendedConfigurationForVirtualMachine(RecommendedMachineConfiguration recommendedConfig)
{
this.Inner.Recommended = recommendedConfig;
return this;
}
///GENMHASH:4B9730E760025024AE0695C6FF9355B8:D8AD9C6C8CC4609ADE980226D7CE3AEB
public GalleryImageImpl WithRecommendedCPUsCountForVirtualMachine(int minCount, int maxCount)
{
if (this.Inner.Recommended == null)
{
this.Inner.Recommended = new RecommendedMachineConfiguration();
}
this.Inner.Recommended.VCPUs = new ResourceRange();
this.Inner.Recommended.VCPUs.Min = minCount;
this.Inner.Recommended.VCPUs.Max = maxCount;
return this;
}
///GENMHASH:DDA950D600673E301DECA66A7863B693:924C935C729B6146EC774C42879D933F
public GalleryImageImpl WithRecommendedMaximumCPUsCountForVirtualMachine(int maxCount)
{
if (this.Inner.Recommended == null)
{
this.Inner.Recommended = new RecommendedMachineConfiguration();
}
if (this.Inner.Recommended.VCPUs == null)
{
this.Inner.Recommended.VCPUs = new ResourceRange();
}
this.Inner.Recommended.VCPUs.Max = maxCount;
return this;
}
///GENMHASH:2ED7D3217FD38DE3DA520C7017035348:EBCB4883E483A73B5F2C7252C4B36813
public GalleryImageImpl WithRecommendedMaximumMemoryForVirtualMachine(int maxMB)
{
if (this.Inner.Recommended == null)
{
this.Inner.Recommended = new RecommendedMachineConfiguration();
}
if (this.Inner.Recommended.Memory == null)
{
this.Inner.Recommended.Memory = new ResourceRange();
}
this.Inner.Recommended.Memory.Max = maxMB;
return this;
}
///GENMHASH:2863D36B6A808F64907758A2B0A545C2:7EA77ABCEDE9DAC4A98451F7B01A8605
public GalleryImageImpl WithRecommendedMemoryForVirtualMachine(int minMB, int maxMB)
{
if (this.Inner.Recommended == null)
{
this.Inner.Recommended = new RecommendedMachineConfiguration();
}
this.Inner.Recommended.Memory = new ResourceRange();
this.Inner.Recommended.Memory.Min = minMB;
this.Inner.Recommended.Memory.Max = maxMB;
return this;
}
///GENMHASH:F7ACEEC719739062CB2C5BA6C1B464CE:A244673762C643DCAAC847470E807C35
public GalleryImageImpl WithRecommendedMinimumCPUsCountForVirtualMachine(int minCount)
{
if (this.Inner.Recommended == null)
{
this.Inner.Recommended = new RecommendedMachineConfiguration();
}
if (this.Inner.Recommended.VCPUs == null)
{
this.Inner.Recommended.VCPUs = new ResourceRange();
}
this.Inner.Recommended.VCPUs.Min = minCount;
return this;
}
///GENMHASH:D9EF1129EF6CFD5E1A9EC1C65BF718DA:F854E305471A3B494755B48029FEB01B
public GalleryImageImpl WithRecommendedMinimumMemoryForVirtualMachine(int minMB)
{
if (this.Inner.Recommended == null)
{
this.Inner.Recommended = new RecommendedMachineConfiguration();
}
if (this.Inner.Recommended.Memory == null)
{
this.Inner.Recommended.Memory = new ResourceRange();
}
this.Inner.Recommended.Memory.Min = minMB;
//$ return this;
return this;
}
///GENMHASH:8702D5B193A52AEA4A057F86D0EB6218:C967D26B6FD51C024F09767139ADC2EC
public GalleryImageImpl WithReleaseNoteUri(string releaseNoteUri)
{
this.Inner.ReleaseNoteUri = releaseNoteUri;
return this;
}
///GENMHASH:32E35A609CF1108D0FC5FAAF9277C1AA:0A35F4FBFC584D98FAACCA25325781E8
public GalleryImageImpl WithTags(IDictionary<string,string> tags)
{
this.Inner.Tags = tags;
return this;
}
///GENMHASH:BA0EA3BD50E3CD77EC22B73FFC802C41:744865003C628CE889C88FAC8E7D6E87
public GalleryImageImpl WithUnsupportedDiskType(DiskSkuTypes diskType)
{
if (this.Inner.Disallowed == null)
{
this.Inner.Disallowed = new Disallowed();
}
if (this.Inner.Disallowed.DiskTypes == null)
{
this.Inner.Disallowed.DiskTypes = new List<string>();
}
bool found = false;
string newDiskTypeStr = diskType.ToString();
foreach(var diskTypeStr in this.Inner.Disallowed.DiskTypes)
{
if (diskTypeStr.Equals(newDiskTypeStr, StringComparison.OrdinalIgnoreCase))
{
found = true;
break;
}
}
if (!found)
{
this.Inner.Disallowed.DiskTypes.Add(diskType.ToString());
}
return this;
}
///GENMHASH:847C05E525547573F21D410720E5BB39:0EA8BD8DFAC2B974572CF97EE781C58C
public GalleryImageImpl WithUnsupportedDiskTypes(IList<Models.DiskSkuTypes> diskTypes)
{
if (this.Inner.Disallowed == null)
{
this.Inner.Disallowed = new Disallowed();
}
this.Inner.Disallowed.DiskTypes = new List<string>();
foreach(var diskType in diskTypes)
{
this.Inner.Disallowed.DiskTypes.Add(diskType.ToString());
}
return this;
}
///GENMHASH:255C87A909686D389A226B73B5FC61E0:9D9164D3A619DF1BDF4D73358606FD40
public GalleryImageImpl WithWindows(OperatingSystemStateTypes osState)
{
this.Inner.OsType = OperatingSystemTypes.Windows;
this.Inner.OsState = osState;
return this;
}
///GENMHASH:040C20433B133A485717B23B1FE2B123:C873BEE2B01DFD8C21B2393F5FD68243
private static string GetValueFromIdByName(string id, string name)
{
if (id == null)
{
return null;
}
else
{
IEnumerable<string> enumerable = id.Split(new char[] { '/' });
var itr = enumerable.GetEnumerator();
while (itr.MoveNext())
{
string part = itr.Current;
if (!string.IsNullOrEmpty(part))
{
if (part.Equals(name, StringComparison.OrdinalIgnoreCase))
{
if (itr.MoveNext())
{
return itr.Current;
}
else
{
return null;
}
}
}
}
return null;
}
}
}
}
| |
// ------------------------------------------------------------------------------
// <copyright file="_HttpRequestStream.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ------------------------------------------------------------------------------
namespace System.Net {
using System.IO;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;
using System.Collections;
using System.Security.Permissions;
using System.Threading.Tasks;
unsafe class HttpRequestStream : Stream {
private HttpListenerContext m_HttpContext;
private uint m_DataChunkOffset;
private int m_DataChunkIndex;
private bool m_Closed;
internal const int MaxReadSize = 0x20000; //http.sys recommends we limit reads to 128k
private bool m_InOpaqueMode;
internal HttpRequestStream(HttpListenerContext httpContext) {
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::.ctor() HttpListenerContext#" + ValidationHelper.HashString(httpContext));
m_HttpContext = httpContext;
}
public override bool CanSeek {
get {
return false;
}
}
public override bool CanWrite {
get {
return false;
}
}
public override bool CanRead {
get {
return true;
}
}
internal bool Closed
{
get
{
return m_Closed;
}
}
internal bool BufferedDataChunksAvailable
{
get
{
return m_DataChunkIndex > -1;
}
}
// This low level API should only be consumed if the caller can make sure that the state is not corrupted
// WebSocketHttpListenerDuplexStream (a duplex wrapper around HttpRequestStream/HttpResponseStream)
// is currenlty the only consumer of this API
internal HttpListenerContext InternalHttpContext
{
get
{
return m_HttpContext;
}
}
public override void Flush() {
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public override long Length {
get {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
}
public override long Position {
get {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
set {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
}
public override long Seek(long offset, SeekOrigin origin) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
public override void SetLength(long value) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
public override int Read([In, Out] byte[] buffer, int offset, int size) {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "Read", "");
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::Read() size:" + size + " offset:" + offset);
if (buffer==null) {
throw new ArgumentNullException("buffer");
}
if (offset<0 || offset>buffer.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (size<0 || size>buffer.Length-offset) {
throw new ArgumentOutOfRangeException("size");
}
if (size==0 || m_Closed) {
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "Read", "dataRead:0");
return 0;
}
uint dataRead = 0;
if (m_DataChunkIndex != -1) {
dataRead = UnsafeNclNativeMethods.HttpApi.GetChunks(m_HttpContext.Request.RequestBuffer, m_HttpContext.Request.OriginalBlobAddress, ref m_DataChunkIndex, ref m_DataChunkOffset, buffer, offset, size);
}
if(m_DataChunkIndex == -1 && dataRead < size){
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::Read() size:" + size + " offset:" + offset);
uint statusCode = 0;
uint extraDataRead = 0;
offset+= (int) dataRead;
size-=(int)dataRead;
//the http.sys team recommends that we limit the size to 128kb
if(size > MaxReadSize){
size = MaxReadSize;
}
fixed (byte *pBuffer = buffer) {
// issue unmanaged blocking call
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::Read() calling UnsafeNclNativeMethods.HttpApi.HttpReceiveRequestEntityBody");
uint flags = 0;
if (!m_InOpaqueMode)
{
flags = (uint)UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY;
}
statusCode =
UnsafeNclNativeMethods.HttpApi.HttpReceiveRequestEntityBody(
m_HttpContext.RequestQueueHandle,
m_HttpContext.RequestId,
flags,
(void*)(pBuffer + offset),
(uint)size,
out extraDataRead,
null);
dataRead+=extraDataRead;
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::Read() call to UnsafeNclNativeMethods.HttpApi.HttpReceiveRequestEntityBody returned:" + statusCode + " dataRead:" + dataRead);
}
if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_HANDLE_EOF) {
Exception exception = new HttpListenerException((int)statusCode);
if(Logging.On)Logging.Exception(Logging.HttpListener, this, "Read", exception);
throw exception;
}
UpdateAfterRead(statusCode, dataRead);
}
if(Logging.On)Logging.Dump(Logging.HttpListener, this, "Read", buffer, offset, (int)dataRead);
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::Read() returning dataRead:" + dataRead);
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "Read", "dataRead:" + dataRead);
return (int)dataRead;
}
void UpdateAfterRead(uint statusCode, uint dataRead) {
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::UpdateAfterRead() statusCode:" + statusCode + " m_Closed:" + m_Closed);
if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_HANDLE_EOF || dataRead == 0) {
Close();
}
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::UpdateAfterRead() statusCode:" + statusCode + " m_Closed:" + m_Closed);
}
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) {
if(Logging.On) Logging.Enter(Logging.HttpListener, this, "BeginRead", "");
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::BeginRead() buffer.Length:" + buffer.Length + " size:" + size + " offset:" + offset);
if (buffer==null) {
throw new ArgumentNullException("buffer");
}
if (offset<0 || offset>buffer.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (size<0 || size>buffer.Length-offset) {
throw new ArgumentOutOfRangeException("size");
}
if (size==0 || m_Closed) {
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "BeginRead", "");
HttpRequestStreamAsyncResult result = new HttpRequestStreamAsyncResult(this, state, callback);
result.InvokeCallback((uint) 0);
return result;
}
HttpRequestStreamAsyncResult asyncResult = null;
uint dataRead = 0;
if (m_DataChunkIndex != -1) {
dataRead = UnsafeNclNativeMethods.HttpApi.GetChunks(m_HttpContext.Request.RequestBuffer, m_HttpContext.Request.OriginalBlobAddress, ref m_DataChunkIndex, ref m_DataChunkOffset, buffer, offset, size);
if (m_DataChunkIndex != -1 && dataRead == size) {
asyncResult = new HttpRequestStreamAsyncResult(this, state, callback, buffer, offset, (uint)size, 0);
asyncResult.InvokeCallback(dataRead);
}
}
if (m_DataChunkIndex == -1 && dataRead < size) {
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::BeginRead() size:" + size + " offset:" + offset);
uint statusCode = 0;
offset += (int)dataRead;
size -= (int)dataRead;
//the http.sys team recommends that we limit the size to 128kb
if (size > MaxReadSize) {
size = MaxReadSize;
}
asyncResult = new HttpRequestStreamAsyncResult(this, state, callback, buffer, offset, (uint)size, dataRead);
uint bytesReturned;
try {
fixed (byte* pBuffer = buffer) {
// issue unmanaged blocking call
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::BeginRead() calling UnsafeNclNativeMethods.HttpApi.HttpReceiveRequestEntityBody");
m_HttpContext.EnsureBoundHandle();
uint flags = 0;
if (!m_InOpaqueMode)
{
flags = (uint)UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY;
}
statusCode =
UnsafeNclNativeMethods.HttpApi.HttpReceiveRequestEntityBody(
m_HttpContext.RequestQueueHandle,
m_HttpContext.RequestId,
flags,
asyncResult.m_pPinnedBuffer,
(uint)size,
out bytesReturned,
asyncResult.m_pOverlapped);
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::BeginRead() call to UnsafeNclNativeMethods.HttpApi.HttpReceiveRequestEntityBody returned:" + statusCode + " dataRead:" + dataRead);
}
}
catch (Exception e) {
if (Logging.On) Logging.Exception(Logging.HttpListener, this, "BeginRead", e);
asyncResult.InternalCleanup();
throw;
}
if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING) {
asyncResult.InternalCleanup();
if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_HANDLE_EOF) {
asyncResult = new HttpRequestStreamAsyncResult(this, state, callback, dataRead);
asyncResult.InvokeCallback((uint)0);
}
else {
Exception exception = new HttpListenerException((int)statusCode);
if (Logging.On) Logging.Exception(Logging.HttpListener, this, "BeginRead", exception);
asyncResult.InternalCleanup();
throw exception;
}
}
else if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
// IO operation completed synchronously - callback won't be called to signal completion.
asyncResult.IOCompleted(statusCode, bytesReturned);
}
}
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "BeginRead", "");
return asyncResult;
}
public override int EndRead(IAsyncResult asyncResult) {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "EndRead", "");
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::EndRead() asyncResult#" + ValidationHelper.HashString(asyncResult));
if (asyncResult==null) {
throw new ArgumentNullException("asyncResult");
}
HttpRequestStreamAsyncResult castedAsyncResult = asyncResult as HttpRequestStreamAsyncResult;
if (castedAsyncResult==null || castedAsyncResult.AsyncObject!=this) {
throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
}
if (castedAsyncResult.EndCalled) {
throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndRead"));
}
castedAsyncResult.EndCalled = true;
// wait & then check for errors
object returnValue = castedAsyncResult.InternalWaitForCompletion();
Exception exception = returnValue as Exception;
if (exception!=null) {
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::EndRead() rethrowing exception:" + exception);
if(Logging.On)Logging.Exception(Logging.HttpListener, this, "EndRead", exception);
throw exception;
}
//
uint dataRead = (uint)returnValue;
UpdateAfterRead((uint)castedAsyncResult.ErrorCode, dataRead);
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::EndRead() returning returnValue:" + ValidationHelper.ToString(returnValue));
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "EndRead", "");
return (int)dataRead + (int)castedAsyncResult.m_dataAlreadyRead;
}
public override void Write(byte[] buffer, int offset, int size) {
throw new InvalidOperationException(SR.GetString(SR.net_readonlystream));
}
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) {
throw new InvalidOperationException(SR.GetString(SR.net_readonlystream));
}
public override void EndWrite(IAsyncResult asyncResult) {
throw new InvalidOperationException(SR.GetString(SR.net_readonlystream));
}
protected override void Dispose(bool disposing) {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "Dispose", "");
try {
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::Dispose(bool) m_Closed:" + m_Closed);
m_Closed = true;
}
finally {
base.Dispose(disposing);
}
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "Dispose", "");
}
internal void SwitchToOpaqueMode()
{
GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::SwitchToOpaqueMode()");
m_InOpaqueMode = true;
}
// This low level API should only be consumed if the caller can make sure that the state is not corrupted
// WebSocketHttpListenerDuplexStream (a duplex wrapper around HttpRequestStream/HttpResponseStream)
// is currenlty the only consumer of this API
internal uint GetChunks(byte[] buffer, int offset, int size)
{
return UnsafeNclNativeMethods.HttpApi.GetChunks(m_HttpContext.Request.RequestBuffer,
m_HttpContext.Request.OriginalBlobAddress,
ref m_DataChunkIndex,
ref m_DataChunkOffset,
buffer,
offset,
size);
}
unsafe class HttpRequestStreamAsyncResult : LazyAsyncResult {
internal NativeOverlapped* m_pOverlapped;
internal void* m_pPinnedBuffer;
internal uint m_dataAlreadyRead = 0;
private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(Callback);
internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback) : base(asyncObject, userState, callback) {
}
internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback, uint dataAlreadyRead) : base(asyncObject, userState, callback) {
m_dataAlreadyRead = dataAlreadyRead;
}
internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback, byte[] buffer, int offset, uint size, uint dataAlreadyRead): base(asyncObject, userState, callback) {
m_dataAlreadyRead = dataAlreadyRead;
Overlapped overlapped = new Overlapped();
overlapped.AsyncResult = this;
m_pOverlapped = overlapped.Pack(s_IOCallback, buffer);
m_pPinnedBuffer = (void*)(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset));
}
internal void IOCompleted(uint errorCode, uint numBytes)
{
IOCompleted(this, errorCode, numBytes);
}
private static void IOCompleted(HttpRequestStreamAsyncResult asyncResult, uint errorCode, uint numBytes)
{
GlobalLog.Print("HttpRequestStreamAsyncResult#" + ValidationHelper.HashString(asyncResult) + "::Callback() errorCode:0x" + errorCode.ToString("x8") + " numBytes:" + numBytes);
object result = null;
try {
if (errorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && errorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_HANDLE_EOF) {
asyncResult.ErrorCode = (int)errorCode;
result = new HttpListenerException((int)errorCode);
}
else {
result = numBytes;
if(Logging.On)Logging.Dump(Logging.HttpListener, asyncResult, "Callback", (IntPtr)asyncResult.m_pPinnedBuffer, (int)numBytes);
}
GlobalLog.Print("HttpRequestStreamAsyncResult#" + ValidationHelper.HashString(asyncResult) + "::Callback() calling Complete()");
}
catch (Exception e) {
result = e;
}
asyncResult.InvokeCallback(result);
}
private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) {
Overlapped callbackOverlapped = Overlapped.Unpack(nativeOverlapped);
HttpRequestStreamAsyncResult asyncResult = callbackOverlapped.AsyncResult as HttpRequestStreamAsyncResult;
GlobalLog.Print("HttpRequestStreamAsyncResult#" + ValidationHelper.HashString(asyncResult) + "::Callback() errorCode:0x" + errorCode.ToString("x8") + " numBytes:" + numBytes + " nativeOverlapped:0x" + ((IntPtr)nativeOverlapped).ToString("x8"));
IOCompleted(asyncResult, errorCode, numBytes);
}
// Will be called from the base class upon InvokeCallback()
protected override void Cleanup() {
base.Cleanup();
if (m_pOverlapped != null) {
Overlapped.Free(m_pOverlapped);
}
}
}
}
}
| |
/*
Copyright (c) 2001 Lapo Luchini.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
/* This file is a port of jzlib v1.0.7, com.jcraft.jzlib.ZOutputStream.java
*/
using System;
using System.Diagnostics;
using System.IO;
namespace Org.BouncyCastle.Utilities.Zlib
{
public class ZOutputStream
: Stream
{
private const int BufferSize = 512;
protected ZStream z = new ZStream();
protected int flushLevel = JZlib.Z_NO_FLUSH;
// TODO Allow custom buf
protected byte[] buf = new byte[BufferSize];
protected byte[] buf1 = new byte[1];
protected bool compress;
protected Stream output;
protected bool closed;
public ZOutputStream(Stream output)
: base()
{
Debug.Assert(output.CanWrite);
this.output = output;
this.z.inflateInit();
this.compress = false;
}
public ZOutputStream(Stream output, int level)
: this(output, level, false)
{
}
public ZOutputStream(Stream output, int level, bool nowrap)
: base()
{
Debug.Assert(output.CanWrite);
this.output = output;
this.z.deflateInit(level, nowrap);
this.compress = true;
}
public sealed override bool CanRead { get { return false; } }
public sealed override bool CanSeek { get { return false; } }
public sealed override bool CanWrite { get { return !closed; } }
#if !NETFX_CORE
public override void Close()
{
if (this.closed)
return;
try
{
try
{
Finish();
}
catch (IOException)
{
// Ignore
}
}
finally
{
this.closed = true;
End();
output.Close();
output = null;
}
}
#else
protected override void Dispose(bool disposing)
{
if (this.closed)
return;
try
{
try
{
Finish();
}
catch (IOException)
{
// Ignore
}
}
finally
{
this.closed = true;
End();
output.Dispose();
output = null;
}
base.Dispose(disposing);
}
#endif
public virtual void End()
{
if (z == null)
return;
if (compress)
z.deflateEnd();
else
z.inflateEnd();
z.free();
z = null;
}
public virtual void Finish()
{
do
{
z.next_out = buf;
z.next_out_index = 0;
z.avail_out = buf.Length;
int err = compress
? z.deflate(JZlib.Z_FINISH)
: z.inflate(JZlib.Z_FINISH);
if (err != JZlib.Z_STREAM_END && err != JZlib.Z_OK)
// TODO
// throw new ZStreamException((compress?"de":"in")+"flating: "+z.msg);
throw new IOException((compress ? "de" : "in") + "flating: " + z.msg);
int count = buf.Length - z.avail_out;
if (count > 0)
{
output.Write(buf, 0, count);
}
}
while (z.avail_in > 0 || z.avail_out == 0);
Flush();
}
public override void Flush()
{
if(output != null)
output.Flush();
}
public virtual int FlushMode
{
get { return flushLevel; }
set { this.flushLevel = value; }
}
public sealed override long Length { get { throw new NotSupportedException(); } }
public sealed override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public sealed override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
public sealed override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
public sealed override void SetLength(long value) { throw new NotSupportedException(); }
public virtual long TotalIn
{
get { return z.total_in; }
}
public virtual long TotalOut
{
get { return z.total_out; }
}
public override void Write(byte[] b, int off, int len)
{
if (len == 0)
return;
z.next_in = b;
z.next_in_index = off;
z.avail_in = len;
do
{
z.next_out = buf;
z.next_out_index = 0;
z.avail_out = buf.Length;
int err = compress
? z.deflate(flushLevel)
: z.inflate(flushLevel);
if (err != JZlib.Z_OK)
// TODO
// throw new ZStreamException((compress ? "de" : "in") + "flating: " + z.msg);
throw new IOException((compress ? "de" : "in") + "flating: " + z.msg);
output.Write(buf, 0, buf.Length - z.avail_out);
}
while (z.avail_in > 0 || z.avail_out == 0);
}
public override void WriteByte(byte b)
{
buf1[0] = b;
Write(buf1, 0, 1);
}
}
}
| |
/*
* CID000b.cs - fi culture handler.
*
* Copyright (c) 2003 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "fi.txt".
namespace I18N.West
{
using System;
using System.Globalization;
using I18N.Common;
public class CID000b : RootCulture
{
public CID000b() : base(0x000B) {}
public CID000b(int culture) : base(culture) {}
public override String Name
{
get
{
return "fi";
}
}
public override String ThreeLetterISOLanguageName
{
get
{
return "fin";
}
}
public override String ThreeLetterWindowsLanguageName
{
get
{
return "FIN";
}
}
public override String TwoLetterISOLanguageName
{
get
{
return "fi";
}
}
public override DateTimeFormatInfo DateTimeFormat
{
get
{
DateTimeFormatInfo dfi = base.DateTimeFormat;
dfi.AbbreviatedDayNames = new String[] {"su", "ma", "ti", "ke", "to", "pe", "la"};
dfi.DayNames = new String[] {"sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai"};
dfi.AbbreviatedMonthNames = new String[] {"tammi", "helmi", "maalis", "huhti", "touko", "kes\u00E4", "hein\u00E4", "elo", "syys", "loka", "marras", "joulu", ""};
dfi.MonthNames = new String[] {"tammikuu", "helmikuu", "maaliskuu", "huhtikuu", "toukokuu", "kes\u00E4kuu", "hein\u00E4kuu", "elokuu", "syyskuu", "lokakuu", "marraskuu", "joulukuu", ""};
dfi.DateSeparator = ".";
dfi.TimeSeparator = ":";
dfi.LongDatePattern = "d. MMMM'ttt 'yyyy";
dfi.LongTimePattern = "HH:mm:ss z";
dfi.ShortDatePattern = "d.M.yyyy";
dfi.ShortTimePattern = "HH:mm";
dfi.FullDateTimePattern = "d. MMMM'ttt 'yyyy HH:mm:ss z";
dfi.I18NSetDateTimePatterns(new String[] {
"d:d.M.yyyy",
"D:d. MMMM'ttt 'yyyy",
"f:d. MMMM'ttt 'yyyy HH:mm:ss z",
"f:d. MMMM'ttt 'yyyy HH:mm:ss z",
"f:d. MMMM'ttt 'yyyy HH:mm:ss",
"f:d. MMMM'ttt 'yyyy HH:mm",
"F:d. MMMM'ttt 'yyyy HH:mm:ss",
"g:d.M.yyyy HH:mm:ss z",
"g:d.M.yyyy HH:mm:ss z",
"g:d.M.yyyy HH:mm:ss",
"g:d.M.yyyy HH:mm",
"G:d.M.yyyy HH:mm:ss",
"m:MMMM dd",
"M:MMMM dd",
"r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"s:yyyy'-'MM'-'dd'T'HH':'mm':'ss",
"t:HH:mm:ss z",
"t:HH:mm:ss z",
"t:HH:mm:ss",
"t:HH:mm",
"T:HH:mm:ss",
"u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
"U:dddd, dd MMMM yyyy HH:mm:ss",
"y:yyyy MMMM",
"Y:yyyy MMMM",
});
return dfi;
}
set
{
base.DateTimeFormat = value; // not used
}
}
public override NumberFormatInfo NumberFormat
{
get
{
NumberFormatInfo nfi = base.NumberFormat;
nfi.CurrencyDecimalSeparator = ",";
nfi.CurrencyGroupSeparator = "\u00A0";
nfi.NumberGroupSeparator = "\u00A0";
nfi.PercentGroupSeparator = "\u00A0";
nfi.NegativeSign = "-";
nfi.NumberDecimalSeparator = ",";
nfi.PercentDecimalSeparator = ",";
nfi.PercentSymbol = "%";
nfi.PerMilleSymbol = "\u2030";
return nfi;
}
set
{
base.NumberFormat = value; // not used
}
}
public override String ResolveLanguage(String name)
{
switch(name)
{
case "ar": return "arabia";
case "az": return "azerbaizani";
case "ba": return "baski";
case "be": return "valkoven\u00e4j\u00e4";
case "bg": return "bulgaria";
case "bh": return "bihari";
case "bn": return "bengali";
case "ca": return "katalaani";
case "cs": return "tsekki";
case "da": return "tanska";
case "de": return "saksa";
case "el": return "kreikka";
case "en": return "englanti";
case "es": return "espanja";
case "et": return "viro";
case "fa": return "farsi";
case "fi": return "suomi";
case "fr": return "ranska";
case "he": return "heprea";
case "hi": return "hindi";
case "hr": return "kroatia";
case "hu": return "unkari";
case "id": return "indonesia";
case "it": return "italia";
case "ja": return "japani";
case "ka": return "georgia";
case "kk": return "kazakki";
case "km": return "khmer";
case "kn": return "kannada";
case "ko": return "korea";
case "ku": return "kurdi";
case "la": return "latinalainen";
case "lt": return "liettua";
case "lv": return "latvia";
case "mk": return "makedonia";
case "mr": return "marathi";
case "my": return "burma";
case "nl": return "hollanti";
case "no": return "norja";
case "pl": return "puola";
case "pt": return "portugali";
case "ro": return "romania";
case "ru": return "ven\u00e4j\u00e4";
case "sk": return "slovakia";
case "sl": return "slovenia";
case "sq": return "albania";
case "sr": return "serbia";
case "sv": return "ruotsi";
case "sw": return "swahili";
case "te": return "telugu";
case "th": return "thai";
case "tk": return "tagalog";
case "tr": return "turkki";
case "uk": return "ukraina";
case "ur": return "urdu";
case "uz": return "uzbekki";
case "zh": return "kiina";
}
return base.ResolveLanguage(name);
}
public override String ResolveCountry(String name)
{
switch(name)
{
case "AE": return "Yhdistyneet Arabiemiraatit";
case "AT": return "It\u00e4valta";
case "BA": return "Bosnia";
case "BE": return "Belgia";
case "BR": return "Brasilia";
case "BY": return "Valko-Ven\u00e4j\u00e4";
case "CA": return "Kanada";
case "CH": return "Sveitsi";
case "CN": return "Kiina";
case "CO": return "Kolumbia";
case "CZ": return "Tsekin tasavalta";
case "DE": return "Saksa";
case "DK": return "Tanska";
case "DO": return "Dominikaaninen tasavalta";
case "EC": return "Equador";
case "EE": return "Viro";
case "EG": return "Egypti";
case "ES": return "Espanja";
case "FI": return "Suomi";
case "FR": return "Ranska";
case "GB": return "Iso-Britannia";
case "GR": return "Kreikka";
case "HR": return "Kroatia";
case "HU": return "Unkari";
case "HK": return "Hongknog, erit.hall.alue";
case "IE": return "Irlanti";
case "IN": return "Intia";
case "IS": return "Islanti";
case "IT": return "Italia";
case "JO": return "Jordania";
case "JP": return "Japani";
case "KR": return "Korea";
case "LA": return "Latinalainen Amerikka";
case "LB": return "Libanon";
case "LT": return "Liettua";
case "LU": return "Luxemburg";
case "MA": return "Marokko";
case "MK": return "Makedonia (FYR)";
case "MO": return "Macao, erit.hall.alue";
case "MX": return "Meksiko";
case "NL": return "Alankomaat";
case "NO": return "Norja";
case "NZ": return "Uusi Seelanti";
case "PL": return "Puola";
case "PT": return "Portugali";
case "RU": return "Ven\u00e4j\u00e4";
case "SA": return "Saudi-Arabia";
case "SE": return "Ruotsi";
case "SY": return "Syyria";
case "TH": return "Thaimaa";
case "TR": return "Turkki";
case "UA": return "Ukraina";
case "US": return "Yhdysvallat";
case "YE": return "Jemen";
case "ZA": return "Etel\u00e4-Afrikka";
}
return base.ResolveCountry(name);
}
private class PrivateTextInfo : _I18NTextInfo
{
public PrivateTextInfo(int culture) : base(culture) {}
public override int EBCDICCodePage
{
get
{
return 20278;
}
}
public override int OEMCodePage
{
get
{
return 850;
}
}
public override String ListSeparator
{
get
{
return ";";
}
}
}; // class PrivateTextInfo
public override TextInfo TextInfo
{
get
{
return new PrivateTextInfo(LCID);
}
}
}; // class CID000b
public class CNfi : CID000b
{
public CNfi() : base() {}
}; // class CNfi
}; // namespace I18N.West
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class CompilationContext
{
private static readonly SymbolDisplayFormat s_fullNameFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
internal readonly CSharpCompilation Compilation;
internal readonly Binder NamespaceBinder; // Internal for test purposes.
private readonly MetadataDecoder _metadataDecoder;
private readonly MethodSymbol _currentFrame;
private readonly ImmutableArray<LocalSymbol> _locals;
private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables;
private readonly ImmutableHashSet<string> _hoistedParameterNames;
private readonly ImmutableArray<LocalSymbol> _localsForBinding;
private readonly CSharpSyntaxNode _syntax;
private readonly bool _methodNotType;
/// <summary>
/// Create a context to compile expressions within a method scope.
/// </summary>
internal CompilationContext(
CSharpCompilation compilation,
MetadataDecoder metadataDecoder,
MethodSymbol currentFrame,
ImmutableArray<LocalSymbol> locals,
InScopeHoistedLocals inScopeHoistedLocals,
MethodDebugInfo methodDebugInfo,
CSharpSyntaxNode syntax)
{
Debug.Assert(string.IsNullOrEmpty(methodDebugInfo.DefaultNamespaceName));
Debug.Assert((syntax == null) || (syntax is ExpressionSyntax) || (syntax is LocalDeclarationStatementSyntax));
// TODO: syntax.SyntaxTree should probably be added to the compilation,
// but it isn't rooted by a CompilationUnitSyntax so it doesn't work (yet).
_currentFrame = currentFrame;
_syntax = syntax;
_methodNotType = !locals.IsDefault;
// NOTE: Since this is done within CompilationContext, it will not be cached.
// CONSIDER: The values should be the same everywhere in the module, so they
// could be cached.
// (Catch: what happens in a type context without a method def?)
this.Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords);
_metadataDecoder = metadataDecoder;
// Each expression compile should use a unique compilation
// to ensure expression-specific synthesized members can be
// added (anonymous types, for instance).
Debug.Assert(this.Compilation != compilation);
this.NamespaceBinder = CreateBinderChain(
this.Compilation,
(PEModuleSymbol)currentFrame.ContainingModule,
currentFrame.ContainingNamespace,
methodDebugInfo.ImportRecordGroups,
_metadataDecoder);
if (_methodNotType)
{
_locals = locals;
ImmutableArray<string> displayClassVariableNamesInOrder;
GetDisplayClassVariables(
currentFrame,
_locals,
inScopeHoistedLocals,
out displayClassVariableNamesInOrder,
out _displayClassVariables,
out _hoistedParameterNames);
Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count);
_localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables);
}
else
{
_locals = ImmutableArray<LocalSymbol>.Empty;
_displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
_localsForBinding = ImmutableArray<LocalSymbol>.Empty;
}
// Assert that the cheap check for "this" is equivalent to the expensive check for "this".
Debug.Assert(
_displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()) ==
_displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This));
}
internal CommonPEModuleBuilder CompileExpression(
string typeName,
string methodName,
ImmutableArray<Alias> aliases,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics,
out ResultProperties resultProperties)
{
var properties = default(ResultProperties);
var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object);
var synthesizedType = new EENamedTypeSymbol(
this.Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
methodName,
this,
(method, diags) =>
{
var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName());
var binder = ExtendBinderChain(
_syntax,
aliases,
method,
this.NamespaceBinder,
hasDisplayClassThis,
_methodNotType);
var statementSyntax = _syntax as StatementSyntax;
return (statementSyntax == null) ?
BindExpression(binder, (ExpressionSyntax)_syntax, diags, out properties) :
BindStatement(binder, statementSyntax, diags, out properties);
});
var module = CreateModuleBuilder(
this.Compilation,
synthesizedType.Methods,
additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType),
synthesizedType: synthesizedType,
testData: testData,
diagnostics: diagnostics);
Debug.Assert(module != null);
this.Compilation.Compile(
module,
win32Resources: null,
xmlDocStream: null,
emittingPdb: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: CancellationToken.None);
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
// Should be no name mangling since the caller provided explicit names.
Debug.Assert(synthesizedType.MetadataName == typeName);
Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName);
resultProperties = properties;
return module;
}
internal CommonPEModuleBuilder CompileAssignment(
string typeName,
string methodName,
ImmutableArray<Alias> aliases,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics,
out ResultProperties resultProperties)
{
var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object);
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
methodName,
this,
(method, diags) =>
{
var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName());
var binder = ExtendBinderChain(
_syntax,
aliases,
method,
this.NamespaceBinder,
hasDisplayClassThis,
methodNotType: true);
return BindAssignment(binder, (ExpressionSyntax)_syntax, diags);
});
var module = CreateModuleBuilder(
this.Compilation,
synthesizedType.Methods,
additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType),
synthesizedType: synthesizedType,
testData: testData,
diagnostics: diagnostics);
Debug.Assert(module != null);
this.Compilation.Compile(
module,
win32Resources: null,
xmlDocStream: null,
emittingPdb: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: CancellationToken.None);
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
// Should be no name mangling since the caller provided explicit names.
Debug.Assert(synthesizedType.MetadataName == typeName);
Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName);
resultProperties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect);
return module;
}
private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder)
{
return string.Format("<>m{0}", builder.Count);
}
/// <summary>
/// Generate a class containing methods that represent
/// the set of arguments and locals at the current scope.
/// </summary>
internal CommonPEModuleBuilder CompileGetLocals(
string typeName,
ArrayBuilder<LocalAndMethod> localBuilder,
bool argumentsOnly,
ImmutableArray<Alias> aliases,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics)
{
var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object);
var allTypeParameters = _currentFrame.GetAllTypeParameters();
var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance();
EENamedTypeSymbol typeVariablesType = null;
if (!argumentsOnly && (allTypeParameters.Length > 0))
{
// Generate a generic type with matching type parameters.
// A null instance of the type will be used to represent the
// "Type variables" local.
typeVariablesType = new EENamedTypeSymbol(
this.Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
ExpressionCompilerConstants.TypeVariablesClassName,
(m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)),
allTypeParameters,
(t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2));
additionalTypes.Add(typeVariablesType);
}
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
(m, container) =>
{
var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance();
if (!argumentsOnly)
{
// Pseudo-variables: $exception, $ReturnValue, etc.
if (aliases.Length > 0)
{
var sourceAssembly = Compilation.SourceAssembly;
var typeNameDecoder = new EETypeNameDecoder(Compilation, (PEModuleSymbol)_currentFrame.ContainingModule);
foreach (var alias in aliases)
{
var local = PlaceholderLocalSymbol.Create(
typeNameDecoder,
_currentFrame,
sourceAssembly,
alias);
var methodName = GetNextMethodName(methodBuilder);
var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken));
var aliasMethod = this.CreateMethod(container, methodName, syntax, (method, diags) =>
{
var expression = new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
var flags = local.IsWritable ? DkmClrCompilationResultFlags.None : DkmClrCompilationResultFlags.ReadOnlyResult;
localBuilder.Add(MakeLocalAndMethod(local, aliasMethod, flags));
methodBuilder.Add(aliasMethod);
}
}
// "this" for non-static methods that are not display class methods or
// display class methods where the display class contains "<>4__this".
if (!m.IsStatic && (!IsDisplayClassType(m.ContainingType) || _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName())))
{
var methodName = GetNextMethodName(methodBuilder);
var method = this.GetThisMethod(container, methodName);
localBuilder.Add(new CSharpLocalAndMethod("this", "this", method, DkmClrCompilationResultFlags.None)); // Note: writable in dev11.
methodBuilder.Add(method);
}
}
// Hoisted method parameters (represented as locals in the EE).
if (!_hoistedParameterNames.IsEmpty)
{
int localIndex = 0;
foreach (var local in _localsForBinding)
{
// Since we are showing hoisted method parameters first, the parameters may appear out of order
// in the Locals window if only some of the parameters are hoisted. This is consistent with the
// behavior of the old EE.
if (_hoistedParameterNames.Contains(local.Name))
{
AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local));
}
localIndex++;
}
}
// Method parameters (except those that have been hoisted).
int parameterIndex = m.IsStatic ? 0 : 1;
foreach (var parameter in m.Parameters)
{
var parameterName = parameter.Name;
if (!_hoistedParameterNames.Contains(parameterName) && GeneratedNames.GetKind(parameterName) == GeneratedNameKind.None)
{
AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex);
}
parameterIndex++;
}
if (!argumentsOnly)
{
// Locals.
int localIndex = 0;
foreach (var local in _localsForBinding)
{
if (!_hoistedParameterNames.Contains(local.Name))
{
AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local));
}
localIndex++;
}
// "Type variables".
if ((object)typeVariablesType != null)
{
var methodName = GetNextMethodName(methodBuilder);
var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>());
var method = this.GetTypeVariablesMethod(container, methodName, returnType);
localBuilder.Add(new CSharpLocalAndMethod(
ExpressionCompilerConstants.TypeVariablesLocalName,
ExpressionCompilerConstants.TypeVariablesLocalName,
method,
DkmClrCompilationResultFlags.ReadOnlyResult));
methodBuilder.Add(method);
}
}
return methodBuilder.ToImmutableAndFree();
});
additionalTypes.Add(synthesizedType);
var module = CreateModuleBuilder(
this.Compilation,
synthesizedType.Methods,
additionalTypes: additionalTypes.ToImmutableAndFree(),
synthesizedType: synthesizedType,
testData: testData,
diagnostics: diagnostics);
Debug.Assert(module != null);
this.Compilation.Compile(
module,
win32Resources: null,
xmlDocStream: null,
emittingPdb: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: CancellationToken.None);
return diagnostics.HasAnyErrors() ? null : module;
}
private void AppendLocalAndMethod(
ArrayBuilder<LocalAndMethod> localBuilder,
ArrayBuilder<MethodSymbol> methodBuilder,
LocalSymbol local,
EENamedTypeSymbol container,
int localIndex,
DkmClrCompilationResultFlags resultFlags)
{
var methodName = GetNextMethodName(methodBuilder);
var method = this.GetLocalMethod(container, methodName, local.Name, localIndex);
localBuilder.Add(MakeLocalAndMethod(local, method, resultFlags));
methodBuilder.Add(method);
}
private void AppendParameterAndMethod(
ArrayBuilder<LocalAndMethod> localBuilder,
ArrayBuilder<MethodSymbol> methodBuilder,
ParameterSymbol parameter,
EENamedTypeSymbol container,
int parameterIndex)
{
// Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
// the ResultProvider needs to be able to disambiguate cases like "this" and "@this",
// which it can't do correctly without semantic information.
var name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name);
var methodName = GetNextMethodName(methodBuilder);
var method = this.GetParameterMethod(container, methodName, name, parameterIndex);
localBuilder.Add(new CSharpLocalAndMethod(name, name, method, DkmClrCompilationResultFlags.None));
methodBuilder.Add(method);
}
private static LocalAndMethod MakeLocalAndMethod(LocalSymbol local, MethodSymbol method, DkmClrCompilationResultFlags flags)
{
// Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
// the ResultProvider needs to be able to disambiguate cases like "this" and "@this",
// which it can't do correctly without semantic information.
var escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name);
var displayName = (local as PlaceholderLocalSymbol)?.DisplayName ?? escapedName;
return new CSharpLocalAndMethod(escapedName, displayName, method, flags);
}
private static EEAssemblyBuilder CreateModuleBuilder(
CSharpCompilation compilation,
ImmutableArray<MethodSymbol> methods,
ImmutableArray<NamedTypeSymbol> additionalTypes,
EENamedTypeSymbol synthesizedType,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics)
{
// Each assembly must have a unique name.
var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName());
var dynamicOperationContextType = GetNonDisplayClassContainer(synthesizedType.SubstitutedSourceType);
string runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics);
var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion);
return new EEAssemblyBuilder(compilation.SourceAssembly, emitOptions, methods, serializationProperties, additionalTypes, dynamicOperationContextType, testData);
}
internal EEMethodSymbol CreateMethod(
EENamedTypeSymbol container,
string methodName,
CSharpSyntaxNode syntax,
GenerateMethodBody generateMethodBody)
{
return new EEMethodSymbol(
container,
methodName,
syntax.Location,
_currentFrame,
_locals,
_localsForBinding,
_displayClassVariables,
generateMethodBody);
}
private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex)
{
var syntax = SyntaxFactory.IdentifierName(localName);
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var local = method.LocalsForBinding[localIndex];
var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, diagnostics), type: local.Type);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex)
{
var syntax = SyntaxFactory.IdentifierName(parameterName);
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var parameter = method.Parameters[parameterIndex];
var expression = new BoundParameter(syntax, parameter);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName)
{
var syntax = SyntaxFactory.ThisExpression();
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType));
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType)
{
var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken));
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var type = method.TypeMap.SubstituteNamedType(typeVariablesType);
var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]);
var statement = new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
return statement;
});
}
private static BoundStatement BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties)
{
var flags = DkmClrCompilationResultFlags.None;
// In addition to C# expressions, the native EE also supports
// type names which are bound to a representation of the type
// (but not System.Type) that the user can expand to see the
// base type. Instead, we only allow valid C# expressions.
var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue);
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression))
{
flags |= DkmClrCompilationResultFlags.PotentialSideEffect;
}
var expressionType = expression.Type;
if ((object)expressionType == null)
{
expression = binder.CreateReturnConversion(
syntax,
diagnostics,
expression,
binder.Compilation.GetSpecialType(SpecialType.System_Object));
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
}
else if (expressionType.SpecialType == SpecialType.System_Void)
{
flags |= DkmClrCompilationResultFlags.ReadOnlyResult;
Debug.Assert(expression.ConstantValue == null);
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false);
return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true };
}
else if (expressionType.SpecialType == SpecialType.System_Boolean)
{
flags |= DkmClrCompilationResultFlags.BoolResult;
}
if (!IsAssignableExpression(binder, expression))
{
flags |= DkmClrCompilationResultFlags.ReadOnlyResult;
}
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
}
private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties)
{
properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
return binder.BindStatement(syntax, diagnostics);
}
private static bool IsAssignableExpression(Binder binder, BoundExpression expression)
{
// NOTE: Surprisingly, binder.CheckValueKind will return true (!) for readonly fields
// in contexts where they cannot be assigned - it simply reports a diagnostic.
// Presumably, this is done to avoid producing a confusing error message about the
// field not being an lvalue.
var diagnostics = DiagnosticBag.GetInstance();
var result = binder.CheckValueKind(expression, Binder.BindValueKind.Assignment, diagnostics) &&
!diagnostics.HasAnyErrors();
diagnostics.Free();
return result;
}
private static BoundStatement BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics)
{
var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue);
if (diagnostics.HasAnyErrors())
{
return null;
}
return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true };
}
private static Binder CreateBinderChain(
CSharpCompilation compilation,
PEModuleSymbol module,
NamespaceSymbol @namespace,
ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups,
MetadataDecoder metadataDecoder)
{
var stack = ArrayBuilder<string>.GetInstance();
while ((object)@namespace != null)
{
stack.Push(@namespace.Name);
@namespace = @namespace.ContainingNamespace;
}
var binder = (new BuckStopsHereBinder(compilation)).WithAdditionalFlags(
BinderFlags.SuppressObsoleteChecks |
BinderFlags.IgnoreAccessibility |
BinderFlags.UnsafeRegion |
BinderFlags.UncheckedRegion |
BinderFlags.AllowManagedAddressOf |
BinderFlags.AllowAwaitInUnsafeContext |
BinderFlags.IgnoreCorLibraryDuplicatedTypes);
var hasImports = !importRecordGroups.IsDefaultOrEmpty;
var numImportStringGroups = hasImports ? importRecordGroups.Length : 0;
var currentStringGroup = numImportStringGroups - 1;
// PERF: We used to call compilation.GetCompilationNamespace on every iteration,
// but that involved walking up to the global namespace, which we have to do
// anyway. Instead, we'll inline the functionality into our own walk of the
// namespace chain.
@namespace = compilation.GlobalNamespace;
while (stack.Count > 0)
{
var namespaceName = stack.Pop();
if (namespaceName.Length > 0)
{
// We're re-getting the namespace, rather than using the one containing
// the current frame method, because we want the merged namespace.
@namespace = @namespace.GetNestedNamespace(namespaceName);
Debug.Assert((object)@namespace != null,
$"We worked backwards from symbols to names, but no symbol exists for name '{namespaceName}'");
}
else
{
Debug.Assert((object)@namespace == (object)compilation.GlobalNamespace);
}
Imports imports = null;
if (hasImports)
{
if (currentStringGroup < 0)
{
Debug.WriteLine($"No import string group for namespace '{@namespace}'");
break;
}
var importsBinder = new InContainerBinder(@namespace, binder);
imports = BuildImports(compilation, module, importRecordGroups[currentStringGroup], importsBinder, metadataDecoder);
currentStringGroup--;
}
binder = new InContainerBinder(@namespace, binder, imports);
}
stack.Free();
if (currentStringGroup >= 0)
{
// CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since
// the usings are already for the wrong method.
Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces");
}
return binder;
}
private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords)
{
if (externAliasRecords.IsDefaultOrEmpty)
{
return compilation.Clone();
}
var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance();
var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance();
foreach (var reference in compilation.References)
{
updatedReferences.Add(reference);
assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference));
}
Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count);
var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree();
foreach (var externAliasRecord in externAliasRecords)
{
int index = externAliasRecord.GetIndexOfTargetAssembly(assembliesAndModules, compilation.Options.AssemblyIdentityComparer);
if (index < 0)
{
Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'");
continue;
}
var externAlias = externAliasRecord.Alias;
var assemblyReference = updatedReferences[index];
var oldAliases = assemblyReference.Properties.Aliases;
var newAliases = oldAliases.IsEmpty
? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias)
: oldAliases.Concat(ImmutableArray.Create(externAlias));
// NOTE: Dev12 didn't emit custom debug info about "global", so we don't have
// a good way to distinguish between a module aliased with both (e.g.) "X" and
// "global" and a module aliased with only "X". As in Dev12, we assume that
// "global" is a valid alias to remain at least as permissive as source.
// NOTE: In the event that this introduces ambiguities between two assemblies
// (e.g. because one was "global" in source and the other was "X"), it should be
// possible to disambiguate as long as each assembly has a distinct extern alias,
// not necessarily used in source.
Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias));
// Replace the value in the map with the updated reference.
updatedReferences[index] = assemblyReference.WithAliases(newAliases);
}
compilation = compilation.WithReferences(updatedReferences);
updatedReferences.Free();
return compilation;
}
private static Binder ExtendBinderChain(
CSharpSyntaxNode syntax,
ImmutableArray<Alias> aliases,
EEMethodSymbol method,
Binder binder,
bool hasDisplayClassThis,
bool methodNotType)
{
var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis);
var substitutedSourceType = substitutedSourceMethod.ContainingType;
var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance();
for (var type = substitutedSourceType; (object)type != null; type = type.ContainingType)
{
stack.Add(type);
}
while (stack.Count > 0)
{
substitutedSourceType = stack.Pop();
binder = new InContainerBinder(substitutedSourceType, binder);
if (substitutedSourceType.Arity > 0)
{
binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArguments, binder);
}
}
stack.Free();
if (substitutedSourceMethod.Arity > 0)
{
binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArguments, binder);
}
if (methodNotType)
{
// Method locals and parameters shadow pseudo-variables.
var typeNameDecoder = new EETypeNameDecoder(binder.Compilation, (PEModuleSymbol)substitutedSourceMethod.ContainingModule);
binder = new PlaceholderLocalBinder(
syntax,
aliases,
method,
typeNameDecoder,
binder);
}
binder = new EEMethodBinder(method, substitutedSourceMethod, binder);
if (methodNotType)
{
binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder);
}
return binder;
}
private static Imports BuildImports(CSharpCompilation compilation, PEModuleSymbol module, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder, MetadataDecoder metadataDecoder)
{
// We make a first pass to extract all of the extern aliases because other imports may depend on them.
var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance();
foreach (var importRecord in importRecords)
{
if (importRecord.TargetKind != ImportTargetKind.Assembly)
{
continue;
}
var alias = importRecord.Alias;
IdentifierNameSyntax aliasNameSyntax;
if (!TryParseIdentifierNameSyntax(alias, out aliasNameSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'");
continue;
}
var externAliasSyntax = SyntaxFactory.ExternAliasDirective(aliasNameSyntax.Identifier);
var aliasSymbol = new AliasSymbol(binder, externAliasSyntax); // Binder is only used to access compilation.
externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null)); // We have one, but we pass null for consistency.
}
var externs = externsBuilder.ToImmutableAndFree();
if (externs.Any())
{
// NB: This binder (and corresponding Imports) is only used to bind the other imports.
// We'll merge the externs into a final Imports object and return that to be used in
// the actual binder chain.
binder = new InContainerBinder(
binder.Container,
binder,
Imports.FromCustomDebugInfo(binder.Compilation, ImmutableDictionary<string, AliasAndUsingDirective>.Empty, ImmutableArray<NamespaceOrTypeAndUsingDirective>.Empty, externs));
}
var usingAliases = ImmutableDictionary.CreateBuilder<string, AliasAndUsingDirective>();
var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance();
foreach (var importRecord in importRecords)
{
switch (importRecord.TargetKind)
{
case ImportTargetKind.Type:
{
var portableImportRecord = importRecord as PortableImportRecord;
TypeSymbol typeSymbol = portableImportRecord != null
? portableImportRecord.GetTargetType(metadataDecoder)
: metadataDecoder.GetTypeSymbolForSerializedType(importRecord.TargetString);
Debug.Assert((object)typeSymbol != null);
if (typeSymbol.IsErrorType())
{
// Type is unrecognized. The import may have been
// valid in the original source but unnecessary.
continue; // Don't add anything for this import.
}
else if (importRecord.Alias == null && !typeSymbol.IsStatic)
{
// Only static types can be directly imported.
continue;
}
if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord))
{
continue;
}
break;
}
case ImportTargetKind.Namespace:
{
var namespaceName = importRecord.TargetString;
NameSyntax targetSyntax;
if (!SyntaxHelpers.TryParseDottedName(namespaceName, out targetSyntax))
{
// DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}".
// Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}"
// (which will rarely work and never be correct).
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'");
continue;
}
NamespaceSymbol namespaceSymbol;
var portableImportRecord = importRecord as PortableImportRecord;
if (portableImportRecord != null)
{
var targetAssembly = portableImportRecord.GetTargetAssembly<ModuleSymbol, AssemblySymbol>(module, module.Module);
if ((object)targetAssembly == null)
{
namespaceSymbol = BindNamespace(namespaceName, compilation.GlobalNamespace);
}
else if (targetAssembly.IsMissing)
{
Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'");
continue;
}
else
{
namespaceSymbol = BindNamespace(namespaceName, targetAssembly.GlobalNamespace);
}
}
else
{
var globalNamespace = compilation.GlobalNamespace;
var externAlias = ((NativeImportRecord)importRecord).ExternAlias;
if (externAlias != null)
{
IdentifierNameSyntax externAliasSyntax = null;
if (!TryParseIdentifierNameSyntax(externAlias, out externAliasSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{externAlias}'");
continue;
}
var unusedDiagnostics = DiagnosticBag.GetInstance();
var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, unusedDiagnostics);
unusedDiagnostics.Free();
if ((object)aliasSymbol == null)
{
Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{externAlias}'");
continue;
}
globalNamespace = (NamespaceSymbol)aliasSymbol.Target;
}
namespaceSymbol = BindNamespace(namespaceName, globalNamespace);
}
if ((object)namespaceSymbol == null)
{
// Namespace is unrecognized. The import may have been
// valid in the original source but unnecessary.
continue; // Don't add anything for this import.
}
if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord))
{
continue;
}
break;
}
case ImportTargetKind.Assembly:
{
// Handled in first pass (above).
break;
}
default:
{
throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind);
}
}
}
return Imports.FromCustomDebugInfo(binder.Compilation, usingAliases.ToImmutableDictionary(), usingsBuilder.ToImmutableAndFree(), externs);
}
private static NamespaceSymbol BindNamespace(string namespaceName, NamespaceSymbol globalNamespace)
{
var namespaceSymbol = globalNamespace;
foreach (var name in namespaceName.Split('.'))
{
var members = namespaceSymbol.GetMembers(name);
namespaceSymbol = members.Length == 1
? members[0] as NamespaceSymbol
: null;
if ((object)namespaceSymbol == null)
{
break;
}
}
return namespaceSymbol;
}
private static bool TryAddImport(
string alias,
NamespaceOrTypeSymbol targetSymbol,
ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder,
ImmutableDictionary<string, AliasAndUsingDirective>.Builder usingAliases,
InContainerBinder binder,
ImportRecord importRecord)
{
if (alias == null)
{
usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null));
}
else
{
IdentifierNameSyntax aliasSyntax;
if (!TryParseIdentifierNameSyntax(alias, out aliasSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'");
return false;
}
var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder);
usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null));
}
return true;
}
private static bool TryParseIdentifierNameSyntax(string name, out IdentifierNameSyntax syntax)
{
Debug.Assert(name != null);
if (name == MetadataReferenceProperties.GlobalAlias)
{
syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword));
return true;
}
NameSyntax nameSyntax;
if (!SyntaxHelpers.TryParseDottedName(name, out nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName)
{
syntax = null;
return false;
}
syntax = (IdentifierNameSyntax)nameSyntax;
return true;
}
internal CommonMessageProvider MessageProvider
{
get { return this.Compilation.MessageProvider; }
}
private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local)
{
// CONSIDER: We might want to prevent the user from modifying pinned locals -
// that's pretty dangerous.
return local.IsConst
? DkmClrCompilationResultFlags.ReadOnlyResult
: DkmClrCompilationResultFlags.None;
}
/// <summary>
/// Generate the set of locals to use for binding.
/// </summary>
private static ImmutableArray<LocalSymbol> GetLocalsForBinding(
ImmutableArray<LocalSymbol> locals,
ImmutableArray<string> displayClassVariableNamesInOrder,
ImmutableDictionary<string, DisplayClassVariable> displayClassVariables)
{
var builder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var local in locals)
{
var name = local.Name;
if (name == null)
{
continue;
}
if (GeneratedNames.GetKind(name) != GeneratedNameKind.None)
{
continue;
}
// Although Roslyn doesn't name synthesized locals unless they are well-known to EE,
// Dev12 did so we need to skip them here.
if (GeneratedNames.IsSynthesizedLocalName(name))
{
continue;
}
builder.Add(local);
}
foreach (var variableName in displayClassVariableNamesInOrder)
{
var variable = displayClassVariables[variableName];
switch (variable.Kind)
{
case DisplayClassVariableKind.Local:
case DisplayClassVariableKind.Parameter:
builder.Add(new EEDisplayClassFieldLocalSymbol(variable));
break;
}
}
return builder.ToImmutableAndFree();
}
/// <summary>
/// Return a mapping of captured variables (parameters, locals, and
/// "this") to locals. The mapping is needed to expose the original
/// local identifiers (those from source) in the binder.
/// </summary>
private static void GetDisplayClassVariables(
MethodSymbol method,
ImmutableArray<LocalSymbol> locals,
InScopeHoistedLocals inScopeHoistedLocals,
out ImmutableArray<string> displayClassVariableNamesInOrder,
out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables,
out ImmutableHashSet<string> hoistedParameterNames)
{
// Calculated the shortest paths from locals to instances of display
// classes. There should not be two instances of the same display
// class immediately within any particular method.
var displayClassTypes = PooledHashSet<NamedTypeSymbol>.GetInstance();
var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance();
// Add any display class instances from locals (these will contain any hoisted locals).
foreach (var local in locals)
{
var name = local.Name;
if ((name != null) && (GeneratedNames.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField))
{
var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local);
displayClassTypes.Add(instance.Type);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
}
foreach (var parameter in method.Parameters)
{
if (GeneratedNames.GetKind(parameter.Name) == GeneratedNameKind.TransparentIdentifier)
{
var instance = new DisplayClassInstanceFromParameter(parameter);
displayClassTypes.Add(instance.Type);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
}
var containingType = method.ContainingType;
bool isIteratorOrAsyncMethod = false;
if (IsDisplayClassType(containingType))
{
if (!method.IsStatic)
{
// Add "this" display class instance.
var instance = new DisplayClassInstanceFromParameter(method.ThisParameter);
displayClassTypes.Add(instance.Type);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
isIteratorOrAsyncMethod = GeneratedNames.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType;
}
if (displayClassInstances.Any())
{
// Find any additional display class instances breadth first.
for (int depth = 0; GetDisplayClassInstances(displayClassTypes, displayClassInstances, depth) > 0; depth++)
{
}
// The locals are the set of all fields from the display classes.
var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance();
var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance();
var parameterNames = PooledHashSet<string>.GetInstance();
if (isIteratorOrAsyncMethod)
{
Debug.Assert(IsDisplayClassType(containingType));
foreach (var field in containingType.GetMembers().OfType<FieldSymbol>())
{
// All iterator and async state machine fields (including hoisted locals) have mangled names, except
// for hoisted parameters (whose field names are always the same as the original source parameters).
var fieldName = field.Name;
if (GeneratedNames.GetKind(fieldName) == GeneratedNameKind.None)
{
parameterNames.Add(fieldName);
}
}
}
else
{
foreach (var p in method.Parameters)
{
parameterNames.Add(p.Name);
}
}
var pooledHoistedParameterNames = PooledHashSet<string>.GetInstance();
foreach (var instance in displayClassInstances)
{
GetDisplayClassVariables(
displayClassVariableNamesInOrderBuilder,
displayClassVariablesBuilder,
parameterNames,
inScopeHoistedLocals,
instance,
pooledHoistedParameterNames);
}
hoistedParameterNames = pooledHoistedParameterNames.ToImmutableHashSet<string>();
pooledHoistedParameterNames.Free();
parameterNames.Free();
displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree();
displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary();
displayClassVariablesBuilder.Free();
}
else
{
hoistedParameterNames = ImmutableHashSet<string>.Empty;
displayClassVariableNamesInOrder = ImmutableArray<string>.Empty;
displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
}
displayClassTypes.Free();
displayClassInstances.Free();
}
/// <summary>
/// Return the set of display class instances that can be reached
/// from the given local. A particular display class may be reachable
/// from multiple locals. In those cases, the instance from the
/// shortest path (fewest intermediate fields) is returned.
/// </summary>
private static int GetDisplayClassInstances(
HashSet<NamedTypeSymbol> displayClassTypes,
ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances,
int depth)
{
Debug.Assert(displayClassInstances.All(p => p.Depth <= depth));
var atDepth = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance();
atDepth.AddRange(displayClassInstances.Where(p => p.Depth == depth));
Debug.Assert(atDepth.Count > 0);
int n = 0;
foreach (var instance in atDepth)
{
n += GetDisplayClassInstances(displayClassTypes, displayClassInstances, instance);
}
atDepth.Free();
return n;
}
private static int GetDisplayClassInstances(
HashSet<NamedTypeSymbol> displayClassTypes,
ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances,
DisplayClassInstanceAndFields instance)
{
// Display class instance. The display class fields are variables.
int n = 0;
foreach (var member in instance.Type.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldType = field.Type;
var fieldKind = GeneratedNames.GetKind(field.Name);
if (fieldKind == GeneratedNameKind.DisplayClassLocalOrField ||
fieldKind == GeneratedNameKind.TransparentIdentifier ||
IsTransparentIdentifierFieldInAnonymousType(field) ||
(fieldKind == GeneratedNameKind.ThisProxyField && GeneratedNames.GetKind(fieldType.Name) == GeneratedNameKind.LambdaDisplayClass)) // Async lambda case.
{
Debug.Assert(!field.IsStatic);
// A local that is itself a display class instance.
if (displayClassTypes.Add((NamedTypeSymbol)fieldType))
{
var other = instance.FromField(field);
displayClassInstances.Add(other);
n++;
}
}
}
return n;
}
private static bool IsTransparentIdentifierFieldInAnonymousType(FieldSymbol field)
{
string fieldName = field.Name;
if (GeneratedNames.GetKind(fieldName) != GeneratedNameKind.AnonymousTypeField)
{
return false;
}
GeneratedNameKind kind;
int openBracketOffset;
int closeBracketOffset;
if (!GeneratedNames.TryParseGeneratedName(fieldName, out kind, out openBracketOffset, out closeBracketOffset))
{
return false;
}
fieldName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
return GeneratedNames.GetKind(fieldName) == GeneratedNameKind.TransparentIdentifier;
}
private static void GetDisplayClassVariables(
ArrayBuilder<string> displayClassVariableNamesInOrderBuilder,
Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder,
HashSet<string> parameterNames,
InScopeHoistedLocals inScopeHoistedLocals,
DisplayClassInstanceAndFields instance,
HashSet<string> hoistedParameterNames)
{
// Display class instance. The display class fields are variables.
foreach (var member in instance.Type.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldName = field.Name;
REPARSE:
DisplayClassVariableKind variableKind;
string variableName;
GeneratedNameKind fieldKind;
int openBracketOffset;
int closeBracketOffset;
GeneratedNames.TryParseGeneratedName(fieldName, out fieldKind, out openBracketOffset, out closeBracketOffset);
switch (fieldKind)
{
case GeneratedNameKind.AnonymousTypeField:
Debug.Assert(fieldName == field.Name); // This only happens once.
fieldName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
goto REPARSE;
case GeneratedNameKind.TransparentIdentifier:
// A transparent identifier (field) in an anonymous type synthesized for a transparent identifier.
Debug.Assert(!field.IsStatic);
continue;
case GeneratedNameKind.DisplayClassLocalOrField:
// A local that is itself a display class instance.
Debug.Assert(!field.IsStatic);
continue;
case GeneratedNameKind.HoistedLocalField:
// Filter out hoisted locals that are known to be out-of-scope at the current IL offset.
// Hoisted locals with invalid indices will be included since more information is better
// than less in error scenarios.
if (!inScopeHoistedLocals.IsInScope(fieldName))
{
continue;
}
variableName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
variableKind = DisplayClassVariableKind.Local;
Debug.Assert(!field.IsStatic);
break;
case GeneratedNameKind.ThisProxyField:
// A reference to "this".
variableName = fieldName;
variableKind = DisplayClassVariableKind.This;
Debug.Assert(!field.IsStatic);
break;
case GeneratedNameKind.None:
// A reference to a parameter or local.
variableName = fieldName;
if (parameterNames.Contains(variableName))
{
variableKind = DisplayClassVariableKind.Parameter;
hoistedParameterNames.Add(variableName);
}
else
{
variableKind = DisplayClassVariableKind.Local;
}
Debug.Assert(!field.IsStatic);
break;
default:
continue;
}
if (displayClassVariablesBuilder.ContainsKey(variableName))
{
// Only expecting duplicates for async state machine
// fields (that should be at the top-level).
Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1);
Debug.Assert(instance.Fields.Count() >= 1); // greater depth
Debug.Assert((variableKind == DisplayClassVariableKind.Parameter) ||
(variableKind == DisplayClassVariableKind.This));
}
else if (variableKind != DisplayClassVariableKind.This || GeneratedNames.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass)
{
// In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one.
// In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one).
displayClassVariableNamesInOrderBuilder.Add(variableName);
displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field));
}
}
}
private static bool IsDisplayClassType(NamedTypeSymbol type)
{
switch (GeneratedNames.GetKind(type.Name))
{
case GeneratedNameKind.LambdaDisplayClass:
case GeneratedNameKind.StateMachineType:
return true;
default:
return false;
}
}
private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type)
{
// 1) Display class and state machine types are always nested within the types
// that use them (so that they can access private members of those types).
// 2) The native compiler used to produce nested display classes for nested lambdas,
// so we may have to walk out more than one level.
while (IsDisplayClassType(type))
{
type = type.ContainingType;
}
Debug.Assert((object)type != null);
return type;
}
/// <summary>
/// Identifies the method in which binding should occur.
/// </summary>
/// <param name="candidateSubstitutedSourceMethod">
/// The symbol of the method that is currently on top of the callstack, with
/// EE type parameters substituted in place of the original type parameters.
/// </param>
/// <param name="sourceMethodMustBeInstance">
/// True if "this" is available via a display class in the current context.
/// </param>
/// <returns>
/// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated,
/// then we will attempt to determine which user-defined method caused it to be
/// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/>
/// is a state machine MoveNext method, then we will try to find the iterator or
/// async method for which it was generated. If we are able to find the original
/// method, then we will substitute in the EE type parameters. Otherwise, we will
/// return <paramref name="candidateSubstitutedSourceMethod"/>.
/// </returns>
/// <remarks>
/// In the event that the original method is overloaded, we may not be able to determine
/// which overload actually corresponds to the state machine. In particular, we do not
/// have information about the signature of the original method (i.e. number of parameters,
/// parameter types and ref-kinds, return type). However, we conjecture that this
/// level of uncertainty is acceptable, since parameters are managed by a separate binder
/// in the synthesized binder chain and we have enough information to check the other method
/// properties that are used during binding (e.g. static-ness, generic arity, type parameter
/// constraints).
/// </remarks>
internal static MethodSymbol GetSubstitutedSourceMethod(
MethodSymbol candidateSubstitutedSourceMethod,
bool sourceMethodMustBeInstance)
{
var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType;
string desiredMethodName;
if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) ||
GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName))
{
// We could be in the MoveNext method of an async lambda.
string tempMethodName;
if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName))
{
desiredMethodName = tempMethodName;
var containing = candidateSubstitutedSourceType.ContainingType;
Debug.Assert((object)containing != null);
if (GeneratedNames.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass)
{
candidateSubstitutedSourceType = containing;
sourceMethodMustBeInstance = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNames.GetKind).Contains(GeneratedNameKind.ThisProxyField);
}
}
var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters;
// Type containing the original iterator, async, or lambda-containing method.
var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType);
foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>())
{
if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, sourceMethodMustBeInstance))
{
return desiredTypeParameters.Length == 0
? candidateMethod
: candidateMethod.Construct(candidateSubstitutedSourceType.TypeArguments);
}
}
Debug.Assert(false, "Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?");
}
return candidateSubstitutedSourceMethod;
}
private static bool IsViableSourceMethod(
MethodSymbol candidateMethod,
string desiredMethodName, ImmutableArray<TypeParameterSymbol> desiredTypeParameters, bool desiredMethodMustBeInstance)
{
return
!candidateMethod.IsAbstract &&
(!(desiredMethodMustBeInstance && candidateMethod.IsStatic)) &&
candidateMethod.Name == desiredMethodName &&
HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters);
}
private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters)
{
int arity = candidateTypeParameters.Length;
if (arity != desiredTypeParameters.Length)
{
return false;
}
else if (arity == 0)
{
return true;
}
var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity);
var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true);
var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true);
return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap);
}
private struct DisplayClassInstanceAndFields
{
internal readonly DisplayClassInstance Instance;
internal readonly ConsList<FieldSymbol> Fields;
internal DisplayClassInstanceAndFields(DisplayClassInstance instance) :
this(instance, ConsList<FieldSymbol>.Empty)
{
Debug.Assert(IsDisplayClassType(instance.Type) ||
GeneratedNames.GetKind(instance.Type.Name) == GeneratedNameKind.AnonymousType);
}
private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields)
{
this.Instance = instance;
this.Fields = fields;
}
internal NamedTypeSymbol Type
{
get { return this.Fields.Any() ? (NamedTypeSymbol)this.Fields.Head.Type : this.Instance.Type; }
}
internal int Depth
{
get { return this.Fields.Count(); }
}
internal DisplayClassInstanceAndFields FromField(FieldSymbol field)
{
Debug.Assert(IsDisplayClassType((NamedTypeSymbol)field.Type) ||
GeneratedNames.GetKind(field.Type.Name) == GeneratedNameKind.AnonymousType);
return new DisplayClassInstanceAndFields(this.Instance, this.Fields.Prepend(field));
}
internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field)
{
return new DisplayClassVariable(name, kind, this.Instance, this.Fields.Prepend(field));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using Codentia.Common.Reporting.DL;
using Microsoft.Reporting.WebForms;
namespace Codentia.Common.Reporting.BL
{
/// <summary>
/// CEReport class
/// </summary>
public class CEReport
{
private string _reportCode = string.Empty;
private int _reportId;
private string _reportName = string.Empty;
private string _rdlName = string.Empty;
private bool _isRdlc = false;
private string _tagReplacementXml = string.Empty;
private string _tagReplacementSP = string.Empty;
private Dictionary<string, CEReportDataSource> _mitReportDataSources = new Dictionary<string, CEReportDataSource>();
/// <summary>
/// Initializes a new instance of the <see cref="CEReport"/> class.
/// </summary>
/// <param name="reportCode">The report code.</param>
public CEReport(string reportCode)
{
_reportCode = reportCode;
DataTable dt = ReportingData.GetDataForReport(_reportCode);
DataRow dr = dt.Rows[0];
_reportId = Convert.ToInt32(dr["ReportId"]);
_reportName = Convert.ToString(dr["ReportName"]);
_rdlName = Convert.ToString(dr["RdlName"]);
_isRdlc = Convert.ToBoolean(dr["IsRdlc"]);
_tagReplacementXml = Convert.ToString(dr["TagReplacementXml"]);
_tagReplacementSP = Convert.ToString(dr["TagReplacementSP"]);
LoadDataSources();
}
/// <summary>
/// Gets the ReportCode
/// </summary>
public string ReportCode
{
get
{
return _reportCode;
}
}
/// <summary>
/// Gets the ReportId
/// </summary>
public int ReportId
{
get
{
return _reportId;
}
}
/// <summary>
/// Gets the ReportName
/// </summary>
public string ReportName
{
get
{
return _reportName;
}
}
/// <summary>
/// Gets the Rdl Name
/// </summary>
public string RdlName
{
get
{
return _rdlName;
}
}
/// <summary>
/// Gets or sets a value indicating whether the IsRdlc flag is set
/// </summary>
public bool IsRdlc
{
get
{
return _isRdlc;
}
set
{
_isRdlc = value;
}
}
/// <summary>
/// Gets the CEReportDataSources
/// </summary>
public Dictionary<string, CEReportDataSource> CEReportDataSources
{
get
{
return _mitReportDataSources;
}
}
/// <summary>
/// Gets the CollatedReportParameters
/// </summary>
public ReportParameter[] CollatedReportParameters
{
get
{
if (_isRdlc)
{
throw new Exception("CollatedReportParameters can only be used for rdl reports");
}
// Collate Report parameters for all data sources
Dictionary<int, ReportParameter[]> dict = new Dictionary<int, ReportParameter[]>();
int paramCount = 0;
IEnumerator<string> ieRP = _mitReportDataSources.Keys.GetEnumerator();
while (ieRP.MoveNext())
{
CEReportDataSource mrds = _mitReportDataSources[ieRP.Current];
if (mrds.CEReportParameters.Count > 0)
{
paramCount += mrds.CEReportParameters.Count;
}
}
ReportParameter[] repArray1 = new ReportParameter[paramCount];
int paramCount2 = 0;
int actualParamCount = 0;
StringBuilder sbCheck = new StringBuilder();
IEnumerator<string> ie2 = _mitReportDataSources.Keys.GetEnumerator();
while (ie2.MoveNext())
{
CEReportDataSource mrds = _mitReportDataSources[ie2.Current];
if (mrds.ReportParameters != null)
{
for (int i = 0; i < mrds.ReportParameters.Length; i++)
{
// ensure Parameter has not already been added
if (sbCheck.ToString().IndexOf(mrds.ReportParameters[i].Name) == -1)
{
repArray1[paramCount2] = mrds.ReportParameters[i];
sbCheck.Append(string.Format("{0} ", mrds.ReportParameters[i].Name));
actualParamCount++;
}
paramCount2++;
}
}
}
// correct Array for any null
ReportParameter[] repArray = new ReportParameter[actualParamCount];
int j = 0;
for (int i = 0; i < paramCount2; i++)
{
if (repArray1[i] != null)
{
repArray[j] = repArray1[i];
j++;
}
}
return repArray;
}
}
/// <summary>
/// Gets a value indicating whether ParametersAreRendered
/// </summary>
public bool ParametersAreRendered
{
get
{
IEnumerator<string> ieRP = _mitReportDataSources.Keys.GetEnumerator();
while (ieRP.MoveNext())
{
CEReportDataSource mrds = _mitReportDataSources[ieRP.Current];
if (mrds.ParametersAreRendered)
{
return true;
}
}
return false;
}
}
/// <summary>
/// Get ReportResult DataSet
/// Use the dictionary parameterValues to populate the parameters for each data source then return the dataset if the datatables
/// </summary>
/// <param name="parameterValues">parameter Values</param>
/// <returns>DataSet from report results</returns>
public DataSet GetReportResultDataSet(Dictionary<string, object> parameterValues)
{
// set values for all parameters in all data sources
IEnumerator<string> ie = parameterValues.Keys.GetEnumerator();
while (ie.MoveNext())
{
string[] arrDS = ie.Current.Split('_');
string ds = arrDS[0];
string paramCode = arrDS[1];
CEReportDataSource rds = _mitReportDataSources[ds];
rds.SetParameterValue(string.Format("{0}_{1}", rds.ReportDataSourceCode, paramCode), parameterValues[ie.Current]);
}
DataSet dsResult = new DataSet();
IEnumerator<string> ieDT = _mitReportDataSources.Keys.GetEnumerator();
while (ieDT.MoveNext())
{
CEReportDataSource rdsDT = _mitReportDataSources[ieDT.Current];
dsResult.Tables.Add(rdsDT.ResultTable);
}
return dsResult;
}
/// <summary>
/// Get Rdl StringReader
/// </summary>
/// <param name="applicationPath">path of application</param>
/// <returns>StringReader for Rdl</returns>
public StringReader GetRdlStringReader(string applicationPath)
{
if (_isRdlc)
{
throw new ArgumentException("GetRdlStringReader can only be used for rdl reports");
}
DataRow dr = null;
if (!string.IsNullOrEmpty(_tagReplacementXml) && !string.IsNullOrEmpty(_tagReplacementSP))
{
DataTable dt = ReportingData.RunReportProc(_tagReplacementSP, null);
if (dt.Rows.Count > 0)
{
dr = dt.Rows[0];
}
}
return ReportEngine.GetRdlStringReader(applicationPath, _rdlName, dr, _tagReplacementXml);
}
private void LoadDataSources()
{
DataTable dt = ReportingData.GetDataSourcesForReport(_reportId);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
int reportDataSourceId = Convert.ToInt32(dr["ReportDataSourceId"]);
string reportDataSourceCode = Convert.ToString(dr["ReportDataSourceCode"]);
string reportDataSourceSP = Convert.ToString(dr["ReportDataSourceSP"]);
CEReportDataSource ds = new CEReportDataSource(reportDataSourceId, reportDataSourceCode, reportDataSourceSP);
_mitReportDataSources.Add(reportDataSourceCode, ds);
}
}
}
}
}
| |
// 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.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Security
{
public enum EncryptionPolicy
{
// Prohibit null ciphers (current system defaults)
RequireEncryption = 0,
// Add null ciphers to current system defaults
AllowNoEncryption,
// Request null ciphers only
NoEncryption
}
// A user delegate used to verify remote SSL certificate.
public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors);
// A user delegate used to select local SSL certificate.
public delegate X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers);
// Internal versions of the above delegates.
internal delegate bool RemoteCertValidationCallback(string host, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors);
internal delegate X509Certificate LocalCertSelectionCallback(string targetHost, X509CertificateCollection localCertificates, X509Certificate2 remoteCertificate, string[] acceptableIssuers);
public class SslStream : AuthenticatedStream
{
private SslState _sslState;
private object _remoteCertificateOrBytes;
internal RemoteCertificateValidationCallback _userCertificateValidationCallback;
internal LocalCertificateSelectionCallback _userCertificateSelectionCallback;
internal RemoteCertValidationCallback _certValidationDelegate;
internal LocalCertSelectionCallback _certSelectionDelegate;
internal EncryptionPolicy _encryptionPolicy;
public SslStream(Stream innerStream)
: this(innerStream, false, null, null)
{
}
public SslStream(Stream innerStream, bool leaveInnerStreamOpen)
: this(innerStream, leaveInnerStreamOpen, null, null, EncryptionPolicy.RequireEncryption)
{
}
public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback)
: this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, null, EncryptionPolicy.RequireEncryption)
{
}
public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback,
LocalCertificateSelectionCallback userCertificateSelectionCallback)
: this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback, EncryptionPolicy.RequireEncryption)
{
}
public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback,
LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy)
: base(innerStream, leaveInnerStreamOpen)
{
if (encryptionPolicy != EncryptionPolicy.RequireEncryption && encryptionPolicy != EncryptionPolicy.AllowNoEncryption && encryptionPolicy != EncryptionPolicy.NoEncryption)
{
throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(encryptionPolicy));
}
_userCertificateValidationCallback = userCertificateValidationCallback;
_userCertificateSelectionCallback = userCertificateSelectionCallback;
_encryptionPolicy = encryptionPolicy;
_certValidationDelegate = new RemoteCertValidationCallback(UserCertValidationCallbackWrapper);
_certSelectionDelegate = userCertificateSelectionCallback == null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper);
_sslState = new SslState(innerStream);
}
public SslApplicationProtocol NegotiatedApplicationProtocol
{
get
{
return _sslState.NegotiatedApplicationProtocol;
}
}
private void SetAndVerifyValidationCallback(RemoteCertificateValidationCallback callback)
{
if (_userCertificateValidationCallback == null)
{
_userCertificateValidationCallback = callback;
_certValidationDelegate = new RemoteCertValidationCallback(UserCertValidationCallbackWrapper);
}
else if (callback != null && _userCertificateValidationCallback != callback)
{
throw new InvalidOperationException(SR.Format(SR.net_conflicting_options, nameof(RemoteCertificateValidationCallback)));
}
}
private void SetAndVerifySelectionCallback(LocalCertificateSelectionCallback callback)
{
if (_userCertificateSelectionCallback == null)
{
_userCertificateSelectionCallback = callback;
_certSelectionDelegate = _userCertificateSelectionCallback == null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper);
}
else if (callback != null && _userCertificateSelectionCallback != callback)
{
throw new InvalidOperationException(SR.Format(SR.net_conflicting_options, nameof(LocalCertificateSelectionCallback)));
}
}
private bool UserCertValidationCallbackWrapper(string hostName, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
_remoteCertificateOrBytes = certificate == null ? null : certificate.RawData;
if (_userCertificateValidationCallback == null)
{
if (!_sslState.RemoteCertRequired)
{
sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNotAvailable;
}
return (sslPolicyErrors == SslPolicyErrors.None);
}
else
{
return _userCertificateValidationCallback(this, certificate, chain, sslPolicyErrors);
}
}
private X509Certificate UserCertSelectionCallbackWrapper(string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
{
return _userCertificateSelectionCallback(this, targetHost, localCertificates, remoteCertificate, acceptableIssuers);
}
//
// Client side auth.
//
public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient(targetHost, null, SecurityProtocol.SystemDefaultSecurityProtocols, false,
asyncCallback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates,
bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates,
SslProtocols enabledSslProtocols, bool checkCertificateRevocation,
AsyncCallback asyncCallback, object asyncState)
{
SslClientAuthenticationOptions options = new SslClientAuthenticationOptions
{
TargetHost = targetHost,
ClientCertificates = clientCertificates,
EnabledSslProtocols = enabledSslProtocols,
CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
EncryptionPolicy = _encryptionPolicy,
};
return BeginAuthenticateAsClient(options, CancellationToken.None, asyncCallback, asyncState);
}
internal virtual IAsyncResult BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, object asyncState)
{
SecurityProtocol.ThrowOnNotAllowed(sslClientAuthenticationOptions.EnabledSslProtocols);
SetAndVerifyValidationCallback(sslClientAuthenticationOptions.RemoteCertificateValidationCallback);
SetAndVerifySelectionCallback(sslClientAuthenticationOptions.LocalCertificateSelectionCallback);
// Set the delegates on the options.
sslClientAuthenticationOptions._certValidationDelegate = _certValidationDelegate;
sslClientAuthenticationOptions._certSelectionDelegate = _certSelectionDelegate;
_sslState.ValidateCreateContext(sslClientAuthenticationOptions);
LazyAsyncResult result = new LazyAsyncResult(_sslState, asyncState, asyncCallback);
_sslState.ProcessAuthentication(result);
return result;
}
public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult)
{
_sslState.EndProcessAuthentication(asyncResult);
}
//
// Server side auth.
//
public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsServer(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false,
asyncCallback,
asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired,
bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired,
SslProtocols enabledSslProtocols, bool checkCertificateRevocation,
AsyncCallback asyncCallback,
object asyncState)
{
SslServerAuthenticationOptions options = new SslServerAuthenticationOptions
{
ServerCertificate = serverCertificate,
ClientCertificateRequired = clientCertificateRequired,
EnabledSslProtocols = enabledSslProtocols,
CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
EncryptionPolicy = _encryptionPolicy,
};
return BeginAuthenticateAsServer(options, CancellationToken.None, asyncCallback, asyncState);
}
private IAsyncResult BeginAuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, object asyncState)
{
SecurityProtocol.ThrowOnNotAllowed(sslServerAuthenticationOptions.EnabledSslProtocols);
SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback);
// Set the delegate on the options.
sslServerAuthenticationOptions._certValidationDelegate = _certValidationDelegate;
_sslState.ValidateCreateContext(sslServerAuthenticationOptions);
LazyAsyncResult result = new LazyAsyncResult(_sslState, asyncState, asyncCallback);
_sslState.ProcessAuthentication(result);
return result;
}
public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult)
{
_sslState.EndProcessAuthentication(asyncResult);
}
internal virtual IAsyncResult BeginShutdown(AsyncCallback asyncCallback, object asyncState)
{
return _sslState.BeginShutdown(asyncCallback, asyncState);
}
internal virtual void EndShutdown(IAsyncResult asyncResult)
{
_sslState.EndShutdown(asyncResult);
}
public TransportContext TransportContext
{
get
{
return new SslStreamContext(this);
}
}
internal ChannelBinding GetChannelBinding(ChannelBindingKind kind)
{
return _sslState.GetChannelBinding(kind);
}
#region Synchronous methods
public virtual void AuthenticateAsClient(string targetHost)
{
AuthenticateAsClient(targetHost, null, SecurityProtocol.SystemDefaultSecurityProtocols, false);
}
public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation)
{
AuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation);
}
public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
{
SslClientAuthenticationOptions options = new SslClientAuthenticationOptions
{
TargetHost = targetHost,
ClientCertificates = clientCertificates,
EnabledSslProtocols = enabledSslProtocols,
CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
EncryptionPolicy = _encryptionPolicy,
};
AuthenticateAsClient(options);
}
private void AuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions)
{
SecurityProtocol.ThrowOnNotAllowed(sslClientAuthenticationOptions.EnabledSslProtocols);
SetAndVerifyValidationCallback(sslClientAuthenticationOptions.RemoteCertificateValidationCallback);
SetAndVerifySelectionCallback(sslClientAuthenticationOptions.LocalCertificateSelectionCallback);
// Set the delegates on the options.
sslClientAuthenticationOptions._certValidationDelegate = _certValidationDelegate;
sslClientAuthenticationOptions._certSelectionDelegate = _certSelectionDelegate;
_sslState.ValidateCreateContext(sslClientAuthenticationOptions);
_sslState.ProcessAuthentication(null);
}
public virtual void AuthenticateAsServer(X509Certificate serverCertificate)
{
AuthenticateAsServer(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false);
}
public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation)
{
AuthenticateAsServer(serverCertificate, clientCertificateRequired, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation);
}
public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
{
SslServerAuthenticationOptions options = new SslServerAuthenticationOptions
{
ServerCertificate = serverCertificate,
ClientCertificateRequired = clientCertificateRequired,
EnabledSslProtocols = enabledSslProtocols,
CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
EncryptionPolicy = _encryptionPolicy,
};
AuthenticateAsServer(options);
}
private void AuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions)
{
SecurityProtocol.ThrowOnNotAllowed(sslServerAuthenticationOptions.EnabledSslProtocols);
SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback);
// Set the delegate on the options.
sslServerAuthenticationOptions._certValidationDelegate = _certValidationDelegate;
_sslState.ValidateCreateContext(sslServerAuthenticationOptions);
_sslState.ProcessAuthentication(null);
}
#endregion
#region Task-based async public methods
public virtual Task AuthenticateAsClientAsync(string targetHost) =>
Task.Factory.FromAsync(
(arg1, callback, state) => ((SslStream)state).BeginAuthenticateAsClient(arg1, callback, state),
iar => ((SslStream)iar.AsyncState).EndAuthenticateAsClient(iar),
targetHost,
this);
public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation) =>
Task.Factory.FromAsync(
(arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsClient(arg1, arg2, SecurityProtocol.SystemDefaultSecurityProtocols, arg3, callback, state),
iar => ((SslStream)iar.AsyncState).EndAuthenticateAsClient(iar),
targetHost, clientCertificates, checkCertificateRevocation,
this);
public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
{
var beginMethod = checkCertificateRevocation ? (Func<string, X509CertificateCollection, SslProtocols, AsyncCallback, object, IAsyncResult>)
((arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsClient(arg1, arg2, arg3, true, callback, state)) :
((arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsClient(arg1, arg2, arg3, false, callback, state));
return Task.Factory.FromAsync(
beginMethod,
iar => ((SslStream)iar.AsyncState).EndAuthenticateAsClient(iar),
targetHost, clientCertificates, enabledSslProtocols,
this);
}
public Task AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken)
{
return Task.Factory.FromAsync(
(arg1, arg2, callback, state) => ((SslStream)state).BeginAuthenticateAsClient(arg1, arg2, callback, state),
iar => ((SslStream)iar.AsyncState).EndAuthenticateAsClient(iar),
sslClientAuthenticationOptions, cancellationToken,
this);
}
public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate) =>
Task.Factory.FromAsync(
(arg1, callback, state) => ((SslStream)state).BeginAuthenticateAsServer(arg1, callback, state),
iar => ((SslStream)iar.AsyncState).EndAuthenticateAsServer(iar),
serverCertificate,
this);
public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) =>
Task.Factory.FromAsync(
(arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsServer(arg1, arg2, SecurityProtocol.SystemDefaultSecurityProtocols, arg3, callback, state),
iar => ((SslStream)iar.AsyncState).EndAuthenticateAsServer(iar),
serverCertificate, clientCertificateRequired, checkCertificateRevocation,
this);
public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
{
var beginMethod = checkCertificateRevocation ? (Func<X509Certificate, bool, SslProtocols, AsyncCallback, object, IAsyncResult>)
((arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsServer(arg1, arg2, arg3, true, callback, state)) :
((arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsServer(arg1, arg2, arg3, false, callback, state));
return Task.Factory.FromAsync(
beginMethod,
iar => ((SslStream)iar.AsyncState).EndAuthenticateAsServer(iar),
serverCertificate, clientCertificateRequired, enabledSslProtocols,
this);
}
public Task AuthenticateAsServerAsync(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken)
{
return Task.Factory.FromAsync(
(arg1, arg2, callback, state) => ((SslStream)state).BeginAuthenticateAsServer(arg1, arg2, callback, state),
iar => ((SslStream)iar.AsyncState).EndAuthenticateAsServer(iar),
sslServerAuthenticationOptions, cancellationToken,
this);
}
public virtual Task ShutdownAsync() =>
Task.Factory.FromAsync(
(callback, state) => ((SslStream)state).BeginShutdown(callback, state),
iar => ((SslStream)iar.AsyncState).EndShutdown(iar),
this);
#endregion
public override bool IsAuthenticated
{
get
{
return _sslState.IsAuthenticated;
}
}
public override bool IsMutuallyAuthenticated
{
get
{
return _sslState.IsMutuallyAuthenticated;
}
}
public override bool IsEncrypted
{
get
{
return IsAuthenticated;
}
}
public override bool IsSigned
{
get
{
return IsAuthenticated;
}
}
public override bool IsServer
{
get
{
return _sslState.IsServer;
}
}
public virtual SslProtocols SslProtocol
{
get
{
return _sslState.SslProtocol;
}
}
public virtual bool CheckCertRevocationStatus
{
get
{
return _sslState.CheckCertRevocationStatus;
}
}
public virtual X509Certificate LocalCertificate
{
get
{
return _sslState.LocalCertificate;
}
}
public virtual X509Certificate RemoteCertificate
{
get
{
_sslState.CheckThrow(true);
object chkCertificateOrBytes = _remoteCertificateOrBytes;
if (chkCertificateOrBytes != null && chkCertificateOrBytes.GetType() == typeof(byte[]))
{
return (X509Certificate)(_remoteCertificateOrBytes = new X509Certificate2((byte[])chkCertificateOrBytes));
}
else
{
return chkCertificateOrBytes as X509Certificate;
}
}
}
public virtual CipherAlgorithmType CipherAlgorithm
{
get
{
return _sslState.CipherAlgorithm;
}
}
public virtual int CipherStrength
{
get
{
return _sslState.CipherStrength;
}
}
public virtual HashAlgorithmType HashAlgorithm
{
get
{
return _sslState.HashAlgorithm;
}
}
public virtual int HashStrength
{
get
{
return _sslState.HashStrength;
}
}
public virtual ExchangeAlgorithmType KeyExchangeAlgorithm
{
get
{
return _sslState.KeyExchangeAlgorithm;
}
}
public virtual int KeyExchangeStrength
{
get
{
return _sslState.KeyExchangeStrength;
}
}
//
// Stream contract implementation.
//
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanRead
{
get
{
return _sslState.IsAuthenticated && InnerStream.CanRead;
}
}
public override bool CanTimeout
{
get
{
return InnerStream.CanTimeout;
}
}
public override bool CanWrite
{
get
{
return _sslState.IsAuthenticated && InnerStream.CanWrite && !_sslState.IsShutdown;
}
}
public override int ReadTimeout
{
get
{
return InnerStream.ReadTimeout;
}
set
{
InnerStream.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
return InnerStream.WriteTimeout;
}
set
{
InnerStream.WriteTimeout = value;
}
}
public override long Length
{
get
{
return InnerStream.Length;
}
}
public override long Position
{
get
{
return InnerStream.Position;
}
set
{
throw new NotSupportedException(SR.net_noseek);
}
}
public override void SetLength(long value)
{
InnerStream.SetLength(value);
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.net_noseek);
}
public override void Flush()
{
_sslState.Flush();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return _sslState.FlushAsync(cancellationToken);
}
protected override void Dispose(bool disposing)
{
try
{
_sslState.Close();
}
finally
{
base.Dispose(disposing);
}
}
public override int ReadByte()
{
return _sslState.SecureStream.ReadByte();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _sslState.SecureStream.Read(buffer, offset, count);
}
public void Write(byte[] buffer)
{
_sslState.SecureStream.Write(buffer, 0, buffer.Length);
}
public override void Write(byte[] buffer, int offset, int count)
{
_sslState.SecureStream.Write(buffer, offset, count);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
return _sslState.SecureStream.BeginRead(buffer, offset, count, asyncCallback, asyncState);
}
public override int EndRead(IAsyncResult asyncResult)
{
return _sslState.SecureStream.EndRead(asyncResult);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
return _sslState.SecureStream.BeginWrite(buffer, offset, count, asyncCallback, asyncState);
}
public override void EndWrite(IAsyncResult asyncResult)
{
_sslState.SecureStream.EndWrite(asyncResult);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _sslState.SecureStream.WriteAsync(buffer, offset, count, cancellationToken);
}
public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
{
return _sslState.SecureStream.WriteAsync(source, cancellationToken);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _sslState.SecureStream.ReadAsync(buffer, offset, count, cancellationToken);
}
public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default)
{
return _sslState.SecureStream.ReadAsync(destination, cancellationToken);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Collections.Specialized
{
/// <devdoc>
/// <para>
/// This is a simple implementation of IDictionary using a singly linked list. This
/// will be smaller and faster than a Hashtable if the number of elements is 10 or less.
/// This should not be used if performance is important for large numbers of elements.
/// </para>
/// </devdoc>
[Serializable]
public class ListDictionary : IDictionary
{
private DictionaryNode _head;
private int _version;
private int _count;
private readonly IComparer _comparer;
[NonSerialized]
private Object _syncRoot;
public ListDictionary()
{
}
public ListDictionary(IComparer comparer)
{
_comparer = comparer;
}
public object this[object key]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
DictionaryNode node = _head;
if (_comparer == null)
{
while (node != null)
{
object oldKey = node.key;
if (oldKey.Equals(key))
{
return node.value;
}
node = node.next;
}
}
else
{
while (node != null)
{
object oldKey = node.key;
if (_comparer.Compare(oldKey, key) == 0)
{
return node.value;
}
node = node.next;
}
}
return null;
}
set
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
_version++;
DictionaryNode last = null;
DictionaryNode node;
for (node = _head; node != null; node = node.next)
{
object oldKey = node.key;
if ((_comparer == null) ? oldKey.Equals(key) : _comparer.Compare(oldKey, key) == 0)
{
break;
}
last = node;
}
if (node != null)
{
// Found it
node.value = value;
return;
}
// Not found, so add a new one
DictionaryNode newNode = new DictionaryNode();
newNode.key = key;
newNode.value = value;
if (last != null)
{
last.next = newNode;
}
else
{
_head = newNode;
}
_count++;
}
}
public int Count
{
get
{
return _count;
}
}
public ICollection Keys
{
get
{
return new NodeKeyValueCollection(this, true);
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public bool IsFixedSize
{
get
{
return false;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public object SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
public ICollection Values
{
get
{
return new NodeKeyValueCollection(this, false);
}
}
public void Add(object key, object value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
_version++;
DictionaryNode last = null;
DictionaryNode node;
for (node = _head; node != null; node = node.next)
{
object oldKey = node.key;
if ((_comparer == null) ? oldKey.Equals(key) : _comparer.Compare(oldKey, key) == 0)
{
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key));
}
last = node;
}
// Not found, so add a new one
DictionaryNode newNode = new DictionaryNode();
newNode.key = key;
newNode.value = value;
if (last != null)
{
last.next = newNode;
}
else
{
_head = newNode;
}
_count++;
}
public void Clear()
{
_count = 0;
_head = null;
_version++;
}
public bool Contains(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
for (DictionaryNode node = _head; node != null; node = node.next)
{
object oldKey = node.key;
if ((_comparer == null) ? oldKey.Equals(key) : _comparer.Compare(oldKey, key) == 0)
{
return true;
}
}
return false;
}
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < _count)
throw new ArgumentException(SR.Arg_InsufficientSpace);
for (DictionaryNode node = _head; node != null; node = node.next)
{
array.SetValue(new DictionaryEntry(node.key, node.value), index);
index++;
}
}
public IDictionaryEnumerator GetEnumerator()
{
return new NodeEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new NodeEnumerator(this);
}
public void Remove(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
_version++;
DictionaryNode last = null;
DictionaryNode node;
for (node = _head; node != null; node = node.next)
{
object oldKey = node.key;
if ((_comparer == null) ? oldKey.Equals(key) : _comparer.Compare(oldKey, key) == 0)
{
break;
}
last = node;
}
if (node == null)
{
return;
}
if (node == _head)
{
_head = node.next;
}
else
{
last.next = node.next;
}
_count--;
}
private class NodeEnumerator : IDictionaryEnumerator
{
private ListDictionary _list;
private DictionaryNode _current;
private int _version;
private bool _start;
public NodeEnumerator(ListDictionary list)
{
_list = list;
_version = list._version;
_start = true;
_current = null;
}
public object Current
{
get
{
return Entry;
}
}
public DictionaryEntry Entry
{
get
{
if (_current == null)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return new DictionaryEntry(_current.key, _current.value);
}
}
public object Key
{
get
{
if (_current == null)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _current.key;
}
}
public object Value
{
get
{
if (_current == null)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _current.value;
}
}
public bool MoveNext()
{
if (_version != _list._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if (_start)
{
_current = _list._head;
_start = false;
}
else if (_current != null)
{
_current = _current.next;
}
return (_current != null);
}
public void Reset()
{
if (_version != _list._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_start = true;
_current = null;
}
}
private class NodeKeyValueCollection : ICollection
{
private ListDictionary _list;
private bool _isKeys;
public NodeKeyValueCollection(ListDictionary list, bool isKeys)
{
_list = list;
_isKeys = isKeys;
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
for (DictionaryNode node = _list._head; node != null; node = node.next)
{
array.SetValue(_isKeys ? node.key : node.value, index);
index++;
}
}
int ICollection.Count
{
get
{
int count = 0;
for (DictionaryNode node = _list._head; node != null; node = node.next)
{
count++;
}
return count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return _list.SyncRoot;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return new NodeKeyValueEnumerator(_list, _isKeys);
}
private class NodeKeyValueEnumerator : IEnumerator
{
private ListDictionary _list;
private DictionaryNode _current;
private int _version;
private bool _isKeys;
private bool _start;
public NodeKeyValueEnumerator(ListDictionary list, bool isKeys)
{
_list = list;
_isKeys = isKeys;
_version = list._version;
_start = true;
_current = null;
}
public object Current
{
get
{
if (_current == null)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _isKeys ? _current.key : _current.value;
}
}
public bool MoveNext()
{
if (_version != _list._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if (_start)
{
_current = _list._head;
_start = false;
}
else if (_current != null)
{
_current = _current.next;
}
return (_current != null);
}
public void Reset()
{
if (_version != _list._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_start = true;
_current = null;
}
}
}
[Serializable]
private class DictionaryNode
{
public object key;
public object value;
public DictionaryNode next;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="QueueSourceSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
using Dropped = Akka.Streams.QueueOfferResult.Dropped;
using Enqueued = Akka.Streams.QueueOfferResult.Enqueued;
using QueueClosed = Akka.Streams.QueueOfferResult.QueueClosed;
namespace Akka.Streams.Tests.Dsl
{
public class QueueSourceSpec : AkkaSpec
{
private readonly ActorMaterializer _materializer;
private readonly TimeSpan _pause = TimeSpan.FromMilliseconds(300);
public QueueSourceSpec(ITestOutputHelper output) : base(output)
{
_materializer = Sys.Materializer();
}
private static void AssertSuccess(Task<IQueueOfferResult> task)
{
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.Should().Be(Enqueued.Instance);
}
[Fact]
public void QueueSource_should_emit_received_message_to_the_stream()
{
var s = this.CreateManualSubscriberProbe<int>();
var queue =
Source.Queue<int>(10, OverflowStrategy.Fail).To(Sink.FromSubscriber(s)).Run(_materializer);
var sub = s.ExpectSubscription();
sub.Request(2);
AssertSuccess(queue.OfferAsync(1));
s.ExpectNext(1);
AssertSuccess(queue.OfferAsync(2));
s.ExpectNext(2);
AssertSuccess(queue.OfferAsync(3));
sub.Cancel();
}
[Fact]
public void QueueSource_should_be_reusable()
{
var source = Source.Queue<int>(0, OverflowStrategy.Backpressure);
var q1 = source.To(Sink.Ignore<int>()).Run(_materializer);
q1.Complete();
var task = q1.WatchCompletionAsync();
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
var q2 = source.To(Sink.Ignore<int>()).Run(_materializer);
task = q2.WatchCompletionAsync();
task.Wait(TimeSpan.FromSeconds(3)).Should().BeFalse();
}
[Fact]
public void QueueSource_should_reject_elements_when_backpressuring_with_maxBuffer_0()
{
var t =
Source.Queue<int>(0, OverflowStrategy.Backpressure)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(_materializer);
var source = t.Item1;
var probe = t.Item2;
var task = source.OfferAsync(42);
var ex = source.OfferAsync(43);
ex.Invoking(_ => _.Wait(TimeSpan.FromSeconds(3)))
.ShouldThrow<IllegalStateException>()
.And.Message.Should()
.Contain("have to wait");
probe.RequestNext().Should().Be(42);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.Should().Be(Enqueued.Instance);
}
[Fact]
public void QueueSource_should_buffer_when_needed()
{
var s = this.CreateManualSubscriberProbe<int>();
var queue =
Source.Queue<int>(100, OverflowStrategy.DropHead)
.To(Sink.FromSubscriber(s))
.Run(_materializer);
var sub = s.ExpectSubscription();
for (var i = 1; i <= 20; i++) AssertSuccess(queue.OfferAsync(i));
sub.Request(10);
for (var i = 1; i <= 10; i++) AssertSuccess(queue.OfferAsync(i));
sub.Request(10);
for (var i = 11; i <= 20; i++) AssertSuccess(queue.OfferAsync(i));
for (var i = 200; i <= 399; i++) AssertSuccess(queue.OfferAsync(i));
sub.Request(100);
for (var i = 300; i <= 399; i++) AssertSuccess(queue.OfferAsync(i));
sub.Cancel();
}
[Fact]
public void QueueSource_should_not_fail_when_0_buffer_space_and_demand_is_signalled()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var queue =
Source.Queue<int>(0, OverflowStrategy.DropHead)
.To(Sink.FromSubscriber(s))
.Run(_materializer);
var sub = s.ExpectSubscription();
sub.Request(1);
AssertSuccess(queue.OfferAsync(1));
sub.Cancel();
}, _materializer);
}
[Fact]
public void QueueSource_should_wait_for_demand_when_buffer_is_0()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var queue =
Source.Queue<int>(0, OverflowStrategy.DropHead)
.To(Sink.FromSubscriber(s))
.Run(_materializer);
var sub = s.ExpectSubscription();
queue.OfferAsync(1).PipeTo(TestActor);
ExpectNoMsg(_pause);
sub.Request(1);
ExpectMsg<Enqueued>();
s.ExpectNext(1);
sub.Cancel();
}, _materializer);
}
[Fact]
public void QueueSource_should_finish_offer_and_complete_futures_when_stream_completed()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var queue =
Source.Queue<int>(0, OverflowStrategy.DropHead)
.To(Sink.FromSubscriber(s))
.Run(_materializer);
var sub = s.ExpectSubscription();
queue.WatchCompletionAsync()
.ContinueWith(t => "done", TaskContinuationOptions.OnlyOnRanToCompletion)
.PipeTo(TestActor);
queue.OfferAsync(1).PipeTo(TestActor);
ExpectNoMsg(_pause);
sub.Cancel();
ExpectMsgAllOf<object>(QueueClosed.Instance, "done");
}, _materializer);
}
[Fact]
public void QueueSource_should_fail_stream_on_buffer_overflow_in_fail_mode()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var queue =
Source.Queue<int>(1, OverflowStrategy.Fail)
.To(Sink.FromSubscriber(s))
.Run(_materializer);
s.ExpectSubscription();
queue.OfferAsync(1);
queue.OfferAsync(1);
s.ExpectError();
}, _materializer);
}
[Fact]
public void QueueSource_should_remember_pull_from_downstream_to_send_offered_element_immediately()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var probe = CreateTestProbe();
var queue = TestSourceStage<int, ISourceQueueWithComplete<int>>.Create(
new QueueSource<int>(1, OverflowStrategy.DropHead), probe)
.To(Sink.FromSubscriber(s))
.Run(_materializer);
var sub = s.ExpectSubscription();
sub.Request(1);
probe.ExpectMsg<GraphStageMessages.Pull>();
AssertSuccess(queue.OfferAsync(1));
s.ExpectNext(1);
sub.Cancel();
}, _materializer);
}
[Fact]
public void QueueSource_should_fail_offer_future_if_user_does_not_wait_in_backpressure_mode()
{
this.AssertAllStagesStopped(() =>
{
var tuple =
Source.Queue<int>(5, OverflowStrategy.Backpressure)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(_materializer);
var queue = tuple.Item1;
var probe = tuple.Item2;
for (var i = 1; i <= 5; i++)
AssertSuccess(queue.OfferAsync(i));
queue.OfferAsync(6).PipeTo(TestActor);
queue.OfferAsync(7).PipeTo(TestActor);
ExpectMsg<Status.Failure>().Cause.InnerException.Should().BeOfType<IllegalStateException>();
probe.RequestNext(1);
ExpectMsg(Enqueued.Instance);
queue.Complete();
probe.Request(6)
.ExpectNext(2, 3, 4, 5, 6)
.ExpectComplete();
}, _materializer);
}
[Fact]
public void QueueSource_should_complete_watching_future_with_failure_if_stream_failed()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var queue =
Source.Queue<int>(1, OverflowStrategy.Fail)
.To(Sink.FromSubscriber(s))
.Run(_materializer);
queue.WatchCompletionAsync().PipeTo(TestActor);
queue.OfferAsync(1); // need to wait when first offer is done as initialization can be done in this moment
queue.OfferAsync(2);
ExpectMsg<Status.Failure>();
}, _materializer);
}
[Fact]
public void QueueSource_should_return_false_when_element_was_not_added_to_buffer()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var queue =
Source.Queue<int>(1, OverflowStrategy.DropNew)
.To(Sink.FromSubscriber(s))
.Run(_materializer);
var sub = s.ExpectSubscription();
queue.OfferAsync(1);
queue.OfferAsync(2).PipeTo(TestActor);
ExpectMsg<Dropped>();
sub.Request(1);
s.ExpectNext(1);
sub.Cancel();
}, _materializer);
}
[Fact]
public void QueueSource_should_wait_when_buffer_is_full_and_backpressure_is_on()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var queue =
Source.Queue<int>(1, OverflowStrategy.Backpressure)
.To(Sink.FromSubscriber(s))
.Run(_materializer);
var sub = s.ExpectSubscription();
AssertSuccess(queue.OfferAsync(1));
queue.OfferAsync(2).PipeTo(TestActor);
ExpectNoMsg(_pause);
sub.Request(1);
s.ExpectNext(1);
sub.Request(1);
s.ExpectNext(2);
ExpectMsg<Enqueued>();
sub.Cancel();
}, _materializer);
}
[Fact]
public void QueueSource_should_fail_offer_future_when_stream_is_completed()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var queue =
Source.Queue<int>(1, OverflowStrategy.DropNew)
.To(Sink.FromSubscriber(s))
.Run(_materializer);
var sub = s.ExpectSubscription();
queue.WatchCompletionAsync().ContinueWith(t => "done").PipeTo(TestActor);
sub.Cancel();
ExpectMsg("done");
queue.OfferAsync(1).ContinueWith(t => t.Exception.Should().BeOfType<IllegalStateException>());
}, _materializer);
}
[Fact]
public void QueueSource_should_not_share_future_across_materializations()
{
var source = Source.Queue<string>(1, OverflowStrategy.Fail);
var mat1Subscriber = this.CreateSubscriberProbe<string>();
var mat2Subscriber = this.CreateSubscriberProbe<string>();
var sourceQueue1 = source.To(Sink.FromSubscriber(mat1Subscriber)).Run(_materializer);
var sourceQueue2 = source.To(Sink.FromSubscriber(mat2Subscriber)).Run(_materializer);
mat1Subscriber.EnsureSubscription();
mat2Subscriber.EnsureSubscription();
mat1Subscriber.Request(1);
sourceQueue1.OfferAsync("hello");
mat1Subscriber.ExpectNext("hello");
mat1Subscriber.Cancel();
sourceQueue1.WatchCompletionAsync().ContinueWith(task => task.IsCompleted).PipeTo(TestActor);
ExpectMsg(true);
sourceQueue2.WatchCompletionAsync().IsCompleted.Should().BeFalse();
}
[Fact]
public void QueueSource_should_complete_the_stream_when_buffer_is_empty()
{
var tuple =
Source.Queue<int>(1, OverflowStrategy.Fail)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(_materializer);
var source = tuple.Item1;
var probe = tuple.Item2;
source.Complete();
var task = source.WatchCompletionAsync();
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
probe.EnsureSubscription().ExpectComplete();
}
[Fact]
public void QueueSource_should_complete_the_stream_when_buffer_is_full()
{
var tuple =
Source.Queue<int>(1, OverflowStrategy.Fail)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(_materializer);
var source = tuple.Item1;
var probe = tuple.Item2;
source.OfferAsync(1);
source.Complete();
probe.RequestNext(1).ExpectComplete();
var task = source.WatchCompletionAsync();
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
}
[Fact]
public void QueueSource_should_complete_the_stream_when_buffer_is_full_and_element_is_pending()
{
var tuple =
Source.Queue<int>(1, OverflowStrategy.Backpressure)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(_materializer);
var source = tuple.Item1;
var probe = tuple.Item2;
source.OfferAsync(1);
source.OfferAsync(2);
source.Complete();
probe.RequestNext(1)
.RequestNext(2)
.ExpectComplete();
var task = source.WatchCompletionAsync();
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
}
[Fact]
public void QueueSource_should_complete_the_stream_when_no_buffer_is_used()
{
var tuple =
Source.Queue<int>(0, OverflowStrategy.Fail)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(_materializer);
var source = tuple.Item1;
var probe = tuple.Item2;
source.Complete();
var task = source.WatchCompletionAsync();
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
probe.EnsureSubscription().ExpectComplete();
}
[Fact]
public void QueueSource_should_complete_the_stream_when_no_buffer_is_used_and_element_is_pending()
{
var tuple =
Source.Queue<int>(0, OverflowStrategy.Fail)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(_materializer);
var source = tuple.Item1;
var probe = tuple.Item2;
source.OfferAsync(1);
source.Complete();
probe.RequestNext(1).ExpectComplete();
var task = source.WatchCompletionAsync();
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
}
private static readonly Exception Ex = new Exception("BUH");
[Fact]
public void QueueSource_should_fail_the_stream_when_buffer_is_empty()
{
var tuple =
Source.Queue<int>(1, OverflowStrategy.Fail)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(_materializer);
var source = tuple.Item1;
var probe = tuple.Item2;
source.Fail(Ex);
var task = source.WatchCompletionAsync();
task.Invoking(_ => _.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Exception>().And.Should().Be(Ex);
probe.EnsureSubscription().ExpectError().Should().Be(Ex);
}
[Fact]
public void QueueSource_should_fail_the_stream_when_buffer_is_full()
{
var tuple =
Source.Queue<int>(1, OverflowStrategy.Fail)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(_materializer);
var source = tuple.Item1;
var probe = tuple.Item2;
source.OfferAsync(1);
source.Fail(Ex);
var task = source.WatchCompletionAsync();
task.Invoking(_ => _.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Exception>().And.Should().Be(Ex);
probe.EnsureSubscription().ExpectError().Should().Be(Ex);
}
[Fact]
public void QueueSource_should_fail_the_stream_when_buffer_is_full_and_element_is_pending()
{
var tuple =
Source.Queue<int>(1, OverflowStrategy.Backpressure)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(_materializer);
var source = tuple.Item1;
var probe = tuple.Item2;
source.OfferAsync(1);
source.OfferAsync(2);
source.Fail(Ex);
var task = source.WatchCompletionAsync();
task.Invoking(_ => _.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Exception>().And.Should().Be(Ex);
probe.EnsureSubscription().ExpectError().Should().Be(Ex);
}
[Fact]
public void QueueSource_should_fail_the_stream_when_no_buffer_is_used()
{
var tuple =
Source.Queue<int>(0, OverflowStrategy.Fail)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(_materializer);
var source = tuple.Item1;
var probe = tuple.Item2;
source.Fail(Ex);
var task = source.WatchCompletionAsync();
task.Invoking(_ => _.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Exception>().And.Should().Be(Ex);
probe.EnsureSubscription().ExpectError().Should().Be(Ex);
}
[Fact]
public void QueueSource_should_fail_the_stream_when_no_buffer_is_used_and_element_is_pending()
{
var tuple =
Source.Queue<int>(0, OverflowStrategy.Fail)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(_materializer);
var source = tuple.Item1;
var probe = tuple.Item2;
source.OfferAsync(1);
source.Fail(Ex);
var task = source.WatchCompletionAsync();
task.Invoking(_ => _.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Exception>().And.Should().Be(Ex);
probe.EnsureSubscription().ExpectError().Should().Be(Ex);
}
}
}
| |
// <copyright file="GPGSUtil.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// Keep this even if NO_GPGS is defined so we can clean up the project
// post build.
#if (UNITY_ANDROID || UNITY_IPHONE)
namespace GooglePlayGames.Editor
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Utility class to perform various tasks in the editor.
/// </summary>
public static class GPGSUtil
{
/// <summary>Property key for project requiring G+ access
public const string REQUIREGOOGLEPLUSKEY = "proj.requireGPlus";
/// <summary>Property key for project settings.</summary>
public const string SERVICEIDKEY = "App.NearbdServiceId";
/// <summary>Property key for project settings.</summary>
public const string APPIDKEY = "proj.AppId";
/// <summary>Property key for project settings.</summary>
public const string CLASSDIRECTORYKEY = "proj.classDir";
/// <summary>Property key for project settings.</summary>
public const string CLASSNAMEKEY = "proj.ConstantsClassName";
/// <summary>Property key for project settings.</summary>
public const string WEBCLIENTIDKEY = "and.ClientId";
/// <summary>Property key for project settings.</summary>
public const string IOSCLIENTIDKEY = "ios.ClientId";
/// <summary>Property key for project settings.</summary>
public const string IOSBUNDLEIDKEY = "ios.BundleId";
/// <summary>Property key for project settings.</summary>
public const string ANDROIDRESOURCEKEY = "and.ResourceData";
/// <summary>Property key for project settings.</summary>
public const string ANDROIDSETUPDONEKEY = "android.SetupDone";
/// <summary>Property key for project settings.</summary>
public const string ANDROIDBUNDLEIDKEY = "and.BundleId";
/// <summary>Property key for project settings.</summary>
public const string IOSRESOURCEKEY = "ios.ResourceData";
/// <summary>Property key for project settings.</summary>
public const string IOSSETUPDONEKEY = "ios.SetupDone";
/// <summary>Property key for plugin version.</summary>
public const string PLUGINVERSIONKEY = "proj.pluginVersion";
/// <summary>Property key for nearby settings done.</summary>
public const string NEARBYSETUPDONEKEY = "android.NearbySetupDone";
/// <summary>Property key for project settings.</summary>
public const string LASTUPGRADEKEY = "lastUpgrade";
/// <summary>Constant for token replacement</summary>
private const string SERVICEIDPLACEHOLDER = "__NEARBY_SERVICE_ID__";
/// <summary>Constant for token replacement</summary>
private const string APPIDPLACEHOLDER = "__APP_ID__";
/// <summary>Constant for token replacement</summary>
private const string CLASSNAMEPLACEHOLDER = "__Class__";
/// <summary>Constant for token replacement</summary>
private const string WEBCLIENTIDPLACEHOLDER = "__WEB_CLIENTID__";
/// <summary>Constant for token replacement</summary>
private const string IOSCLIENTIDPLACEHOLDER = "__IOS_CLIENTID__";
/// <summary>Constant for token replacement</summary>
private const string IOSBUNDLEIDPLACEHOLDER = "__BUNDLEID__";
/// <summary>Constant for token replacement</summary>
private const string PLUGINVERSIONPLACEHOLDER = "__PLUGIN_VERSION__";
/// <summary>Constant for require google plus token replacement</summary>
private const string REQUIREGOOGLEPLUSPLACEHOLDER = "__REQUIRE_GOOGLE_PLUS__";
/// <summary>Property key for project settings.</summary>
private const string TOKENPERMISSIONKEY = "proj.tokenPermissions";
/// <summary>Constant for token replacement</summary>
private const string NAMESPACESTARTPLACEHOLDER = "__NameSpaceStart__";
/// <summary>Constant for token replacement</summary>
private const string NAMESPACEENDPLACEHOLDER = "__NameSpaceEnd__";
/// <summary>Constant for token replacement</summary>
private const string CONSTANTSPLACEHOLDER = "__Constant_Properties__";
/// <summary>
/// The game info file path. This is a generated file.
/// </summary>
private const string GameInfoPath = "Assets/GooglePlayGames/GameInfo.cs";
/// <summary>
/// The map of replacements for filling in code templates. The
/// key is the string that appears in the template as a placeholder,
/// the value is the key into the GPGSProjectSettings.
/// </summary>
private static Dictionary<string, string> replacements =
new Dictionary<string, string>()
{
{ SERVICEIDPLACEHOLDER, SERVICEIDKEY },
{ APPIDPLACEHOLDER, APPIDKEY },
{ CLASSNAMEPLACEHOLDER, CLASSNAMEKEY },
{ WEBCLIENTIDPLACEHOLDER, WEBCLIENTIDKEY },
{ IOSCLIENTIDPLACEHOLDER, IOSCLIENTIDKEY },
{ IOSBUNDLEIDPLACEHOLDER, IOSBUNDLEIDKEY },
{ REQUIREGOOGLEPLUSPLACEHOLDER, REQUIREGOOGLEPLUSKEY },
{ PLUGINVERSIONPLACEHOLDER, PLUGINVERSIONKEY}
};
/// <summary>
/// Replaces / in file path to be the os specific separator.
/// </summary>
/// <returns>The path.</returns>
/// <param name="path">Path with correct separators.</param>
public static string SlashesToPlatformSeparator(string path)
{
return path.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString());
}
/// <summary>
/// Reads the file.
/// </summary>
/// <returns>The file contents. The slashes are corrected.</returns>
/// <param name="filePath">File path.</param>
public static string ReadFile(string filePath)
{
filePath = SlashesToPlatformSeparator(filePath);
if (!File.Exists(filePath))
{
Alert("Plugin error: file not found: " + filePath);
return null;
}
StreamReader sr = new StreamReader(filePath);
string body = sr.ReadToEnd();
sr.Close();
return body;
}
/// <summary>
/// Reads the editor template.
/// </summary>
/// <returns>The editor template contents.</returns>
/// <param name="name">Name of the template in the editor directory.</param>
public static string ReadEditorTemplate(string name)
{
return ReadFile(SlashesToPlatformSeparator("Assets/GooglePlayGames/Editor/" + name + ".txt"));
}
/// <summary>
/// Writes the file.
/// </summary>
/// <param name="file">File path - the slashes will be corrected.</param>
/// <param name="body">Body of the file to write.</param>
public static void WriteFile(string file, string body)
{
file = SlashesToPlatformSeparator(file);
using (var wr = new StreamWriter(file, false))
{
wr.Write(body);
}
}
/// <summary>
/// Validates the string to be a valid nearby service id.
/// </summary>
/// <returns><c>true</c>, if like valid service identifier was looksed, <c>false</c> otherwise.</returns>
/// <param name="s">string to test.</param>
public static bool LooksLikeValidServiceId(string s)
{
if (s.Length < 3)
{
return false;
}
foreach (char c in s)
{
if (!char.IsLetterOrDigit(c) && c != '.')
{
return false;
}
}
return true;
}
/// <summary>
/// Looks the like valid app identifier.
/// </summary>
/// <returns><c>true</c>, if valid app identifier, <c>false</c> otherwise.</returns>
/// <param name="s">the string to test.</param>
public static bool LooksLikeValidAppId(string s)
{
if (s.Length < 5)
{
return false;
}
foreach (char c in s)
{
if (c < '0' || c > '9')
{
return false;
}
}
return true;
}
/// <summary>
/// Looks the like valid client identifier.
/// </summary>
/// <returns><c>true</c>, if valid client identifier, <c>false</c> otherwise.</returns>
/// <param name="s">the string to test.</param>
public static bool LooksLikeValidClientId(string s)
{
return s.EndsWith(".googleusercontent.com");
}
/// <summary>
/// Looks the like a valid bundle identifier.
/// </summary>
/// <returns><c>true</c>, if valid bundle identifier, <c>false</c> otherwise.</returns>
/// <param name="s">the string to test.</param>
public static bool LooksLikeValidBundleId(string s)
{
return s.Length > 3;
}
/// <summary>
/// Looks like a valid package.
/// </summary>
/// <returns><c>true</c>, if valid package name, <c>false</c> otherwise.</returns>
/// <param name="s">the string to test.</param>
public static bool LooksLikeValidPackageName(string s)
{
if (string.IsNullOrEmpty(s))
{
throw new Exception("cannot be empty");
}
string[] parts = s.Split(new char[] { '.' });
foreach (string p in parts)
{
char[] bytes = p.ToCharArray();
for (int i = 0; i < bytes.Length; i++)
{
if (i == 0 && !char.IsLetter(bytes[i]))
{
throw new Exception("each part must start with a letter");
}
else if (char.IsWhiteSpace(bytes[i]))
{
throw new Exception("cannot contain spaces");
}
else if (!char.IsLetterOrDigit(bytes[i]) && bytes[i] != '_')
{
throw new Exception("must be alphanumeric or _");
}
}
}
return parts.Length >= 1;
}
/// <summary>
/// Determines if is setup done.
/// </summary>
/// <returns><c>true</c> if is setup done; otherwise, <c>false</c>.</returns>
public static bool IsSetupDone()
{
bool doneSetup = true;
#if UNITY_ANDROID
doneSetup = GPGSProjectSettings.Instance.GetBool(ANDROIDSETUPDONEKEY, false);
// check gameinfo
if (File.Exists(GameInfoPath))
{
string contents = ReadFile(GameInfoPath);
if (contents.Contains(APPIDPLACEHOLDER))
{
Debug.Log("GameInfo not initialized with AppId. " +
"Run Window > Google Play Games > Setup > Android Setup...");
return false;
}
}
else
{
Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > Android Setup...");
return false;
}
#elif (UNITY_IPHONE && !NO_GPGS)
doneSetup = GPGSProjectSettings.Instance.GetBool(IOSSETUPDONEKEY, false);
// check gameinfo
if (File.Exists(GameInfoPath))
{
string contents = ReadFile(GameInfoPath);
if (contents.Contains(IOSCLIENTIDPLACEHOLDER))
{
Debug.Log("GameInfo not initialized with Client Id. " +
"Run Window > Google Play Games > Setup > iOS Setup...");
return false;
}
}
else
{
Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > iOS Setup...");
return false;
}
#endif
return doneSetup;
}
/// <summary>
/// Makes legal identifier from string.
/// Returns a legal C# identifier from the given string. The transformations are:
/// - spaces => underscore _
/// - punctuation => empty string
/// - leading numbers are prefixed with underscore.
/// </summary>
/// <returns>the id</returns>
/// <param name="key">Key to convert to an identifier.</param>
public static string MakeIdentifier(string key)
{
string s;
string retval = string.Empty;
if (string.IsNullOrEmpty(key))
{
return "_";
}
s = key.Trim().Replace(' ', '_');
foreach (char c in s)
{
if (char.IsLetterOrDigit(c) || c == '_')
{
retval += c;
}
}
return retval;
}
/// <summary>
/// Displays an error dialog.
/// </summary>
/// <param name="s">the message</param>
public static void Alert(string s)
{
Alert(GPGSStrings.Error, s);
}
/// <summary>
/// Displays a dialog with the given title and message.
/// </summary>
/// <param name="title">the title.</param>
/// <param name="message">the message.</param>
public static void Alert(string title, string message)
{
EditorUtility.DisplayDialog(title, message, GPGSStrings.Ok);
}
/// <summary>
/// Gets the android sdk path.
/// </summary>
/// <returns>The android sdk path.</returns>
public static string GetAndroidSdkPath()
{
string sdkPath = EditorPrefs.GetString("AndroidSdkRoot");
if (sdkPath != null && (sdkPath.EndsWith("/") || sdkPath.EndsWith("\\")))
{
sdkPath = sdkPath.Substring(0, sdkPath.Length - 1);
}
return sdkPath;
}
/// <summary>
/// Determines if the android sdk exists.
/// </summary>
/// <returns><c>true</c> if android sdk exists; otherwise, <c>false</c>.</returns>
public static bool HasAndroidSdk()
{
string sdkPath = GetAndroidSdkPath();
return sdkPath != null && sdkPath.Trim() != string.Empty && System.IO.Directory.Exists(sdkPath);
}
/// <summary>
/// Gets the unity major version.
/// </summary>
/// <returns>The unity major version.</returns>
public static int GetUnityMajorVersion()
{
#if UNITY_5
string majorVersion = Application.unityVersion.Split('.')[0];
int ver;
if (!int.TryParse(majorVersion, out ver))
{
ver = 0;
}
return ver;
#elif UNITY_4_6
return 4;
#else
return 0;
#endif
}
/// <summary>
/// Checks for the android manifest file exsistance.
/// </summary>
/// <returns><c>true</c>, if the file exists <c>false</c> otherwise.</returns>
public static bool AndroidManifestExists()
{
string destFilename = GPGSUtil.SlashesToPlatformSeparator(
"Assets/Plugins/Android/MainLibProj/AndroidManifest.xml");
return File.Exists(destFilename);
}
/// <summary>
/// Generates the android manifest.
/// </summary>
public static void GenerateAndroidManifest()
{
string destFilename = GPGSUtil.SlashesToPlatformSeparator(
"Assets/Plugins/Android/MainLibProj/AndroidManifest.xml");
// Generate AndroidManifest.xml
string manifestBody = GPGSUtil.ReadEditorTemplate("template-AndroidManifest");
Dictionary<string, string> overrideValues =
new Dictionary<string, string>();
foreach (KeyValuePair<string, string> ent in replacements)
{
string value =
GPGSProjectSettings.Instance.Get(ent.Value, overrideValues);
manifestBody = manifestBody.Replace(ent.Key, value);
}
GPGSUtil.WriteFile(destFilename, manifestBody);
GPGSUtil.UpdateGameInfo();
}
/// <summary>
/// Writes the resource identifiers file. This file contains the
/// resource ids copied (downloaded?) from the play game app console.
/// </summary>
/// <param name="classDirectory">Class directory.</param>
/// <param name="className">Class name.</param>
/// <param name="resourceKeys">Resource keys.</param>
public static void WriteResourceIds(string classDirectory, string className, Hashtable resourceKeys)
{
string constantsValues = string.Empty;
string[] parts = className.Split('.');
string dirName = classDirectory;
if (string.IsNullOrEmpty(dirName))
{
dirName = "Assets";
}
string nameSpace = string.Empty;
for (int i = 0; i < parts.Length - 1; i++)
{
dirName += "/" + parts[i];
if (nameSpace != string.Empty)
{
nameSpace += ".";
}
nameSpace += parts[i];
}
EnsureDirExists(dirName);
foreach (DictionaryEntry ent in resourceKeys)
{
string key = MakeIdentifier((string)ent.Key);
constantsValues += " public const string " +
key + " = \"" + ent.Value + "\"; // <GPGSID>\n";
}
string fileBody = GPGSUtil.ReadEditorTemplate("template-Constants");
if (nameSpace != string.Empty)
{
fileBody = fileBody.Replace(
NAMESPACESTARTPLACEHOLDER,
"namespace " + nameSpace + "\n{");
}
else
{
fileBody = fileBody.Replace(NAMESPACESTARTPLACEHOLDER, string.Empty);
}
fileBody = fileBody.Replace(CLASSNAMEPLACEHOLDER, parts[parts.Length - 1]);
fileBody = fileBody.Replace(CONSTANTSPLACEHOLDER, constantsValues);
if (nameSpace != string.Empty)
{
fileBody = fileBody.Replace(
NAMESPACEENDPLACEHOLDER,
"}");
}
else
{
fileBody = fileBody.Replace(NAMESPACEENDPLACEHOLDER, string.Empty);
}
WriteFile(Path.Combine(dirName, parts[parts.Length - 1] + ".cs"), fileBody);
}
/// <summary>
/// Updates the game info file. This is a generated file containing the
/// app and client ids.
/// </summary>
public static void UpdateGameInfo()
{
string fileBody = GPGSUtil.ReadEditorTemplate("template-GameInfo");
foreach (KeyValuePair<string, string> ent in replacements)
{
string value =
GPGSProjectSettings.Instance.Get(ent.Value);
fileBody = fileBody.Replace(ent.Key, value);
}
GPGSUtil.WriteFile(GameInfoPath, fileBody);
}
/// <summary>
/// Ensures the dir exists.
/// </summary>
/// <param name="dir">Directory to check.</param>
public static void EnsureDirExists(string dir)
{
dir = SlashesToPlatformSeparator(dir);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
/// <summary>
/// Deletes the dir if exists.
/// </summary>
/// <param name="dir">Directory to delete.</param>
public static void DeleteDirIfExists(string dir)
{
dir = SlashesToPlatformSeparator(dir);
if (Directory.Exists(dir))
{
Directory.Delete(dir, true);
}
}
/// <summary>
/// Gets the Google Play Services library version. This is only
/// needed for Unity versions less than 5.
/// </summary>
/// <returns>The GPS version.</returns>
/// <param name="libProjPath">Lib proj path.</param>
private static int GetGPSVersion(string libProjPath)
{
string versionFile = libProjPath + "/res/values/version.xml";
XmlTextReader reader = new XmlTextReader(new StreamReader(versionFile));
bool inResource = false;
int version = -1;
while (reader.Read())
{
if (reader.Name == "resources")
{
inResource = true;
}
if (inResource && reader.Name == "integer")
{
if ("google_play_services_version".Equals(
reader.GetAttribute("name")))
{
reader.Read();
Debug.Log("Read version string: " + reader.Value);
version = Convert.ToInt32(reader.Value);
}
}
}
reader.Close();
return version;
}
}
}
#endif
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Timers;
using System.Threading;
using WOSI.CallButler.Data;
using CallButler.Manager.Forms;
namespace CallButler.Manager.ViewControls
{
public partial class ProvidersView : CallButler.Manager.ViewControls.ViewControlBase
{
private System.Timers.Timer timer;
public ProvidersView()
{
InitializeComponent();
providerGrid.ReadOnly = false;
SetColumnPriviledges();
this.HelpRTFText = Properties.Resources.ProviderHelp;
}
private void SetColumnPriviledges()
{
foreach (DataGridViewColumn col in providerGrid.Columns)
{
if (col.HeaderText.Equals("Default") || col.HeaderText.Equals("Enabled"))
{
col.ReadOnly = false;
}
else
{
col.ReadOnly = true;
}
}
}
private System.Timers.Timer Timer
{
get
{
if (timer == null)
{
timer = new System.Timers.Timer();
timer.Interval = 5000;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
}
return timer;
}
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
timer.Stop();
lock (callButlerDataset)
{
callButlerDataset.Providers.Merge(ManagementInterfaceClient.ManagementInterface.GetProviders(ManagementInterfaceClient.AuthInfo));
}
}
catch { }
finally
{
timer.Start();
}
}
private void btnAddNewProvider_Click(object sender, EventArgs e)
{
AddNewProvider();
}
internal static DialogResult Add3rdPartyProvider()
{
return DialogResult.OK;
}
internal DialogResult AddNewProvider()
{
return AddNewProvider(ProviderType.None, true);
}
internal DialogResult AddNewProvider(ProviderType type, bool showInitialDialog)
{
DialogResult res = DialogResult.Cancel;
CallButler.Manager.Plugin.CallButlerManagementProviderPlugin providerPlugin = null;
/*if (showInitialDialog)
{
InitialProviderDialog dlg = new InitialProviderDialog();
if (dlg.ShowDialog(this) == DialogResult.OK)
{
type = dlg.ProviderType;
}
}*/
/*switch (type)
{
case ProviderType.CallButler:
// Get our default CallButler provider plugin
providerPlugin = (CallButler.Manager.Plugin.CallButlerManagementProviderPlugin)PluginManager.GetPluginFromID(new Guid(Properties.Settings.Default.PreferredVoIPProviderPluginID));
break;*/
//case ProviderType.Other:
providerPlugin = (CallButler.Manager.Plugin.CallButlerManagementProviderPlugin)PluginManager.GetPluginFromID(new Guid(Properties.Settings.Default.DefaultVoIPProviderPluginID));
//break;
//}
if (providerPlugin != null)
{
CallButler.Manager.Plugin.ProviderData providerData = providerPlugin.AddNewProvider();
if (providerData != null)
{
CallButlerDataset.ProvidersRow provider = CreateProviderRow(providerData, providerPlugin.ServicePluginID.ToString());
callButlerDataset.Providers.AddProvidersRow(provider);
SaveProviderRow(provider);
res = DialogResult.OK;
}
}
return res;
}
private int DefaultCount
{
get
{
DataRow[] rows = callButlerDataset.Providers.Select("IsDefault = true");
return rows.Length;
}
}
private void providerGrid_DeleteDataRow(object sender, CallButler.Manager.Controls.DataRowEventArgs e)
{
if (MessageBox.Show(this, CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.ProvidersView_ConfirmDelete), CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.Common_ConfirmDelete), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
DeleteProvider((CallButlerDataset.ProvidersRow)e.DataRow);
}
}
private void DeleteProvider(CallButlerDataset.ProvidersRow provider)
{
Guid providerID = provider.ProviderID;
callButlerDataset.Providers.RemoveProvidersRow(provider);
ManagementInterfaceClient.ManagementInterface.DeleteProvider(ManagementInterfaceClient.AuthInfo, providerID);
}
protected override void OnLoadData()
{
lock (callButlerDataset)
{
callButlerDataset.Providers.Merge(ManagementInterfaceClient.ManagementInterface.GetProviders(ManagementInterfaceClient.AuthInfo));
callButlerDataset.AcceptChanges();
}
providerGrid.CellValueChanged += new DataGridViewCellEventHandler(providerGrid_CellValueChanged);
providerGrid.CurrentCellDirtyStateChanged += new EventHandler(providerGrid_CurrentCellDirtyStateChanged);
Thread regTimerThread = new Thread(new ThreadStart(StartRegStatusTimer));
regTimerThread.Start();
}
protected override void OnSaveData()
{
Timer.Stop();
Timer.Dispose();
}
private void StartRegStatusTimer()
{
Timer.Stop();
Timer.Start();
}
private void providerGrid_EditDataRow(object sender, CallButler.Manager.Controls.DataRowEventArgs e)
{
EditProvider((CallButlerDataset.ProvidersRow)e.DataRow);
}
private void EditProvider(CallButlerDataset.ProvidersRow provider)
{
// Get the provider editor plugin
CallButler.Manager.Plugin.CallButlerManagementProviderPlugin providerPlugin = (CallButler.Manager.Plugin.CallButlerManagementProviderPlugin)PluginManager.GetPluginFromID(new Guid(Properties.Settings.Default.DefaultVoIPProviderPluginID));
/*try
{
// Check to see if this provider uses a different plugin
if(provider.PluginID != null && provider.PluginID.Length > 0)
providerPlugin = (CallButler.Manager.Plugin.CallButlerManagementProviderPlugin)PluginManager.GetPluginFromID(new Guid(provider.PluginID));
}
catch
{
}*/
if (providerPlugin != null)
{
// Copy our provider row into our provider data
CallButler.Manager.Plugin.ProviderData providerData = new CallButler.Manager.Plugin.ProviderData();
if (provider.AuthPassword != null && provider.AuthPassword.Length > 0)
providerData.AuthPassword = WOSI.Utilities.CryptoUtils.Decrypt(provider.AuthPassword, WOSI.CallButler.Data.Constants.EncryptionPassword);
providerData.AuthUsername = provider.AuthUsername;
providerData.DisplayName = provider.DisplayName;
providerData.Domain = provider.Domain;
providerData.EnableRegistration = provider.EnableRegistration;
providerData.Expires = provider.Expires;
providerData.ExtraData = provider.ExtraData;
providerData.IsEnabled = provider.IsEnabled;
providerData.Name = provider.Name;
providerData.SIPProxy = provider.SIPProxy;
providerData.SIPRegistrar = provider.SIPRegistrar;
providerData.Username = provider.Username;
// Edit the data
providerData = providerPlugin.EditProvider(providerData);
if (providerData != null)
{
// Copy the data back into our provider row
if (providerData.AuthPassword != null && providerData.AuthPassword.Length > 0)
provider.AuthPassword = WOSI.Utilities.CryptoUtils.Encrypt(providerData.AuthPassword, WOSI.CallButler.Data.Constants.EncryptionPassword);
provider.AuthUsername = providerData.AuthUsername;
provider.DisplayName = providerData.DisplayName;
provider.Domain = providerData.Domain;
provider.EnableRegistration = providerData.EnableRegistration;
provider.Expires = providerData.Expires;
provider.ExtraData = providerData.ExtraData;
provider.IsEnabled = providerData.IsEnabled;
provider.Name = providerData.Name;
provider.SIPProxy = providerData.SIPProxy;
provider.SIPRegistrar = providerData.SIPRegistrar;
provider.Username = providerData.Username;
SaveProviderRow(provider);
LoadData();
}
}
}
void providerGrid_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (providerGrid.IsCurrentCellDirty)
{
providerGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void providerGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1)
{
DataRowView rv = (DataRowView)providerGrid.Rows[e.RowIndex].DataBoundItem;
DataRow row = rv.Row;
bool IsChecked = (bool) providerGrid[e.ColumnIndex, e.RowIndex].Value;
if (IsChecked)
{
if (providerGrid.Columns[e.ColumnIndex].HeaderText.Equals("Default"))
{
foreach (DataGridViewRow dr in providerGrid.Rows)
{
if (dr.Index != e.RowIndex)
{
dr.Cells["IsDefault"].Value = false;
}
}
}
}
rv.EndEdit();
if (!IsChecked)
{
if (providerGrid.CurrentRow.Index == e.RowIndex && DefaultCount == 0)
{
providerGrid[e.ColumnIndex, e.RowIndex].Value = true;
}
}
SaveProviderRow((CallButlerDataset.ProvidersRow) row);
providerGrid.InvalidateRow(e.RowIndex);
}
}
private CallButlerDataset.ProvidersRow CreateProviderRow(CallButler.Manager.Plugin.ProviderData providerData, string pluginID)
{
CallButlerDataset.ProvidersRow provider = callButlerDataset.Providers.NewProvidersRow();
if (DefaultCount == 0)
{
provider.IsDefault = true;
}
provider.CustomerID = Properties.Settings.Default.CustomerID;
provider.ProviderID = Guid.NewGuid();
provider.PluginID = pluginID;
if (providerData.AuthPassword != null && providerData.AuthPassword.Length > 0)
provider.AuthPassword = WOSI.Utilities.CryptoUtils.Encrypt(providerData.AuthPassword, WOSI.CallButler.Data.Constants.EncryptionPassword);
provider.AuthUsername = providerData.AuthUsername;
provider.DisplayName = providerData.DisplayName;
provider.Domain = providerData.Domain;
provider.EnableRegistration = providerData.EnableRegistration;
provider.Expires = providerData.Expires;
provider.IsEnabled = providerData.IsEnabled;
provider.ExtraData = providerData.ExtraData;
provider.Name = providerData.Name;
provider.SIPProxy = providerData.SIPProxy;
provider.SIPRegistrar = providerData.SIPRegistrar;
provider.Username = providerData.Username;
return provider;
}
private void SaveProviderRow( CallButlerDataset.ProvidersRow row )
{
CallButlerDataset.ProvidersDataTable providerDataTable = Utils.TableUtils<CallButlerDataset.ProvidersDataTable>.CreateTableFromRow(row);
ManagementInterfaceClient.ManagementInterface.PersistProviders(ManagementInterfaceClient.AuthInfo, providerDataTable);
}
private void providerGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == usernameDataGridViewTextBoxColumn.Index && e.Value != System.DBNull.Value)
{
e.Value = WOSI.Utilities.StringUtils.FormatPhoneNumber((string)e.Value);
}
}
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Worker;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Xunit;
using System.Threading;
using System.Collections.ObjectModel;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker
{
public sealed class JobRunnerL0
{
private IExecutionContext _jobEc;
private JobRunner _jobRunner;
private JobInitializeResult _initResult = new JobInitializeResult();
private Pipelines.AgentJobRequestMessage _message;
private CancellationTokenSource _tokenSource;
private Mock<IJobServer> _jobServer;
private Mock<IJobServerQueue> _jobServerQueue;
private Mock<IVstsAgentWebProxy> _proxyConfig;
private Mock<IAgentCertificateManager> _cert;
private Mock<IConfigurationStore> _config;
private Mock<ITaskServer> _taskServer;
private Mock<IExtensionManager> _extensions;
private Mock<IStepsRunner> _stepRunner;
private Mock<IJobExtension> _jobExtension;
private Mock<IPagingLogger> _logger;
private Mock<ITempDirectoryManager> _temp;
private Mock<IDiagnosticLogManager> _diagnosticLogManager;
private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
{
var hc = new TestHostContext(this, testName);
_jobEc = new Agent.Worker.ExecutionContext();
_config = new Mock<IConfigurationStore>();
_extensions = new Mock<IExtensionManager>();
_jobExtension = new Mock<IJobExtension>();
_jobServer = new Mock<IJobServer>();
_jobServerQueue = new Mock<IJobServerQueue>();
_proxyConfig = new Mock<IVstsAgentWebProxy>();
_cert = new Mock<IAgentCertificateManager>();
_taskServer = new Mock<ITaskServer>();
_stepRunner = new Mock<IStepsRunner>();
_logger = new Mock<IPagingLogger>();
_temp = new Mock<ITempDirectoryManager>();
_diagnosticLogManager = new Mock<IDiagnosticLogManager>();
if (_tokenSource != null)
{
_tokenSource.Dispose();
_tokenSource = null;
}
_tokenSource = new CancellationTokenSource();
var expressionManager = new ExpressionManager();
expressionManager.Initialize(hc);
hc.SetSingleton<IExpressionManager>(expressionManager);
_jobRunner = new JobRunner();
_jobRunner.Initialize(hc);
TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
TimelineReference timeline = new Timeline(Guid.NewGuid());
JobEnvironment environment = new JobEnvironment();
environment.Variables[Constants.Variables.System.Culture] = "en-US";
environment.SystemConnection = new ServiceEndpoint()
{
Name = WellKnownServiceEndpointNames.SystemVssConnection,
Url = new Uri("https://test.visualstudio.com"),
Authorization = new EndpointAuthorization()
{
Scheme = "Test",
}
};
environment.SystemConnection.Authorization.Parameters["AccessToken"] = "token";
List<TaskInstance> tasks = new List<TaskInstance>();
Guid JobId = Guid.NewGuid();
_message = Pipelines.AgentJobRequestMessageUtil.Convert(new AgentJobRequestMessage(plan, timeline, JobId, testName, testName, environment, tasks));
_extensions.Setup(x => x.GetExtensions<IJobExtension>()).
Returns(new[] { _jobExtension.Object }.ToList());
_initResult.PreJobSteps.Clear();
_initResult.JobSteps.Clear();
_initResult.PostJobStep.Clear();
_jobExtension.Setup(x => x.InitializeJob(It.IsAny<IExecutionContext>(), It.IsAny<Pipelines.AgentJobRequestMessage>())).
Returns(Task.FromResult(_initResult));
_jobExtension.Setup(x => x.HostType)
.Returns<string>(null);
_proxyConfig.Setup(x => x.ProxyAddress)
.Returns(string.Empty);
var settings = new AgentSettings
{
AgentId = 1,
AgentName = "agent1",
ServerUrl = "https://test.visualstudio.com",
WorkFolder = "_work",
};
_config.Setup(x => x.GetSettings())
.Returns(settings);
_logger.Setup(x => x.Setup(It.IsAny<Guid>(), It.IsAny<Guid>()));
hc.SetSingleton(_config.Object);
hc.SetSingleton(_jobServer.Object);
hc.SetSingleton(_jobServerQueue.Object);
hc.SetSingleton(_proxyConfig.Object);
hc.SetSingleton(_cert.Object);
hc.SetSingleton(_taskServer.Object);
hc.SetSingleton(_stepRunner.Object);
hc.SetSingleton(_extensions.Object);
hc.SetSingleton(_temp.Object);
hc.SetSingleton(_diagnosticLogManager.Object);
hc.EnqueueInstance<IExecutionContext>(_jobEc);
hc.EnqueueInstance<IPagingLogger>(_logger.Object);
return hc;
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task JobExtensionInitializeFailure()
{
using (TestHostContext hc = CreateTestContext())
{
_jobExtension.Setup(x => x.InitializeJob(It.IsAny<IExecutionContext>(), It.IsAny<Pipelines.AgentJobRequestMessage>()))
.Throws(new Exception());
await _jobRunner.RunAsync(_message, _tokenSource.Token);
Assert.Equal(TaskResult.Failed, _jobEc.Result);
_stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.IsAny<IList<IStep>>()), Times.Never);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task JobExtensionInitializeCancelled()
{
using (TestHostContext hc = CreateTestContext())
{
_jobExtension.Setup(x => x.InitializeJob(It.IsAny<IExecutionContext>(), It.IsAny<Pipelines.AgentJobRequestMessage>()))
.Throws(new OperationCanceledException());
_tokenSource.Cancel();
await _jobRunner.RunAsync(_message, _tokenSource.Token);
Assert.Equal(TaskResult.Canceled, _jobEc.Result);
_stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.IsAny<IList<IStep>>()), Times.Never);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task UploadDiganosticLogIfEnvironmentVariableSet()
{
using (TestHostContext hc = CreateTestContext())
{
_message.Variables[Constants.Variables.Agent.Diagnostic] = "true";
await _jobRunner.RunAsync(_message, _tokenSource.Token);
_diagnosticLogManager.Verify(x => x.UploadDiagnosticLogsAsync(It.IsAny<IExecutionContext>(),
It.IsAny<Pipelines.AgentJobRequestMessage>(),
It.IsAny<DateTime>()),
Times.Once);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task DontUploadDiagnosticLogIfEnvironmentVariableFalse()
{
using (TestHostContext hc = CreateTestContext())
{
_message.Variables[Constants.Variables.Agent.Diagnostic] = "false";
await _jobRunner.RunAsync(_message, _tokenSource.Token);
_diagnosticLogManager.Verify(x => x.UploadDiagnosticLogsAsync(It.IsAny<IExecutionContext>(),
It.IsAny<Pipelines.AgentJobRequestMessage>(),
It.IsAny<DateTime>()),
Times.Never);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task DontUploadDiagnosticLogIfEnvironmentVariableMissing()
{
using (TestHostContext hc = CreateTestContext())
{
await _jobRunner.RunAsync(_message, _tokenSource.Token);
_diagnosticLogManager.Verify(x => x.UploadDiagnosticLogsAsync(It.IsAny<IExecutionContext>(),
It.IsAny<Pipelines.AgentJobRequestMessage>(),
It.IsAny<DateTime>()),
Times.Never);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Management.Automation.Host;
using System.Security;
using Dbg = System.Management.Automation.Diagnostics;
using InternalHostUserInterface = System.Management.Automation.Internal.Host.InternalHostUserInterface;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// The ServerRemoteHostUserInterface class.
/// </summary>
internal class ServerRemoteHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleChoiceSelection
{
/// <summary>
/// Server method executor.
/// </summary>
private readonly ServerMethodExecutor _serverMethodExecutor;
/// <summary>
/// Constructor for ServerRemoteHostUserInterface.
/// </summary>
internal ServerRemoteHostUserInterface(ServerRemoteHost remoteHost)
{
Dbg.Assert(remoteHost != null, "Expected remoteHost != null");
ServerRemoteHost = remoteHost;
Dbg.Assert(!remoteHost.HostInfo.IsHostUINull, "Expected !remoteHost.HostInfo.IsHostUINull");
_serverMethodExecutor = remoteHost.ServerMethodExecutor;
// Use HostInfo to duplicate host-RawUI as null or non-null based on the client's host-RawUI.
RawUI = remoteHost.HostInfo.IsHostRawUINull ? null : new ServerRemoteHostRawUserInterface(this);
}
/// <summary>
/// Raw ui.
/// </summary>
public override PSHostRawUserInterface RawUI { get; }
/// <summary>
/// Server remote host.
/// </summary>
internal ServerRemoteHost ServerRemoteHost { get; }
/// <summary>
/// Read line.
/// </summary>
public override string ReadLine()
{
return _serverMethodExecutor.ExecuteMethod<string>(RemoteHostMethodId.ReadLine);
}
/// <summary>
/// Prompt for choice.
/// </summary>
public override int PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, int defaultChoice)
{
return _serverMethodExecutor.ExecuteMethod<int>(RemoteHostMethodId.PromptForChoice, new object[] { caption, message, choices, defaultChoice });
}
/// <summary>
/// Prompt for choice. User can select multiple choices.
/// </summary>
/// <param name="caption"></param>
/// <param name="message"></param>
/// <param name="choices"></param>
/// <param name="defaultChoices"></param>
/// <returns></returns>
public Collection<int> PromptForChoice(string caption,
string message,
Collection<ChoiceDescription> choices,
IEnumerable<int> defaultChoices)
{
return _serverMethodExecutor.ExecuteMethod<Collection<int>>(RemoteHostMethodId.PromptForChoiceMultipleSelection,
new object[] { caption, message, choices, defaultChoices });
}
/// <summary>
/// Prompt.
/// </summary>
public override Dictionary<string, PSObject> Prompt(string caption, string message, Collection<FieldDescription> descriptions)
{
// forward the call to the client host
Dictionary<string, PSObject> results = _serverMethodExecutor.ExecuteMethod<Dictionary<string, PSObject>>(
RemoteHostMethodId.Prompt, new object[] { caption, message, descriptions });
// attempt to do the requested type casts on the server (it is okay to fail the cast and return the original object)
foreach (FieldDescription description in descriptions)
{
Type requestedType = InternalHostUserInterface.GetFieldType(description);
if (requestedType != null)
{
PSObject valueFromClient;
if (results.TryGetValue(description.Name, out valueFromClient))
{
object conversionResult;
if (LanguagePrimitives.TryConvertTo(valueFromClient, requestedType, CultureInfo.InvariantCulture, out conversionResult))
{
if (conversionResult != null)
{
results[description.Name] = PSObject.AsPSObject(conversionResult);
}
else
{
results[description.Name] = null;
}
}
}
}
}
return results;
}
/// <summary>
/// Write.
/// </summary>
public override void Write(string message)
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.Write1, new object[] { message });
}
/// <summary>
/// Write.
/// </summary>
public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string message)
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.Write2, new object[] { foregroundColor, backgroundColor, message });
}
/// <summary>
/// Write line.
/// </summary>
public override void WriteLine()
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteLine1);
}
/// <summary>
/// Write line.
/// </summary>
public override void WriteLine(string message)
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteLine2, new object[] { message });
}
/// <summary>
/// Write line.
/// </summary>
public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string message)
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteLine3, new object[] { foregroundColor, backgroundColor, message });
}
/// <summary>
/// Write error line.
/// </summary>
public override void WriteErrorLine(string message)
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteErrorLine, new object[] { message });
}
/// <summary>
/// Write debug line.
/// </summary>
public override void WriteDebugLine(string message)
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteDebugLine, new object[] { message });
}
/// <summary>
/// Write progress.
/// </summary>
public override void WriteProgress(long sourceId, ProgressRecord record)
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteProgress, new object[] { sourceId, record });
}
/// <summary>
/// Write verbose line.
/// </summary>
public override void WriteVerboseLine(string message)
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteVerboseLine, new object[] { message });
}
/// <summary>
/// Write warning line.
/// </summary>
public override void WriteWarningLine(string message)
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteWarningLine, new object[] { message });
}
/// <summary>
/// Read line as secure string.
/// </summary>
public override SecureString ReadLineAsSecureString()
{
return _serverMethodExecutor.ExecuteMethod<SecureString>(RemoteHostMethodId.ReadLineAsSecureString);
}
/// <summary>
/// Prompt for credential.
/// </summary>
public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName)
{
return _serverMethodExecutor.ExecuteMethod<PSCredential>(RemoteHostMethodId.PromptForCredential1,
new object[] { caption, message, userName, targetName });
}
/// <summary>
/// Prompt for credential.
/// </summary>
public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
{
return _serverMethodExecutor.ExecuteMethod<PSCredential>(RemoteHostMethodId.PromptForCredential2,
new object[] { caption, message, userName, targetName, allowedCredentialTypes, options });
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Reflection;
using System.Xml;
[ExecuteInEditMode]
public class GenericEvents : MonoBehaviour
{
#region Variables
protected List<MethodInfo> m_EventFunctions = new List<MethodInfo>();
#endregion
#region Properties
public MethodInfo[] EventMethods
{
get { return m_EventFunctions.ToArray(); }
}
#endregion
#region Functions
public virtual string GetEventType() { return GetType().ToString(); }
void Start()
{
enabled = !Application.isPlaying;
}
public virtual void Update()
{
if (!Application.isPlaying)
{
CheckAvailableEvents();
}
}
static protected T GetComponentFromString<T>(string gameObjectName) where T : Component
{
T comp = default(T);
GameObject go = GameObject.Find(gameObjectName);
if (go != null)
{
comp = go.GetComponent<T>();
if (comp == null)
{
Debug.LogError("Gameobject " + gameObjectName + " doesn't have a renderer component");
}
}
else
{
Debug.LogError("Can't find gameobject " + gameObjectName);
}
return comp;
}
public GenericEvents GetGenericEventsByEventType(string eventType)
{
GenericEvents[] genericEvents = GetComponents<GenericEvents>();
GenericEvents match = Array.Find<GenericEvents>(genericEvents, ge => ge.GetEventType() == eventType);
if (match == null)
{
Debug.LogError(string.Format("Couldn't find GenericEvents with type {0}", eventType));
}
return match;
}
/// <summary>
/// Refreshes the event list in the Machinima Maker
/// </summary>
public void CheckAvailableEvents()
{
m_EventFunctions.Clear();
Type[] nestedTypes = GetType().GetNestedTypes();
for (int i = 0; i < nestedTypes.Length; i++)
{
if (nestedTypes[i].IsClass)
{
MethodInfo[] methods = nestedTypes[i].GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); // only implemented functions
for (int j = 0; j < methods.Length; j++)
{
// ignore methods that are inherited from ICutsceneEventInterface
MethodInfo[] ignoredMethods = typeof(ICutsceneEventInterface).GetMethods();
if (Array.Exists<MethodInfo>(ignoredMethods, delegate(MethodInfo info) { return info.Name == methods[j].Name; }))
{
continue;
}
m_EventFunctions.Add(methods[j]);
}
}
}
}
public string GetLengthDefiningParamFromMethod(string eventMethodName)
{
return GetReturnValueFromFunction<string>(eventMethodName, "GetLengthParameterName", null);
}
public bool IsEventMethodFireAndForget(string eventMethodName)
{
return GetReturnValueFromFunction<bool>(eventMethodName, "IsFireAndForget", null);
}
/// <summary>
/// This is used when we are fast forwarding a cutscene and we're trying to maintain how
/// the cutscene would look if we played it through from the start
/// </summary>
/// <returns><c>true</c>, if to be fired was needsed, <c>false</c> otherwise.</returns>
/// <param name="eventMethodName">Event method name.</param>
public bool NeedsToBeFired(string eventMethodName, CutsceneEvent ce)
{
object[] parameters = new object[1] { ce };
return GetReturnValueFromFunction<bool>(eventMethodName, "NeedsToBeFired", parameters);
}
//public void Fast
/// <summary>
/// Returns the length in time of the event
/// </summary>
/// <param name="eventMethodName"></param>
/// <param name="ce"></param>
/// <returns></returns>
public float CalculateEventLength(string eventMethodName, CutsceneEvent ce)
{
object[] parameters = new object[1] { ce };
return GetReturnValueFromFunction<float>(eventMethodName, "CalculateEventLength", parameters);
}
public string GetXMLString(CutsceneEvent ce)
{
object[] parameters = new object[1] { ce };
return GetReturnValueFromFunction<string>(ce.FunctionName, "GetXMLString", parameters);
}
/// <summary>
/// Uses attribute values from the xml file in order to populate the event's parameters with data
/// </summary>
/// <param name="ce"></param>
/// <param name="reader"></param>
public void SetParameters(CutsceneEvent ce, XmlReader reader)
{
object[] parameters = new object[2] { ce, reader };
InvokeMethod(ce.FunctionName, "SetParameters", parameters);
}
public void SetMetaData(CutsceneEvent ce, object metaData)
{
object[] parameters = new object[1] { metaData };
InvokeMethod(ce.FunctionName, "SetMetaData", parameters);
}
public void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
object[] parameters = new object[2] { ce, param };
InvokeMethod(ce.FunctionName, "UseParamDefaultValue", parameters);
}
/// <summary>
/// Instatiates the event invoker based off the method name
/// </summary>
/// <param name="eventMethodName"></param>
/// <returns></returns>
public ICutsceneEventInterface CreateCutsceneEventInterfaceFromMethod(string eventMethodName)
{
MethodInfo method = null;
ICutsceneEventInterface retVal = CreateInterfaceFromMethod(eventMethodName, "IsFireAndForget", 0, ref method);
return retVal;
}
void InvokeMethod(string eventMethodName, string internalFunctionName, object[] parameters)
{
if (m_EventFunctions.Count == 0)
{
CheckAvailableEvents();
}
MethodInfo method = null;
ICutsceneEventInterface obj = CreateInterfaceFromMethod(eventMethodName, internalFunctionName, 0, ref method);
if (obj != null && method != null)
{
method.Invoke(obj, parameters);
}
else
{
Debug.LogError("Failed InvokeEventMethod on " + internalFunctionName);
}
}
T GetReturnValueFromFunction<T>(string eventMethodName, string internalFunctionName, object[] parameters)
{
T retVal = default(T);
if (m_EventFunctions.Count == 0)
{
CheckAvailableEvents();
}
MethodInfo method = null;
ICutsceneEventInterface obj = CreateInterfaceFromMethod(eventMethodName, internalFunctionName, 0, ref method);
if (obj != null && method != null)
{
retVal = (T)(method.Invoke(obj, parameters));
}
else
{
Debug.LogError("Failed InvokeEventMethod on " + internalFunctionName);
}
return retVal;
}
/// <summary>
/// Invokes an event method overload with the given parameters and time
/// </summary>
/// <param name="eventMethodName"></param>
/// <param name="overloadIndex"></param>
/// <param name="parameters"></param>
/// <param name="time"></param>
public void InvokeEventMethod(string eventMethodName, int overloadIndex, object[] parameters, float time, object metaData, MonoBehaviour behaviour)
{
MethodInfo method = null;
ICutsceneEventInterface obj = CreateInterfaceFromMethod(eventMethodName, eventMethodName, overloadIndex, ref method);
if (obj != null && method != null)
{
obj.SetInterpolationTime(time);
obj.SetMetaData(metaData);
obj.SetMonoBehaviour(behaviour);
method.Invoke(obj, parameters);
}
else
{
Debug.LogError("Failed InvokeEventMethod on " + eventMethodName);
}
}
public ParameterInfo[] GetEventMethodParams(string eventMethodName, int overloadIndex)
{
if (m_EventFunctions.Count == 0)
{
CheckAvailableEvents();
}
List<MethodInfo> methodInfos = m_EventFunctions.FindAll(delegate(MethodInfo info) { return info.Name == eventMethodName; });
ParameterInfo[] parameters = null;
if (methodInfos != null && methodInfos.Count > 0)
{
if (overloadIndex > methodInfos.Count - 1)
{
Debug.Log("bad overload index for function: " + eventMethodName);
return null;
}
parameters = methodInfos[overloadIndex].GetParameters();
}
else
{
Debug.LogError(string.Format("Couldn't GetEventMethodParams. Method: {0}", eventMethodName));
}
return parameters;
}
public MethodInfo[] GetEventMethodOverloads(string eventMethodName)
{
if (m_EventFunctions.Count == 0)
{
CheckAvailableEvents();
}
List<MethodInfo> methodInfos = m_EventFunctions.FindAll(delegate(MethodInfo info) { return info.Name == eventMethodName; });
return methodInfos.ToArray();
}
/// <summary>
/// Creates an ICutsceneEventInterface object which can be used to get and set data of a specific event.
/// </summary>
/// <param name="eventMethodName"></param>
/// <param name="methodToInvokeName"></param>
/// <param name="methodToInvokeOverloadIndex"></param>
/// <param name="out_methodToInvoke"></param>
/// <returns></returns>
protected ICutsceneEventInterface CreateInterfaceFromMethod(string eventMethodName, string methodToInvokeName, int methodToInvokeOverloadIndex, ref MethodInfo out_methodToInvoke)
{
if (m_EventFunctions.Count == 0)
{
CheckAvailableEvents();
}
// make sure the method exists
MethodInfo methodInfo = m_EventFunctions.Find(delegate(MethodInfo info) { return info.Name == eventMethodName; });
if (methodInfo == null)
{
Debug.LogError(string.Format("Couldn't CreateInterfaceFromMethod. Method: {0}", eventMethodName));
return null;
}
// search through the nested types
Type[] nestedTypes = GetType().GetNestedTypes();
for (int i = 0; i < nestedTypes.Length; i++)
{
MethodInfo[] methods = nestedTypes[i].GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); // only implemented functions
if (Array.Exists<MethodInfo>(methods, delegate(MethodInfo info) { return info.Name == eventMethodName; }))
{
// the method that we want exists, get it and create and object that can invoke it
out_methodToInvoke = Array.FindAll<MethodInfo>(nestedTypes[i].GetMethods(), delegate(MethodInfo meth) { return meth.Name == methodToInvokeName; })[methodToInvokeOverloadIndex];
return (ICutsceneEventInterface)Activator.CreateInstance(nestedTypes[i]);
}
}
Debug.LogError(string.Format("Couldn't CreateInterfaceFromMethod. Method: {0}", eventMethodName));
return null;
}
#endregion
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Collections;
#if NET_2_0
using System.Collections.Generic;
#endif
namespace NUnit.Framework.Constraints
{
/// <summary>
/// ConstraintBuilder maintains the stacks that are used in
/// processing a ConstraintExpression. An OperatorStack
/// is used to hold operators that are waiting for their
/// operands to be reognized. a ConstraintStack holds
/// input constraints as well as the results of each
/// operator applied.
/// </summary>
public class ConstraintBuilder
{
#region Nested Operator Stack Class
/// <summary>
/// OperatorStack is a type-safe stack for holding ConstraintOperators
/// </summary>
public class OperatorStack
{
#if NET_2_0
private Stack<ConstraintOperator> stack = new Stack<ConstraintOperator>();
#else
private Stack stack = new Stack();
#endif
/// <summary>
/// Initializes a new instance of the <see cref="T:OperatorStack"/> class.
/// </summary>
/// <param name="builder">The builder.</param>
public OperatorStack(ConstraintBuilder builder)
{
}
/// <summary>
/// Gets a value indicating whether this <see cref="T:OpStack"/> is empty.
/// </summary>
/// <value><c>true</c> if empty; otherwise, <c>false</c>.</value>
public bool Empty
{
get { return stack.Count == 0; }
}
/// <summary>
/// Gets the topmost operator without modifying the stack.
/// </summary>
/// <value>The top.</value>
public ConstraintOperator Top
{
get { return (ConstraintOperator)stack.Peek(); }
}
/// <summary>
/// Pushes the specified operator onto the stack.
/// </summary>
/// <param name="op">The op.</param>
public void Push(ConstraintOperator op)
{
stack.Push(op);
}
/// <summary>
/// Pops the topmost operator from the stack.
/// </summary>
/// <returns></returns>
public ConstraintOperator Pop()
{
return (ConstraintOperator)stack.Pop();
}
}
#endregion
#region Nested Constraint Stack Class
/// <summary>
/// ConstraintStack is a type-safe stack for holding Constraints
/// </summary>
public class ConstraintStack
{
#if NET_2_0
private Stack<Constraint> stack = new Stack<Constraint>();
#else
private Stack stack = new Stack();
#endif
private ConstraintBuilder builder;
/// <summary>
/// Initializes a new instance of the <see cref="T:ConstraintStack"/> class.
/// </summary>
/// <param name="builder">The builder.</param>
public ConstraintStack(ConstraintBuilder builder)
{
this.builder = builder;
}
/// <summary>
/// Gets a value indicating whether this <see cref="T:ConstraintStack"/> is empty.
/// </summary>
/// <value><c>true</c> if empty; otherwise, <c>false</c>.</value>
public bool Empty
{
get { return stack.Count == 0; }
}
/// <summary>
/// Gets the topmost constraint without modifying the stack.
/// </summary>
/// <value>The topmost constraint</value>
public Constraint Top
{
get { return (Constraint)stack.Peek(); }
}
/// <summary>
/// Pushes the specified constraint. As a side effect,
/// the constraint's builder field is set to the
/// ConstraintBuilder owning this stack.
/// </summary>
/// <param name="constraint">The constraint.</param>
public void Push(Constraint constraint)
{
stack.Push(constraint);
constraint.SetBuilder( this.builder );
}
/// <summary>
/// Pops this topmost constrait from the stack.
/// As a side effect, the constraint's builder
/// field is set to null.
/// </summary>
/// <returns></returns>
public Constraint Pop()
{
Constraint constraint = (Constraint)stack.Pop();
constraint.SetBuilder( null );
return constraint;
}
}
#endregion
#region Instance Fields
private OperatorStack ops;
private ConstraintStack constraints;
private object lastPushed;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="T:ConstraintBuilder"/> class.
/// </summary>
public ConstraintBuilder()
{
this.ops = new OperatorStack(this);
this.constraints = new ConstraintStack(this);
}
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether this instance is resolvable.
/// </summary>
/// <value>
/// <c>true</c> if this instance is resolvable; otherwise, <c>false</c>.
/// </value>
public bool IsResolvable
{
get { return lastPushed is Constraint || lastPushed is SelfResolvingOperator; }
}
#endregion
#region Public Methods
/// <summary>
/// Appends the specified operator to the expression by first
/// reducing the operator stack and then pushing the new
/// operator on the stack.
/// </summary>
/// <param name="op">The operator to push.</param>
public void Append(ConstraintOperator op)
{
op.LeftContext = lastPushed;
if (lastPushed is ConstraintOperator)
SetTopOperatorRightContext(op);
// Reduce any lower precedence operators
ReduceOperatorStack(op.LeftPrecedence);
ops.Push(op);
lastPushed = op;
}
/// <summary>
/// Appends the specified constraint to the expresson by pushing
/// it on the constraint stack.
/// </summary>
/// <param name="constraint">The constraint to push.</param>
public void Append(Constraint constraint)
{
if (lastPushed is ConstraintOperator)
SetTopOperatorRightContext(constraint);
constraints.Push(constraint);
lastPushed = constraint;
constraint.SetBuilder( this );
}
/// <summary>
/// Sets the top operator right context.
/// </summary>
/// <param name="rightContext">The right context.</param>
private void SetTopOperatorRightContext(object rightContext)
{
// Some operators change their precedence based on
// the right context - save current precedence.
int oldPrecedence = ops.Top.LeftPrecedence;
ops.Top.RightContext = rightContext;
// If the precedence increased, we may be able to
// reduce the region of the stack below the operator
if (ops.Top.LeftPrecedence > oldPrecedence)
{
ConstraintOperator changedOp = ops.Pop();
ReduceOperatorStack(changedOp.LeftPrecedence);
ops.Push(changedOp);
}
}
/// <summary>
/// Reduces the operator stack until the topmost item
/// precedence is greater than or equal to the target precedence.
/// </summary>
/// <param name="targetPrecedence">The target precedence.</param>
private void ReduceOperatorStack(int targetPrecedence)
{
while (!ops.Empty && ops.Top.RightPrecedence < targetPrecedence)
ops.Pop().Reduce(constraints);
}
/// <summary>
/// Resolves this instance, returning a Constraint. If the builder
/// is not currently in a resolvable state, an exception is thrown.
/// </summary>
/// <returns>The resolved constraint</returns>
public Constraint Resolve()
{
if (!IsResolvable)
throw new InvalidOperationException("A partial expression may not be resolved");
while (!ops.Empty)
{
ConstraintOperator op = ops.Pop();
op.Reduce(constraints);
}
return constraints.Pop();
}
#endregion
}
}
| |
// Resource Checker
// (c) 2012 Simon Oliver / HandCircus / hello@handcircus.com
// (c) 2015 Brice Clocher / Mangatome / hello@mangatome.net
// Public domain, do with whatever you like, commercial or not
// This comes with no warranty, use at your own risk!
// https://github.com/handcircus/Unity-Resource-Checker
using System.Linq;
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
public class TextureDetails
{
public bool isCubeMap;
public int memSizeKB;
public Texture texture;
public TextureFormat format;
public int mipMapCount;
public List<Object> FoundInMaterials = new List<Object>();
public List<Object> FoundInRenderers = new List<Object>();
public List<Object> FoundInAnimators = new List<Object>();
public List<Object> FoundInScripts = new List<Object>();
public TextureDetails()
{
}
};
public class MaterialDetails
{
public Material material;
public List<Renderer> FoundInRenderers = new List<Renderer>();
public MaterialDetails()
{
}
};
public class MeshDetails
{
public Mesh mesh;
public List<MeshFilter> FoundInMeshFilters = new List<MeshFilter>();
public List<SkinnedMeshRenderer> FoundInSkinnedMeshRenderer = new List<SkinnedMeshRenderer>();
public MeshDetails()
{
}
};
public class ResourceChecker : EditorWindow
{
string[] inspectToolbarStrings = { "Textures", "Materials", "Meshes" };
enum InspectType
{
Textures, Materials, Meshes
};
bool IncludeDisabledObjects = false;
bool IncludeSpriteAnimations = true;
bool IncludeScriptReferences = true;
InspectType ActiveInspectType = InspectType.Textures;
float ThumbnailWidth = 40;
float ThumbnailHeight = 40;
List<TextureDetails> ActiveTextures = new List<TextureDetails>();
List<MaterialDetails> ActiveMaterials = new List<MaterialDetails>();
List<MeshDetails> ActiveMeshDetails = new List<MeshDetails>();
Vector2 textureListScrollPos = new Vector2(0, 0);
Vector2 materialListScrollPos = new Vector2(0, 0);
Vector2 meshListScrollPos = new Vector2(0, 0);
int TotalTextureMemory = 0;
int TotalMeshVertices = 0;
bool ctrlPressed = false;
static int MinWidth = 455;
[MenuItem("Window/Resource Checker")]
static void Init()
{
ResourceChecker window = (ResourceChecker)EditorWindow.GetWindow(typeof(ResourceChecker));
window.CheckResources();
window.minSize = new Vector2(MinWidth, 300);
}
void OnGUI()
{
IncludeDisabledObjects = GUILayout.Toggle(IncludeDisabledObjects, "Include disabled and internal objects");
IncludeSpriteAnimations = GUILayout.Toggle(IncludeSpriteAnimations, "Look in sprite animations");
IncludeScriptReferences = GUILayout.Toggle(IncludeScriptReferences, "Look in behavior fields");
if (GUILayout.Button("Refresh")) CheckResources();
GUILayout.BeginHorizontal();
GUILayout.Label("Materials " + ActiveMaterials.Count);
GUILayout.Label("Textures " + ActiveTextures.Count + " - " + FormatSizeString(TotalTextureMemory));
GUILayout.Label("Meshes " + ActiveMeshDetails.Count + " - " + TotalMeshVertices + " verts");
GUILayout.EndHorizontal();
ActiveInspectType = (InspectType)GUILayout.Toolbar((int)ActiveInspectType, inspectToolbarStrings);
ctrlPressed = Event.current.control || Event.current.command;
switch (ActiveInspectType)
{
case InspectType.Textures:
ListTextures();
break;
case InspectType.Materials:
ListMaterials();
break;
case InspectType.Meshes:
ListMeshes();
break;
}
}
int GetBitsPerPixel(TextureFormat format)
{
switch (format)
{
case TextureFormat.Alpha8: // Alpha-only texture format.
return 8;
case TextureFormat.ARGB4444: // A 16 bits/pixel texture format. Texture stores color with an alpha channel.
return 16;
case TextureFormat.RGBA4444: // A 16 bits/pixel texture format.
return 16;
case TextureFormat.RGB24: // A color texture format.
return 24;
case TextureFormat.RGBA32: //Color with an alpha channel texture format.
return 32;
case TextureFormat.ARGB32: //Color with an alpha channel texture format.
return 32;
case TextureFormat.RGB565: // A 16 bit color texture format.
return 16;
case TextureFormat.DXT1: // Compressed color texture format.
return 4;
case TextureFormat.DXT5: // Compressed color with alpha channel texture format.
return 8;
/*
case TextureFormat.WiiI4: // Wii texture format.
case TextureFormat.WiiI8: // Wii texture format. Intensity 8 bit.
case TextureFormat.WiiIA4: // Wii texture format. Intensity + Alpha 8 bit (4 + 4).
case TextureFormat.WiiIA8: // Wii texture format. Intensity + Alpha 16 bit (8 + 8).
case TextureFormat.WiiRGB565: // Wii texture format. RGB 16 bit (565).
case TextureFormat.WiiRGB5A3: // Wii texture format. RGBA 16 bit (4443).
case TextureFormat.WiiRGBA8: // Wii texture format. RGBA 32 bit (8888).
case TextureFormat.WiiCMPR: // Compressed Wii texture format. 4 bits/texel, ~RGB8A1 (Outline alpha is not currently supported).
return 0; //Not supported yet
*/
case TextureFormat.PVRTC_RGB2:// PowerVR (iOS) 2 bits/pixel compressed color texture format.
return 2;
case TextureFormat.PVRTC_RGBA2:// PowerVR (iOS) 2 bits/pixel compressed with alpha channel texture format
return 2;
case TextureFormat.PVRTC_RGB4:// PowerVR (iOS) 4 bits/pixel compressed color texture format.
return 4;
case TextureFormat.PVRTC_RGBA4:// PowerVR (iOS) 4 bits/pixel compressed with alpha channel texture format
return 4;
case TextureFormat.ETC_RGB4:// ETC (GLES2.0) 4 bits/pixel compressed RGB texture format.
return 4;
case TextureFormat.ATC_RGB4:// ATC (ATITC) 4 bits/pixel compressed RGB texture format.
return 4;
case TextureFormat.ATC_RGBA8:// ATC (ATITC) 8 bits/pixel compressed RGB texture format.
return 8;
case TextureFormat.BGRA32:// Format returned by iPhone camera
return 32;
#if !UNITY_5
case TextureFormat.ATF_RGB_DXT1:// Flash-specific RGB DXT1 compressed color texture format.
case TextureFormat.ATF_RGBA_JPG:// Flash-specific RGBA JPG-compressed color texture format.
case TextureFormat.ATF_RGB_JPG:// Flash-specific RGB JPG-compressed color texture format.
return 0; //Not supported yet
#endif
}
return 0;
}
int CalculateTextureSizeBytes(Texture tTexture)
{
int tWidth = tTexture.width;
int tHeight = tTexture.height;
if (tTexture is Texture2D)
{
Texture2D tTex2D = tTexture as Texture2D;
int bitsPerPixel = GetBitsPerPixel(tTex2D.format);
int mipMapCount = tTex2D.mipmapCount;
int mipLevel = 1;
int tSize = 0;
while (mipLevel <= mipMapCount)
{
tSize += tWidth * tHeight * bitsPerPixel / 8;
tWidth = tWidth / 2;
tHeight = tHeight / 2;
mipLevel++;
}
return tSize;
}
if (tTexture is Cubemap)
{
Cubemap tCubemap = tTexture as Cubemap;
int bitsPerPixel = GetBitsPerPixel(tCubemap.format);
return tWidth * tHeight * 6 * bitsPerPixel / 8;
}
return 0;
}
void SelectObject(Object selectedObject, bool append)
{
if (append)
{
List<Object> currentSelection = new List<Object>(Selection.objects);
// Allow toggle selection
if (currentSelection.Contains(selectedObject)) currentSelection.Remove(selectedObject);
else currentSelection.Add(selectedObject);
Selection.objects = currentSelection.ToArray();
}
else Selection.activeObject = selectedObject;
}
void SelectObjects(List<Object> selectedObjects, bool append)
{
if (append)
{
List<Object> currentSelection = new List<Object>(Selection.objects);
currentSelection.AddRange(selectedObjects);
Selection.objects = currentSelection.ToArray();
}
else Selection.objects = selectedObjects.ToArray();
}
void ListTextures()
{
textureListScrollPos = EditorGUILayout.BeginScrollView(textureListScrollPos);
foreach (TextureDetails tDetails in ActiveTextures)
{
GUILayout.BeginHorizontal();
GUILayout.Box(tDetails.texture, GUILayout.Width(ThumbnailWidth), GUILayout.Height(ThumbnailHeight));
if (GUILayout.Button(tDetails.texture.name, GUILayout.Width(150)))
{
SelectObject(tDetails.texture, ctrlPressed);
}
string sizeLabel = "" + tDetails.texture.width + "x" + tDetails.texture.height;
if (tDetails.isCubeMap) sizeLabel += "x6";
sizeLabel += " - " + tDetails.mipMapCount + "mip";
sizeLabel += "\n" + FormatSizeString(tDetails.memSizeKB) + " - " + tDetails.format + "";
GUILayout.Label(sizeLabel, GUILayout.Width(120));
if (GUILayout.Button(tDetails.FoundInMaterials.Count + " Mat", GUILayout.Width(50)))
{
SelectObjects(tDetails.FoundInMaterials, ctrlPressed);
}
HashSet<Object> FoundObjects = new HashSet<Object>();
foreach (Renderer renderer in tDetails.FoundInRenderers) FoundObjects.Add(renderer.gameObject);
foreach (Animator animator in tDetails.FoundInAnimators) FoundObjects.Add(animator.gameObject);
foreach (MonoBehaviour script in tDetails.FoundInScripts) FoundObjects.Add(script.gameObject);
if (GUILayout.Button(FoundObjects.Count + " GO", GUILayout.Width(50)))
{
SelectObjects(new List<Object>(FoundObjects), ctrlPressed);
}
GUILayout.EndHorizontal();
}
if (ActiveTextures.Count > 0)
{
GUILayout.BeginHorizontal();
GUILayout.Box(" ", GUILayout.Width(ThumbnailWidth), GUILayout.Height(ThumbnailHeight));
if (GUILayout.Button("Select All", GUILayout.Width(150)))
{
List<Object> AllTextures = new List<Object>();
foreach (TextureDetails tDetails in ActiveTextures) AllTextures.Add(tDetails.texture);
SelectObjects(AllTextures, ctrlPressed);
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndScrollView();
}
void ListMaterials()
{
materialListScrollPos = EditorGUILayout.BeginScrollView(materialListScrollPos);
foreach (MaterialDetails tDetails in ActiveMaterials)
{
if (tDetails.material != null)
{
GUILayout.BeginHorizontal();
if (tDetails.material.mainTexture != null) GUILayout.Box(tDetails.material.mainTexture, GUILayout.Width(ThumbnailWidth), GUILayout.Height(ThumbnailHeight));
else
{
GUILayout.Box("n/a", GUILayout.Width(ThumbnailWidth), GUILayout.Height(ThumbnailHeight));
}
if (GUILayout.Button(tDetails.material.name, GUILayout.Width(150)))
{
SelectObject(tDetails.material, ctrlPressed);
}
string shaderLabel = tDetails.material.shader != null ? tDetails.material.shader.name : "no shader";
GUILayout.Label(shaderLabel, GUILayout.Width(200));
if (GUILayout.Button(tDetails.FoundInRenderers.Count + " GO", GUILayout.Width(50)))
{
List<Object> FoundObjects = new List<Object>();
foreach (Renderer renderer in tDetails.FoundInRenderers) FoundObjects.Add(renderer.gameObject);
SelectObjects(FoundObjects, ctrlPressed);
}
GUILayout.EndHorizontal();
}
}
EditorGUILayout.EndScrollView();
}
void ListMeshes()
{
meshListScrollPos = EditorGUILayout.BeginScrollView(meshListScrollPos);
foreach (MeshDetails tDetails in ActiveMeshDetails)
{
if (tDetails.mesh != null)
{
GUILayout.BeginHorizontal();
/*
if (tDetails.material.mainTexture!=null) GUILayout.Box(tDetails.material.mainTexture, GUILayout.Width(ThumbnailWidth), GUILayout.Height(ThumbnailHeight));
else
{
GUILayout.Box("n/a",GUILayout.Width(ThumbnailWidth),GUILayout.Height(ThumbnailHeight));
}
*/
if (GUILayout.Button(tDetails.mesh.name, GUILayout.Width(150)))
{
SelectObject(tDetails.mesh, ctrlPressed);
}
string sizeLabel = "" + tDetails.mesh.vertexCount + " vert";
GUILayout.Label(sizeLabel, GUILayout.Width(100));
if (GUILayout.Button(tDetails.FoundInMeshFilters.Count + " GO", GUILayout.Width(50)))
{
List<Object> FoundObjects = new List<Object>();
foreach (MeshFilter meshFilter in tDetails.FoundInMeshFilters) FoundObjects.Add(meshFilter.gameObject);
SelectObjects(FoundObjects, ctrlPressed);
}
if (GUILayout.Button(tDetails.FoundInSkinnedMeshRenderer.Count + " GO", GUILayout.Width(50)))
{
List<Object> FoundObjects = new List<Object>();
foreach (SkinnedMeshRenderer skinnedMeshRenderer in tDetails.FoundInSkinnedMeshRenderer) FoundObjects.Add(skinnedMeshRenderer.gameObject);
SelectObjects(FoundObjects, ctrlPressed);
}
GUILayout.EndHorizontal();
}
}
EditorGUILayout.EndScrollView();
}
string FormatSizeString(int memSizeKB)
{
if (memSizeKB < 1024) return "" + memSizeKB + "k";
else
{
float memSizeMB = ((float)memSizeKB) / 1024.0f;
return memSizeMB.ToString("0.00") + "Mb";
}
}
TextureDetails FindTextureDetails(Texture tTexture)
{
foreach (TextureDetails tTextureDetails in ActiveTextures)
{
if (tTextureDetails.texture == tTexture) return tTextureDetails;
}
return null;
}
MaterialDetails FindMaterialDetails(Material tMaterial)
{
foreach (MaterialDetails tMaterialDetails in ActiveMaterials)
{
if (tMaterialDetails.material == tMaterial) return tMaterialDetails;
}
return null;
}
MeshDetails FindMeshDetails(Mesh tMesh)
{
foreach (MeshDetails tMeshDetails in ActiveMeshDetails)
{
if (tMeshDetails.mesh == tMesh) return tMeshDetails;
}
return null;
}
void CheckResources()
{
ActiveTextures.Clear();
ActiveMaterials.Clear();
ActiveMeshDetails.Clear();
Renderer[] renderers = FindObjects<Renderer>();
//Debug.Log("Total renderers "+renderers.Length);
foreach (Renderer renderer in renderers)
{
//Debug.Log("Renderer is "+renderer.name);
foreach (Material material in renderer.sharedMaterials)
{
MaterialDetails tMaterialDetails = FindMaterialDetails(material);
if (tMaterialDetails == null)
{
tMaterialDetails = new MaterialDetails();
tMaterialDetails.material = material;
ActiveMaterials.Add(tMaterialDetails);
}
tMaterialDetails.FoundInRenderers.Add(renderer);
}
if (renderer is SpriteRenderer)
{
SpriteRenderer tSpriteRenderer = (SpriteRenderer)renderer;
if (tSpriteRenderer.sprite != null)
{
var tSpriteTextureDetail = GetTextureDetail(tSpriteRenderer.sprite.texture, renderer);
if (!ActiveTextures.Contains(tSpriteTextureDetail))
{
ActiveTextures.Add(tSpriteTextureDetail);
}
}
}
}
foreach (MaterialDetails tMaterialDetails in ActiveMaterials)
{
Material tMaterial = tMaterialDetails.material;
if (tMaterial != null)
{
var dependencies = EditorUtility.CollectDependencies(new UnityEngine.Object[] { tMaterial });
foreach (Object obj in dependencies)
{
if (obj is Texture)
{
Texture tTexture = obj as Texture;
var tTextureDetail = GetTextureDetail(tTexture, tMaterial, tMaterialDetails);
ActiveTextures.Add(tTextureDetail);
}
}
//if the texture was downloaded, it won't be included in the editor dependencies
if (tMaterial.mainTexture != null && !dependencies.Contains(tMaterial.mainTexture))
{
var tTextureDetail = GetTextureDetail(tMaterial.mainTexture, tMaterial, tMaterialDetails);
ActiveTextures.Add(tTextureDetail);
}
}
}
MeshFilter[] meshFilters = FindObjects<MeshFilter>();
foreach (MeshFilter tMeshFilter in meshFilters)
{
Mesh tMesh = tMeshFilter.sharedMesh;
if (tMesh != null)
{
MeshDetails tMeshDetails = FindMeshDetails(tMesh);
if (tMeshDetails == null)
{
tMeshDetails = new MeshDetails();
tMeshDetails.mesh = tMesh;
ActiveMeshDetails.Add(tMeshDetails);
}
tMeshDetails.FoundInMeshFilters.Add(tMeshFilter);
}
}
SkinnedMeshRenderer[] skinnedMeshRenderers = FindObjects<SkinnedMeshRenderer>();
foreach (SkinnedMeshRenderer tSkinnedMeshRenderer in skinnedMeshRenderers)
{
Mesh tMesh = tSkinnedMeshRenderer.sharedMesh;
if (tMesh != null)
{
MeshDetails tMeshDetails = FindMeshDetails(tMesh);
if (tMeshDetails == null)
{
tMeshDetails = new MeshDetails();
tMeshDetails.mesh = tMesh;
ActiveMeshDetails.Add(tMeshDetails);
}
tMeshDetails.FoundInSkinnedMeshRenderer.Add(tSkinnedMeshRenderer);
}
}
if (IncludeSpriteAnimations)
{
Animator[] animators = FindObjects<Animator>();
foreach (Animator anim in animators)
{
#if UNITY_4_6 || UNITY_4_5 || UNITY_4_4 || UNITY_4_3
UnityEditorInternal.AnimatorController ac = anim.runtimeAnimatorController as UnityEditorInternal.AnimatorController;
#elif UNITY_5
UnityEditor.Animations.AnimatorController ac = anim.runtimeAnimatorController as UnityEditor.Animations.AnimatorController;
#endif
for (int x = 0; x < anim.layerCount; x++)
{
#if UNITY_4_6 || UNITY_4_5 || UNITY_4_4 || UNITY_4_3
UnityEditorInternal.StateMachine sm = ac.GetLayer(x).stateMachine;
int cnt = sm.stateCount;
#elif UNITY_5
UnityEditor.Animations.AnimatorStateMachine sm = ac.layers[x].stateMachine;
int cnt = sm.states.Length;
#endif
for (int i = 0; i < cnt; i++)
{
#if UNITY_4_6 || UNITY_4_5 || UNITY_4_4 || UNITY_4_3
UnityEditorInternal.State state = sm.GetState(i);
Motion m = state.GetMotion();
#elif UNITY_5
UnityEditor.Animations.AnimatorState state = sm.states[i].state;
Motion m = state.motion;
#endif
if (m != null)
{
AnimationClip clip = m as AnimationClip;
EditorCurveBinding[] ecbs = AnimationUtility.GetObjectReferenceCurveBindings(clip);
foreach (EditorCurveBinding ecb in ecbs)
{
if (ecb.propertyName == "m_Sprite")
{
foreach (ObjectReferenceKeyframe keyframe in AnimationUtility.GetObjectReferenceCurve(clip, ecb))
{
Sprite tSprite = keyframe.value as Sprite;
if (tSprite != null)
{
var tTextureDetail = GetTextureDetail(tSprite.texture, anim);
if (!ActiveTextures.Contains(tTextureDetail))
{
ActiveTextures.Add(tTextureDetail);
}
}
}
}
}
}
}
}
}
}
if (IncludeScriptReferences)
{
MonoBehaviour[] scripts = FindObjects<MonoBehaviour>();
foreach (MonoBehaviour script in scripts)
{
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; // only public non-static fields are bound to by Unity.
FieldInfo[] fields = script.GetType().GetFields(flags);
foreach (FieldInfo field in fields)
{
System.Type fieldType = field.FieldType;
if (fieldType == typeof(Sprite))
{
Sprite tSprite = field.GetValue(script) as Sprite;
if (tSprite != null)
{
var tSpriteTextureDetail = GetTextureDetail(tSprite.texture, script);
if (!ActiveTextures.Contains(tSpriteTextureDetail))
{
ActiveTextures.Add(tSpriteTextureDetail);
}
}
}
}
}
}
TotalTextureMemory = 0;
foreach (TextureDetails tTextureDetails in ActiveTextures) TotalTextureMemory += tTextureDetails.memSizeKB;
TotalMeshVertices = 0;
foreach (MeshDetails tMeshDetails in ActiveMeshDetails) TotalMeshVertices += tMeshDetails.mesh.vertexCount;
// Sort by size, descending
ActiveTextures.Sort(delegate (TextureDetails details1, TextureDetails details2) { return details2.memSizeKB - details1.memSizeKB; });
ActiveMeshDetails.Sort(delegate (MeshDetails details1, MeshDetails details2) { return details2.mesh.vertexCount - details1.mesh.vertexCount; });
}
private T[] FindObjects<T>() where T : Object
{
if (IncludeDisabledObjects)
{
return Resources.FindObjectsOfTypeAll<T>();
}
else
{
return (T[])FindObjectsOfType(typeof(T));
}
}
private TextureDetails GetTextureDetail(Texture tTexture, Material tMaterial, MaterialDetails tMaterialDetails)
{
TextureDetails tTextureDetails = GetTextureDetail(tTexture);
tTextureDetails.FoundInMaterials.Add(tMaterial);
foreach (Renderer renderer in tMaterialDetails.FoundInRenderers)
{
if (!tTextureDetails.FoundInRenderers.Contains(renderer)) tTextureDetails.FoundInRenderers.Add(renderer);
}
return tTextureDetails;
}
private TextureDetails GetTextureDetail(Texture tTexture, Renderer renderer)
{
TextureDetails tTextureDetails = GetTextureDetail(tTexture);
tTextureDetails.FoundInRenderers.Add(renderer);
return tTextureDetails;
}
private TextureDetails GetTextureDetail(Texture tTexture, Animator animator)
{
TextureDetails tTextureDetails = GetTextureDetail(tTexture);
tTextureDetails.FoundInAnimators.Add(animator);
return tTextureDetails;
}
private TextureDetails GetTextureDetail(Texture tTexture, MonoBehaviour script)
{
TextureDetails tTextureDetails = GetTextureDetail(tTexture);
tTextureDetails.FoundInScripts.Add(script);
return tTextureDetails;
}
private TextureDetails GetTextureDetail(Texture tTexture)
{
TextureDetails tTextureDetails = FindTextureDetails(tTexture);
if (tTextureDetails == null)
{
tTextureDetails = new TextureDetails();
tTextureDetails.texture = tTexture;
tTextureDetails.isCubeMap = tTexture is Cubemap;
int memSize = CalculateTextureSizeBytes(tTexture);
tTextureDetails.memSizeKB = memSize / 1024;
TextureFormat tFormat = TextureFormat.RGBA32;
int tMipMapCount = 1;
if (tTexture is Texture2D)
{
tFormat = (tTexture as Texture2D).format;
tMipMapCount = (tTexture as Texture2D).mipmapCount;
}
if (tTexture is Cubemap)
{
tFormat = (tTexture as Cubemap).format;
}
tTextureDetails.format = tFormat;
tTextureDetails.mipMapCount = tMipMapCount;
}
return tTextureDetails;
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
namespace Paramol.Executors
{
/// <summary>
/// Represents the transactional execution of commands against a data source.
/// </summary>
public class TransactionalSqlCommandExecutor :
ISqlNonQueryCommandExecutor,
IAsyncSqlNonQueryCommandExecutor
{
private readonly DbProviderFactory _dbProviderFactory;
private readonly IsolationLevel _isolationLevel;
private readonly int _commandTimeout;
private readonly ConnectionStringSettings _settings;
/// <summary>
/// Initializes a new instance of the <see cref="TransactionalSqlCommandExecutor" /> class.
/// </summary>
/// <param name="settings">The connection string settings.</param>
/// <param name="isolationLevel">The transaction isolation level.</param>
/// <param name="commandTimeout">The command timeout.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="settings" /> is <c>null</c>.</exception>
public TransactionalSqlCommandExecutor(ConnectionStringSettings settings,
IsolationLevel isolationLevel, int commandTimeout = 30)
{
if (settings == null) throw new ArgumentNullException("settings");
_settings = settings;
_isolationLevel = isolationLevel;
_commandTimeout = commandTimeout;
_dbProviderFactory = DbProviderFactories.GetFactory(settings.ProviderName);
}
/// <summary>
/// Executes the specified command.
/// </summary>
/// <param name="command">The command.</param>
/// <returns>The number of <see cref="SqlNonQueryCommand">commands</see> executed.</returns>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="command" /> is <c>null</c>.</exception>
public void ExecuteNonQuery(SqlNonQueryCommand command)
{
if (command == null)
throw new ArgumentNullException("command");
using (var dbConnection = _dbProviderFactory.CreateConnection())
{
dbConnection.ConnectionString = _settings.ConnectionString;
dbConnection.Open();
try
{
using (var dbTransaction = dbConnection.BeginTransaction(_isolationLevel))
{
using (var dbCommand = dbConnection.CreateCommand())
{
dbCommand.Connection = dbConnection;
dbCommand.Transaction = dbTransaction;
dbCommand.CommandTimeout = _commandTimeout;
dbCommand.CommandType = command.Type;
dbCommand.CommandText = command.Text;
dbCommand.Parameters.AddRange(command.Parameters);
dbCommand.ExecuteNonQuery();
}
dbTransaction.Commit();
}
}
finally
{
dbConnection.Close();
}
}
}
/// <summary>
/// Executes the specified commands.
/// </summary>
/// <param name="commands">The commands to execute.</param>
/// <returns>The number of <see cref="SqlNonQueryCommand">commands</see> executed.</returns>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="commands" /> are <c>null</c>.</exception>
public int ExecuteNonQuery(IEnumerable<SqlNonQueryCommand> commands)
{
if (commands == null)
throw new ArgumentNullException("commands");
using (var dbConnection = _dbProviderFactory.CreateConnection())
{
dbConnection.ConnectionString = _settings.ConnectionString;
dbConnection.Open();
try
{
var count = 0;
using (var dbTransaction = dbConnection.BeginTransaction(_isolationLevel))
{
using (var dbCommand = dbConnection.CreateCommand())
{
dbCommand.Connection = dbConnection;
dbCommand.Transaction = dbTransaction;
dbCommand.CommandTimeout = _commandTimeout;
foreach (var command in commands)
{
dbCommand.CommandType = command.Type;
dbCommand.CommandText = command.Text;
dbCommand.Parameters.Clear();
dbCommand.Parameters.AddRange(command.Parameters);
dbCommand.ExecuteNonQuery();
count++;
}
}
dbTransaction.Commit();
}
return count;
}
finally
{
dbConnection.Close();
}
}
}
/// <summary>
/// Executes the specified commands asynchronously.
/// </summary>
/// <param name="commands">The commands</param>
/// <returns>
/// A <see cref="Task" /> that will return the number of <see cref="SqlNonQueryCommand">commands</see>
/// executed.
/// </returns>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="commands" /> are <c>null</c>.</exception>
public Task<int> ExecuteNonQueryAsync(IEnumerable<SqlNonQueryCommand> commands)
{
return ExecuteNonQueryAsync(commands, CancellationToken.None);
}
/// <summary>
/// Executes the specified commands asynchronously.
/// </summary>
/// <param name="commands">The commands.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A <see cref="Task" /> that will return the number of <see cref="SqlNonQueryCommand">commands</see>
/// executed.
/// </returns>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="commands" /> are <c>null</c>.</exception>
public async Task<int> ExecuteNonQueryAsync(IEnumerable<SqlNonQueryCommand> commands, CancellationToken cancellationToken)
{
if (commands == null)
throw new ArgumentNullException("commands");
using (var dbConnection = _dbProviderFactory.CreateConnection())
{
dbConnection.ConnectionString = _settings.ConnectionString;
await dbConnection.OpenAsync(cancellationToken);
try
{
var count = 0;
using (var dbTransaction = dbConnection.BeginTransaction(_isolationLevel))
{
using (var dbCommand = dbConnection.CreateCommand())
{
dbCommand.Connection = dbConnection;
dbCommand.Transaction = dbTransaction;
dbCommand.CommandTimeout = _commandTimeout;
foreach (var command in commands)
{
dbCommand.CommandType = command.Type;
dbCommand.CommandText = command.Text;
dbCommand.Parameters.Clear();
dbCommand.Parameters.AddRange(command.Parameters);
await dbCommand.ExecuteNonQueryAsync(cancellationToken);
count++;
}
}
dbTransaction.Commit();
}
return count;
}
finally
{
dbConnection.Close();
}
}
}
/// <summary>
/// Executes the specified command asynchronously.
/// </summary>
/// <param name="command">The command.</param>
/// <returns>
/// A <see cref="Task" /> that will return when the <see cref="SqlNonQueryCommand">command</see>
/// was executed.
/// </returns>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="command" /> is <c>null</c>.</exception>
public Task ExecuteNonQueryAsync(SqlNonQueryCommand command)
{
return ExecuteNonQueryAsync(command, CancellationToken.None);
}
/// <summary>
/// Executes the specified command asynchronously.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A <see cref="Task" /> that will return when the <see cref="SqlNonQueryCommand">command</see>
/// was executed.
/// </returns>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="command" /> is <c>null</c>.</exception>
public async Task ExecuteNonQueryAsync(SqlNonQueryCommand command, CancellationToken cancellationToken)
{
if (command == null)
throw new ArgumentNullException("command");
using (var dbConnection = _dbProviderFactory.CreateConnection())
{
dbConnection.ConnectionString = _settings.ConnectionString;
await dbConnection.OpenAsync(cancellationToken);
try
{
using (var dbTransaction = dbConnection.BeginTransaction(_isolationLevel))
{
using (var dbCommand = dbConnection.CreateCommand())
{
dbCommand.Connection = dbConnection;
dbCommand.Transaction = dbTransaction;
dbCommand.CommandTimeout = _commandTimeout;
dbCommand.CommandType = command.Type;
dbCommand.CommandText = command.Text;
dbCommand.Parameters.AddRange(command.Parameters);
await dbCommand.ExecuteNonQueryAsync(cancellationToken);
}
dbTransaction.Commit();
}
}
finally
{
dbConnection.Close();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Epi.Data;
using Epi.Data.PostgreSQL;
using Npgsql;
using Epi.Windows.Dialogs;
namespace Epi.Data.PostgreSQL.Forms
{
/// <summary>
/// Dialog for building a MySQL connection string
/// </summary>
public partial class ConnectionStringDialog : DialogBase, IConnectionStringGui
{
#region Public Data Members
#endregion //Public Data Members
#region Constructors
/// <summary>
/// Default Constructor
/// </summary>
public ConnectionStringDialog()
{
InitializeComponent();
this.cmbServerName.Items.Add("<Browse for more>");
this.cmbServerName.Text = "";
dbConnectionStringBuilder = new NpgsqlConnectionStringBuilder();
}
#endregion //Constructors
#region IConnectionStringBuilder Members
public bool ShouldIgnoreNonExistance
{
set { }
}
public virtual void SetDatabaseName(string databaseName) { }
public virtual void SetServerName(string serverName) { }
public virtual void SetUserName(string userName) { }
public virtual void SetPassword(string password) { }
/// <summary>
/// Module-level SqlDBConnectionString object member.
/// </summary>
protected NpgsqlConnectionStringBuilder dbConnectionStringBuilder;
/// <summary>
/// Gets or sets the SqlDBConnectionString Object
/// </summary>
public DbConnectionStringBuilder DbConnectionStringBuilder
{
get
{
return dbConnectionStringBuilder;
}
//set
//{
// dbConnectionStringBuilder = (SqlConnectionStringBuilder)value;
//}
}
/// <summary>
/// Sets the preferred database name
/// </summary>
public virtual string PreferredDatabaseName
{
set
{
txtDatabaseName.Text = value;
}
get
{
return txtDatabaseName.Text;
}
}
/// <summary>
/// Gets a user friendly description of the connection string
/// </summary>
public virtual string ConnectionStringDescription
{
get
{
return cmbServerName.Text + "::" + txtDatabaseName.Text;
}
}
/// <summary>
/// Gets whether or not the user entered a password
/// </summary>
public bool UsesPassword
{
get
{
if (this.txtPassword.Text.Length > 0)
{
return true;
}
else
{
return false;
}
}
}
#endregion //IConnectionStringBuilder Members
#region Event Handlers
/// <summary>
/// Handles the Click event of the OK button
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void btnOK_Click(object sender, EventArgs e)
{
OnOkClick();
}
/// <summary>
/// Handles the Click event of the Cancel button
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void btnCancel_Click(object sender, EventArgs e)
{
OnCancelClick();
}
/// <summary>
/// Handles the Change event of the Server Name's selection
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void cmbServerName_SelectedIndexChanged(object sender, EventArgs e)
{
// if last item in list (Browse for Servers)
if (cmbServerName.SelectedIndex == (cmbServerName.Items.Count - 1))
{
string serverName = string.Empty;// BrowseForServers.BrowseNetworkServers();
if (!string.IsNullOrEmpty(serverName))
{
this.cmbServerName.Items.Insert(0, serverName);
this.cmbServerName.SelectedIndex = 0;
return;
}
this.cmbServerName.SelectedText = string.Empty;
}
}
#endregion Event Handlers
#region Private Methods
#endregion //Private Methods
#region Protected Methods
/// <summary>
/// Validates if all the necessary input is provided.
/// </summary>
/// <returns></returns>
protected override bool ValidateInput()
{
base.ValidateInput();
// Server name
if (Util.IsEmpty(this.cmbServerName.Text.Trim()))
{
ErrorMessages.Add("Server name is required"); // TODO: Hard coded string
}
// Database name
string databaseName = txtDatabaseName.Text.Trim();
Epi.Validator.ValidateDatabaseName(databaseName, ErrorMessages);
// User Id
if (Util.IsEmpty(this.txtUserName.Text.Trim()))
{
ErrorMessages.Add("User name is required"); // TODO: Hard coded string
}
// Password
if (Util.IsEmpty(txtPassword.Text.Trim()))
{
ErrorMessages.Add("Password is required"); // TODO: Hard coded string
}
return (ErrorMessages.Count == 0);
}
/// <summary>
/// Occurs when cancel is clicked
/// </summary>
protected void OnCancelClick()
{
this.dbConnectionStringBuilder.ConnectionString = string.Empty ;
this.PreferredDatabaseName = string.Empty;
this.DialogResult = DialogResult.Cancel;
this.Close();
}
/// <summary>
/// Occurs when OK is clicked
/// </summary>
protected virtual void OnOkClick()
{
if (ValidateInput())
{
dbConnectionStringBuilder = new NpgsqlConnectionStringBuilder();
dbConnectionStringBuilder.Database = txtDatabaseName.Text.Trim();
dbConnectionStringBuilder.Host = cmbServerName.Text.Trim();
dbConnectionStringBuilder.Port = int.Parse(txtPort.Text.Trim());
dbConnectionStringBuilder.UserName = txtUserName.Text.Trim();
dbConnectionStringBuilder.Password = txtPassword.Text.Trim();
this.DialogResult = DialogResult.OK;
this.Hide();
}
else
{
ShowErrorMessages();
}
}
#endregion Protected Methods
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Graphics.Textures;
using osu.Framework.IO.Stores;
using osu.Framework.Lists;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Framework.Statistics;
using osu.Framework.Testing;
using osu.Game.Beatmaps.Formats;
using osu.Game.Database;
using osu.Game.IO;
using osu.Game.IO.Archives;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Objects;
using osu.Game.Skinning;
using osu.Game.Users;
using Decoder = osu.Game.Beatmaps.Formats.Decoder;
namespace osu.Game.Beatmaps
{
/// <summary>
/// Handles the storage and retrieval of Beatmaps/WorkingBeatmaps.
/// </summary>
[ExcludeFromDynamicCompile]
public partial class BeatmapManager : DownloadableArchiveModelManager<BeatmapSetInfo, BeatmapSetFileInfo>, IDisposable, IBeatmapResourceProvider
{
/// <summary>
/// Fired when a single difficulty has been hidden.
/// </summary>
public IBindable<WeakReference<BeatmapInfo>> BeatmapHidden => beatmapHidden;
private readonly Bindable<WeakReference<BeatmapInfo>> beatmapHidden = new Bindable<WeakReference<BeatmapInfo>>();
/// <summary>
/// Fired when a single difficulty has been restored.
/// </summary>
public IBindable<WeakReference<BeatmapInfo>> BeatmapRestored => beatmapRestored;
private readonly Bindable<WeakReference<BeatmapInfo>> beatmapRestored = new Bindable<WeakReference<BeatmapInfo>>();
/// <summary>
/// A default representation of a WorkingBeatmap to use when no beatmap is available.
/// </summary>
public readonly WorkingBeatmap DefaultBeatmap;
public override IEnumerable<string> HandledExtensions => new[] { ".osz" };
protected override string[] HashableFileTypes => new[] { ".osu" };
protected override string ImportFromStablePath => ".";
protected override Storage PrepareStableStorage(StableStorage stableStorage) => stableStorage.GetSongStorage();
private readonly RulesetStore rulesets;
private readonly BeatmapStore beatmaps;
private readonly AudioManager audioManager;
private readonly IResourceStore<byte[]> resources;
private readonly LargeTextureStore largeTextureStore;
private readonly ITrackStore trackStore;
[CanBeNull]
private readonly GameHost host;
[CanBeNull]
private readonly BeatmapOnlineLookupQueue onlineLookupQueue;
public BeatmapManager(Storage storage, IDatabaseContextFactory contextFactory, RulesetStore rulesets, IAPIProvider api, [NotNull] AudioManager audioManager, IResourceStore<byte[]> resources, GameHost host = null,
WorkingBeatmap defaultBeatmap = null, bool performOnlineLookups = false)
: base(storage, contextFactory, api, new BeatmapStore(contextFactory), host)
{
this.rulesets = rulesets;
this.audioManager = audioManager;
this.resources = resources;
this.host = host;
DefaultBeatmap = defaultBeatmap;
beatmaps = (BeatmapStore)ModelStore;
beatmaps.BeatmapHidden += b => beatmapHidden.Value = new WeakReference<BeatmapInfo>(b);
beatmaps.BeatmapRestored += b => beatmapRestored.Value = new WeakReference<BeatmapInfo>(b);
beatmaps.ItemRemoved += removeWorkingCache;
beatmaps.ItemUpdated += removeWorkingCache;
if (performOnlineLookups)
onlineLookupQueue = new BeatmapOnlineLookupQueue(api, storage);
largeTextureStore = new LargeTextureStore(host?.CreateTextureLoaderStore(Files.Store));
trackStore = audioManager.GetTrackStore(Files.Store);
}
protected override ArchiveDownloadRequest<BeatmapSetInfo> CreateDownloadRequest(BeatmapSetInfo set, bool minimiseDownloadSize) =>
new DownloadBeatmapSetRequest(set, minimiseDownloadSize);
protected override bool ShouldDeleteArchive(string path) => Path.GetExtension(path)?.ToLowerInvariant() == ".osz";
public WorkingBeatmap CreateNew(RulesetInfo ruleset, User user)
{
var metadata = new BeatmapMetadata
{
Author = user,
};
var set = new BeatmapSetInfo
{
Metadata = metadata,
Beatmaps = new List<BeatmapInfo>
{
new BeatmapInfo
{
BaseDifficulty = new BeatmapDifficulty(),
Ruleset = ruleset,
Metadata = metadata,
}
}
};
var working = Import(set).Result;
return GetWorkingBeatmap(working.Beatmaps.First());
}
protected override async Task Populate(BeatmapSetInfo beatmapSet, ArchiveReader archive, CancellationToken cancellationToken = default)
{
if (archive != null)
beatmapSet.Beatmaps = createBeatmapDifficulties(beatmapSet.Files);
foreach (BeatmapInfo b in beatmapSet.Beatmaps)
{
// remove metadata from difficulties where it matches the set
if (beatmapSet.Metadata.Equals(b.Metadata))
b.Metadata = null;
b.BeatmapSet = beatmapSet;
}
validateOnlineIds(beatmapSet);
bool hadOnlineBeatmapIDs = beatmapSet.Beatmaps.Any(b => b.OnlineBeatmapID > 0);
if (onlineLookupQueue != null)
await onlineLookupQueue.UpdateAsync(beatmapSet, cancellationToken).ConfigureAwait(false);
// ensure at least one beatmap was able to retrieve or keep an online ID, else drop the set ID.
if (hadOnlineBeatmapIDs && !beatmapSet.Beatmaps.Any(b => b.OnlineBeatmapID > 0))
{
if (beatmapSet.OnlineBeatmapSetID != null)
{
beatmapSet.OnlineBeatmapSetID = null;
LogForModel(beatmapSet, "Disassociating beatmap set ID due to loss of all beatmap IDs");
}
}
}
protected override void PreImport(BeatmapSetInfo beatmapSet)
{
if (beatmapSet.Beatmaps.Any(b => b.BaseDifficulty == null))
throw new InvalidOperationException($"Cannot import {nameof(BeatmapInfo)} with null {nameof(BeatmapInfo.BaseDifficulty)}.");
// check if a set already exists with the same online id, delete if it does.
if (beatmapSet.OnlineBeatmapSetID != null)
{
var existingOnlineId = beatmaps.ConsumableItems.FirstOrDefault(b => b.OnlineBeatmapSetID == beatmapSet.OnlineBeatmapSetID);
if (existingOnlineId != null)
{
Delete(existingOnlineId);
// in order to avoid a unique key constraint, immediately remove the online ID from the previous set.
existingOnlineId.OnlineBeatmapSetID = null;
foreach (var b in existingOnlineId.Beatmaps)
b.OnlineBeatmapID = null;
LogForModel(beatmapSet, $"Found existing beatmap set with same OnlineBeatmapSetID ({beatmapSet.OnlineBeatmapSetID}). It has been deleted.");
}
}
}
private void validateOnlineIds(BeatmapSetInfo beatmapSet)
{
var beatmapIds = beatmapSet.Beatmaps.Where(b => b.OnlineBeatmapID.HasValue).Select(b => b.OnlineBeatmapID).ToList();
// ensure all IDs are unique
if (beatmapIds.GroupBy(b => b).Any(g => g.Count() > 1))
{
LogForModel(beatmapSet, "Found non-unique IDs, resetting...");
resetIds();
return;
}
// find any existing beatmaps in the database that have matching online ids
var existingBeatmaps = QueryBeatmaps(b => beatmapIds.Contains(b.OnlineBeatmapID)).ToList();
if (existingBeatmaps.Count > 0)
{
// reset the import ids (to force a re-fetch) *unless* they match the candidate CheckForExisting set.
// we can ignore the case where the new ids are contained by the CheckForExisting set as it will either be used (import skipped) or deleted.
var existing = CheckForExisting(beatmapSet);
if (existing == null || existingBeatmaps.Any(b => !existing.Beatmaps.Contains(b)))
{
LogForModel(beatmapSet, "Found existing import with IDs already, resetting...");
resetIds();
}
}
void resetIds() => beatmapSet.Beatmaps.ForEach(b => b.OnlineBeatmapID = null);
}
protected override bool CheckLocalAvailability(BeatmapSetInfo model, IQueryable<BeatmapSetInfo> items)
=> base.CheckLocalAvailability(model, items)
|| (model.OnlineBeatmapSetID != null && items.Any(b => b.OnlineBeatmapSetID == model.OnlineBeatmapSetID));
/// <summary>
/// Delete a beatmap difficulty.
/// </summary>
/// <param name="beatmap">The beatmap difficulty to hide.</param>
public void Hide(BeatmapInfo beatmap) => beatmaps.Hide(beatmap);
/// <summary>
/// Restore a beatmap difficulty.
/// </summary>
/// <param name="beatmap">The beatmap difficulty to restore.</param>
public void Restore(BeatmapInfo beatmap) => beatmaps.Restore(beatmap);
/// <summary>
/// Saves an <see cref="IBeatmap"/> file against a given <see cref="BeatmapInfo"/>.
/// </summary>
/// <param name="info">The <see cref="BeatmapInfo"/> to save the content against. The file referenced by <see cref="BeatmapInfo.Path"/> will be replaced.</param>
/// <param name="beatmapContent">The <see cref="IBeatmap"/> content to write.</param>
/// <param name="beatmapSkin">The beatmap <see cref="ISkin"/> content to write, null if to be omitted.</param>
public virtual void Save(BeatmapInfo info, IBeatmap beatmapContent, ISkin beatmapSkin = null)
{
var setInfo = info.BeatmapSet;
using (var stream = new MemoryStream())
{
using (var sw = new StreamWriter(stream, Encoding.UTF8, 1024, true))
new LegacyBeatmapEncoder(beatmapContent, beatmapSkin).Encode(sw);
stream.Seek(0, SeekOrigin.Begin);
using (ContextFactory.GetForWrite())
{
var beatmapInfo = setInfo.Beatmaps.Single(b => b.ID == info.ID);
var metadata = beatmapInfo.Metadata ?? setInfo.Metadata;
// grab the original file (or create a new one if not found).
var fileInfo = setInfo.Files.SingleOrDefault(f => string.Equals(f.Filename, beatmapInfo.Path, StringComparison.OrdinalIgnoreCase)) ?? new BeatmapSetFileInfo();
// metadata may have changed; update the path with the standard format.
beatmapInfo.Path = $"{metadata.Artist} - {metadata.Title} ({metadata.Author}) [{beatmapInfo.Version}].osu";
beatmapInfo.MD5Hash = stream.ComputeMD5Hash();
// update existing or populate new file's filename.
fileInfo.Filename = beatmapInfo.Path;
stream.Seek(0, SeekOrigin.Begin);
ReplaceFile(setInfo, fileInfo, stream);
}
}
removeWorkingCache(info);
}
private readonly WeakList<BeatmapManagerWorkingBeatmap> workingCache = new WeakList<BeatmapManagerWorkingBeatmap>();
/// <summary>
/// Retrieve a <see cref="WorkingBeatmap"/> instance for the provided <see cref="BeatmapInfo"/>
/// </summary>
/// <param name="beatmapInfo">The beatmap to lookup.</param>
/// <returns>A <see cref="WorkingBeatmap"/> instance correlating to the provided <see cref="BeatmapInfo"/>.</returns>
public virtual WorkingBeatmap GetWorkingBeatmap(BeatmapInfo beatmapInfo)
{
// if there are no files, presume the full beatmap info has not yet been fetched from the database.
if (beatmapInfo?.BeatmapSet?.Files.Count == 0)
{
int lookupId = beatmapInfo.ID;
beatmapInfo = QueryBeatmap(b => b.ID == lookupId);
}
if (beatmapInfo?.BeatmapSet == null)
return DefaultBeatmap;
lock (workingCache)
{
var working = workingCache.FirstOrDefault(w => w.BeatmapInfo?.ID == beatmapInfo.ID);
if (working != null)
return working;
beatmapInfo.Metadata ??= beatmapInfo.BeatmapSet.Metadata;
workingCache.Add(working = new BeatmapManagerWorkingBeatmap(beatmapInfo, this));
// best effort; may be higher than expected.
GlobalStatistics.Get<int>(nameof(Beatmaps), $"Cached {nameof(WorkingBeatmap)}s").Value = workingCache.Count();
return working;
}
}
/// <summary>
/// Perform a lookup query on available <see cref="BeatmapSetInfo"/>s.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>The first result for the provided query, or null if no results were found.</returns>
public BeatmapSetInfo QueryBeatmapSet(Expression<Func<BeatmapSetInfo, bool>> query) => beatmaps.ConsumableItems.AsNoTracking().FirstOrDefault(query);
protected override bool CanSkipImport(BeatmapSetInfo existing, BeatmapSetInfo import)
{
if (!base.CanSkipImport(existing, import))
return false;
return existing.Beatmaps.Any(b => b.OnlineBeatmapID != null);
}
protected override bool CanReuseExisting(BeatmapSetInfo existing, BeatmapSetInfo import)
{
if (!base.CanReuseExisting(existing, import))
return false;
var existingIds = existing.Beatmaps.Select(b => b.OnlineBeatmapID).OrderBy(i => i);
var importIds = import.Beatmaps.Select(b => b.OnlineBeatmapID).OrderBy(i => i);
// force re-import if we are not in a sane state.
return existing.OnlineBeatmapSetID == import.OnlineBeatmapSetID && existingIds.SequenceEqual(importIds);
}
/// <summary>
/// Returns a list of all usable <see cref="BeatmapSetInfo"/>s.
/// </summary>
/// <returns>A list of available <see cref="BeatmapSetInfo"/>.</returns>
public List<BeatmapSetInfo> GetAllUsableBeatmapSets(IncludedDetails includes = IncludedDetails.All, bool includeProtected = false) =>
GetAllUsableBeatmapSetsEnumerable(includes, includeProtected).ToList();
/// <summary>
/// Returns a list of all usable <see cref="BeatmapSetInfo"/>s. Note that files are not populated.
/// </summary>
/// <param name="includes">The level of detail to include in the returned objects.</param>
/// <param name="includeProtected">Whether to include protected (system) beatmaps. These should not be included for gameplay playable use cases.</param>
/// <returns>A list of available <see cref="BeatmapSetInfo"/>.</returns>
public IEnumerable<BeatmapSetInfo> GetAllUsableBeatmapSetsEnumerable(IncludedDetails includes, bool includeProtected = false)
{
IQueryable<BeatmapSetInfo> queryable;
switch (includes)
{
case IncludedDetails.Minimal:
queryable = beatmaps.BeatmapSetsOverview;
break;
case IncludedDetails.AllButFiles:
queryable = beatmaps.BeatmapSetsWithoutFiles;
break;
default:
queryable = beatmaps.ConsumableItems;
break;
}
// AsEnumerable used here to avoid applying the WHERE in sql. When done so, ef core 2.x uses an incorrect ORDER BY
// clause which causes queries to take 5-10x longer.
// TODO: remove if upgrading to EF core 3.x.
return queryable.AsEnumerable().Where(s => !s.DeletePending && (includeProtected || !s.Protected));
}
/// <summary>
/// Perform a lookup query on available <see cref="BeatmapSetInfo"/>s.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Results from the provided query.</returns>
public IEnumerable<BeatmapSetInfo> QueryBeatmapSets(Expression<Func<BeatmapSetInfo, bool>> query) => beatmaps.ConsumableItems.AsNoTracking().Where(query);
/// <summary>
/// Perform a lookup query on available <see cref="BeatmapInfo"/>s.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>The first result for the provided query, or null if no results were found.</returns>
public BeatmapInfo QueryBeatmap(Expression<Func<BeatmapInfo, bool>> query) => beatmaps.Beatmaps.AsNoTracking().FirstOrDefault(query);
/// <summary>
/// Perform a lookup query on available <see cref="BeatmapInfo"/>s.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Results from the provided query.</returns>
public IQueryable<BeatmapInfo> QueryBeatmaps(Expression<Func<BeatmapInfo, bool>> query) => beatmaps.Beatmaps.AsNoTracking().Where(query);
protected override string HumanisedModelName => "beatmap";
protected override BeatmapSetInfo CreateModel(ArchiveReader reader)
{
// let's make sure there are actually .osu files to import.
string mapName = reader.Filenames.FirstOrDefault(f => f.EndsWith(".osu", StringComparison.OrdinalIgnoreCase));
if (string.IsNullOrEmpty(mapName))
{
Logger.Log($"No beatmap files found in the beatmap archive ({reader.Name}).", LoggingTarget.Database);
return null;
}
Beatmap beatmap;
using (var stream = new LineBufferedReader(reader.GetStream(mapName)))
beatmap = Decoder.GetDecoder<Beatmap>(stream).Decode(stream);
return new BeatmapSetInfo
{
OnlineBeatmapSetID = beatmap.BeatmapInfo.BeatmapSet?.OnlineBeatmapSetID,
Beatmaps = new List<BeatmapInfo>(),
Metadata = beatmap.Metadata,
DateAdded = DateTimeOffset.UtcNow
};
}
/// <summary>
/// Create all required <see cref="BeatmapInfo"/>s for the provided archive.
/// </summary>
private List<BeatmapInfo> createBeatmapDifficulties(List<BeatmapSetFileInfo> files)
{
var beatmapInfos = new List<BeatmapInfo>();
foreach (var file in files.Where(f => f.Filename.EndsWith(".osu", StringComparison.OrdinalIgnoreCase)))
{
using (var raw = Files.Store.GetStream(file.FileInfo.StoragePath))
using (var ms = new MemoryStream()) // we need a memory stream so we can seek
using (var sr = new LineBufferedReader(ms))
{
raw.CopyTo(ms);
ms.Position = 0;
var decoder = Decoder.GetDecoder<Beatmap>(sr);
IBeatmap beatmap = decoder.Decode(sr);
string hash = ms.ComputeSHA2Hash();
if (beatmapInfos.Any(b => b.Hash == hash))
continue;
beatmap.BeatmapInfo.Path = file.Filename;
beatmap.BeatmapInfo.Hash = hash;
beatmap.BeatmapInfo.MD5Hash = ms.ComputeMD5Hash();
var ruleset = rulesets.GetRuleset(beatmap.BeatmapInfo.RulesetID);
beatmap.BeatmapInfo.Ruleset = ruleset;
// TODO: this should be done in a better place once we actually need to dynamically update it.
beatmap.BeatmapInfo.StarDifficulty = ruleset?.CreateInstance().CreateDifficultyCalculator(new DummyConversionBeatmap(beatmap)).Calculate().StarRating ?? 0;
beatmap.BeatmapInfo.Length = calculateLength(beatmap);
beatmap.BeatmapInfo.BPM = 60000 / beatmap.GetMostCommonBeatLength();
beatmapInfos.Add(beatmap.BeatmapInfo);
}
}
return beatmapInfos;
}
private double calculateLength(IBeatmap b)
{
if (!b.HitObjects.Any())
return 0;
var lastObject = b.HitObjects.Last();
//TODO: this isn't always correct (consider mania where a non-last object may last for longer than the last in the list).
double endTime = lastObject.GetEndTime();
double startTime = b.HitObjects.First().StartTime;
return endTime - startTime;
}
private void removeWorkingCache(BeatmapSetInfo info)
{
if (info.Beatmaps == null) return;
foreach (var b in info.Beatmaps)
removeWorkingCache(b);
}
private void removeWorkingCache(BeatmapInfo info)
{
lock (workingCache)
{
var working = workingCache.FirstOrDefault(w => w.BeatmapInfo?.ID == info.ID);
if (working != null)
workingCache.Remove(working);
}
}
public void Dispose()
{
onlineLookupQueue?.Dispose();
}
#region IResourceStorageProvider
TextureStore IBeatmapResourceProvider.LargeTextureStore => largeTextureStore;
ITrackStore IBeatmapResourceProvider.Tracks => trackStore;
AudioManager IStorageResourceProvider.AudioManager => audioManager;
IResourceStore<byte[]> IStorageResourceProvider.Files => Files.Store;
IResourceStore<byte[]> IStorageResourceProvider.Resources => resources;
IResourceStore<TextureUpload> IStorageResourceProvider.CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => host?.CreateTextureLoaderStore(underlyingStore);
#endregion
/// <summary>
/// A dummy WorkingBeatmap for the purpose of retrieving a beatmap for star difficulty calculation.
/// </summary>
private class DummyConversionBeatmap : WorkingBeatmap
{
private readonly IBeatmap beatmap;
public DummyConversionBeatmap(IBeatmap beatmap)
: base(beatmap.BeatmapInfo, null)
{
this.beatmap = beatmap;
}
protected override IBeatmap GetBeatmap() => beatmap;
protected override Texture GetBackground() => null;
protected override Track GetBeatmapTrack() => null;
protected override ISkin GetSkin() => null;
public override Stream GetStream(string storagePath) => null;
}
}
/// <summary>
/// The level of detail to include in database results.
/// </summary>
public enum IncludedDetails
{
/// <summary>
/// Only include beatmap difficulties and set level metadata.
/// </summary>
Minimal,
/// <summary>
/// Include all difficulties, rulesets, difficulty metadata but no files.
/// </summary>
AllButFiles,
/// <summary>
/// Include everything.
/// </summary>
All
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Abstract base class for performing read operations of Lucene's low-level
/// data types.
///
/// <para/><see cref="DataInput"/> may only be used from one thread, because it is not
/// thread safe (it keeps internal state like file position). To allow
/// multithreaded use, every <see cref="DataInput"/> instance must be cloned before
/// used in another thread. Subclasses must therefore implement <see cref="Clone()"/>,
/// returning a new <see cref="DataInput"/> which operates on the same underlying
/// resource, but positioned independently.
/// </summary>
public abstract class DataInput
#if FEATURE_CLONEABLE
: System.ICloneable
#endif
{
private const int SKIP_BUFFER_SIZE = 1024;
/// <summary>
/// This buffer is used to skip over bytes with the default implementation of
/// skipBytes. The reason why we need to use an instance member instead of
/// sharing a single instance across threads is that some delegating
/// implementations of DataInput might want to reuse the provided buffer in
/// order to eg.update the checksum. If we shared the same buffer across
/// threads, then another thread might update the buffer while the checksum is
/// being computed, making it invalid. See LUCENE-5583 for more information.
/// </summary>
private byte[] skipBuffer;
/// <summary>
/// Reads and returns a single byte. </summary>
/// <seealso cref="DataOutput.WriteByte(byte)"/>
public abstract byte ReadByte();
/// <summary>
/// Reads a specified number of bytes into an array at the specified offset. </summary>
/// <param name="b"> the array to read bytes into </param>
/// <param name="offset"> the offset in the array to start storing bytes </param>
/// <param name="len"> the number of bytes to read </param>
/// <seealso cref="DataOutput.WriteBytes(byte[], int)"/>
public abstract void ReadBytes(byte[] b, int offset, int len);
/// <summary>
/// Reads a specified number of bytes into an array at the
/// specified offset with control over whether the read
/// should be buffered (callers who have their own buffer
/// should pass in "false" for <paramref name="useBuffer"/>). Currently only
/// <see cref="BufferedIndexInput"/> respects this parameter. </summary>
/// <param name="b"> the array to read bytes into </param>
/// <param name="offset"> the offset in the array to start storing bytes </param>
/// <param name="len"> the number of bytes to read </param>
/// <param name="useBuffer"> set to false if the caller will handle
/// buffering. </param>
/// <seealso cref="DataOutput.WriteBytes(byte[],int)"/>
public virtual void ReadBytes(byte[] b, int offset, int len, bool useBuffer)
{
// Default to ignoring useBuffer entirely
ReadBytes(b, offset, len);
}
/// <summary>
/// Reads two bytes and returns a <see cref="short"/>.
/// <para/>
/// LUCENENET NOTE: Important - always cast to ushort (System.UInt16) before using to ensure
/// the value is positive!
/// <para/>
/// NOTE: this was readShort() in Lucene
/// </summary>
/// <seealso cref="DataOutput.WriteInt16(short)"/>
public virtual short ReadInt16()
{
return (short)(ushort)(((ReadByte() & 0xFF) << 8) | (ReadByte() & 0xFF));
}
/// <summary>
/// Reads four bytes and returns an <see cref="int"/>.
/// <para/>
/// NOTE: this was readInt() in Lucene
/// </summary>
/// <seealso cref="DataOutput.WriteInt32(int)"/>
public virtual int ReadInt32()
{
return ((ReadByte() & 0xFF) << 24) | ((ReadByte() & 0xFF) << 16)
| ((ReadByte() & 0xFF) << 8) | (ReadByte() & 0xFF);
}
/// <summary>
/// Reads an <see cref="int"/> stored in variable-length format. Reads between one and
/// five bytes. Smaller values take fewer bytes. Negative numbers are not
/// supported.
/// <para/>
/// The format is described further in <see cref="DataOutput.WriteVInt32(int)"/>.
/// <para/>
/// NOTE: this was readVInt() in Lucene
/// </summary>
/// <seealso cref="DataOutput.WriteVInt32(int)"/>
public virtual int ReadVInt32()
{
byte b = ReadByte();
if ((sbyte)b >= 0)
{
return b;
}
int i = b & 0x7F;
b = ReadByte();
i |= (b & 0x7F) << 7;
if ((sbyte)b >= 0)
{
return i;
}
b = ReadByte();
i |= (b & 0x7F) << 14;
if ((sbyte)b >= 0)
{
return i;
}
b = ReadByte();
i |= (b & 0x7F) << 21;
if ((sbyte)b >= 0)
{
return i;
}
b = ReadByte();
// Warning: the next ands use 0x0F / 0xF0 - beware copy/paste errors:
i |= (b & 0x0F) << 28;
if (((sbyte)b & 0xF0) == 0)
{
return i;
}
throw new IOException("Invalid VInt32 detected (too many bits)");
}
/// <summary>
/// Reads eight bytes and returns a <see cref="long"/>.
/// <para/>
/// NOTE: this was readLong() in Lucene
/// </summary>
/// <seealso cref="DataOutput.WriteInt64(long)"/>
public virtual long ReadInt64()
{
return (((long)ReadInt32()) << 32) | (ReadInt32() & 0xFFFFFFFFL);
}
/// <summary>
/// Reads a <see cref="long"/> stored in variable-length format. Reads between one and
/// nine bytes. Smaller values take fewer bytes. Negative numbers are not
/// supported.
/// <para/>
/// The format is described further in <seealso cref="DataOutput.WriteVInt32(int)"/>.
/// <para/>
/// NOTE: this was readVLong() in Lucene
/// </summary>
/// <seealso cref="DataOutput.WriteVInt64(long)"/>
public virtual long ReadVInt64()
{
/* This is the original code of this method,
* but a Hotspot bug (see LUCENE-2975) corrupts the for-loop if
* readByte() is inlined. So the loop was unwinded!
byte b = readByte();
long i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = readByte();
i |= (b & 0x7FL) << shift;
}
return i;
*/
byte b = ReadByte();
if ((sbyte)b >= 0)
{
return b;
}
long i = b & 0x7FL;
b = ReadByte();
i |= (b & 0x7FL) << 7;
if ((sbyte)b >= 0)
{
return i;
}
b = ReadByte();
i |= (b & 0x7FL) << 14;
if ((sbyte)b >= 0)
{
return i;
}
b = ReadByte();
i |= (b & 0x7FL) << 21;
if ((sbyte)b >= 0)
{
return i;
}
b = ReadByte();
i |= (b & 0x7FL) << 28;
if ((sbyte)b >= 0)
{
return i;
}
b = ReadByte();
i |= (b & 0x7FL) << 35;
if ((sbyte)b >= 0)
{
return i;
}
b = ReadByte();
i |= (b & 0x7FL) << 42;
if ((sbyte)b >= 0)
{
return i;
}
b = ReadByte();
i |= (b & 0x7FL) << 49;
if ((sbyte)b >= 0)
{
return i;
}
b = ReadByte();
i |= (b & 0x7FL) << 56;
if ((sbyte)b >= 0)
{
return i;
}
throw new IOException("Invalid VInt64 detected (negative values disallowed)");
}
/// <summary>
/// Reads a <see cref="string"/>. </summary>
/// <seealso cref="DataOutput.WriteString(string)"/>
public virtual string ReadString()
{
int length = ReadVInt32();
byte[] bytes = new byte[length];
ReadBytes(bytes, 0, length);
return Encoding.UTF8.GetString(bytes);
}
/// <summary>
/// Returns a clone of this stream.
///
/// <para/>Clones of a stream access the same data, and are positioned at the same
/// point as the stream they were cloned from.
///
/// <para/>Expert: Subclasses must ensure that clones may be positioned at
/// different points in the input from each other and from the stream they
/// were cloned from.
/// </summary>
public virtual object Clone()
{
return base.MemberwiseClone();
}
/// <summary>
/// Reads a IDictionary<string,string> previously written
/// with <see cref="DataOutput.WriteStringStringMap(IDictionary{string, string})"/>.
/// </summary>
public virtual IDictionary<string, string> ReadStringStringMap()
{
IDictionary<string, string> map = new Dictionary<string, string>();
int count = ReadInt32();
for (int i = 0; i < count; i++)
{
string key = ReadString();
string val = ReadString();
map[key] = val;
}
return map;
}
/// <summary>
/// Reads a ISet<string> previously written
/// with <see cref="DataOutput.WriteStringSet(ISet{string})"/>.
/// </summary>
public virtual ISet<string> ReadStringSet()
{
ISet<string> set = new JCG.HashSet<string>();
int count = ReadInt32();
for (int i = 0; i < count; i++)
{
set.Add(ReadString());
}
return set;
}
/// <summary>
/// Skip over <paramref name="numBytes"/> bytes. The contract on this method is that it
/// should have the same behavior as reading the same number of bytes into a
/// buffer and discarding its content. Negative values of <paramref name="numBytes"/>
/// are not supported.
/// </summary>
public virtual void SkipBytes(long numBytes)
{
if (numBytes < 0)
{
throw new ArgumentException("numBytes must be >= 0, got " + numBytes);
}
if (skipBuffer == null)
{
skipBuffer = new byte[SKIP_BUFFER_SIZE];
}
Debug.Assert(skipBuffer.Length == SKIP_BUFFER_SIZE);
for (long skipped = 0; skipped < numBytes; )
{
var step = (int)Math.Min(SKIP_BUFFER_SIZE, numBytes - skipped);
ReadBytes(skipBuffer, 0, step, false);
skipped += step;
}
}
}
}
| |
// InflaterInputStream.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// HISTORY
// 11-08-2009 GeoffHart T9121 Added Multi-member gzip support
using System;
using System.IO;
#if !NETCF_1_0
using System.Security.Cryptography;
#endif
namespace GitHub.ICSharpCode.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// An input buffer customised for use by <see cref="InflaterInputStream"/>
/// </summary>
/// <remarks>
/// The buffer supports decryption of incoming data.
/// </remarks>
public class InflaterInputBuffer
{
#region Constructors
/// <summary>
/// Initialise a new instance of <see cref="InflaterInputBuffer"/> with a default buffer size
/// </summary>
/// <param name="stream">The stream to buffer.</param>
public InflaterInputBuffer(Stream stream) : this(stream , 4096)
{
}
/// <summary>
/// Initialise a new instance of <see cref="InflaterInputBuffer"/>
/// </summary>
/// <param name="stream">The stream to buffer.</param>
/// <param name="bufferSize">The size to use for the buffer</param>
/// <remarks>A minimum buffer size of 1KB is permitted. Lower sizes are treated as 1KB.</remarks>
public InflaterInputBuffer(Stream stream, int bufferSize)
{
inputStream = stream;
if ( bufferSize < 1024 ) {
bufferSize = 1024;
}
rawData = new byte[bufferSize];
clearText = rawData;
}
#endregion
/// <summary>
/// Get the length of bytes bytes in the <see cref="RawData"/>
/// </summary>
public int RawLength
{
get {
return rawLength;
}
}
/// <summary>
/// Get the contents of the raw data buffer.
/// </summary>
/// <remarks>This may contain encrypted data.</remarks>
public byte[] RawData
{
get {
return rawData;
}
}
/// <summary>
/// Get the number of useable bytes in <see cref="ClearText"/>
/// </summary>
public int ClearTextLength
{
get {
return clearTextLength;
}
}
/// <summary>
/// Get the contents of the clear text buffer.
/// </summary>
public byte[] ClearText
{
get {
return clearText;
}
}
/// <summary>
/// Get/set the number of bytes available
/// </summary>
public int Available
{
get { return available; }
set { available = value; }
}
/// <summary>
/// Call <see cref="Inflater.SetInput(byte[], int, int)"/> passing the current clear text buffer contents.
/// </summary>
/// <param name="inflater">The inflater to set input for.</param>
public void SetInflaterInput(Inflater inflater)
{
if ( available > 0 ) {
inflater.SetInput(clearText, clearTextLength - available, available);
available = 0;
}
}
/// <summary>
/// Fill the buffer from the underlying input stream.
/// </summary>
public void Fill()
{
rawLength = 0;
int toRead = rawData.Length;
while (toRead > 0) {
int count = inputStream.Read(rawData, rawLength, toRead);
if ( count <= 0 ) {
break;
}
rawLength += count;
toRead -= count;
}
#if !NETCF_1_0
if ( cryptoTransform != null ) {
clearTextLength = cryptoTransform.TransformBlock(rawData, 0, rawLength, clearText, 0);
}
else
#endif
{
clearTextLength = rawLength;
}
available = clearTextLength;
}
/// <summary>
/// Read a buffer directly from the input stream
/// </summary>
/// <param name="buffer">The buffer to fill</param>
/// <returns>Returns the number of bytes read.</returns>
public int ReadRawBuffer(byte[] buffer)
{
return ReadRawBuffer(buffer, 0, buffer.Length);
}
/// <summary>
/// Read a buffer directly from the input stream
/// </summary>
/// <param name="outBuffer">The buffer to read into</param>
/// <param name="offset">The offset to start reading data into.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>Returns the number of bytes read.</returns>
public int ReadRawBuffer(byte[] outBuffer, int offset, int length)
{
if ( length < 0 ) {
throw new ArgumentOutOfRangeException("length");
}
int currentOffset = offset;
int currentLength = length;
while ( currentLength > 0 ) {
if ( available <= 0 ) {
Fill();
if (available <= 0) {
return 0;
}
}
int toCopy = Math.Min(currentLength, available);
System.Array.Copy(rawData, rawLength - (int)available, outBuffer, currentOffset, toCopy);
currentOffset += toCopy;
currentLength -= toCopy;
available -= toCopy;
}
return length;
}
/// <summary>
/// Read clear text data from the input stream.
/// </summary>
/// <param name="outBuffer">The buffer to add data to.</param>
/// <param name="offset">The offset to start adding data at.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>Returns the number of bytes actually read.</returns>
public int ReadClearTextBuffer(byte[] outBuffer, int offset, int length)
{
if ( length < 0 ) {
throw new ArgumentOutOfRangeException("length");
}
int currentOffset = offset;
int currentLength = length;
while ( currentLength > 0 ) {
if ( available <= 0 ) {
Fill();
if (available <= 0) {
return 0;
}
}
int toCopy = Math.Min(currentLength, available);
Array.Copy(clearText, clearTextLength - (int)available, outBuffer, currentOffset, toCopy);
currentOffset += toCopy;
currentLength -= toCopy;
available -= toCopy;
}
return length;
}
/// <summary>
/// Read a <see cref="byte"/> from the input stream.
/// </summary>
/// <returns>Returns the byte read.</returns>
public int ReadLeByte()
{
if (available <= 0) {
Fill();
if (available <= 0) {
throw new ZipException("EOF in header");
}
}
byte result = rawData[rawLength - available];
available -= 1;
return result;
}
/// <summary>
/// Read an <see cref="short"/> in little endian byte order.
/// </summary>
/// <returns>The short value read case to an int.</returns>
public int ReadLeShort()
{
return ReadLeByte() | (ReadLeByte() << 8);
}
/// <summary>
/// Read an <see cref="int"/> in little endian byte order.
/// </summary>
/// <returns>The int value read.</returns>
public int ReadLeInt()
{
return ReadLeShort() | (ReadLeShort() << 16);
}
/// <summary>
/// Read a <see cref="long"/> in little endian byte order.
/// </summary>
/// <returns>The long value read.</returns>
public long ReadLeLong()
{
return (uint)ReadLeInt() | ((long)ReadLeInt() << 32);
}
#if !NETCF_1_0
/// <summary>
/// Get/set the <see cref="ICryptoTransform"/> to apply to any data.
/// </summary>
/// <remarks>Set this value to null to have no transform applied.</remarks>
public ICryptoTransform CryptoTransform
{
set {
cryptoTransform = value;
if ( cryptoTransform != null ) {
if ( rawData == clearText ) {
if ( internalClearText == null ) {
internalClearText = new byte[rawData.Length];
}
clearText = internalClearText;
}
clearTextLength = rawLength;
if ( available > 0 ) {
cryptoTransform.TransformBlock(rawData, rawLength - available, available, clearText, rawLength - available);
}
} else {
clearText = rawData;
clearTextLength = rawLength;
}
}
}
#endif
#region Instance Fields
int rawLength;
byte[] rawData;
int clearTextLength;
byte[] clearText;
#if !NETCF_1_0
byte[] internalClearText;
#endif
int available;
#if !NETCF_1_0
ICryptoTransform cryptoTransform;
#endif
Stream inputStream;
#endregion
}
/// <summary>
/// This filter stream is used to decompress data compressed using the "deflate"
/// format. The "deflate" format is described in RFC 1951.
///
/// This stream may form the basis for other decompression filters, such
/// as the <see cref="ICSharpCode.SharpZipLib.GZip.GZipInputStream">GZipInputStream</see>.
///
/// Author of the original java version : John Leuner.
/// </summary>
public class InflaterInputStream : Stream
{
#region Constructors
/// <summary>
/// Create an InflaterInputStream with the default decompressor
/// and a default buffer size of 4KB.
/// </summary>
/// <param name = "baseInputStream">
/// The InputStream to read bytes from
/// </param>
public InflaterInputStream(Stream baseInputStream)
: this(baseInputStream, new Inflater(), 4096)
{
}
/// <summary>
/// Create an InflaterInputStream with the specified decompressor
/// and a default buffer size of 4KB.
/// </summary>
/// <param name = "baseInputStream">
/// The source of input data
/// </param>
/// <param name = "inf">
/// The decompressor used to decompress data read from baseInputStream
/// </param>
public InflaterInputStream(Stream baseInputStream, Inflater inf)
: this(baseInputStream, inf, 4096)
{
}
/// <summary>
/// Create an InflaterInputStream with the specified decompressor
/// and the specified buffer size.
/// </summary>
/// <param name = "baseInputStream">
/// The InputStream to read bytes from
/// </param>
/// <param name = "inflater">
/// The decompressor to use
/// </param>
/// <param name = "bufferSize">
/// Size of the buffer to use
/// </param>
public InflaterInputStream(Stream baseInputStream, Inflater inflater, int bufferSize)
{
if (baseInputStream == null) {
throw new ArgumentNullException("baseInputStream");
}
if (inflater == null) {
throw new ArgumentNullException("inflater");
}
if (bufferSize <= 0) {
throw new ArgumentOutOfRangeException("bufferSize");
}
this.baseInputStream = baseInputStream;
this.inf = inflater;
inputBuffer = new InflaterInputBuffer(baseInputStream, bufferSize);
}
#endregion
/// <summary>
/// Get/set flag indicating ownership of underlying stream.
/// When the flag is true <see cref="Close"/> will close the underlying stream also.
/// </summary>
/// <remarks>
/// The default value is true.
/// </remarks>
public bool IsStreamOwner
{
get { return isStreamOwner; }
set { isStreamOwner = value; }
}
/// <summary>
/// Skip specified number of bytes of uncompressed data
/// </summary>
/// <param name ="count">
/// Number of bytes to skip
/// </param>
/// <returns>
/// The number of bytes skipped, zero if the end of
/// stream has been reached
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="count">The number of bytes</paramref> to skip is less than or equal to zero.
/// </exception>
public long Skip(long count)
{
if (count <= 0) {
throw new ArgumentOutOfRangeException("count");
}
// v0.80 Skip by seeking if underlying stream supports it...
if (baseInputStream.CanSeek) {
baseInputStream.Seek(count, SeekOrigin.Current);
return count;
}
else {
int length = 2048;
if (count < length) {
length = (int) count;
}
byte[] tmp = new byte[length];
int readCount = 1;
long toSkip = count;
while ((toSkip > 0) && (readCount > 0) ) {
if (toSkip < length) {
length = (int)toSkip;
}
readCount = baseInputStream.Read(tmp, 0, length);
toSkip -= readCount;
}
return count - toSkip;
}
}
/// <summary>
/// Clear any cryptographic state.
/// </summary>
protected void StopDecrypting()
{
#if !NETCF_1_0
inputBuffer.CryptoTransform = null;
#endif
}
/// <summary>
/// Returns 0 once the end of the stream (EOF) has been reached.
/// Otherwise returns 1.
/// </summary>
public virtual int Available
{
get {
return inf.IsFinished ? 0 : 1;
}
}
/// <summary>
/// Fills the buffer with more data to decompress.
/// </summary>
/// <exception cref="SharpZipBaseException">
/// Stream ends early
/// </exception>
protected void Fill()
{
// Protect against redundant calls
if (inputBuffer.Available <= 0) {
inputBuffer.Fill();
if (inputBuffer.Available <= 0) {
throw new SharpZipBaseException("Unexpected EOF");
}
}
inputBuffer.SetInflaterInput(inf);
}
#region Stream Overrides
/// <summary>
/// Gets a value indicating whether the current stream supports reading
/// </summary>
public override bool CanRead
{
get {
return baseInputStream.CanRead;
}
}
/// <summary>
/// Gets a value of false indicating seeking is not supported for this stream.
/// </summary>
public override bool CanSeek {
get {
return false;
}
}
/// <summary>
/// Gets a value of false indicating that this stream is not writeable.
/// </summary>
public override bool CanWrite {
get {
return false;
}
}
/// <summary>
/// A value representing the length of the stream in bytes.
/// </summary>
public override long Length {
get {
return inputBuffer.RawLength;
}
}
/// <summary>
/// The current position within the stream.
/// Throws a NotSupportedException when attempting to set the position
/// </summary>
/// <exception cref="NotSupportedException">Attempting to set the position</exception>
public override long Position {
get {
return baseInputStream.Position;
}
set {
throw new NotSupportedException("InflaterInputStream Position not supported");
}
}
/// <summary>
/// Flushes the baseInputStream
/// </summary>
public override void Flush()
{
baseInputStream.Flush();
}
/// <summary>
/// Sets the position within the current stream
/// Always throws a NotSupportedException
/// </summary>
/// <param name="offset">The relative offset to seek to.</param>
/// <param name="origin">The <see cref="SeekOrigin"/> defining where to seek from.</param>
/// <returns>The new position in the stream.</returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException("Seek not supported");
}
/// <summary>
/// Set the length of the current stream
/// Always throws a NotSupportedException
/// </summary>
/// <param name="value">The new length value for the stream.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void SetLength(long value)
{
throw new NotSupportedException("InflaterInputStream SetLength not supported");
}
/// <summary>
/// Writes a sequence of bytes to stream and advances the current position
/// This method always throws a NotSupportedException
/// </summary>
/// <param name="buffer">Thew buffer containing data to write.</param>
/// <param name="offset">The offset of the first byte to write.</param>
/// <param name="count">The number of bytes to write.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException("InflaterInputStream Write not supported");
}
/// <summary>
/// Writes one byte to the current stream and advances the current position
/// Always throws a NotSupportedException
/// </summary>
/// <param name="value">The byte to write.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void WriteByte(byte value)
{
throw new NotSupportedException("InflaterInputStream WriteByte not supported");
}
/// <summary>
/// Entry point to begin an asynchronous write. Always throws a NotSupportedException.
/// </summary>
/// <param name="buffer">The buffer to write data from</param>
/// <param name="offset">Offset of first byte to write</param>
/// <param name="count">The maximum number of bytes to write</param>
/// <param name="callback">The method to be called when the asynchronous write operation is completed</param>
/// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests</param>
/// <returns>An <see cref="System.IAsyncResult">IAsyncResult</see> that references the asynchronous write</returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException("InflaterInputStream BeginWrite not supported");
}
/// <summary>
/// Closes the input stream. When <see cref="IsStreamOwner"></see>
/// is true the underlying stream is also closed.
/// </summary>
public override void Close()
{
if ( !isClosed ) {
isClosed = true;
if ( isStreamOwner ) {
baseInputStream.Close();
}
}
}
/// <summary>
/// Reads decompressed data into the provided buffer byte array
/// </summary>
/// <param name ="buffer">
/// The array to read and decompress data into
/// </param>
/// <param name ="offset">
/// The offset indicating where the data should be placed
/// </param>
/// <param name ="count">
/// The number of bytes to decompress
/// </param>
/// <returns>The number of bytes read. Zero signals the end of stream</returns>
/// <exception cref="SharpZipBaseException">
/// Inflater needs a dictionary
/// </exception>
public override int Read(byte[] buffer, int offset, int count)
{
if (inf.IsNeedingDictionary)
{
throw new SharpZipBaseException("Need a dictionary");
}
int remainingBytes = count;
while (true) {
int bytesRead = inf.Inflate(buffer, offset, remainingBytes);
offset += bytesRead;
remainingBytes -= bytesRead;
if (remainingBytes == 0 || inf.IsFinished) {
break;
}
if ( inf.IsNeedingInput ) {
Fill();
}
else if ( bytesRead == 0 ) {
throw new ZipException("Dont know what to do");
}
}
return count - remainingBytes;
}
#endregion
#region Instance Fields
/// <summary>
/// Decompressor for this stream
/// </summary>
protected Inflater inf;
/// <summary>
/// <see cref="InflaterInputBuffer">Input buffer</see> for this stream.
/// </summary>
protected InflaterInputBuffer inputBuffer;
/// <summary>
/// Base stream the inflater reads from.
/// </summary>
private Stream baseInputStream;
/// <summary>
/// The compressed size
/// </summary>
protected long csize;
/// <summary>
/// Flag indicating wether this instance has been closed or not.
/// </summary>
bool isClosed;
/// <summary>
/// Flag indicating wether this instance is designated the stream owner.
/// When closing if this flag is true the underlying stream is closed.
/// </summary>
bool isStreamOwner = true;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
namespace Umbraco.Core.Services
{
/// <summary>
/// Defines the ContentTypeService, which is an easy access to operations involving <see cref="IContentType"/>
/// </summary>
public interface IContentTypeService : IService
{
int CountContentTypes();
int CountMediaTypes();
/// <summary>
/// Validates the composition, if its invalid a list of property type aliases that were duplicated is returned
/// </summary>
/// <param name="compo"></param>
/// <returns></returns>
Attempt<string[]> ValidateComposition(IContentTypeComposition compo);
Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateContentTypeContainer(int parentId, string name, int userId = 0);
Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateMediaTypeContainer(int parentId, string name, int userId = 0);
Attempt<OperationStatus> SaveContentTypeContainer(EntityContainer container, int userId = 0);
Attempt<OperationStatus> SaveMediaTypeContainer(EntityContainer container, int userId = 0);
EntityContainer GetContentTypeContainer(int containerId);
EntityContainer GetContentTypeContainer(Guid containerId);
IEnumerable<EntityContainer> GetContentTypeContainers(int[] containerIds);
IEnumerable<EntityContainer> GetContentTypeContainers(IContentType contentType);
IEnumerable<EntityContainer> GetContentTypeContainers(string folderName, int level);
EntityContainer GetMediaTypeContainer(int containerId);
EntityContainer GetMediaTypeContainer(Guid containerId);
IEnumerable<EntityContainer> GetMediaTypeContainers(int[] containerIds);
IEnumerable<EntityContainer> GetMediaTypeContainers(string folderName, int level);
IEnumerable<EntityContainer> GetMediaTypeContainers(IMediaType mediaType);
Attempt<OperationStatus> DeleteMediaTypeContainer(int folderId, int userId = 0);
Attempt<OperationStatus> DeleteContentTypeContainer(int containerId, int userId = 0);
/// <summary>
/// Gets all property type aliases.
/// </summary>
/// <returns></returns>
IEnumerable<string> GetAllPropertyTypeAliases();
/// <summary>
/// Gets all content type aliases
/// </summary>
/// <param name="objectTypes">
/// If this list is empty, it will return all content type aliases for media, members and content, otherwise
/// it will only return content type aliases for the object types specified
/// </param>
/// <returns></returns>
IEnumerable<string> GetAllContentTypeAliases(params Guid[] objectTypes);
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parentId">
/// The parent to copy the content type to, default is -1 (root)
/// </param>
/// <returns></returns>
IContentType Copy(IContentType original, string alias, string name, int parentId = -1);
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parent">
/// The parent to copy the content type to
/// </param>
/// <returns></returns>
IContentType Copy(IContentType original, string alias, string name, IContentType parent);
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
IContentType GetContentType(int id);
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
IContentType GetContentType(string alias);
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Key
/// </summary>
/// <param name="id">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
IContentType GetContentType(Guid id);
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
IEnumerable<IContentType> GetAllContentTypes(params int[] ids);
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
IEnumerable<IContentType> GetAllContentTypes(IEnumerable<Guid> ids);
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
IEnumerable<IContentType> GetContentTypeChildren(int id);
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
IEnumerable<IContentType> GetContentTypeChildren(Guid id);
/// <summary>
/// Saves a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to save</param>
/// <param name="userId">Optional Id of the User saving the ContentType</param>
void Save(IContentType contentType, int userId = 0);
/// <summary>
/// Saves a collection of <see cref="IContentType"/> objects
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to save</param>
/// <param name="userId">Optional Id of the User saving the ContentTypes</param>
void Save(IEnumerable<IContentType> contentTypes, int userId = 0);
/// <summary>
/// Deletes a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to delete</param>
/// <remarks>Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/></remarks>
/// <param name="userId">Optional Id of the User deleting the ContentType</param>
void Delete(IContentType contentType, int userId = 0);
/// <summary>
/// Deletes a collection of <see cref="IContentType"/> objects
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to delete</param>
/// <remarks>Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/></remarks>
/// <param name="userId">Optional Id of the User deleting the ContentTypes</param>
void Delete(IEnumerable<IContentType> contentTypes, int userId = 0);
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
IMediaType GetMediaType(int id);
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
IMediaType GetMediaType(string alias);
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
IMediaType GetMediaType(Guid id);
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
IEnumerable<IMediaType> GetAllMediaTypes(params int[] ids);
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
IEnumerable<IMediaType> GetAllMediaTypes(IEnumerable<Guid> ids);
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
IEnumerable<IMediaType> GetMediaTypeChildren(int id);
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
IEnumerable<IMediaType> GetMediaTypeChildren(Guid id);
/// <summary>
/// Saves a single <see cref="IMediaType"/> object
/// </summary>
/// <param name="mediaType"><see cref="IMediaType"/> to save</param>
/// <param name="userId">Optional Id of the User saving the MediaType</param>
void Save(IMediaType mediaType, int userId = 0);
/// <summary>
/// Saves a collection of <see cref="IMediaType"/> objects
/// </summary>
/// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to save</param>
/// <param name="userId">Optional Id of the User saving the MediaTypes</param>
void Save(IEnumerable<IMediaType> mediaTypes, int userId = 0);
/// <summary>
/// Deletes a single <see cref="IMediaType"/> object
/// </summary>
/// <param name="mediaType"><see cref="IMediaType"/> to delete</param>
/// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks>
/// <param name="userId">Optional Id of the User deleting the MediaType</param>
void Delete(IMediaType mediaType, int userId = 0);
/// <summary>
/// Deletes a collection of <see cref="IMediaType"/> objects
/// </summary>
/// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to delete</param>
/// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks>
/// <param name="userId">Optional Id of the User deleting the MediaTypes</param>
void Delete(IEnumerable<IMediaType> mediaTypes, int userId = 0);
/// <summary>
/// Generates the complete (simplified) XML DTD.
/// </summary>
/// <returns>The DTD as a string</returns>
string GetDtd();
/// <summary>
/// Generates the complete XML DTD without the root.
/// </summary>
/// <returns>The DTD as a string</returns>
string GetContentTypesDtd();
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
bool HasChildren(int id);
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
bool HasChildren(Guid id);
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
bool MediaTypeHasChildren(int id);
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
bool MediaTypeHasChildren(Guid id);
Attempt<OperationStatus<MoveOperationStatusType>> MoveMediaType(IMediaType toMove, int containerId);
Attempt<OperationStatus<MoveOperationStatusType>> MoveContentType(IContentType toMove, int containerId);
Attempt<OperationStatus<IMediaType, MoveOperationStatusType>> CopyMediaType(IMediaType toCopy, int containerId);
Attempt<OperationStatus<IContentType, MoveOperationStatusType>> CopyContentType(IContentType toCopy, int containerId);
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryLessThanTests
{
#region Test methods
[Fact]
public static void CheckByteLessThanTest()
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyByteLessThan(array[i], array[j]);
}
}
}
[Fact]
public static void CheckCharLessThanTest()
{
char[] array = new char[] { '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyCharLessThan(array[i], array[j]);
}
}
}
[Fact]
public static void CheckDecimalLessThanTest()
{
decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDecimalLessThan(array[i], array[j]);
}
}
}
[Fact]
public static void CheckDoubleLessThanTest()
{
double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDoubleLessThan(array[i], array[j]);
}
}
}
[Fact]
public static void CheckFloatLessThanTest()
{
float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyFloatLessThan(array[i], array[j]);
}
}
}
[Fact]
public static void CheckIntLessThanTest()
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyIntLessThan(array[i], array[j]);
}
}
}
[Fact]
public static void CheckLongLessThanTest()
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongLessThan(array[i], array[j]);
}
}
}
[Fact]
public static void CheckSByteLessThanTest()
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifySByteLessThan(array[i], array[j]);
}
}
}
[Fact]
public static void CheckShortLessThanTest()
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyShortLessThan(array[i], array[j]);
}
}
}
[Fact]
public static void CheckUIntLessThanTest()
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUIntLessThan(array[i], array[j]);
}
}
}
[Fact]
public static void CheckULongLessThanTest()
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyULongLessThan(array[i], array[j]);
}
}
}
[Fact]
public static void CheckUShortLessThanTest()
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUShortLessThan(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyByteLessThan(byte a, byte b)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(byte))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
// compute with expression tree
bool etResult = default(bool);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool csResult = default(bool);
Exception csException = null;
try
{
csResult = (bool)(a < b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyCharLessThan(char a, char b)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(char)),
Expression.Constant(b, typeof(char))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
// compute with expression tree
bool etResult = default(bool);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool csResult = default(bool);
Exception csException = null;
try
{
csResult = (bool)(a < b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyDecimalLessThan(decimal a, decimal b)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
// compute with expression tree
bool etResult = default(bool);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool csResult = default(bool);
Exception csException = null;
try
{
csResult = (bool)(a < b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyDoubleLessThan(double a, double b)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
// compute with expression tree
bool etResult = default(bool);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool csResult = default(bool);
Exception csException = null;
try
{
csResult = (bool)(a < b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyFloatLessThan(float a, float b)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
// compute with expression tree
bool etResult = default(bool);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool csResult = default(bool);
Exception csException = null;
try
{
csResult = (bool)(a < b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyIntLessThan(int a, int b)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
// compute with expression tree
bool etResult = default(bool);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool csResult = default(bool);
Exception csException = null;
try
{
csResult = (bool)(a < b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyLongLessThan(long a, long b)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
// compute with expression tree
bool etResult = default(bool);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool csResult = default(bool);
Exception csException = null;
try
{
csResult = (bool)(a < b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifySByteLessThan(sbyte a, sbyte b)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(sbyte))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
// compute with expression tree
bool etResult = default(bool);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool csResult = default(bool);
Exception csException = null;
try
{
csResult = (bool)(a < b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyShortLessThan(short a, short b)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
// compute with expression tree
bool etResult = default(bool);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool csResult = default(bool);
Exception csException = null;
try
{
csResult = (bool)(a < b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyUIntLessThan(uint a, uint b)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
// compute with expression tree
bool etResult = default(bool);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool csResult = default(bool);
Exception csException = null;
try
{
csResult = (bool)(a < b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyULongLessThan(ulong a, ulong b)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
// compute with expression tree
bool etResult = default(bool);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool csResult = default(bool);
Exception csException = null;
try
{
csResult = (bool)(a < b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyUShortLessThan(ushort a, ushort b)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
// compute with expression tree
bool etResult = default(bool);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool csResult = default(bool);
Exception csException = null;
try
{
csResult = (bool)(a < b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
#endregion
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.LessThan(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void ThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.LessThan(null, Expression.Constant(0)));
}
[Fact]
public static void ThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.LessThan(Expression.Constant(0), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.LessThan(value, Expression.Constant(1)));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.LessThan(Expression.Constant(1), value));
}
}
}
| |
/// <summary>
/// Copyright 2013 The Loon Authors
/// 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.
/// </summary>
///
using Loon.Core.Geom;
using Loon.Utils;
namespace Loon.Physics {
public class PHingeJoint : PJoint {
private Vector2f anchor1;
private Vector2f anchor2;
private float angI;
private float angM;
private PBody b1;
private PBody b2;
private bool enableLimit;
private bool enableMotor;
private Vector2f impulse;
private float limI;
private int limitState;
private Vector2f localAnchor1;
private Vector2f localAnchor2;
private float localAngle;
private PTransformer mass;
private float maxAngle;
private float minAngle;
private float motI;
private float motorSpeed;
private float motorTorque;
private Vector2f relAnchor1;
private Vector2f relAnchor2;
private float rest;
private float targetAngleSpeed;
public PHingeJoint(PBody b1_0, PBody b2_1, float rel1x, float rel1y,
float rel2x, float rel2y) {
this.b1 = b1_0;
this.b2 = b2_1;
localAngle = b2_1.ang - b1_0.ang;
localAnchor1 = new Vector2f(rel1x, rel1y);
localAnchor2 = new Vector2f(rel2x, rel2y);
b1_0.mAng.Transpose().MulEqual(localAnchor1);
b2_1.mAng.Transpose().MulEqual(localAnchor2);
anchor1 = b1_0.mAng.Mul(localAnchor1);
anchor1.AddLocal(b1_0.pos);
anchor2 = b2_1.mAng.Mul(localAnchor2);
anchor2.AddLocal(b2_1.pos);
type = Physics.PJointType.HINGE_JOINT;
mass = new PTransformer();
impulse = new Vector2f();
}
public Vector2f GetAnchorPoint1() {
return anchor1.Clone();
}
public Vector2f GetAnchorPoint2() {
return anchor2.Clone();
}
public PBody GetBody1() {
return b1;
}
public PBody GetBody2() {
return b2;
}
public float GetLimitRestitution(float restitution) {
return rest;
}
public float GetMaxAngle() {
return maxAngle;
}
public float GetMinAngle() {
return minAngle;
}
public float GetMotorSpeed() {
return motorSpeed;
}
public float GetMotorTorque() {
return motorTorque;
}
public Vector2f GetRelativeAnchorPoint1() {
return relAnchor1.Clone();
}
public Vector2f GetRelativeAnchorPoint2() {
return relAnchor2.Clone();
}
public bool IsEnableLimit() {
return enableLimit;
}
public bool IsEnableMotor() {
return enableMotor;
}
internal override void PreSolve(float dt) {
relAnchor1 = b1.mAng.Mul(localAnchor1);
relAnchor2 = b2.mAng.Mul(localAnchor2);
anchor1.Set(relAnchor1.x + b1.pos.x, relAnchor1.y + b1.pos.y);
anchor2.Set(relAnchor2.x + b2.pos.x, relAnchor2.y + b2.pos.y);
mass = PTransformer.CalcEffectiveMass(b1, b2, relAnchor1, relAnchor2);
angM = 1.0F / (b1.invI + b2.invI);
float ang = b2.ang - b1.ang - localAngle;
if (!enableMotor) {
motI = 0.0F;
}
if (enableLimit) {
if (ang < minAngle) {
if (limitState != -1) {
limI = 0.0F;
}
limitState = -1;
if (b2.angVel - b1.angVel < 0.0F) {
targetAngleSpeed = (b2.angVel - b1.angVel) * -rest;
} else {
targetAngleSpeed = 0.0F;
}
} else if (ang > maxAngle) {
if (limitState != 1) {
limI = 0.0F;
}
limitState = 1;
if (b2.angVel - b1.angVel > 0.0F) {
targetAngleSpeed = (b2.angVel - b1.angVel) * -rest;
} else {
targetAngleSpeed = 0.0F;
}
} else {
limI = limitState = 0;
}
} else {
limI = limitState = 0;
}
angI = 0.0F;
b1.ApplyImpulse(impulse.x, impulse.y, anchor1.x, anchor1.y);
b2.ApplyImpulse(-impulse.x, -impulse.y, anchor2.x, anchor2.y);
b1.ApplyTorque(motI + limI);
b2.ApplyTorque(-motI - limI);
}
public void SetEnableLimit(bool enable) {
enableLimit = enable;
}
public void SetEnableMotor(bool enable) {
enableMotor = enable;
}
public void SetLimitAngle(float minAngle_0, float maxAngle_1) {
this.minAngle = minAngle_0;
this.maxAngle = maxAngle_1;
}
public void SetLimitRestitution(float restitution) {
rest = restitution;
}
public void SetMaxAngle(float maxAngle_0) {
this.maxAngle = maxAngle_0;
}
public void SetMinAngle(float minAngle_0) {
this.minAngle = minAngle_0;
}
public void SetMotor(float speed, float torque) {
motorSpeed = speed;
motorTorque = torque;
}
public void SetMotorSpeed(float speed) {
motorSpeed = speed;
}
public void SetMotorTorque(float torque) {
motorTorque = torque;
}
public void SetRelativeAnchorPoint1(float relx, float rely) {
localAnchor1.Set(relx, rely);
b1.mAng.Transpose().MulEqual(localAnchor1);
}
public void SetRelativeAnchorPoint2(float relx, float rely) {
localAnchor2.Set(relx, rely);
b2.mAng.Transpose().MulEqual(localAnchor2);
}
internal override void SolvePosition() {
if (enableLimit && limitState != 0) {
float over = b2.ang - b1.ang - localAngle;
if (over < minAngle) {
over += 0.008F;
over = ((over - minAngle) + b2.correctAngVel)
- b1.correctAngVel;
float torque = over * 0.2F * angM;
float subAngleImpulse = angI;
angI = MathUtils.Min(angI + torque, 0.0F);
torque = angI - subAngleImpulse;
b1.PositionCorrection(torque);
b2.PositionCorrection(-torque);
}
if (over > maxAngle) {
over -= 0.008F;
over = ((over - maxAngle) + b2.correctAngVel)
- b1.correctAngVel;
float torque_0 = over * 0.2F * angM;
float subAngleImpulse_1 = angI;
angI = MathUtils.Max(angI + torque_0, 0.0F);
torque_0 = angI - subAngleImpulse_1;
b1.PositionCorrection(torque_0);
b2.PositionCorrection(-torque_0);
}
}
Vector2f force = anchor2.Sub(anchor1);
force.SubLocal(PTransformer.CalcRelativeCorrectVelocity(b1, b2,
relAnchor1, relAnchor2));
float length = force.Length();
force.Normalize();
force.MulLocal(System.Math.Max(length * 0.2F - 0.002F,0.0F));
mass.MulEqual(force);
b1.PositionCorrection(force.x, force.y, anchor1.x, anchor1.y);
b2.PositionCorrection(-force.x, -force.y, anchor2.x, anchor2.y);
}
internal override void SolveVelocity(float dt) {
Vector2f relVel = PTransformer.CalcRelativeVelocity(b1, b2, relAnchor1,
relAnchor2);
Vector2f force = mass.Mul(relVel).Negate();
impulse.AddLocal(force);
b1.ApplyImpulse(force.x, force.y, anchor1.x, anchor1.y);
b2.ApplyImpulse(-force.x, -force.y, anchor2.x, anchor2.y);
if (enableMotor) {
float angRelVel = b2.angVel - b1.angVel - motorSpeed;
float torque = angM * angRelVel;
float subMotorI = motI;
motI = MathUtils.Clamp(motI + torque, -motorTorque * dt,
motorTorque * dt);
torque = motI - subMotorI;
b1.ApplyTorque(torque);
b2.ApplyTorque(-torque);
}
if (enableLimit && limitState != 0) {
float angRelVel_0 = b2.angVel - b1.angVel - targetAngleSpeed;
float torque_1 = angM * angRelVel_0;
float subLimitI = limI;
if (limitState == -1) {
limI = MathUtils.Min(limI + torque_1, 0.0F);
} else {
if (limitState == 1) {
limI = MathUtils.Max(limI + torque_1, 0.0F);
}
}
torque_1 = limI - subLimitI;
b1.ApplyTorque(torque_1);
b2.ApplyTorque(-torque_1);
}
}
internal override void Update() {
relAnchor1 = b1.mAng.Mul(localAnchor1);
relAnchor2 = b2.mAng.Mul(localAnchor2);
anchor1.Set(relAnchor1.x + b1.pos.x, relAnchor1.y + b1.pos.y);
anchor2.Set(relAnchor2.x + b2.pos.x, relAnchor2.y + b2.pos.y);
if (b1.rem || b2.rem || b1.fix && b2.fix) {
rem = true;
}
}
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace System.ComponentModel.DataAnnotations
{
/// <summary>
/// Attribute to provide a hint to the presentation layer about what control it should use
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
public class UIHintAttribute : Attribute
{
private readonly UIHintImplementation _implementation;
/// <summary>
/// Constructor that accepts the name of the control, without specifying which presentation layer to use
/// </summary>
/// <param name="uiHint">The name of the UI control.</param>
public UIHintAttribute(string uiHint)
: this(uiHint, null, Array.Empty<object>())
{
}
/// <summary>
/// Constructor that accepts both the name of the control as well as the presentation layer
/// </summary>
/// <param name="uiHint">The name of the control to use</param>
/// <param name="presentationLayer">The name of the presentation layer that supports this control</param>
public UIHintAttribute(string uiHint, string presentationLayer)
: this(uiHint, presentationLayer, Array.Empty<object>())
{
}
/// <summary>
/// Full constructor that accepts the name of the control, presentation layer, and optional parameters
/// to use when constructing the control
/// </summary>
/// <param name="uiHint">The name of the control</param>
/// <param name="presentationLayer">The presentation layer</param>
/// <param name="controlParameters">The list of parameters for the control</param>
public UIHintAttribute(string uiHint, string presentationLayer, params object[] controlParameters)
{
_implementation = new UIHintImplementation(uiHint, presentationLayer, controlParameters);
}
/// <summary>
/// Gets the name of the control that is most appropriate for this associated property or field
/// </summary>
public string UIHint => _implementation.UIHint;
/// <summary>
/// Gets the name of the presentation layer that supports the control type in <see cref="UIHint" />
/// </summary>
public string PresentationLayer => _implementation.PresentationLayer;
/// <summary>
/// Gets the name-value pairs used as parameters to the control's constructor
/// </summary>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is ill-formed.</exception>
public IDictionary<string, object> ControlParameters => _implementation.ControlParameters;
public override int GetHashCode() => _implementation.GetHashCode();
public override bool Equals(object obj) =>
obj is UIHintAttribute otherAttribute && _implementation.Equals(otherAttribute._implementation);
internal class UIHintImplementation
{
private readonly object[] _inputControlParameters;
private IDictionary<string, object> _controlParameters;
public UIHintImplementation(string uiHint, string presentationLayer, params object[] controlParameters)
{
UIHint = uiHint;
PresentationLayer = presentationLayer;
if (controlParameters != null)
{
_inputControlParameters = new object[controlParameters.Length];
Array.Copy(controlParameters, 0, _inputControlParameters, 0, controlParameters.Length);
}
}
/// <summary>
/// Gets the name of the control that is most appropriate for this associated property or field
/// </summary>
public string UIHint { get; }
/// <summary>
/// Gets the name of the presentation layer that supports the control type in <see cref="UIHint" />
/// </summary>
public string PresentationLayer { get; }
// Lazy load the dictionary. It's fine if this method executes multiple times in stress scenarios.
// If the method throws (indicating that the input params are invalid) this property will throw
// every time it's accessed.
public IDictionary<string, object> ControlParameters =>
_controlParameters ?? (_controlParameters = BuildControlParametersDictionary());
/// <summary>
/// Returns the hash code for this UIHintAttribute.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
var a = UIHint ?? string.Empty;
var b = PresentationLayer ?? string.Empty;
return a.GetHashCode() ^ b.GetHashCode();
}
/// <summary>
/// Determines whether this instance of UIHintAttribute and a specified object,
/// which must also be a UIHintAttribute object, have the same value.
/// </summary>
/// <param name="obj">An System.Object.</param>
/// <returns>true if obj is a UIHintAttribute and its value is the same as this instance; otherwise, false.</returns>
public override bool Equals(object obj)
{
// don't need to perform a type check on obj since this is an internal class
var otherImplementation = (UIHintImplementation)obj;
if (UIHint != otherImplementation.UIHint || PresentationLayer != otherImplementation.PresentationLayer)
{
return false;
}
IDictionary<string, object> leftParams;
IDictionary<string, object> rightParams;
try
{
leftParams = ControlParameters;
rightParams = otherImplementation.ControlParameters;
}
catch (InvalidOperationException)
{
return false;
}
Debug.Assert(leftParams != null, "leftParams shouldn't be null");
Debug.Assert(rightParams != null, "rightParams shouldn't be null");
if (leftParams.Count != rightParams.Count)
{
return false;
}
return leftParams.OrderBy(p => p.Key).SequenceEqual(rightParams.OrderBy(p => p.Key));
}
/// <summary>
/// Validates the input control parameters and throws InvalidOperationException if they are not correct.
/// </summary>
/// <returns>
/// Dictionary of control parameters.
/// </returns>
private IDictionary<string, object> BuildControlParametersDictionary()
{
IDictionary<string, object> controlParameters = new Dictionary<string, object>();
object[] inputControlParameters = _inputControlParameters;
if (inputControlParameters == null || inputControlParameters.Length == 0)
{
return controlParameters;
}
if (inputControlParameters.Length % 2 != 0)
{
throw new InvalidOperationException(SR.UIHintImplementation_NeedEvenNumberOfControlParameters);
}
for (int i = 0; i < inputControlParameters.Length; i += 2)
{
object key = inputControlParameters[i];
object value = inputControlParameters[i + 1];
if (key == null)
{
throw new InvalidOperationException(SR.Format(SR.UIHintImplementation_ControlParameterKeyIsNull, i));
}
if (!(key is string keyString))
{
throw new InvalidOperationException(SR.Format(SR.UIHintImplementation_ControlParameterKeyIsNotAString,
i,
inputControlParameters[i].ToString()));
}
if (controlParameters.ContainsKey(keyString))
{
throw new InvalidOperationException(SR.Format(SR.UIHintImplementation_ControlParameterKeyOccursMoreThanOnce,
i,
keyString));
}
controlParameters[keyString] = value;
}
return controlParameters;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using DotNetOpenId;
using DotNetOpenId.Provider;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web;
namespace OpenSim.Server.Handlers.Authentication
{
/// <summary>
/// Temporary, in-memory store for OpenID associations
/// </summary>
public class ProviderMemoryStore : IAssociationStore<AssociationRelyingPartyType>
{
private class AssociationItem
{
public AssociationRelyingPartyType DistinguishingFactor;
public string Handle;
public DateTime Expires;
public byte[] PrivateData;
}
Dictionary<string, AssociationItem> m_store = new Dictionary<string, AssociationItem>();
SortedList<DateTime, AssociationItem> m_sortedStore = new SortedList<DateTime, AssociationItem>();
object m_syncRoot = new object();
#region IAssociationStore<AssociationRelyingPartyType> Members
public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc)
{
AssociationItem item = new AssociationItem();
item.DistinguishingFactor = distinguishingFactor;
item.Handle = assoc.Handle;
item.Expires = assoc.Expires.ToLocalTime();
item.PrivateData = assoc.SerializePrivateData();
lock (m_syncRoot)
{
m_store[item.Handle] = item;
m_sortedStore[item.Expires] = item;
}
}
public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor)
{
lock (m_syncRoot)
{
if (m_sortedStore.Count > 0)
{
AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1];
return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
}
else
{
return null;
}
}
}
public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
{
AssociationItem item;
bool success = false;
lock (m_syncRoot)
success = m_store.TryGetValue(handle, out item);
if (success)
return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
else
return null;
}
public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
{
lock (m_syncRoot)
{
for (int i = 0; i < m_sortedStore.Values.Count; i++)
{
AssociationItem item = m_sortedStore.Values[i];
if (item.Handle == handle)
{
m_sortedStore.RemoveAt(i);
break;
}
}
return m_store.Remove(handle);
}
}
public void ClearExpiredAssociations()
{
lock (m_syncRoot)
{
List<AssociationItem> itemsCopy = new List<AssociationItem>(m_sortedStore.Values);
DateTime now = DateTime.Now;
for (int i = 0; i < itemsCopy.Count; i++)
{
AssociationItem item = itemsCopy[i];
if (item.Expires <= now)
{
m_sortedStore.RemoveAt(i);
m_store.Remove(item.Handle);
}
}
}
}
#endregion
}
public class OpenIdStreamHandler : BaseOutputStreamHandler, IStreamHandler
{
#region HTML
/// <summary>Login form used to authenticate OpenID requests</summary>
const string LOGIN_PAGE =
@"<html>
<head><title>OpenSim OpenID Login</title></head>
<body>
<h3>OpenSim Login</h3>
<form method=""post"">
<label for=""first"">First Name:</label> <input readonly type=""text"" name=""first"" id=""first"" value=""{0}""/>
<label for=""last"">Last Name:</label> <input readonly type=""text"" name=""last"" id=""last"" value=""{1}""/>
<label for=""pass"">Password:</label> <input type=""password"" name=""pass"" id=""pass""/>
<input type=""submit"" value=""Login"">
</form>
</body>
</html>";
/// <summary>Page shown for a valid OpenID identity</summary>
const string OPENID_PAGE =
@"<html>
<head>
<title>{2} {3}</title>
<link rel=""openid2.provider openid.server"" href=""{0}://{1}/openid/server/""/>
</head>
<body>OpenID identifier for {2} {3}</body>
</html>
";
/// <summary>Page shown for an invalid OpenID identity</summary>
const string INVALID_OPENID_PAGE =
@"<html><head><title>Identity not found</title></head>
<body>Invalid OpenID identity</body></html>";
/// <summary>Page shown if the OpenID endpoint is requested directly</summary>
const string ENDPOINT_PAGE =
@"<html><head><title>OpenID Endpoint</title></head><body>
This is an OpenID server endpoint, not a human-readable resource.
For more information, see <a href='http://openid.net/'>http://openid.net/</a>.
</body></html>";
#endregion HTML
IAuthenticationService m_authenticationService;
IUserAccountService m_userAccountService;
ProviderMemoryStore m_openidStore = new ProviderMemoryStore();
public override string ContentType { get { return "text/html"; } }
/// <summary>
/// Constructor
/// </summary>
public OpenIdStreamHandler(
string httpMethod, string path, IUserAccountService userService, IAuthenticationService authService)
: base(httpMethod, path, "OpenId", "OpenID stream handler")
{
m_authenticationService = authService;
m_userAccountService = userService;
}
/// <summary>
/// Handles all GET and POST requests for OpenID identifier pages and endpoint
/// server communication
/// </summary>
protected override void ProcessRequest(
string path, Stream request, Stream response, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath));
// Defult to returning HTML content
httpResponse.ContentType = ContentType;
try
{
NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd());
NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query);
NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery);
OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery);
if (provider.Request != null)
{
if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest)
{
IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request;
string[] passwordValues = postQuery.GetValues("pass");
UserAccount account;
if (TryGetAccount(new Uri(authRequest.ClaimedIdentifier.ToString()), out account))
{
// Check for form POST data
if (passwordValues != null && passwordValues.Length == 1)
{
if (account != null &&
(m_authenticationService.Authenticate(account.PrincipalID,Util.Md5Hash(passwordValues[0]), 30) != string.Empty))
authRequest.IsAuthenticated = true;
else
authRequest.IsAuthenticated = false;
}
else
{
// Authentication was requested, send the client a login form
using (StreamWriter writer = new StreamWriter(response))
writer.Write(String.Format(LOGIN_PAGE, account.FirstName, account.LastName));
return;
}
}
else
{
// Cannot find an avatar matching the claimed identifier
authRequest.IsAuthenticated = false;
}
}
// Add OpenID headers to the response
foreach (string key in provider.Request.Response.Headers.Keys)
httpResponse.AddHeader(key, provider.Request.Response.Headers[key]);
string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type");
if (contentTypeValues != null && contentTypeValues.Length == 1)
httpResponse.ContentType = contentTypeValues[0];
// Set the response code and document body based on the OpenID result
httpResponse.StatusCode = (int)provider.Request.Response.Code;
response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length);
response.Close();
}
else if (httpRequest.Url.AbsolutePath.Contains("/openid/server"))
{
// Standard HTTP GET was made on the OpenID endpoint, send the client the default error page
using (StreamWriter writer = new StreamWriter(response))
writer.Write(ENDPOINT_PAGE);
}
else
{
// Try and lookup this avatar
UserAccount account;
if (TryGetAccount(httpRequest.Url, out account))
{
using (StreamWriter writer = new StreamWriter(response))
{
// TODO: Print out a full profile page for this avatar
writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme,
httpRequest.Url.Authority, account.FirstName, account.LastName));
}
}
else
{
// Couldn't parse an avatar name, or couldn't find the avatar in the user server
using (StreamWriter writer = new StreamWriter(response))
writer.Write(INVALID_OPENID_PAGE);
}
}
}
catch (Exception ex)
{
httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
using (StreamWriter writer = new StreamWriter(response))
writer.Write(ex.Message);
}
}
/// <summary>
/// Parse a URL with a relative path of the form /users/First_Last and try to
/// retrieve the profile matching that avatar name
/// </summary>
/// <param name="requestUrl">URL to parse for an avatar name</param>
/// <param name="profile">Profile data for the avatar</param>
/// <returns>True if the parse and lookup were successful, otherwise false</returns>
bool TryGetAccount(Uri requestUrl, out UserAccount account)
{
if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/")
{
// Parse the avatar name from the path
string username = requestUrl.Segments[requestUrl.Segments.Length - 1];
string[] name = username.Split('_');
if (name.Length == 2)
{
account = m_userAccountService.GetUserAccount(UUID.Zero, name[0], name[1]);
return (account != null);
}
}
account = null;
return false;
}
}
}
| |
using UnityEngine;
using System.Collections;
[System.Serializable]
public class BendingSegment {
public Transform firstTransform;
public Transform lastTransform;
public float thresholdAngleDifference = 0;
public float bendingMultiplier = 0.6f;
public float maxAngleDifference = 30;
public float maxBendingAngle = 80;
public float responsiveness = 5;
internal float angleH;
internal float angleV;
internal Vector3 dirUp;
internal Vector3 referenceLookDir;
internal Vector3 referenceUpDir;
internal int chainLength;
internal Quaternion[] origRotations;
}
[System.Serializable]
public class NonAffectedJoints {
public Transform joint;
public float effect = 0;
}
public class HeadLookController : MonoBehaviour {
public Transform rootNode;
public BendingSegment[] segments;
public NonAffectedJoints[] nonAffectedJoints;
public Vector3 headLookVector = Vector3.forward;
public Vector3 headUpVector = Vector3.up;
public Vector3 target = Vector3.zero;
public float effect = 1;
public bool overrideAnimation = false;
void Start () {
if (rootNode == null) {
rootNode = transform;
}
// Setup segments
foreach (BendingSegment segment in segments) {
Quaternion parentRot = segment.firstTransform.parent.rotation;
Quaternion parentRotInv = Quaternion.Inverse(parentRot);
segment.referenceLookDir =
parentRotInv * rootNode.rotation * headLookVector.normalized;
segment.referenceUpDir =
parentRotInv * rootNode.rotation * headUpVector.normalized;
segment.angleH = 0;
segment.angleV = 0;
segment.dirUp = segment.referenceUpDir;
segment.chainLength = 1;
Transform t = segment.lastTransform;
while (t != segment.firstTransform && t != t.root) {
segment.chainLength++;
t = t.parent;
}
segment.origRotations = new Quaternion[segment.chainLength];
t = segment.lastTransform;
for (int i=segment.chainLength-1; i>=0; i--) {
segment.origRotations[i] = t.localRotation;
t = t.parent;
}
}
}
void LateUpdate () {
if (Time.deltaTime == 0)
return;
// Remember initial directions of joints that should not be affected
Vector3[] jointDirections = new Vector3[nonAffectedJoints.Length];
for (int i=0; i<nonAffectedJoints.Length; i++) {
foreach (Transform child in nonAffectedJoints[i].joint) {
jointDirections[i] = child.position - nonAffectedJoints[i].joint.position;
break;
}
}
// Handle each segment
foreach (BendingSegment segment in segments) {
Transform t = segment.lastTransform;
if (overrideAnimation) {
for (int i=segment.chainLength-1; i>=0; i--) {
t.localRotation = segment.origRotations[i];
t = t.parent;
}
}
Quaternion parentRot = segment.firstTransform.parent.rotation;
Quaternion parentRotInv = Quaternion.Inverse(parentRot);
// Desired look direction in world space
Vector3 lookDirWorld = (target - segment.lastTransform.position).normalized;
// Desired look directions in neck parent space
Vector3 lookDirGoal = (parentRotInv * lookDirWorld);
// Get the horizontal and vertical rotation angle to look at the target
float hAngle = AngleAroundAxis(
segment.referenceLookDir, lookDirGoal, segment.referenceUpDir
);
Vector3 rightOfTarget = Vector3.Cross(segment.referenceUpDir, lookDirGoal);
Vector3 lookDirGoalinHPlane =
lookDirGoal - Vector3.Project(lookDirGoal, segment.referenceUpDir);
float vAngle = AngleAroundAxis(
lookDirGoalinHPlane, lookDirGoal, rightOfTarget
);
// Handle threshold angle difference, bending multiplier,
// and max angle difference here
float hAngleThr = Mathf.Max(
0, Mathf.Abs(hAngle) - segment.thresholdAngleDifference
) * Mathf.Sign(hAngle);
float vAngleThr = Mathf.Max(
0, Mathf.Abs(vAngle) - segment.thresholdAngleDifference
) * Mathf.Sign(vAngle);
hAngle = Mathf.Max(
Mathf.Abs(hAngleThr) * Mathf.Abs(segment.bendingMultiplier),
Mathf.Abs(hAngle) - segment.maxAngleDifference
) * Mathf.Sign(hAngle) * Mathf.Sign(segment.bendingMultiplier);
vAngle = Mathf.Max(
Mathf.Abs(vAngleThr) * Mathf.Abs(segment.bendingMultiplier),
Mathf.Abs(vAngle) - segment.maxAngleDifference
) * Mathf.Sign(vAngle) * Mathf.Sign(segment.bendingMultiplier);
// Handle max bending angle here
hAngle = Mathf.Clamp(hAngle, -segment.maxBendingAngle, segment.maxBendingAngle);
vAngle = Mathf.Clamp(vAngle, -segment.maxBendingAngle, segment.maxBendingAngle);
Vector3 referenceRightDir =
Vector3.Cross(segment.referenceUpDir, segment.referenceLookDir);
// Lerp angles
segment.angleH = Mathf.Lerp(
segment.angleH, hAngle, Time.deltaTime * segment.responsiveness
);
segment.angleV = Mathf.Lerp(
segment.angleV, vAngle, Time.deltaTime * segment.responsiveness
);
// Get direction
lookDirGoal = Quaternion.AngleAxis(segment.angleH, segment.referenceUpDir)
* Quaternion.AngleAxis(segment.angleV, referenceRightDir)
* segment.referenceLookDir;
// Make look and up perpendicular
Vector3 upDirGoal = segment.referenceUpDir;
Vector3.OrthoNormalize(ref lookDirGoal, ref upDirGoal);
// Interpolated look and up directions in neck parent space
Vector3 lookDir = lookDirGoal;
segment.dirUp = Vector3.Slerp(segment.dirUp, upDirGoal, Time.deltaTime*5);
Vector3.OrthoNormalize(ref lookDir, ref segment.dirUp);
// Look rotation in world space
Quaternion lookRot = (
(parentRot * Quaternion.LookRotation(lookDir, segment.dirUp))
* Quaternion.Inverse(
parentRot * Quaternion.LookRotation(
segment.referenceLookDir, segment.referenceUpDir
)
)
);
// Distribute rotation over all joints in segment
Quaternion dividedRotation =
Quaternion.Slerp(Quaternion.identity, lookRot, effect / segment.chainLength);
t = segment.lastTransform;
for (int i=0; i<segment.chainLength; i++) {
t.rotation = dividedRotation * t.rotation;
t = t.parent;
}
}
// Handle non affected joints
for (int i=0; i<nonAffectedJoints.Length; i++) {
Vector3 newJointDirection = Vector3.zero;
foreach (Transform child in nonAffectedJoints[i].joint) {
newJointDirection = child.position - nonAffectedJoints[i].joint.position;
break;
}
Vector3 combinedJointDirection = Vector3.Slerp(
jointDirections[i], newJointDirection, nonAffectedJoints[i].effect
);
nonAffectedJoints[i].joint.rotation = Quaternion.FromToRotation(
newJointDirection, combinedJointDirection
) * nonAffectedJoints[i].joint.rotation;
}
}
// The angle between dirA and dirB around axis
public static float AngleAroundAxis (Vector3 dirA, Vector3 dirB, Vector3 axis) {
// Project A and B onto the plane orthogonal target axis
dirA = dirA - Vector3.Project(dirA, axis);
dirB = dirB - Vector3.Project(dirB, axis);
// Find (positive) angle between A and B
float angle = Vector3.Angle(dirA, dirB);
// Return angle multiplied with 1 or -1
return angle * (Vector3.Dot(axis, Vector3.Cross(dirA, dirB)) < 0 ? -1 : 1);
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using IO = System.IO;
namespace WixSharp.Test
{
public class SamplesTest : WixLocator
{
IEnumerable<string> nonMsiProjects = @"CustomAttributes,
External_UI,
Custom_IDs,
ASP.NETApp,
EnvVariables,
WixBootstrapper"
.Split(',').Select(x => x.Trim());
int completedSamples = 0;
int samplesTotal = 0;
Stopwatch testTime = new Stopwatch();
[Fact]
public void CanBuildAllSamples()
{
// if (Environment.GetEnvironmentVariable("APPVEYOR") != null)
// return;
// need to exclude some samples; for example the two samples from the same dir will interfere with each other;
// or some other tests are built as a part of the solution
string[] exclude = new string[] { };
var failedSamples = new List<string>();
int startStep = 0;
int? howManyToRun = null; //null - all
int? whichOneToRun = null; //null - all
int sampleDirIndex = 0;
var files = Directory.GetFiles(@"..\..\..\WixSharp.Samples\Wix# Samples", "build*.cmd", SearchOption.AllDirectories);
var compiled_scripts = Directory.GetFiles(@"..\..\..\WixSharp.Samples\Wix# Samples", "setup*.cs.dll", SearchOption.AllDirectories);
compiled_scripts.ForEach(x => System.IO.File.Delete(x));
files = files.Where(f => !exclude.Any(y => f.EndsWith(y, ignoreCase: true))).ToArray();
files = files.Skip(startStep).ToArray();
if (whichOneToRun.HasValue)
files = new[] { files[whichOneToRun.Value] };
if (howManyToRun.HasValue)
files = files.Take(howManyToRun.Value).ToArray();
samplesTotal = files.Count();
testTime.Reset();
testTime.Start();
var samples = files.GroupBy(x => Path.GetDirectoryName(x));
var allSamples = samples.Select(g => new { Category = g.Key, Items = g, Index = ++sampleDirIndex }).ToArray();
var parallel = false;
#if DEBUG
parallel = true;
ShowLogFileToObserveProgress();
// System.Diagnostics.Process.GetProcessesByName("cmd").ToList().ForEach(x => { try { x.Kill(); } catch { } });
// System.Diagnostics.Process.GetProcessesByName("cscs").ToList().ForEach(x => { try { x.Kill(); } catch { } });
// System.Diagnostics.Process.GetProcessesByName("conhost").ToList().ForEach(x => { try { x.Kill(); } catch { } });
#endif
void processDir(dynamic group)
{
string sampleDir = group.Category;
var sampleFiles = Directory.GetFiles(sampleDir, "build*.cmd")
.Select(x => Path.GetFullPath(x))
.ToArray();
foreach (string batchFile in sampleFiles)
{
BuildSample(batchFile, group.Index, failedSamples);
}
};
if (parallel)
{
// allSamples.ForEach(item =>
// ThreadPool.QueueUserWorkItem(x =>
// processDir(item)));
Parallel.ForEach(allSamples, processDir);
while (completedSamples < samplesTotal)
{
Thread.Sleep(1000);
}
}
else
{
foreach (var item in allSamples)
processDir(item);
}
testTime.Stop();
LogAppend("\r\n--- END ---");
if (failedSamples.Any())
{
string error = " Completed Samples: " + completedSamples + "\r\n Failed Samples:\r\n" + string.Join(Environment.NewLine, failedSamples.ToArray());
Assert.True(false, error);
}
}
void BuildSample(string batchFile, int currentStep, List<string> failedSamples)
{
try
{
var dir = Path.GetDirectoryName(batchFile);
bool nonMsi = nonMsiProjects.Where(x => batchFile.Contains(x)).Any();
if (!nonMsi)
{
DeleteAllMsis(dir);
Assert.False(HasAnyMsis(dir), "Cannot clear directory for the test...");
}
DisablePause(batchFile);
string output = Run(batchFile);
IO.File.WriteAllText(batchFile + ".log",
$"CurrDir: {Environment.CurrentDirectory}{Environment.NewLine}" +
$"Cmd: {batchFile}{Environment.NewLine}" +
$"======================================{Environment.NewLine}" +
$"{output}");
if (batchFile.Contains("InjectXml"))
{
Debug.Assert(false);
}
if (output.Contains(" : error") || output.Contains("Error: ") || (!nonMsi && !HasAnyMsis(dir)))
{
if (batchFile.EndsWith(@"Signing\Build.cmd") && output.Contains("SignTool Error:"))
{
//just ignore as the certificate is just a demo certificate
}
else
lock (failedSamples)
{
failedSamples.Add(currentStep + ":" + batchFile);
}
}
if (!nonMsi)
DeleteAllMsis(dir);
}
catch (Exception e)
{
lock (failedSamples)
{
failedSamples.Add(currentStep + ":" + batchFile + "\t" + e.Message.Replace("\r\n", "\n").Replace("\n", ""));
}
}
finally
{
completedSamples++;
Log(currentStep, failedSamples);
RestorePause(batchFile);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "useful for debugging")]
void Log(int currentStep, List<string> failedSamples)
{
lock (failedSamples)
{
var logFile = @"..\..\..\WixSharp.Samples\test_progress.txt";
var content = string.Format("Failed-{0}; Completed-{1}; Total-{2}; Time-{3}\r\n", failedSamples.Count, completedSamples, samplesTotal, testTime.Elapsed) + string.Join(Environment.NewLine, failedSamples.ToArray());
IO.File.WriteAllText(logFile, content);
}
}
void LogAppend(string text)
{
var logFile = @"..\..\..\WixSharp.Samples\test_progress.txt";
using (var writer = new StreamWriter(logFile, true))
writer.WriteLine(text);
}
void ShowLogFileToObserveProgress()
{
var logFile = @"..\..\..\WixSharp.Samples\test_progress.txt".PathGetFullPath();
if (IO.File.Exists(logFile))
IO.File.WriteAllText(logFile, "The file will be updated as soon as the samples will start being tested.");
try
{
// sublimme is always installed in x64 progfiles, but this process is x86 process so
// envar always returns x86 location fro %PROGRAMFILES%
Process.Start(@"%PROGRAMFILES%\Sublime Text 3\sublime_text.exe".ExpandEnvVars().Replace(" (x86)", ""), $"\"{logFile}\"");
}
catch
{
try
{
Process.Start("notepad++.exe", $"\"{logFile}\"");
}
catch
{
// notepad does not support reloading on changes
// Process.Start("notepad.exe", $"\"{logFile}\"");
}
}
}
void DisablePause(string batchFile)
{
var batchContent = IO.File.ReadAllText(batchFile).Replace("\npause", "\nrem pause");
IO.File.WriteAllText(batchFile, batchContent);
}
void RestorePause(string batchFile)
{
var batchContent = IO.File.ReadAllText(batchFile).Replace("\nrem pause", "\npause");
IO.File.WriteAllText(batchFile, batchContent);
}
bool HasAnyMsis(string dir)
{
return Directory.GetFiles(dir, "*.ms?").Any();
}
void DeleteAllMsis(string dir)
{
foreach (var msiFile in Directory.GetFiles(dir, "*.ms?"))
System.IO.File.Delete(msiFile);
}
string Run(string batchFile)
{
var process = new Process();
process.StartInfo.FileName = batchFile;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WorkingDirectory = IO.Path.GetDirectoryName(batchFile);
process.Start();
return process.StandardOutput.ReadToEnd();
// string line;
// var output = new StringBuilder();
// while (null != (line = process.StandardOutput.ReadLine()))
// {
// output.AppendLine(line);
// }
// process.WaitForExit();
// return output.ToString();
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Analyzer = Lucene.Net.Analysis.Analyzer;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
///
/// <summary>
/// @lucene.experimental
/// </summary>
[TestFixture]
public class TestOmitPositions : LuceneTestCase
{
[Test]
public virtual void TestBasic()
{
Directory dir = NewDirectory();
RandomIndexWriter w = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
Document doc = new Document();
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.IndexOptions = IndexOptions.DOCS_AND_FREQS;
Field f = NewField("foo", "this is a test test", ft);
doc.Add(f);
for (int i = 0; i < 100; i++)
{
w.AddDocument(doc);
}
IndexReader reader = w.GetReader();
w.Dispose();
Assert.IsNull(MultiFields.GetTermPositionsEnum(reader, null, "foo", new BytesRef("test")));
DocsEnum de = TestUtil.Docs(Random, reader, "foo", new BytesRef("test"), null, null, DocsFlags.FREQS);
while (de.NextDoc() != DocIdSetIterator.NO_MORE_DOCS)
{
Assert.AreEqual(2, de.Freq);
}
reader.Dispose();
dir.Dispose();
}
// Tests whether the DocumentWriter correctly enable the
// omitTermFreqAndPositions bit in the FieldInfo
[Test]
public virtual void TestPositions()
{
Directory ram = NewDirectory();
Analyzer analyzer = new MockAnalyzer(Random);
IndexWriter writer = new IndexWriter(ram, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
Document d = new Document();
// f1,f2,f3: docs only
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.IndexOptions = IndexOptions.DOCS_ONLY;
Field f1 = NewField("f1", "this field has docs only", ft);
d.Add(f1);
Field f2 = NewField("f2", "this field has docs only", ft);
d.Add(f2);
Field f3 = NewField("f3", "this field has docs only", ft);
d.Add(f3);
FieldType ft2 = new FieldType(TextField.TYPE_NOT_STORED);
ft2.IndexOptions = IndexOptions.DOCS_AND_FREQS;
// f4,f5,f6 docs and freqs
Field f4 = NewField("f4", "this field has docs and freqs", ft2);
d.Add(f4);
Field f5 = NewField("f5", "this field has docs and freqs", ft2);
d.Add(f5);
Field f6 = NewField("f6", "this field has docs and freqs", ft2);
d.Add(f6);
FieldType ft3 = new FieldType(TextField.TYPE_NOT_STORED);
ft3.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS;
// f7,f8,f9 docs/freqs/positions
Field f7 = NewField("f7", "this field has docs and freqs and positions", ft3);
d.Add(f7);
Field f8 = NewField("f8", "this field has docs and freqs and positions", ft3);
d.Add(f8);
Field f9 = NewField("f9", "this field has docs and freqs and positions", ft3);
d.Add(f9);
writer.AddDocument(d);
writer.ForceMerge(1);
// now we add another document which has docs-only for f1, f4, f7, docs/freqs for f2, f5, f8,
// and docs/freqs/positions for f3, f6, f9
d = new Document();
// f1,f4,f7: docs only
f1 = NewField("f1", "this field has docs only", ft);
d.Add(f1);
f4 = NewField("f4", "this field has docs only", ft);
d.Add(f4);
f7 = NewField("f7", "this field has docs only", ft);
d.Add(f7);
// f2, f5, f8: docs and freqs
f2 = NewField("f2", "this field has docs and freqs", ft2);
d.Add(f2);
f5 = NewField("f5", "this field has docs and freqs", ft2);
d.Add(f5);
f8 = NewField("f8", "this field has docs and freqs", ft2);
d.Add(f8);
// f3, f6, f9: docs and freqs and positions
f3 = NewField("f3", "this field has docs and freqs and positions", ft3);
d.Add(f3);
f6 = NewField("f6", "this field has docs and freqs and positions", ft3);
d.Add(f6);
f9 = NewField("f9", "this field has docs and freqs and positions", ft3);
d.Add(f9);
writer.AddDocument(d);
// force merge
writer.ForceMerge(1);
// flush
writer.Dispose();
SegmentReader reader = GetOnlySegmentReader(DirectoryReader.Open(ram));
FieldInfos fi = reader.FieldInfos;
// docs + docs = docs
Assert.AreEqual(IndexOptions.DOCS_ONLY, fi.FieldInfo("f1").IndexOptions);
// docs + docs/freqs = docs
Assert.AreEqual(IndexOptions.DOCS_ONLY, fi.FieldInfo("f2").IndexOptions);
// docs + docs/freqs/pos = docs
Assert.AreEqual(IndexOptions.DOCS_ONLY, fi.FieldInfo("f3").IndexOptions);
// docs/freqs + docs = docs
Assert.AreEqual(IndexOptions.DOCS_ONLY, fi.FieldInfo("f4").IndexOptions);
// docs/freqs + docs/freqs = docs/freqs
Assert.AreEqual(IndexOptions.DOCS_AND_FREQS, fi.FieldInfo("f5").IndexOptions);
// docs/freqs + docs/freqs/pos = docs/freqs
Assert.AreEqual(IndexOptions.DOCS_AND_FREQS, fi.FieldInfo("f6").IndexOptions);
// docs/freqs/pos + docs = docs
Assert.AreEqual(IndexOptions.DOCS_ONLY, fi.FieldInfo("f7").IndexOptions);
// docs/freqs/pos + docs/freqs = docs/freqs
Assert.AreEqual(IndexOptions.DOCS_AND_FREQS, fi.FieldInfo("f8").IndexOptions);
// docs/freqs/pos + docs/freqs/pos = docs/freqs/pos
Assert.AreEqual(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, fi.FieldInfo("f9").IndexOptions);
reader.Dispose();
ram.Dispose();
}
private void AssertNoPrx(Directory dir)
{
string[] files = dir.ListAll();
for (int i = 0; i < files.Length; i++)
{
Assert.IsFalse(files[i].EndsWith(".prx", StringComparison.Ordinal));
Assert.IsFalse(files[i].EndsWith(".pos", StringComparison.Ordinal));
}
}
// Verifies no *.prx exists when all fields omit term positions:
[Test]
public virtual void TestNoPrxFile()
{
Directory ram = NewDirectory();
Analyzer analyzer = new MockAnalyzer(Random);
IndexWriter writer = new IndexWriter(ram, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetMaxBufferedDocs(3).SetMergePolicy(NewLogMergePolicy()));
LogMergePolicy lmp = (LogMergePolicy)writer.Config.MergePolicy;
lmp.MergeFactor = 2;
lmp.NoCFSRatio = 0.0;
Document d = new Document();
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.IndexOptions = IndexOptions.DOCS_AND_FREQS;
Field f1 = NewField("f1", "this field has term freqs", ft);
d.Add(f1);
for (int i = 0; i < 30; i++)
{
writer.AddDocument(d);
}
writer.Commit();
AssertNoPrx(ram);
// now add some documents with positions, and check there is no prox after optimization
d = new Document();
f1 = NewTextField("f1", "this field has positions", Field.Store.NO);
d.Add(f1);
for (int i = 0; i < 30; i++)
{
writer.AddDocument(d);
}
// force merge
writer.ForceMerge(1);
// flush
writer.Dispose();
AssertNoPrx(ram);
ram.Dispose();
}
/// <summary>
/// make sure we downgrade positions and payloads correctly </summary>
[Test]
public virtual void TestMixing()
{
// no positions
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.IndexOptions = IndexOptions.DOCS_AND_FREQS;
Directory dir = NewDirectory();
RandomIndexWriter iw = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
for (int i = 0; i < 20; i++)
{
Document doc = new Document();
if (i < 19 && Random.NextBoolean())
{
for (int j = 0; j < 50; j++)
{
doc.Add(new TextField("foo", "i have positions", Field.Store.NO));
}
}
else
{
for (int j = 0; j < 50; j++)
{
doc.Add(new Field("foo", "i have no positions", ft));
}
}
iw.AddDocument(doc);
iw.Commit();
}
if (Random.NextBoolean())
{
iw.ForceMerge(1);
}
DirectoryReader ir = iw.GetReader();
FieldInfos fis = MultiFields.GetMergedFieldInfos(ir);
Assert.AreEqual(IndexOptions.DOCS_AND_FREQS, fis.FieldInfo("foo").IndexOptions);
Assert.IsFalse(fis.FieldInfo("foo").HasPayloads);
iw.Dispose();
ir.Dispose();
dir.Dispose(); // checkindex
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.Scripting.XmlRpcGridRouterModule
{
public class XmlRpcInfo
{
public UUID item;
public UUID channel;
public string uri;
}
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XmlRpcGridRouter")]
public class XmlRpcGridRouter : INonSharedRegionModule, IXmlRpcRouter
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<UUID, UUID> m_Channels =
new Dictionary<UUID, UUID>();
private bool m_Enabled = false;
private string m_ServerURI = String.Empty;
#region INonSharedRegionModule
public void Initialise(IConfigSource config)
{
IConfig startupConfig = config.Configs["XMLRPC"];
if (startupConfig == null)
return;
if (startupConfig.GetString("XmlRpcRouterModule",
"XmlRpcRouterModule") == "XmlRpcGridRouterModule")
{
m_ServerURI = startupConfig.GetString("XmlRpcHubURI", String.Empty);
if (m_ServerURI == String.Empty)
{
m_log.Error("[XMLRPC GRID ROUTER] Module configured but no URI given. Disabling");
return;
}
m_Enabled = true;
}
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IXmlRpcRouter>(this);
IScriptModule scriptEngine = scene.RequestModuleInterface<IScriptModule>();
if ( scriptEngine != null )
{
scriptEngine.OnScriptRemoved += this.ScriptRemoved;
scriptEngine.OnObjectRemoved += this.ObjectRemoved;
}
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.UnregisterModuleInterface<IXmlRpcRouter>(this);
}
public void Close()
{
}
public string Name
{
get { return "XmlRpcGridRouterModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
public void RegisterNewReceiver(IScriptModule scriptEngine, UUID channel, UUID objectID, UUID itemID, string uri)
{
if (!m_Enabled)
return;
m_log.InfoFormat("[XMLRPC GRID ROUTER]: New receiver Obj: {0} Ch: {1} ID: {2} URI: {3}",
objectID.ToString(), channel.ToString(), itemID.ToString(), uri);
XmlRpcInfo info = new XmlRpcInfo();
info.channel = channel;
info.uri = uri;
info.item = itemID;
bool success = SynchronousRestObjectRequester.MakeRequest<XmlRpcInfo, bool>(
"POST", m_ServerURI+"/RegisterChannel/", info);
if (!success)
{
m_log.Error("[XMLRPC GRID ROUTER] Error contacting server");
}
m_Channels[itemID] = channel;
}
public void UnRegisterReceiver(string channelID, UUID itemID)
{
if (!m_Enabled)
return;
RemoveChannel(itemID);
}
public void ScriptRemoved(UUID itemID)
{
if (!m_Enabled)
return;
RemoveChannel(itemID);
}
public void ObjectRemoved(UUID objectID)
{
// m_log.InfoFormat("[XMLRPC GRID ROUTER]: Object Removed {0}",objectID.ToString());
}
private bool RemoveChannel(UUID itemID)
{
if(!m_Channels.ContainsKey(itemID))
{
m_log.InfoFormat("[XMLRPC GRID ROUTER]: Attempted to unregister non-existing Item: {0}", itemID.ToString());
return false;
}
XmlRpcInfo info = new XmlRpcInfo();
info.channel = m_Channels[itemID];
info.item = itemID;
info.uri = "http://0.0.0.0:00";
if (info != null)
{
bool success = SynchronousRestObjectRequester.MakeRequest<XmlRpcInfo, bool>(
"POST", m_ServerURI+"/RemoveChannel/", info);
if (!success)
{
m_log.Error("[XMLRPC GRID ROUTER] Error contacting server");
}
m_Channels.Remove(itemID);
return true;
}
return false;
}
}
}
| |
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;
namespace Facebook
{
enum HttpVerb
{
GET,
POST,
DELETE
}
/// <summary>
/// Wrapper around the Facebook Graph API.
/// </summary>
public class FacebookAPI
{
/// <summary>
/// The access token used to authenticate API calls.
/// </summary>
public string AccessToken { get; set; }
/// <summary>
/// Create a new instance of the API, with public access only.
/// </summary>
public FacebookAPI()
: this(null) { }
/// <summary>
/// Create a new instance of the API, using the given token to
/// authenticate.
/// </summary>
/// <param name="token">The access token used for
/// authentication</param>
public FacebookAPI(string token)
{
AccessToken = token;
}
/// <summary>
/// Makes a Facebook Graph API GET request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
public JSONObject Get(string relativePath)
{
return Call(relativePath, HttpVerb.GET, null);
}
/// <summary>
/// Makes a Facebook Graph API GET request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
/// <param name="args">A dictionary of key/value pairs that
/// will get passed as query arguments.</param>
public JSONObject Get(string relativePath,
Dictionary<string, string> args)
{
return Call(relativePath, HttpVerb.GET, args);
}
/// <summary>
/// Makes a Facebook Graph API DELETE request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
public JSONObject Delete(string relativePath)
{
return Call(relativePath, HttpVerb.DELETE, null);
}
/// <summary>
/// Makes a Facebook Graph API POST request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
/// <param name="args">A dictionary of key/value pairs that
/// will get passed as query arguments. These determine
/// what will get set in the graph API.</param>
public JSONObject Post(string relativePath,
Dictionary<string, string> args)
{
return Call(relativePath, HttpVerb.POST, args);
}
/// <summary>
/// Makes a Facebook Graph API Call.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
/// <param name="httpVerb">The HTTP verb to use, e.g.
/// GET, POST, DELETE</param>
/// <param name="args">A dictionary of key/value pairs that
/// will get passed as query arguments.</param>
private JSONObject Call(string relativePath,
HttpVerb httpVerb,
Dictionary<string, string> args)
{
Uri baseURL = new Uri("https://graph.facebook.com");
Uri url = new Uri(baseURL, relativePath);
if (args == null)
{
args = new Dictionary<string, string>();
}
if (!string.IsNullOrEmpty(AccessToken))
{
args["access_token"] = AccessToken;
}
JSONObject obj = JSONObject.CreateFromString(MakeRequest(url,
httpVerb,
args));
if (obj.IsDictionary && obj.Dictionary.ContainsKey("error"))
{
throw new FacebookAPIException(obj.Dictionary["error"]
.Dictionary["type"]
.String,
obj.Dictionary["error"]
.Dictionary["message"]
.String);
}
return obj;
}
/// <summary>
/// Make an HTTP request, with the given query args
/// </summary>
/// <param name="url">The URL of the request</param>
/// <param name="verb">The HTTP verb to use</param>
/// <param name="args">Dictionary of key/value pairs that represents
/// the key/value pairs for the request</param>
private string MakeRequest(Uri url, HttpVerb httpVerb,
Dictionary<string, string> args)
{
if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.GET)
{
url = new Uri(url.ToString() + EncodeDictionary(args, true));
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = httpVerb.ToString();
if (httpVerb == HttpVerb.POST)
{
string postData = EncodeDictionary(args, false);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] postDataBytes = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();
}
try
{
using (HttpWebResponse response
= request.GetResponse() as HttpWebResponse)
{
StreamReader reader
= new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
catch (WebException e)
{
throw new FacebookAPIException("Server Error", e.Message);
}
}
/// <summary>
/// Encode a dictionary of key/value pairs as an HTTP query string.
/// </summary>
/// <param name="dict">The dictionary to encode</param>
/// <param name="questionMark">Whether or not to start it
/// with a question mark (for GET requests)</param>
private string EncodeDictionary(Dictionary<string, string> dict,
bool questionMark)
{
StringBuilder sb = new StringBuilder();
if (questionMark)
{
sb.Append("?");
}
foreach (KeyValuePair<string, string> kvp in dict)
{
sb.Append(HttpUtility.UrlEncode(kvp.Key));
sb.Append("=");
sb.Append(HttpUtility.UrlEncode(kvp.Value));
sb.Append("&");
}
sb.Remove(sb.Length - 1, 1); // Remove trailing &
return sb.ToString();
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Messages.Messages
File: CurrencyTypes.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Messages
{
using System;
using System.Runtime.Serialization;
using System.Xml.Serialization;
//[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.4927")]
/// <summary>
/// Currency type.
/// </summary>
/// <remarks>
/// The codes are set in accordance with the ISO 4217 Currency Codes.
/// </remarks>
[Serializable]
[XmlType(Namespace = "http://www.webserviceX.NET/")]
[DataContract]
public enum CurrencyTypes
{
// ReSharper disable InconsistentNaming
/// <summary>
/// Afghanistan, Afghanis.
/// </summary>
[EnumMember]
AFA,
/// <summary>
/// Turkmenistan, Turkmenistani manat.
/// </summary>
[EnumMember]
TMT,
/// <summary>
/// Uzbekistan, Uzbekistan som.
/// </summary>
[EnumMember]
UZS,
/// <summary>
/// Tajikistan, Somoni.
/// </summary>
[EnumMember]
TJS,
/// <summary>
/// Armenia, Armenian dram.
/// </summary>
[EnumMember]
AMD,
/// <summary>
/// International Monetary Fund, Special Drawing Rights.
/// </summary>
[EnumMember]
XDR,
/// <summary>
/// Azerbaijan, Azerbaijani manat.
/// </summary>
[EnumMember]
AZN,
/// <summary>
/// Belarus, Belarusian ruble.
/// </summary>
[EnumMember]
BYR,
/// <summary>
/// Belarus, Belarusian ruble.
/// </summary>
[EnumMember]
BYN,
/// <summary>
/// Romania, Romanian new leu.
/// </summary>
[EnumMember]
RON,
/// <summary>
/// Bulgaria, Bulgarian lev.
/// </summary>
[EnumMember]
BGN,
/// <summary>
/// Kyrgyzstan, Kyrgyzstani som.
/// </summary>
[EnumMember]
KGS,
/// <summary>
/// Albania, Leke.
/// </summary>
[EnumMember]
ALL,
/// <summary>
/// Algeria, Algeria Dinars.
/// </summary>
[EnumMember]
DZD,
/// <summary>
/// Argentina, Pesos.
/// </summary>
[EnumMember]
ARS,
/// <summary>
/// Aruba, Guilders (also called Florins).
/// </summary>
[EnumMember]
AWG,
/// <summary>
/// Australia, Dollars.
/// </summary>
[EnumMember]
AUD,
/// <summary>
/// Bahamas, Dollars.
/// </summary>
[EnumMember]
BSD,
/// <summary>
/// Bahrain, Dinars.
/// </summary>
[EnumMember]
BHD,
/// <summary>
/// Bangladesh, Taka.
/// </summary>
[EnumMember]
BDT,
/// <summary>
/// Barbados, Dollars.
/// </summary>
[EnumMember]
BBD,
/// <summary>
/// Belize, Dollars.
/// </summary>
[EnumMember]
BZD,
/// <summary>
/// Bermuda, Dollars.
/// </summary>
[EnumMember]
BMD,
/// <summary>
/// Bhutan, Ngultrum.
/// </summary>
[EnumMember]
BTN,
/// <summary>
/// Bolivia, Bolivianos.
/// </summary>
[EnumMember]
BOB,
/// <summary>
/// Botswana, Pulas.
/// </summary>
[EnumMember]
BWP,
/// <summary>
/// Brazil, Brazil Real.
/// </summary>
[EnumMember]
BRL,
/// <summary>
/// United Kingdom, Pounds sterling.
/// </summary>
[EnumMember]
GBP,
/// <summary>
/// Brunei Darussalam, Dollars.
/// </summary>
[EnumMember]
BND,
/// <summary>
/// Burundi, Francs.
/// </summary>
[EnumMember]
BIF,
/// <summary>
/// Communaute Financiere Africaine BCEAO, Francs.
/// </summary>
[EnumMember]
XOF,
/// <summary>
/// Communaute Financiere Africaine BEAC, Francs.
/// </summary>
[EnumMember]
XAF,
/// <summary>
/// Cambodia, Riels.
/// </summary>
[EnumMember]
KHR,
/// <summary>
/// Canada, Dollars.
/// </summary>
[EnumMember]
CAD,
/// <summary>
/// Cape Verde, Escudos.
/// </summary>
[EnumMember]
CVE,
/// <summary>
/// Cayman Islands, Dollars.
/// </summary>
[EnumMember]
KYD,
/// <summary>
/// Chile, Pesos.
/// </summary>
[EnumMember]
CLP,
/// <summary>
/// China, Yuan Renminbi.
/// </summary>
[EnumMember]
CNY,
/// <summary>
/// China, offshore RMB.
/// </summary>
[EnumMember]
CNH,
/// <summary>
/// Colombia, Pesos.
/// </summary>
[EnumMember]
COP,
/// <summary>
/// Comoros, Francs.
/// </summary>
[EnumMember]
KMF,
/// <summary>
/// Costa Rica, Colones.
/// </summary>
[EnumMember]
CRC,
/// <summary>
/// Croatia, Kuna.
/// </summary>
[EnumMember]
HRK,
/// <summary>
/// Cuba, Pesos.
/// </summary>
[EnumMember]
CUP,
/// <summary>
/// Cyprus, Pounds.
/// </summary>
[EnumMember]
CYP,
/// <summary>
/// Czech Republic, Koruny.
/// </summary>
[EnumMember]
CZK,
/// <summary>
/// Denmark, Kroner.
/// </summary>
[EnumMember]
DKK,
/// <summary>
/// Djibouti, Francs.
/// </summary>
[EnumMember]
DJF,
/// <summary>
/// Dominican Republic, Pesos.
/// </summary>
[EnumMember]
DOP,
/// <summary>
/// East Caribbean Dollars.
/// </summary>
[EnumMember]
XCD,
/// <summary>
/// Egypt, Pounds.
/// </summary>
[EnumMember]
EGP,
/// <summary>
/// El Salvador, Colones.
/// </summary>
[EnumMember]
SVC,
/// <summary>
/// Estonia, Krooni.
/// </summary>
[EnumMember]
EEK,
/// <summary>
/// Ethiopia, Birr.
/// </summary>
[EnumMember]
ETB,
/// <summary>
/// Euro Member Countries, Euro.
/// </summary>
[EnumMember]
EUR,
/// <summary>
/// Falkland Islands (Malvinas), Pounds.
/// </summary>
[EnumMember]
FKP,
/// <summary>
/// Gambia, Dalasi.
/// </summary>
[EnumMember]
GMD,
/// <summary>
/// Ghana, Cedis.
/// </summary>
[EnumMember]
GHC,
/// <summary>
/// Gibraltar, Pounds.
/// </summary>
[EnumMember]
GIP,
/// <summary>
/// Gold, Ounces.
/// </summary>
[EnumMember]
XAU,
/// <summary>
/// Guatemala, Quetzales.
/// </summary>
[EnumMember]
GTQ,
/// <summary>
/// Guinea, Francs.
/// </summary>
[EnumMember]
GNF,
/// <summary>
/// Guyana, Dollars.
/// </summary>
[EnumMember]
GYD,
/// <summary>
/// Haiti, Gourdes.
/// </summary>
[EnumMember]
HTG,
/// <summary>
/// Honduras, Lempiras.
/// </summary>
[EnumMember]
HNL,
/// <summary>
/// Hong Kong, Dollars.
/// </summary>
[EnumMember]
HKD,
/// <summary>
/// Hungary, Forint.
/// </summary>
[EnumMember]
HUF,
/// <summary>
/// Iceland, Kronur.
/// </summary>
[EnumMember]
ISK,
/// <summary>
/// India, Rupees.
/// </summary>
[EnumMember]
INR,
/// <summary>
/// Indonesia, Rupiahs.
/// </summary>
[EnumMember]
IDR,
/// <summary>
/// Iraq, Dinars.
/// </summary>
[EnumMember]
IQD,
/// <summary>
/// Israel, New Shekels.
/// </summary>
[EnumMember]
ILS,
/// <summary>
/// Jamaica, Dollars.
/// </summary>
[EnumMember]
JMD,
/// <summary>
/// Japan, Yen.
/// </summary>
[EnumMember]
JPY,
/// <summary>
/// Jordan, Dinars.
/// </summary>
[EnumMember]
JOD,
/// <summary>
/// Kazakstan, Tenge.
/// </summary>
[EnumMember]
KZT,
/// <summary>
/// Kenya, Shillings.
/// </summary>
[EnumMember]
KES,
/// <summary>
/// Korea (South), Won.
/// </summary>
[EnumMember]
KRW,
/// <summary>
/// Kuwait, Dinars.
/// </summary>
[EnumMember]
KWD,
/// <summary>
/// Laos, Kips.
/// </summary>
[EnumMember]
LAK,
/// <summary>
/// Latvia, Lati.
/// </summary>
[EnumMember]
LVL,
/// <summary>
/// Lebanon, Pounds.
/// </summary>
[EnumMember]
LBP,
/// <summary>
/// Lesotho, Maloti.
/// </summary>
[EnumMember]
LSL,
/// <summary>
/// Liberia, Dollars.
/// </summary>
[EnumMember]
LRD,
/// <summary>
/// Libya, Dinars.
/// </summary>
[EnumMember]
LYD,
/// <summary>
/// Lithuania, Litai.
/// </summary>
[EnumMember]
LTL,
/// <summary>
/// Macau, Patacas.
/// </summary>
[EnumMember]
MOP,
/// <summary>
/// Macedonia, Denars.
/// </summary>
[EnumMember]
MKD,
/// <summary>
/// Malagasy, Franc.
/// </summary>
[EnumMember]
MGF,
/// <summary>
/// Malawi, Kwachas.
/// </summary>
[EnumMember]
MWK,
/// <summary>
/// Malaysia, Ringgits.
/// </summary>
[EnumMember]
MYR,
/// <summary>
/// Maldives (Maldive Islands), Rufiyaa.
/// </summary>
[EnumMember]
MVR,
/// <summary>
/// Malta, Liri.
/// </summary>
[EnumMember]
MTL,
/// <summary>
/// Mauritania, Ouguiyas.
/// </summary>
[EnumMember]
MRO,
/// <summary>
/// Mauritius, Rupees.
/// </summary>
[EnumMember]
MUR,
/// <summary>
/// Mexico, Pesos.
/// </summary>
[EnumMember]
MXN,
/// <summary>
/// Moldova, Lei.
/// </summary>
[EnumMember]
MDL,
/// <summary>
/// Mongolia, Tugriks.
/// </summary>
[EnumMember]
MNT,
/// <summary>
/// Morocco, Dirhams.
/// </summary>
[EnumMember]
MAD,
/// <summary>
/// Mozambique, Meticais.
/// </summary>
[EnumMember]
MZM,
/// <summary>
/// Myanmar (Burma), Kyats.
/// </summary>
[EnumMember]
MMK,
/// <summary>
/// Namibia, Dollars.
/// </summary>
[EnumMember]
NAD,
/// <summary>
/// Nepal, Nepal Rupees.
/// </summary>
[EnumMember]
NPR,
/// <summary>
/// Netherlands Antilles, Guilders (also called Florins).
/// </summary>
[EnumMember]
ANG,
/// <summary>
/// New Zealand, Dollars.
/// </summary>
[EnumMember]
NZD,
/// <summary>
/// Nicaragua, Gold Cordobas.
/// </summary>
[EnumMember]
NIO,
/// <summary>
/// Nigeria, Nairas.
/// </summary>
[EnumMember]
NGN,
/// <summary>
/// Korea (North), Won.
/// </summary>
[EnumMember]
KPW,
/// <summary>
/// Norway, Krone.
/// </summary>
[EnumMember]
NOK,
/// <summary>
/// Oman, Rials.
/// </summary>
[EnumMember]
OMR,
/// <summary>
/// Comptoirs Francais du Pacifique Francs.
/// </summary>
[EnumMember]
XPF,
/// <summary>
/// Pakistan, Rupees.
/// </summary>
[EnumMember]
PKR,
/// <summary>
/// Palladium Ounces.
/// </summary>
[EnumMember]
XPD,
/// <summary>
/// Panama, Balboa.
/// </summary>
[EnumMember]
PAB,
/// <summary>
/// Papua New Guinea, Kina.
/// </summary>
[EnumMember]
PGK,
/// <summary>
/// Paraguay, Guarani.
/// </summary>
[EnumMember]
PYG,
/// <summary>
/// Peru, Nuevos Soles.
/// </summary>
[EnumMember]
PEN,
/// <summary>
/// Philippines, Pesos.
/// </summary>
[EnumMember]
PHP,
/// <summary>
/// Platinum, Ounces.
/// </summary>
[EnumMember]
XPT,
/// <summary>
/// Poland, Zlotych.
/// </summary>
[EnumMember]
PLN,
/// <summary>
/// Qatar, Rials.
/// </summary>
[EnumMember]
QAR,
/// <summary>
/// Russia, Abkhazia, South Ossetia, Russian rouble.
/// </summary>
[EnumMember]
RUB,
/// <summary>
/// Samoa, Tala.
/// </summary>
[EnumMember]
WST,
/// <summary>
/// Sao Tome and Principe, Dobras.
/// </summary>
[EnumMember]
STD,
/// <summary>
/// Saudi Arabia, Riyals.
/// </summary>
[EnumMember]
SAR,
/// <summary>
/// Seychelles, Rupees.
/// </summary>
[EnumMember]
SCR,
/// <summary>
/// Sierra Leone, Leones.
/// </summary>
[EnumMember]
SLL,
/// <summary>
/// Silver, Ounces.
/// </summary>
[EnumMember]
XAG,
/// <summary>
/// Singapore, Dollars.
/// </summary>
[EnumMember]
SGD,
/// <summary>
/// Slovakia, Koruny.
/// </summary>
[EnumMember]
SKK,
/// <summary>
/// Slovenia, Tolars.
/// </summary>
[EnumMember]
SIT,
/// <summary>
/// Solomon Islands, Dollars.
/// </summary>
[EnumMember]
SBD,
/// <summary>
/// Somalia, Shillings.
/// </summary>
[EnumMember]
SOS,
/// <summary>
/// South Africa, Rand.
/// </summary>
[EnumMember]
ZAR,
/// <summary>
/// Sri Lanka, Rupees.
/// </summary>
[EnumMember]
LKR,
/// <summary>
/// Saint Helena, Pounds.
/// </summary>
[EnumMember]
SHP,
/// <summary>
/// Sudan, Dinars.
/// </summary>
[EnumMember]
SDD,
/// <summary>
/// Surinamese dollar.
/// </summary>
[EnumMember]
SRD,
/// <summary>
/// Swaziland, Emalangeni.
/// </summary>
[EnumMember]
SZL,
/// <summary>
/// Sweden, Kronor.
/// </summary>
[EnumMember]
SEK,
/// <summary>
/// Switzerland, Francs.
/// </summary>
[EnumMember]
CHF,
/// <summary>
/// Syria, Pounds.
/// </summary>
[EnumMember]
SYP,
/// <summary>
/// Taiwan, New Dollars.
/// </summary>
[EnumMember]
TWD,
/// <summary>
/// Tanzania, Shillings.
/// </summary>
[EnumMember]
TZS,
/// <summary>
/// Thailand, Baht.
/// </summary>
[EnumMember]
THB,
/// <summary>
/// Tonga, Pa'anga.
/// </summary>
[EnumMember]
TOP,
/// <summary>
/// Trinidad and Tobago, Dollars.
/// </summary>
[EnumMember]
TTD,
/// <summary>
/// Tunisia, Dinars.
/// </summary>
[EnumMember]
TND,
/// <summary>
/// Turkey, Liras.
/// </summary>
[EnumMember]
TRL,
/// <summary>
/// United States of America, Dollars.
/// </summary>
[EnumMember]
USD,
/// <summary>
/// United Arab Emirates, Dirhams.
/// </summary>
[EnumMember]
AED,
/// <summary>
/// Uganda, Shillings.
/// </summary>
[EnumMember]
UGX,
/// <summary>
/// Ukraine, Hryvnia.
/// </summary>
[EnumMember]
UAH,
/// <summary>
/// Uruguay, Pesos.
/// </summary>
[EnumMember]
UYU,
/// <summary>
/// Vanuatu, Vatu.
/// </summary>
[EnumMember]
VUV,
/// <summary>
/// Venezuela, Bolivares.
/// </summary>
[EnumMember]
VEB,
/// <summary>
/// Viet Nam, Dong.
/// </summary>
[EnumMember]
VND,
/// <summary>
/// Yemen, Rials.
/// </summary>
[EnumMember]
YER,
/// <summary>
/// Serbian dinar.
/// </summary>
[EnumMember]
CSD,
/// <summary>
/// Zambia, Kwacha.
/// </summary>
[EnumMember]
ZMK,
/// <summary>
/// Zimbabwe, Zimbabwe Dollars.
/// </summary>
[EnumMember]
ZWD,
/// <summary>
/// Turkey, Northern Cyprus, Turkish lira.
/// </summary>
[EnumMember]
TRY,
/// <summary>
/// Ven.
/// </summary>
[EnumMember]
XVN,
/// <summary>
/// Bitcoin.
/// </summary>
[EnumMember]
BTC,
/// <summary>
/// United Kingdom, Pence sterling.
/// </summary>
[EnumMember]
GBX,
/// <summary>
/// Ghana, Ghanaian Cedi.
/// </summary>
[EnumMember]
GHS,
// ReSharper restore InconsistentNaming
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using Xunit;
namespace System.Net.Http.Unit.Tests
{
public class EntityTagHeaderValueTest
{
[Fact]
public void Ctor_ETagNull_Throw()
{
Assert.Throws<ArgumentException>(() => { new EntityTagHeaderValue(null); });
}
[Fact]
public void Ctor_ETagEmpty_Throw()
{
// null and empty should be treated the same. So we also throw for empty strings.
Assert.Throws<ArgumentException>(() => { new EntityTagHeaderValue(string.Empty); });
}
[Fact]
public void Ctor_ETagInvalidFormat_ThrowFormatException()
{
// When adding values using strongly typed objects, no leading/trailing LWS (whitespaces) are allowed.
AssertFormatException("tag");
AssertFormatException("*");
AssertFormatException(" tag ");
AssertFormatException("\"tag\" invalid");
AssertFormatException("\"tag");
AssertFormatException("tag\"");
AssertFormatException("\"tag\"\"");
AssertFormatException("\"\"tag\"\"");
AssertFormatException("\"\"tag\"");
AssertFormatException("W/\"tag\"");
}
[Fact]
public void Ctor_ETagValidFormat_SuccessfullyCreated()
{
EntityTagHeaderValue etag = new EntityTagHeaderValue("\"tag\"");
Assert.Equal("\"tag\"", etag.Tag);
Assert.False(etag.IsWeak);
}
[Fact]
public void Ctor_ETagValidFormatAndIsWeak_SuccessfullyCreated()
{
EntityTagHeaderValue etag = new EntityTagHeaderValue("\"e tag\"", true);
Assert.Equal("\"e tag\"", etag.Tag);
Assert.True(etag.IsWeak);
}
[Fact]
public void ToString_UseDifferentETags_AllSerializedCorrectly()
{
EntityTagHeaderValue etag = new EntityTagHeaderValue("\"e tag\"");
Assert.Equal("\"e tag\"", etag.ToString());
etag = new EntityTagHeaderValue("\"e tag\"", true);
Assert.Equal("W/\"e tag\"", etag.ToString());
etag = new EntityTagHeaderValue("\"\"", false);
Assert.Equal("\"\"", etag.ToString());
}
[Fact]
public void GetHashCode_UseSameAndDifferentETags_SameOrDifferentHashCodes()
{
EntityTagHeaderValue etag1 = new EntityTagHeaderValue("\"tag\"");
EntityTagHeaderValue etag2 = new EntityTagHeaderValue("\"TAG\"");
EntityTagHeaderValue etag3 = new EntityTagHeaderValue("\"tag\"", true);
EntityTagHeaderValue etag4 = new EntityTagHeaderValue("\"tag1\"");
EntityTagHeaderValue etag5 = new EntityTagHeaderValue("\"tag\"");
EntityTagHeaderValue etag6 = EntityTagHeaderValue.Any;
Assert.NotEqual(etag1.GetHashCode(), etag2.GetHashCode());
Assert.NotEqual(etag1.GetHashCode(), etag3.GetHashCode());
Assert.NotEqual(etag1.GetHashCode(), etag4.GetHashCode());
Assert.NotEqual(etag1.GetHashCode(), etag6.GetHashCode());
Assert.Equal(etag1.GetHashCode(), etag5.GetHashCode());
}
[Fact]
public void Equals_UseSameAndDifferentETags_EqualOrNotEqualNoExceptions()
{
EntityTagHeaderValue etag1 = new EntityTagHeaderValue("\"tag\"");
EntityTagHeaderValue etag2 = new EntityTagHeaderValue("\"TAG\"");
EntityTagHeaderValue etag3 = new EntityTagHeaderValue("\"tag\"", true);
EntityTagHeaderValue etag4 = new EntityTagHeaderValue("\"tag1\"");
EntityTagHeaderValue etag5 = new EntityTagHeaderValue("\"tag\"");
EntityTagHeaderValue etag6 = EntityTagHeaderValue.Any;
Assert.False(etag1.Equals(etag2));
Assert.False(etag2.Equals(etag1));
Assert.False(etag1.Equals(null));
Assert.False(etag1.Equals(etag3));
Assert.False(etag3.Equals(etag1));
Assert.False(etag1.Equals(etag4));
Assert.False(etag1.Equals(etag6));
Assert.True(etag1.Equals(etag5));
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
EntityTagHeaderValue source = new EntityTagHeaderValue("\"tag\"");
EntityTagHeaderValue clone = (EntityTagHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Tag, clone.Tag);
Assert.Equal(source.IsWeak, clone.IsWeak);
source = new EntityTagHeaderValue("\"tag\"", true);
clone = (EntityTagHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Tag, clone.Tag);
Assert.Equal(source.IsWeak, clone.IsWeak);
Assert.Same(EntityTagHeaderValue.Any, ((ICloneable)EntityTagHeaderValue.Any).Clone());
}
[Fact]
public void GetEntityTagLength_DifferentValidScenarios_AllReturnNonZero()
{
EntityTagHeaderValue result = null;
Assert.Equal(6, EntityTagHeaderValue.GetEntityTagLength("\"ta\u4F1Ag\"", 0, out result));
Assert.Equal("\"ta\u4F1Ag\"", result.Tag);
Assert.False(result.IsWeak);
Assert.Equal(9, EntityTagHeaderValue.GetEntityTagLength("W/\"tag\" ", 0, out result));
Assert.Equal("\"tag\"", result.Tag);
Assert.True(result.IsWeak);
// Note that even if after a valid tag & whitespaces there are invalid characters, GetEntityTagLength()
// will return the length of the valid tag and ignore the invalid characters at the end. It is the callers
// responsibility to consider the whole string invalid if after a valid ETag there are invalid chars.
Assert.Equal(11, EntityTagHeaderValue.GetEntityTagLength("\"tag\" \r\n !!", 0, out result));
Assert.Equal("\"tag\"", result.Tag);
Assert.False(result.IsWeak);
Assert.Equal(7, EntityTagHeaderValue.GetEntityTagLength("\"W/tag\"", 0, out result));
Assert.Equal("\"W/tag\"", result.Tag);
Assert.False(result.IsWeak);
Assert.Equal(9, EntityTagHeaderValue.GetEntityTagLength("W/ \"tag\"", 0, out result));
Assert.Equal("\"tag\"", result.Tag);
Assert.True(result.IsWeak);
// We also accept lower-case 'w': e.g. 'w/"tag"' rather than 'W/"tag"'
Assert.Equal(4, EntityTagHeaderValue.GetEntityTagLength("w/\"\"", 0, out result));
Assert.Equal("\"\"", result.Tag);
Assert.True(result.IsWeak);
Assert.Equal(2, EntityTagHeaderValue.GetEntityTagLength("\"\"", 0, out result));
Assert.Equal("\"\"", result.Tag);
Assert.False(result.IsWeak);
Assert.Equal(2, EntityTagHeaderValue.GetEntityTagLength(",* , ", 1, out result));
Assert.Same(EntityTagHeaderValue.Any, result);
}
[Fact]
public void GetEntityTagLength_DifferentInvalidScenarios_AllReturnZero()
{
EntityTagHeaderValue result = null;
// no leading spaces allowed.
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(" \"tag\"", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("\"tag", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("tag\"", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("a/\"tag\"", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W//\"tag\"", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W/", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W/\"", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(null, 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(string.Empty, 0, out result));
Assert.Null(result);
}
[Fact]
public void Parse_SetOfValidValueStrings_ParsedCorrectly()
{
CheckValidParse("\"tag\"", new EntityTagHeaderValue("\"tag\""));
CheckValidParse(" \"tag\" ", new EntityTagHeaderValue("\"tag\""));
CheckValidParse("\r\n \"tag\"\r\n ", new EntityTagHeaderValue("\"tag\""));
CheckValidParse("\"tag\"", new EntityTagHeaderValue("\"tag\""));
CheckValidParse("\"tag\u4F1A\"", new EntityTagHeaderValue("\"tag\u4F1A\""));
CheckValidParse("W/\"tag\"", new EntityTagHeaderValue("\"tag\"", true));
}
[Fact]
public void Parse_SetOfInvalidValueStrings_Throws()
{
CheckInvalidParse(null);
CheckInvalidParse(string.Empty);
CheckInvalidParse(" ");
CheckInvalidParse(" !");
CheckInvalidParse("tag\" !");
CheckInvalidParse("!\"tag\"");
CheckInvalidParse("\"tag\",");
CheckInvalidParse("\"tag\" \"tag2\"");
CheckInvalidParse("/\"tag\"");
CheckInvalidParse("*"); // "any" is not allowed as ETag value.
}
[Fact]
public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
{
CheckValidTryParse("\"tag\"", new EntityTagHeaderValue("\"tag\""));
CheckValidTryParse(" \"tag\" ", new EntityTagHeaderValue("\"tag\""));
CheckValidTryParse("\r\n \"tag\"\r\n ", new EntityTagHeaderValue("\"tag\""));
CheckValidTryParse("\"tag\"", new EntityTagHeaderValue("\"tag\""));
CheckValidTryParse("\"tag\u4F1A\"", new EntityTagHeaderValue("\"tag\u4F1A\""));
CheckValidTryParse("W/\"tag\"", new EntityTagHeaderValue("\"tag\"", true));
}
[Fact]
public void TryParse_SetOfInvalidValueStrings_ReturnsFalse()
{
CheckInvalidTryParse(null);
CheckInvalidTryParse(string.Empty);
CheckInvalidTryParse(" ");
CheckInvalidTryParse(" !");
CheckInvalidTryParse("tag\" !");
CheckInvalidTryParse("!\"tag\"");
CheckInvalidTryParse("\"tag\",");
CheckInvalidTryParse("\"tag\" \"tag2\"");
CheckInvalidTryParse("/\"tag\"");
CheckInvalidTryParse("*"); // "any" is not allowed as ETag value.
}
#region Helper methods
private void CheckValidParse(string input, EntityTagHeaderValue expectedResult)
{
EntityTagHeaderValue result = EntityTagHeaderValue.Parse(input);
Assert.Equal(expectedResult, result);
}
private void CheckInvalidParse(string input)
{
Assert.Throws<FormatException>(() => { EntityTagHeaderValue.Parse(input); });
}
private void CheckValidTryParse(string input, EntityTagHeaderValue expectedResult)
{
EntityTagHeaderValue result = null;
Assert.True(EntityTagHeaderValue.TryParse(input, out result));
Assert.Equal(expectedResult, result);
}
private void CheckInvalidTryParse(string input)
{
EntityTagHeaderValue result = null;
Assert.False(EntityTagHeaderValue.TryParse(input, out result));
Assert.Null(result);
}
private static void AssertFormatException(string tag)
{
Assert.Throws<FormatException>(() => { new EntityTagHeaderValue(tag); });
}
#endregion
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics.Application;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Xml;
class SecurityTraceRecord : TraceRecord
{
String traceName;
internal SecurityTraceRecord(String traceName)
{
if (String.IsNullOrEmpty(traceName))
this.traceName = "Empty";
else
this.traceName = traceName;
}
internal override string EventId { get { return BuildEventId(traceName); } }
}
internal static class SecurityTraceRecordHelper
{
internal static void TraceRemovedCachedServiceToken<T>(IssuanceTokenProviderBase<T> provider, SecurityToken serviceToken)
where T : IssuanceTokenProviderState
{
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.IssuanceTokenProviderRemovedCachedToken, SR.GetString(SR.TraceCodeIssuanceTokenProviderRemovedCachedToken), new IssuanceProviderTraceRecord<T>(provider, serviceToken));
}
}
internal static void TraceUsingCachedServiceToken<T>(IssuanceTokenProviderBase<T> provider, SecurityToken serviceToken, EndpointAddress target)
where T : IssuanceTokenProviderState
{
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.IssuanceTokenProviderUsingCachedToken, SR.GetString(SR.TraceCodeIssuanceTokenProviderUsingCachedToken), new IssuanceProviderTraceRecord<T>(provider, serviceToken, target));
}
}
internal static void TraceBeginSecurityNegotiation<T>(IssuanceTokenProviderBase<T> provider, EndpointAddress target)
where T : IssuanceTokenProviderState
{
if (TD.SecurityNegotiationStartIsEnabled())
{
TD.SecurityNegotiationStart(provider.EventTraceActivity);
}
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.IssuanceTokenProviderBeginSecurityNegotiation, SR.GetString(SR.TraceCodeIssuanceTokenProviderBeginSecurityNegotiation), new IssuanceProviderTraceRecord<T>(provider, target));
}
}
internal static void TraceEndSecurityNegotiation<T>(IssuanceTokenProviderBase<T> provider, SecurityToken serviceToken, EndpointAddress target)
where T : IssuanceTokenProviderState
{
if (TD.SecurityNegotiationStopIsEnabled())
{
TD.SecurityNegotiationStop(provider.EventTraceActivity);
}
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.IssuanceTokenProviderEndSecurityNegotiation, SR.GetString(SR.TraceCodeIssuanceTokenProviderEndSecurityNegotiation), new IssuanceProviderTraceRecord<T>(provider, serviceToken, target));
}
}
internal static void TraceRedirectApplied<T>(IssuanceTokenProviderBase<T> provider, EndpointAddress newTarget, EndpointAddress oldTarget)
where T : IssuanceTokenProviderState
{
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.IssuanceTokenProviderRedirectApplied, SR.GetString(SR.TraceCodeIssuanceTokenProviderRedirectApplied), new IssuanceProviderTraceRecord<T>(provider, newTarget, oldTarget));
}
}
internal static void TraceClientServiceTokenCacheFull<T>(IssuanceTokenProviderBase<T> provider, int cacheSize)
where T : IssuanceTokenProviderState
{
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.IssuanceTokenProviderServiceTokenCacheFull, SR.GetString(SR.TraceCodeIssuanceTokenProviderServiceTokenCacheFull), new IssuanceProviderTraceRecord<T>(provider, cacheSize));
}
}
internal static void TraceClientSpnego(WindowsSspiNegotiation windowsNegotiation)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SpnegoClientNegotiationCompleted, SR.GetString(SR.TraceCodeSpnegoClientNegotiationCompleted), new WindowsSspiNegotiationTraceRecord(windowsNegotiation));
}
}
internal static void TraceServiceSpnego(WindowsSspiNegotiation windowsNegotiation)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SpnegoServiceNegotiationCompleted, SR.GetString(SR.TraceCodeSpnegoServiceNegotiationCompleted), new WindowsSspiNegotiationTraceRecord(windowsNegotiation));
}
}
internal static void TraceClientOutgoingSpnego(WindowsSspiNegotiation windowsNegotiation)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SpnegoClientNegotiation, SR.GetString(SR.TraceCodeSpnegoClientNegotiation), new WindowsSspiNegotiationTraceRecord(windowsNegotiation));
}
}
internal static void TraceServiceOutgoingSpnego(WindowsSspiNegotiation windowsNegotiation)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SpnegoServiceNegotiation, SR.GetString(SR.TraceCodeSpnegoServiceNegotiation), new WindowsSspiNegotiationTraceRecord(windowsNegotiation));
}
}
internal static void TraceNegotiationTokenAuthenticatorAttached<T>(NegotiationTokenAuthenticator<T> authenticator, IChannelListener transportChannelListener)
where T : NegotiationTokenAuthenticatorState
{
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.NegotiationAuthenticatorAttached, SR.GetString(SR.TraceCodeNegotiationAuthenticatorAttached), new NegotiationAuthenticatorTraceRecord<T>(authenticator, transportChannelListener));
}
}
internal static void TraceServiceSecurityNegotiationCompleted<T>(Message message, NegotiationTokenAuthenticator<T> authenticator, SecurityContextSecurityToken serviceToken)
where T : NegotiationTokenAuthenticatorState
{
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ServiceSecurityNegotiationCompleted, SR.GetString(SR.TraceCodeServiceSecurityNegotiationCompleted),
new NegotiationAuthenticatorTraceRecord<T>(authenticator, serviceToken));
}
if (TD.ServiceSecurityNegotiationCompletedIsEnabled())
{
EventTraceActivity activity = EventTraceActivityHelper.TryExtractActivity(message);
TD.ServiceSecurityNegotiationCompleted(activity);
}
}
internal static void TraceServiceSecurityNegotiationFailure<T>(EventTraceActivity eventTraceActivity, NegotiationTokenAuthenticator<T> authenticator, Exception e)
where T : NegotiationTokenAuthenticatorState
{
if (DiagnosticUtility.ShouldTraceWarning)
{
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecurityNegotiationProcessingFailure, SR.GetString(SR.TraceCodeSecurityNegotiationProcessingFailure), new NegotiationAuthenticatorTraceRecord<T>(authenticator, e));
}
if (TD.SecurityNegotiationProcessingFailureIsEnabled())
{
TD.SecurityNegotiationProcessingFailure(eventTraceActivity);
}
}
internal static void TraceSecurityContextTokenCacheFull(int capacity, int pruningAmount)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityContextTokenCacheFull, SR.GetString(SR.TraceCodeSecurityContextTokenCacheFull),
new SecurityContextTokenCacheTraceRecord(capacity, pruningAmount));
}
}
internal static void TraceIdentityVerificationSuccess(EventTraceActivity eventTraceActivity, EndpointIdentity identity, Claim claim, Type identityVerifier)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityIdentityVerificationSuccess, SR.GetString(SR.TraceCodeSecurityIdentityVerificationSuccess), new IdentityVerificationSuccessTraceRecord(identity, claim, identityVerifier));
if (TD.SecurityIdentityVerificationSuccessIsEnabled())
{
TD.SecurityIdentityVerificationSuccess(eventTraceActivity);
}
}
internal static void TraceIdentityVerificationFailure(EndpointIdentity identity, AuthorizationContext authContext, Type identityVerifier)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityIdentityVerificationFailure, SR.GetString(SR.TraceCodeSecurityIdentityVerificationFailure), new IdentityVerificationFailureTraceRecord(identity, authContext, identityVerifier));
}
internal static void TraceIdentityDeterminationSuccess(EndpointAddress epr, EndpointIdentity identity, Type identityVerifier)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityIdentityDeterminationSuccess, SR.GetString(SR.TraceCodeSecurityIdentityDeterminationSuccess), new IdentityDeterminationSuccessTraceRecord(epr, identity, identityVerifier));
}
internal static void TraceIdentityDeterminationFailure(EndpointAddress epr, Type identityVerifier)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityIdentityDeterminationFailure, SR.GetString(SR.TraceCodeSecurityIdentityDeterminationFailure), new IdentityDeterminationFailureTraceRecord(epr, identityVerifier));
}
internal static void TraceIdentityHostNameNormalizationFailure(EndpointAddress epr, Type identityVerifier, Exception e)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityIdentityHostNameNormalizationFailure, SR.GetString(SR.TraceCodeSecurityIdentityHostNameNormalizationFailure), new IdentityHostNameNormalizationFailureTraceRecord(epr, identityVerifier, e));
}
internal static void TraceExportChannelBindingEntry()
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ExportSecurityChannelBindingEntry, SR.GetString(SR.TraceCodeExportSecurityChannelBindingEntry), (object)null);
}
internal static void TraceExportChannelBindingExit()
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ExportSecurityChannelBindingExit, SR.GetString(SR.TraceCodeExportSecurityChannelBindingExit));
}
internal static void TraceImportChannelBindingEntry()
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ImportSecurityChannelBindingEntry, SR.GetString(SR.TraceCodeImportSecurityChannelBindingEntry), (object)null);
}
internal static void TraceImportChannelBindingExit()
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ImportSecurityChannelBindingExit, SR.GetString(SR.TraceCodeImportSecurityChannelBindingExit));
}
internal static void TraceTokenProviderOpened(EventTraceActivity eventTraceActivity, SecurityTokenProvider provider)
{
if (TD.SecurityTokenProviderOpenedIsEnabled())
{
TD.SecurityTokenProviderOpened(eventTraceActivity);
}
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityTokenProviderOpened, SR.GetString(SR.TraceCodeSecurityTokenProviderOpened), new TokenProviderTraceRecord(provider));
}
internal static void TraceTokenProviderClosed(SecurityTokenProvider provider)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityTokenProviderClosed, SR.GetString(SR.TraceCodeSecurityTokenProviderClosed), new TokenProviderTraceRecord(provider));
}
internal static void TraceTokenAuthenticatorOpened(SecurityTokenAuthenticator authenticator)
{
if (DiagnosticUtility.ShouldTraceVerbose)
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.SecurityTokenAuthenticatorOpened, SR.GetString(SR.TraceCodeSecurityTokenAuthenticatorOpened), new TokenAuthenticatorTraceRecord(authenticator));
}
internal static void TraceTokenAuthenticatorClosed(SecurityTokenAuthenticator authenticator)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityTokenAuthenticatorClosed, SR.GetString(SR.TraceCodeSecurityTokenAuthenticatorClosed), new TokenAuthenticatorTraceRecord(authenticator));
}
internal static void TraceOutgoingMessageSecured(SecurityProtocol binding, Message message)
{
if (TD.OutgoingMessageSecuredIsEnabled())
{
EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
TD.OutgoingMessageSecured(eventTraceActivity);
}
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityBindingOutgoingMessageSecured,
SR.GetString(SR.TraceCodeSecurityBindingOutgoingMessageSecured), new MessageSecurityTraceRecord(binding, message), null, null, message);
}
}
internal static void TraceIncomingMessageVerified(SecurityProtocol binding, Message message)
{
if (TD.IncomingMessageVerifiedIsEnabled())
{
EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
TD.IncomingMessageVerified(eventTraceActivity);
}
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityBindingIncomingMessageVerified,
SR.GetString(SR.TraceCodeSecurityBindingIncomingMessageVerified), new MessageSecurityTraceRecord(binding, message), null, null, message);
}
}
internal static void TraceSecureOutgoingMessageFailure(SecurityProtocol binding, Message message)
{
if (DiagnosticUtility.ShouldTraceWarning)
{
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecurityBindingSecureOutgoingMessageFailure,
SR.GetString(SR.TraceCodeSecurityBindingSecureOutgoingMessageFailure), new MessageSecurityTraceRecord(binding, message), null, null, message);
}
}
internal static void TraceVerifyIncomingMessageFailure(SecurityProtocol binding, Message message)
{
if (DiagnosticUtility.ShouldTraceWarning)
{
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecurityBindingVerifyIncomingMessageFailure,
SR.GetString(SR.TraceCodeSecurityBindingVerifyIncomingMessageFailure), new MessageSecurityTraceRecord(binding, message), null, null, message);
}
}
internal static void TraceSpnToSidMappingFailure(string spn, Exception e)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecuritySpnToSidMappingFailure, SR.GetString(SR.TraceCodeSecuritySpnToSidMappingFailure), new SpnToSidMappingTraceRecord(spn, e));
}
internal static void TraceSessionRedirectApplied(EndpointAddress previousTarget, EndpointAddress newTarget, GenericXmlSecurityToken sessionToken)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecuritySessionRedirectApplied, SR.GetString(SR.TraceCodeSecuritySessionRedirectApplied), new SessionRedirectAppliedTraceRecord(previousTarget, newTarget, sessionToken));
}
internal static void TraceCloseMessageSent(SecurityToken sessionToken, EndpointAddress remoteTarget)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityClientSessionCloseSent, SR.GetString(SR.TraceCodeSecurityClientSessionCloseSent), new ClientSessionTraceRecord(sessionToken, null, remoteTarget));
}
internal static void TraceCloseResponseMessageSent(SecurityToken sessionToken, EndpointAddress remoteTarget)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityClientSessionCloseResponseSent, SR.GetString(SR.TraceCodeSecurityClientSessionCloseResponseSent), new ClientSessionTraceRecord(sessionToken, null, remoteTarget));
}
internal static void TraceCloseMessageReceived(SecurityToken sessionToken, EndpointAddress remoteTarget)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityClientSessionCloseMessageReceived, SR.GetString(SR.TraceCodeSecurityClientSessionCloseMessageReceived), new ClientSessionTraceRecord(sessionToken, null, remoteTarget));
}
internal static void TraceSessionKeyRenewalFault(SecurityToken sessionToken, EndpointAddress remoteTarget)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecuritySessionKeyRenewalFaultReceived, SR.GetString(SR.TraceCodeSecuritySessionKeyRenewalFaultReceived), new ClientSessionTraceRecord(sessionToken, null, remoteTarget));
}
internal static void TraceRemoteSessionAbortedFault(SecurityToken sessionToken, EndpointAddress remoteTarget)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecuritySessionAbortedFaultReceived, SR.GetString(SR.TraceCodeSecuritySessionAbortedFaultReceived), new ClientSessionTraceRecord(sessionToken, null, remoteTarget));
}
internal static void TraceCloseResponseReceived(SecurityToken sessionToken, EndpointAddress remoteTarget)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecuritySessionClosedResponseReceived, SR.GetString(SR.TraceCodeSecuritySessionClosedResponseReceived), new ClientSessionTraceRecord(sessionToken, null, remoteTarget));
}
internal static void TracePreviousSessionKeyDiscarded(SecurityToken previousSessionToken, SecurityToken currentSessionToken, EndpointAddress remoteAddress)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityClientSessionPreviousKeyDiscarded, SR.GetString(SR.TraceCodeSecurityClientSessionPreviousKeyDiscarded), new ClientSessionTraceRecord(currentSessionToken, previousSessionToken, remoteAddress));
}
internal static void TraceSessionKeyRenewed(SecurityToken newSessionToken, SecurityToken currentSessionToken, EndpointAddress remoteAddress)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityClientSessionKeyRenewed, SR.GetString(SR.TraceCodeSecurityClientSessionKeyRenewed), new ClientSessionTraceRecord(newSessionToken, currentSessionToken, remoteAddress));
}
internal static void TracePendingSessionAdded(UniqueId sessionId, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityPendingServerSessionAdded, SR.GetString(SR.TraceCodeSecurityPendingServerSessionAdded), new ServerSessionTraceRecord(sessionId, listenAddress));
}
internal static void TracePendingSessionClosed(UniqueId sessionId, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecurityPendingServerSessionClosed, SR.GetString(SR.TraceCodeSecurityPendingServerSessionClosed), new ServerSessionTraceRecord(sessionId, listenAddress));
}
internal static void TracePendingSessionActivated(UniqueId sessionId, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityPendingServerSessionActivated, SR.GetString(SR.TraceCodeSecurityPendingServerSessionActivated), new ServerSessionTraceRecord(sessionId, listenAddress));
}
internal static void TraceActiveSessionRemoved(UniqueId sessionId, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityActiveServerSessionRemoved, SR.GetString(SR.TraceCodeSecurityActiveServerSessionRemoved), new ServerSessionTraceRecord(sessionId, listenAddress));
}
internal static void TraceNewServerSessionKeyIssued(SecurityContextSecurityToken newToken, SecurityContextSecurityToken supportingToken, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityNewServerSessionKeyIssued, SR.GetString(SR.TraceCodeSecurityNewServerSessionKeyIssued), new ServerSessionTraceRecord(newToken, supportingToken, listenAddress));
}
internal static void TraceInactiveSessionFaulted(SecurityContextSecurityToken sessionToken, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecurityInactiveSessionFaulted, SR.GetString(SR.TraceCodeSecurityInactiveSessionFaulted), new ServerSessionTraceRecord(sessionToken, (SecurityContextSecurityToken)null, listenAddress));
}
internal static void TraceServerSessionKeyUpdated(SecurityContextSecurityToken sessionToken, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityServerSessionKeyUpdated, SR.GetString(SR.TraceCodeSecurityServerSessionKeyUpdated), new ServerSessionTraceRecord(sessionToken, (SecurityContextSecurityToken)null, listenAddress));
}
internal static void TraceServerSessionCloseReceived(SecurityContextSecurityToken sessionToken, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityServerSessionCloseReceived, SR.GetString(SR.TraceCodeSecurityServerSessionCloseReceived), new ServerSessionTraceRecord(sessionToken, (SecurityContextSecurityToken)null, listenAddress));
}
internal static void TraceServerSessionCloseResponseReceived(SecurityContextSecurityToken sessionToken, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityServerSessionCloseResponseReceived, SR.GetString(SR.TraceCodeSecurityServerSessionCloseResponseReceived), new ServerSessionTraceRecord(sessionToken, (SecurityContextSecurityToken)null, listenAddress));
}
internal static void TraceSessionRenewalFaultSent(SecurityContextSecurityToken sessionToken, Uri listenAddress, Message message)
{
if (DiagnosticUtility.ShouldTraceWarning)
{
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecurityServerSessionRenewalFaultSent,
SR.GetString(SR.TraceCodeSecurityServerSessionRenewalFaultSent), new ServerSessionTraceRecord(sessionToken, message, listenAddress), null, null, message);
}
}
internal static void TraceSessionAbortedFaultSent(SecurityContextSecurityToken sessionToken, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecurityServerSessionAbortedFaultSent, SR.GetString(SR.TraceCodeSecurityServerSessionAbortedFaultSent), new ServerSessionTraceRecord(sessionToken, (SecurityContextSecurityToken)null, listenAddress));
}
internal static void TraceSessionClosedResponseSent(SecurityContextSecurityToken sessionToken, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecuritySessionCloseResponseSent, SR.GetString(SR.TraceCodeSecuritySessionCloseResponseSent), new ServerSessionTraceRecord(sessionToken, (SecurityContextSecurityToken)null, listenAddress));
}
internal static void TraceSessionClosedSent(SecurityContextSecurityToken sessionToken, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecuritySessionServerCloseSent, SR.GetString(SR.TraceCodeSecuritySessionServerCloseSent), new ServerSessionTraceRecord(sessionToken, (SecurityContextSecurityToken)null, listenAddress));
}
internal static void TraceRenewFaultSendFailure(SecurityContextSecurityToken sessionToken, Uri listenAddress, Exception e)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecuritySessionRenewFaultSendFailure, SR.GetString(SR.TraceCodeSecuritySessionRenewFaultSendFailure), new ServerSessionTraceRecord(sessionToken, listenAddress), e);
}
internal static void TraceSessionAbortedFaultSendFailure(SecurityContextSecurityToken sessionToken, Uri listenAddress, Exception e)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecuritySessionAbortedFaultSendFailure, SR.GetString(SR.TraceCodeSecuritySessionAbortedFaultSendFailure), new ServerSessionTraceRecord(sessionToken, listenAddress), e);
}
internal static void TraceSessionClosedResponseSendFailure(SecurityContextSecurityToken sessionToken, Uri listenAddress, Exception e)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecuritySessionClosedResponseSendFailure, SR.GetString(SR.TraceCodeSecuritySessionClosedResponseSendFailure), new ServerSessionTraceRecord(sessionToken, listenAddress), e);
}
internal static void TraceSessionCloseSendFailure(SecurityContextSecurityToken sessionToken, Uri listenAddress, Exception e)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecuritySessionServerCloseSendFailure, SR.GetString(SR.TraceCodeSecuritySessionServerCloseSendFailure), new ServerSessionTraceRecord(sessionToken, listenAddress), e);
}
internal static void TraceBeginSecuritySessionOperation(SecuritySessionOperation operation, EndpointAddress target, SecurityToken currentToken)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecuritySessionRequestorStartOperation, SR.GetString(SR.TraceCodeSecuritySessionRequestorStartOperation), new SessionRequestorTraceRecord(operation, currentToken, (GenericXmlSecurityToken)null, target));
}
internal static void TraceSecuritySessionOperationSuccess(SecuritySessionOperation operation, EndpointAddress target, SecurityToken currentToken, SecurityToken issuedToken)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecuritySessionRequestorOperationSuccess, SR.GetString(SR.TraceCodeSecuritySessionRequestorOperationSuccess), new SessionRequestorTraceRecord(operation, currentToken, issuedToken, target));
}
internal static void TraceSecuritySessionOperationFailure(SecuritySessionOperation operation, EndpointAddress target, SecurityToken currentToken, Exception e)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecuritySessionRequestorOperationFailure, SR.GetString(SR.TraceCodeSecuritySessionRequestorOperationFailure), new SessionRequestorTraceRecord(operation, currentToken, e, target));
}
internal static void TraceServerSessionOperationException(SecuritySessionOperation operation, Exception e, Uri listenAddress)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecuritySessionResponderOperationFailure, SR.GetString(SR.TraceCodeSecuritySessionResponderOperationFailure), new SessionResponderTraceRecord(operation, e, listenAddress));
}
internal static void TraceImpersonationSucceeded(EventTraceActivity eventTraceActivity, DispatchOperationRuntime operation)
{
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SecurityImpersonationSuccess, SR.GetString(SR.TraceCodeSecurityImpersonationSuccess), new ImpersonationTraceRecord(operation));
if (TD.SecurityImpersonationSuccessIsEnabled())
{
TD.SecurityImpersonationSuccess(eventTraceActivity);
}
}
internal static void TraceImpersonationFailed(EventTraceActivity eventTraceActivity, DispatchOperationRuntime operation, Exception e)
{
if (DiagnosticUtility.ShouldTraceWarning)
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.SecurityImpersonationFailure, SR.GetString(SR.TraceCodeSecurityImpersonationFailure), new ImpersonationTraceRecord(operation), e);
if (TD.SecurityImpersonationFailureIsEnabled())
{
TD.SecurityImpersonationFailure(eventTraceActivity);
}
}
static void WritePossibleGenericXmlToken(XmlWriter writer, string startElement, SecurityToken token)
{
if (writer == null)
return;
writer.WriteStartElement(startElement);
GenericXmlSecurityToken gxt = token as GenericXmlSecurityToken;
if (gxt != null)
{
WriteGenericXmlToken(writer, gxt);
}
else
{
if (token != null)
writer.WriteElementString("TokenType", token.GetType().ToString());
}
writer.WriteEndElement();
}
static void WriteGenericXmlToken(XmlWriter xml, SecurityToken sessiontoken)
{
if (xml == null || sessiontoken == null)
return;
xml.WriteElementString("SessionTokenType", sessiontoken.GetType().ToString());
xml.WriteElementString("ValidFrom", XmlConvert.ToString(sessiontoken.ValidFrom, XmlDateTimeSerializationMode.Utc));
xml.WriteElementString("ValidTo", XmlConvert.ToString(sessiontoken.ValidTo, XmlDateTimeSerializationMode.Utc));
GenericXmlSecurityToken token = sessiontoken as GenericXmlSecurityToken;
if (token != null)
{
if (token.InternalTokenReference != null)
{
xml.WriteElementString("InternalTokenReference", token.InternalTokenReference.ToString());
}
if (token.ExternalTokenReference != null)
{
xml.WriteElementString("ExternalTokenReference", token.ExternalTokenReference.ToString());
}
xml.WriteElementString("IssuedTokenElementName", token.TokenXml.LocalName);
xml.WriteElementString("IssuedTokenElementNamespace", token.TokenXml.NamespaceURI);
}
}
static void WriteSecurityContextToken(XmlWriter xml, SecurityContextSecurityToken token)
{
xml.WriteElementString("ContextId", token.ContextId.ToString());
if (token.KeyGeneration != null)
{
xml.WriteElementString("KeyGeneration", token.KeyGeneration.ToString());
}
}
static internal void WriteClaim(XmlWriter xml, Claim claim)
{
if (xml == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("xml");
if (claim != null)
{
xml.WriteStartElement("Claim");
if (null != DiagnosticUtility.DiagnosticTrace
&& null != DiagnosticUtility.DiagnosticTrace.TraceSource
&& DiagnosticUtility.DiagnosticTrace.ShouldLogPii)
{
//
// ClaimType
//
xml.WriteElementString("ClaimType", claim.ClaimType);
//
// Right
//
xml.WriteElementString("Right", claim.Right);
//
// Resource object type: most of time, it is a System.String
//
if (claim.Resource != null)
xml.WriteElementString("ResourceType", claim.Resource.GetType().ToString());
else
xml.WriteElementString("Resource", "null");
}
else
{
xml.WriteString(claim.GetType().AssemblyQualifiedName);
}
xml.WriteEndElement();
}
}
class SessionResponderTraceRecord : SecurityTraceRecord
{
SecuritySessionOperation operation;
Exception e;
Uri listenAddress;
public SessionResponderTraceRecord(SecuritySessionOperation operation, Exception e, Uri listenAddress)
: base("SecuritySession")
{
this.operation = operation;
this.e = e;
this.listenAddress = listenAddress;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
xml.WriteElementString("Operation", this.operation.ToString());
if (this.e != null)
{
xml.WriteElementString("Exception", e.ToString());
}
if (this.listenAddress != null)
xml.WriteElementString("ListenAddress", this.listenAddress.ToString());
}
}
class SessionRequestorTraceRecord : SecurityTraceRecord
{
SecuritySessionOperation operation;
SecurityToken currentToken;
SecurityToken issuedToken;
EndpointAddress target;
Exception e;
public SessionRequestorTraceRecord(SecuritySessionOperation operation, SecurityToken currentToken, SecurityToken issuedToken, EndpointAddress target)
: base("SecuritySession")
{
this.operation = operation;
this.currentToken = currentToken;
this.issuedToken = issuedToken;
this.target = target;
}
public SessionRequestorTraceRecord(SecuritySessionOperation operation, SecurityToken currentToken, Exception e, EndpointAddress target)
: base("SecuritySession")
{
this.operation = operation;
this.currentToken = currentToken;
this.e = e;
this.target = target;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
xml.WriteElementString("Operation", this.operation.ToString());
if (this.currentToken != null)
{
WritePossibleGenericXmlToken(xml, "SupportingToken", this.currentToken);
}
if (this.issuedToken != null)
{
WritePossibleGenericXmlToken(xml, "IssuedToken", this.issuedToken);
}
if (this.e != null)
{
xml.WriteElementString("Exception", e.ToString());
}
if (this.target != null)
{
xml.WriteElementString("RemoteAddress", this.target.ToString());
}
}
}
class ServerSessionTraceRecord : SecurityTraceRecord
{
SecurityContextSecurityToken currentSessionToken;
SecurityContextSecurityToken newSessionToken;
UniqueId sessionId;
Message message;
Uri listenAddress;
public ServerSessionTraceRecord(SecurityContextSecurityToken currentSessionToken, SecurityContextSecurityToken newSessionToken, Uri listenAddress)
: base("SecuritySession")
{
this.currentSessionToken = currentSessionToken;
this.newSessionToken = newSessionToken;
this.listenAddress = listenAddress;
}
public ServerSessionTraceRecord(SecurityContextSecurityToken currentSessionToken, Message message, Uri listenAddress)
: base("SecuritySession")
{
this.currentSessionToken = currentSessionToken;
this.message = message;
this.listenAddress = listenAddress;
}
public ServerSessionTraceRecord(SecurityContextSecurityToken currentSessionToken, Uri listenAddress)
: base("SecuritySession")
{
this.currentSessionToken = currentSessionToken;
this.listenAddress = listenAddress;
}
public ServerSessionTraceRecord(UniqueId sessionId, Uri listenAddress)
: base("SecuritySession")
{
this.sessionId = sessionId;
this.listenAddress = listenAddress;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.currentSessionToken != null)
{
xml.WriteStartElement("CurrentSessionToken");
WriteSecurityContextToken(xml, this.currentSessionToken);
xml.WriteEndElement();
}
if (this.newSessionToken != null)
{
xml.WriteStartElement("NewSessionToken");
WriteSecurityContextToken(xml, this.newSessionToken);
xml.WriteEndElement();
}
if (this.sessionId != null)
{
XmlHelper.WriteElementStringAsUniqueId(xml, "SessionId", this.sessionId);
}
if (this.message != null)
{
xml.WriteElementString("MessageAction", message.Headers.Action);
}
if (this.listenAddress != null)
{
xml.WriteElementString("ListenAddress", this.listenAddress.ToString());
}
}
}
class ClientSessionTraceRecord : SecurityTraceRecord
{
SecurityToken currentSessionToken;
SecurityToken previousSessionToken;
EndpointAddress remoteAddress;
public ClientSessionTraceRecord(SecurityToken currentSessionToken, SecurityToken previousSessionToken, EndpointAddress remoteAddress)
: base("SecuritySession")
{
this.currentSessionToken = currentSessionToken;
this.previousSessionToken = previousSessionToken;
this.remoteAddress = remoteAddress;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.remoteAddress != null)
xml.WriteElementString("RemoteAddress", remoteAddress.ToString());
if (this.currentSessionToken != null)
{
xml.WriteStartElement("CurrentSessionToken");
WriteGenericXmlToken(xml, this.currentSessionToken);
xml.WriteEndElement();
}
if (this.previousSessionToken != null)
{
xml.WriteStartElement("PreviousSessionToken");
WriteGenericXmlToken(xml, this.previousSessionToken);
xml.WriteEndElement();
}
}
}
class SessionRedirectAppliedTraceRecord : SecurityTraceRecord
{
EndpointAddress previousTarget;
EndpointAddress newTarget;
GenericXmlSecurityToken sessionToken;
public SessionRedirectAppliedTraceRecord(EndpointAddress previousTarget, EndpointAddress newTarget, GenericXmlSecurityToken sessionToken)
: base("SecuritySession")
{
this.previousTarget = previousTarget;
this.newTarget = newTarget;
this.sessionToken = sessionToken;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.previousTarget != null)
xml.WriteElementString("OriginalRemoteAddress", this.previousTarget.ToString());
if (this.newTarget != null)
xml.WriteElementString("NewRemoteAddress", this.newTarget.ToString());
if (this.sessionToken != null)
{
xml.WriteStartElement("SessionToken");
WriteGenericXmlToken(xml, this.sessionToken);
xml.WriteEndElement();
}
}
}
class SpnToSidMappingTraceRecord : SecurityTraceRecord
{
string spn;
Exception e;
public SpnToSidMappingTraceRecord(string spn, Exception e)
: base("SecurityIdentity")
{
this.spn = spn;
this.e = e;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.spn != null)
xml.WriteElementString("ServicePrincipalName", this.spn);
if (this.e != null)
xml.WriteElementString("Exception", this.e.ToString());
}
}
class MessageSecurityTraceRecord : SecurityTraceRecord
{
SecurityProtocol binding;
Message message;
public MessageSecurityTraceRecord(SecurityProtocol binding, Message message)
: base("SecurityProtocol")
{
this.binding = binding;
this.message = message;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.binding != null)
xml.WriteElementString("SecurityProtocol", this.binding.ToString());
if (this.message != null)
{
string action = this.message.Headers.Action;
Uri to = this.message.Headers.To;
EndpointAddress replyTo = this.message.Headers.ReplyTo;
UniqueId id = this.message.Headers.MessageId;
if (!String.IsNullOrEmpty(action))
{
xml.WriteElementString("Action", action);
}
if (to != null)
{
xml.WriteElementString("To", to.AbsoluteUri);
}
if (replyTo != null)
{
replyTo.WriteTo(this.message.Version.Addressing, xml);
}
if (id != null)
{
xml.WriteElementString("MessageId", id.ToString());
}
}
else
{
xml.WriteElementString("Message", "null");
}
}
}
class TokenProviderTraceRecord : SecurityTraceRecord
{
SecurityTokenProvider provider;
public TokenProviderTraceRecord(SecurityTokenProvider provider)
: base("SecurityTokenProvider")
{
this.provider = provider;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.provider != null)
xml.WriteElementString("SecurityTokenProvider", this.provider.ToString());
}
}
class TokenAuthenticatorTraceRecord : SecurityTraceRecord
{
SecurityTokenAuthenticator authenticator;
public TokenAuthenticatorTraceRecord(SecurityTokenAuthenticator authenticator)
: base("SecurityTokenAuthenticator")
{
this.authenticator = authenticator;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.authenticator != null)
xml.WriteElementString("SecurityTokenAuthenticator", this.authenticator.ToString());
}
}
class SecurityContextTokenCacheTraceRecord : SecurityTraceRecord
{
int capacity;
int pruningAmount;
public SecurityContextTokenCacheTraceRecord(int capacity, int pruningAmount)
: base("ServiceSecurityNegotiation")
{
this.capacity = capacity;
this.pruningAmount = pruningAmount;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
xml.WriteElementString("Capacity", this.capacity.ToString(NumberFormatInfo.InvariantInfo));
xml.WriteElementString("PruningAmount", this.pruningAmount.ToString(NumberFormatInfo.InvariantInfo));
}
}
class NegotiationAuthenticatorTraceRecord<T> : SecurityTraceRecord
where T : NegotiationTokenAuthenticatorState
{
NegotiationTokenAuthenticator<T> authenticator;
IChannelListener transportChannelListener;
SecurityContextSecurityToken serviceToken;
Exception e;
public NegotiationAuthenticatorTraceRecord(NegotiationTokenAuthenticator<T> authenticator, IChannelListener transportChannelListener)
: base("NegotiationTokenAuthenticator")
{
this.authenticator = authenticator;
this.transportChannelListener = transportChannelListener;
}
public NegotiationAuthenticatorTraceRecord(NegotiationTokenAuthenticator<T> authenticator, Exception e)
: base("NegotiationTokenAuthenticator")
{
this.authenticator = authenticator;
this.e = e;
}
public NegotiationAuthenticatorTraceRecord(NegotiationTokenAuthenticator<T> authenticator, SecurityContextSecurityToken serviceToken)
: base("NegotiationTokenAuthenticator")
{
this.authenticator = authenticator;
this.serviceToken = serviceToken;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.authenticator != null)
xml.WriteElementString("NegotiationTokenAuthenticator", base.XmlEncode(this.authenticator.ToString()));
if (this.authenticator != null && this.authenticator.ListenUri != null)
xml.WriteElementString("AuthenticatorListenUri", this.authenticator.ListenUri.AbsoluteUri);
if (this.serviceToken != null)
{
xml.WriteStartElement("SecurityContextSecurityToken");
WriteSecurityContextToken(xml, this.serviceToken);
xml.WriteEndElement();
}
if (this.transportChannelListener != null)
{
xml.WriteElementString("TransportChannelListener", base.XmlEncode(this.transportChannelListener.ToString()));
if (this.transportChannelListener.Uri != null)
xml.WriteElementString("ListenUri", this.transportChannelListener.Uri.AbsoluteUri);
}
if (this.e != null)
{
xml.WriteElementString("Exception", base.XmlEncode(e.ToString()));
}
}
}
class IdentityVerificationSuccessTraceRecord : SecurityTraceRecord
{
EndpointIdentity identity;
Claim claim;
Type identityVerifier;
public IdentityVerificationSuccessTraceRecord(EndpointIdentity identity, Claim claim, Type identityVerifier)
: base("ServiceIdentityVerification")
{
this.identity = identity;
this.claim = claim;
this.identityVerifier = identityVerifier;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
XmlDictionaryWriter xmlWriter = XmlDictionaryWriter.CreateDictionaryWriter(xml);
if (this.identityVerifier != null)
xml.WriteElementString("IdentityVerifierType", this.identityVerifier.ToString());
if (this.identity != null)
this.identity.WriteTo(xmlWriter);
if (this.claim != null)
SecurityTraceRecordHelper.WriteClaim(xmlWriter, this.claim);
}
}
class IdentityVerificationFailureTraceRecord : SecurityTraceRecord
{
EndpointIdentity identity;
AuthorizationContext authContext;
Type identityVerifier;
public IdentityVerificationFailureTraceRecord(EndpointIdentity identity, AuthorizationContext authContext, Type identityVerifier)
: base("ServiceIdentityVerification")
{
this.identity = identity;
this.authContext = authContext;
this.identityVerifier = identityVerifier;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
XmlDictionaryWriter xmlWriter = XmlDictionaryWriter.CreateDictionaryWriter(xml);
if (this.identityVerifier != null)
xml.WriteElementString("IdentityVerifierType", this.identityVerifier.ToString());
if (this.identity != null)
this.identity.WriteTo(xmlWriter);
if (this.authContext != null)
{
for (int i = 0; i < this.authContext.ClaimSets.Count; ++i)
{
ClaimSet claimSet = this.authContext.ClaimSets[i];
if (this.authContext.ClaimSets[i] == null)
continue;
for (int j = 0; j < claimSet.Count; ++j)
{
Claim claim = claimSet[j];
if (claimSet[j] == null)
continue;
xml.WriteStartElement("Claim");
// currently ClaimType and Right cannot be null. Just being defensive
if (claim.ClaimType != null)
xml.WriteElementString("ClaimType", claim.ClaimType);
else
xml.WriteElementString("ClaimType", "null");
if (claim.Right != null)
xml.WriteElementString("Right", claim.Right);
else
xml.WriteElementString("Right", "null");
if (claim.Resource != null)
xml.WriteElementString("ResourceType", claim.Resource.GetType().ToString());
else
xml.WriteElementString("Resource", "null");
xml.WriteEndElement();
}
}
}
}
}
class IdentityDeterminationSuccessTraceRecord : SecurityTraceRecord
{
EndpointIdentity identity;
EndpointAddress epr;
Type identityVerifier;
public IdentityDeterminationSuccessTraceRecord(EndpointAddress epr, EndpointIdentity identity, Type identityVerifier)
: base("ServiceIdentityDetermination")
{
this.identity = identity;
this.epr = epr;
this.identityVerifier = identityVerifier;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.identityVerifier != null)
xml.WriteElementString("IdentityVerifierType", this.identityVerifier.ToString());
if (this.identity != null)
this.identity.WriteTo(XmlDictionaryWriter.CreateDictionaryWriter(xml));
if (this.epr != null)
this.epr.WriteTo(AddressingVersion.WSAddressing10, xml);
}
}
class IdentityDeterminationFailureTraceRecord : SecurityTraceRecord
{
Type identityVerifier;
EndpointAddress epr;
public IdentityDeterminationFailureTraceRecord(EndpointAddress epr, Type identityVerifier)
: base("ServiceIdentityDetermination")
{
this.epr = epr;
this.identityVerifier = identityVerifier;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.identityVerifier != null)
xml.WriteElementString("IdentityVerifierType", this.identityVerifier.ToString());
if (this.epr != null)
this.epr.WriteTo(AddressingVersion.WSAddressing10, xml);
}
}
class IdentityHostNameNormalizationFailureTraceRecord : SecurityTraceRecord
{
Type identityVerifier;
Exception e;
EndpointAddress epr;
public IdentityHostNameNormalizationFailureTraceRecord(EndpointAddress epr, Type identityVerifier, Exception e)
: base("ServiceIdentityDetermination")
{
this.epr = epr;
this.identityVerifier = identityVerifier;
this.e = e;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.identityVerifier != null)
xml.WriteElementString("IdentityVerifierType", this.identityVerifier.ToString());
if (this.epr != null)
this.epr.WriteTo(AddressingVersion.WSAddressing10, xml);
if (e != null)
xml.WriteElementString("Exception", e.ToString());
}
}
class IssuanceProviderTraceRecord<T> : SecurityTraceRecord
where T : IssuanceTokenProviderState
{
IssuanceTokenProviderBase<T> provider;
EndpointAddress target;
EndpointAddress newTarget;
SecurityToken serviceToken;
int cacheSize;
public IssuanceProviderTraceRecord(IssuanceTokenProviderBase<T> provider, SecurityToken serviceToken)
: this(provider, serviceToken, null)
{ }
public IssuanceProviderTraceRecord(IssuanceTokenProviderBase<T> provider, EndpointAddress target)
: this(provider, (SecurityToken)null, target)
{ }
public IssuanceProviderTraceRecord(IssuanceTokenProviderBase<T> provider, SecurityToken serviceToken, EndpointAddress target)
: base("ClientSecurityNegotiation")
{
this.provider = provider;
this.serviceToken = serviceToken;
this.target = target;
}
public IssuanceProviderTraceRecord(IssuanceTokenProviderBase<T> provider, EndpointAddress newTarget, EndpointAddress oldTarget)
: base("ClientSecurityNegotiation")
{
this.provider = provider;
this.newTarget = newTarget;
this.target = oldTarget;
}
public IssuanceProviderTraceRecord(IssuanceTokenProviderBase<T> provider, int cacheSize)
: base("ClientSecurityNegotiation")
{
this.provider = provider;
this.cacheSize = cacheSize;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.provider != null)
xml.WriteElementString("IssuanceTokenProvider", this.provider.ToString());
if (this.serviceToken != null)
WritePossibleGenericXmlToken(xml, "ServiceToken", this.serviceToken);
if (this.target != null)
{
xml.WriteStartElement("Target");
this.target.WriteTo(AddressingVersion.WSAddressing10, xml);
xml.WriteEndElement();
}
if (this.newTarget != null)
{
xml.WriteStartElement("PinnedTarget");
this.newTarget.WriteTo(AddressingVersion.WSAddressing10, xml);
xml.WriteEndElement();
}
if (this.cacheSize != 0)
{
xml.WriteElementString("CacheSize", this.cacheSize.ToString(NumberFormatInfo.InvariantInfo));
}
}
}
class WindowsSspiNegotiationTraceRecord : SecurityTraceRecord
{
WindowsSspiNegotiation windowsNegotiation;
public WindowsSspiNegotiationTraceRecord(WindowsSspiNegotiation windowsNegotiation)
: base("SpnegoSecurityNegotiation")
{
this.windowsNegotiation = windowsNegotiation;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
return;
if (this.windowsNegotiation != null)
{
xml.WriteElementString("Protocol", this.windowsNegotiation.ProtocolName);
xml.WriteElementString("ServicePrincipalName", this.windowsNegotiation.ServicePrincipalName);
xml.WriteElementString("MutualAuthentication", this.windowsNegotiation.IsMutualAuthFlag.ToString());
if (this.windowsNegotiation.IsIdentifyFlag)
{
xml.WriteElementString("ImpersonationLevel", "Identify");
}
else if (this.windowsNegotiation.IsDelegationFlag)
{
xml.WriteElementString("ImpersonationLevel", "Delegate");
}
else
{
xml.WriteElementString("ImpersonationLevel", "Impersonate");
}
}
}
}
class ImpersonationTraceRecord : SecurityTraceRecord
{
private DispatchOperationRuntime operation;
internal ImpersonationTraceRecord(DispatchOperationRuntime operation)
: base("SecurityImpersonation")
{
this.operation = operation;
}
internal override void WriteTo(XmlWriter xml)
{
if (xml == null)
{
// We are inside tracing. Don't throw an exception here just
// return.
return;
}
if (this.operation != null)
{
xml.WriteElementString("OperationAction", this.operation.Action);
xml.WriteElementString("OperationName", this.operation.Name);
}
}
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Reflection;
namespace Noesis
{
// In charge of preprocessing assets
public class BuildToolKernel: IDisposable
{
public BuildToolKernel(string platform)
{
library_ = new Library(UnityEngine.Application.dataPath + "/Editor/NoesisGUI/BuildTool/Noesis");
platform_ = platform.ToLower();
try
{
RegisterFunctions(library_);
Error.RegisterFunctions(library_);
Log.RegisterFunctions(library_);
_Extend.RegisterFunctions(library_);
_NoesisGUI_PINVOKE.RegisterFunctions(library_);
registerLogCallback_(OnLog);
_Extend.RegisterCallbacks();
initKernel_(platform_, UnityEngine.Application.dataPath, UnityEngine.Application.streamingAssetsPath);
Error.Check();
Log.Info(String.Format("Host is Unity v{0}", UnityEngine.Application.unityVersion));
_Extend.Initialized(true);
_Extend.RegisterNativeTypes();
}
catch(Exception e)
{
Dispose();
throw e;
}
}
~BuildToolKernel()
{
Dispose();
}
public void Dispose()
{
if (shutdownKernel_ != null)
{
_Extend.ResetDependencyProperties();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
_Extend.Initialized(false);
shutdownKernel_();
_Extend.UnregisterCallbacks();
UnregisterFunctions();
Error.UnregisterFunctions();
Log.UnregisterFunctions();
_Extend.UnregisterFunctions();
_NoesisGUI_PINVOKE.UnregisterFunctions();
library_.Dispose();
}
System.GC.SuppressFinalize(this);
}
private const string ErrorsKey = "NoesisErrors";
static public bool PendingErrors()
{
return PlayerPrefs.HasKey(ErrorsKey);
}
static public void BuildBegin()
{
assetBeingProcessed_ = "";
PlayerPrefs.DeleteKey(ErrorsKey);
// This is the dictionary used to avoid duplicated logs while building (xaml with errors can be built several times)
assetErrors_.Clear();
}
public static void Clean()
{
AssetDatabase.DeleteAsset("Assets/StreamingAssets/NoesisGUI");
AssetDatabase.DeleteAsset("Assets/Editor/NoesisGUI/assets.txt");
}
public static event Action<String> BuildEvent;
// Build all XAMLs and dependencies
public void BuildAll()
{
Log.Info(String.Format("BUILD {0}", platform_));
buildAll_();
Error.Check();
RefreshComponents();
}
// Builds known assets
public void BuildIncremental()
{
Log.Info(String.Format("BUILD {0}", platform_));
foreach (string asset in ReadAssets())
{
buildResource_(asset);
Error.Check();
}
RefreshComponents();
}
public static void AddAsset(string path)
{
var assets = ReadAssets();
assets.Add(path);
WriteAssets(assets);
}
public static void RemoveAsset(string path)
{
var assets = ReadAssets();
if (assets.Remove(path))
{
string directory = System.IO.Path.GetDirectoryName(path);
string filename = System.IO.Path.GetFileName(path);
foreach (var platform in NoesisSettings.ActivePlatforms)
{
string streamingAssetsDir = "Assets/StreamingAssets/NoesisGUI/" + platform + "/Assets/";
#if UNITY_4_5
string[] searchInFolders = {directory.Replace("Assets/", streamingAssetsDir)};
string[] guids = AssetDatabase.FindAssets(filename, searchInFolders);
foreach (var guid in guids)
{
AssetDatabase.DeleteAsset(AssetDatabase.GUIDToAssetPath(guid));
}
#else
string searchInFolder = directory.Replace("Assets/", streamingAssetsDir);
if (System.IO.Directory.Exists(searchInFolder))
{
string[] files = System.IO.Directory.GetFiles(searchInFolder);
foreach (var file in files)
{
if (System.IO.Path.GetExtension(file) != ".meta" &&
System.IO.Path.GetFileName(file).Contains(filename))
{
AssetDatabase.DeleteAsset(file);
}
}
}
#endif
}
}
WriteAssets(assets);
}
public static void RenameAsset(string from, string to)
{
var assets = ReadAssets();
if (assets.Contains(from))
{
assets.Remove(from);
assets.Add(to);
}
WriteAssets(assets);
}
public static bool AssetExists(string path)
{
return ReadAssets().Contains(path);
}
private void RefreshComponents()
{
// This could be improved a lot, because SetDirty notifies the inspector of a change but
// also marks the component to be serialized to disk. We could use a delegate to notity our
// custom editor.
// Although for now it doesn't seem to be necessary
UnityEngine.Object[] objs = UnityEngine.Object.FindObjectsOfType(typeof(NoesisGUIPanel));
foreach (UnityEngine.Object obj in objs)
{
NoesisGUIPanel noesisGUI = (NoesisGUIPanel)obj;
EditorUtility.SetDirty(noesisGUI);
}
PlayerPrefs.Save();
}
private void RegisterFunctions(Noesis.Library lib)
{
registerLogCallback_ = lib.Find<RegisterLogCallbackDelegate>("Noesis_RegisterLogCallback");
initKernel_ = lib.Find<InitKernelDelegate>("Noesis_InitBuildTool");
shutdownKernel_ = lib.Find<ShutdownKernelDelegate>("Noesis_ShutdownBuildTool");
buildAll_ = lib.Find<BuildAllDelegate>("Noesis_BuildAll");
buildResource_ = lib.Find<BuildResourceDelegate>("Noesis_BuildResource");
}
private void UnregisterFunctions()
{
registerLogCallback_ = null;
initKernel_ = null;
shutdownKernel_ = null;
buildAll_ = null;
buildResource_ = null;
}
public static HashSet<string> ReadAssets()
{
var assets = new HashSet<string>();
string filename = UnityEngine.Application.dataPath + "/Editor/NoesisGUI/assets.txt";
if (System.IO.File.Exists(filename))
{
string[] lines = System.IO.File.ReadAllLines(filename);
foreach (string s in lines)
{
assets.Add(s);
}
}
return assets;
}
private static void WriteAssets(HashSet<string> assets)
{
// Check assets.txt file exists in case package was deleted from the project
string filename = UnityEngine.Application.dataPath + "/Editor/NoesisGUI/assets.txt";
if (System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(filename)))
{
string[] lines = new string[assets.Count];
assets.CopyTo(lines);
System.IO.File.WriteAllLines(filename, lines);
}
}
private static string assetBeingProcessed_;
private static HashSet<string> assetErrors_ = new HashSet<string>();
[MonoPInvokeCallback (typeof(LogCallback))]
private static void OnLog(int severity, string message)
{
switch (severity)
{
case 0: // Critical
{
if (!String.IsNullOrEmpty(assetBeingProcessed_))
{
PlayerPrefs.SetInt(ErrorsKey, 1);
PlayerPrefs.SetString(assetBeingProcessed_ + "_error", message);
string key = assetBeingProcessed_ + "_error" + message;
if (!assetErrors_.Contains(key))
{
Debug.LogError(String.Format("[{0}] {1}\n{2}", platform_, assetBeingProcessed_, message));
assetErrors_.Add(key);
}
}
break;
}
case 10: // Warning
{
if (!String.IsNullOrEmpty(assetBeingProcessed_))
{
PlayerPrefs.SetString(assetBeingProcessed_ + "_warning", message);
string key = assetBeingProcessed_ + "_warning" + message;
if (!assetErrors_.Contains(key))
{
Debug.LogWarning(String.Format("[{0}] {1}\n{2}", platform_, assetBeingProcessed_, message));
assetErrors_.Add(key);
}
}
break;
}
case 20: // Info
{
int index = message.IndexOf(UnityEngine.Application.dataPath);
if (index != -1)
{
assetBeingProcessed_ = "Assets" + message.Substring(index + UnityEngine.Application.dataPath.Length);
PlayerPrefs.DeleteKey(assetBeingProcessed_ + "_warning");
PlayerPrefs.DeleteKey(assetBeingProcessed_ + "_error");
if (BuildEvent != null)
{
BuildEvent(assetBeingProcessed_);
}
AddAsset(assetBeingProcessed_);
}
break;
}
case 30: // Debug
{
break;
}
}
}
private Library library_ = null;
private static string platform_ = null;
private delegate void LogCallback(int severity, [MarshalAs(UnmanagedType.LPWStr)]string message);
private delegate void RegisterLogCallbackDelegate(LogCallback callback);
private RegisterLogCallbackDelegate registerLogCallback_ = null;
private delegate void InitKernelDelegate(string platform, [MarshalAs(UnmanagedType.LPWStr)]string assetsPath,
[MarshalAs(UnmanagedType.LPWStr)]string streamingAssetsPath);
private InitKernelDelegate initKernel_ = null;
private delegate void ShutdownKernelDelegate();
private ShutdownKernelDelegate shutdownKernel_ = null;
private delegate void BuildAllDelegate();
private BuildAllDelegate buildAll_ = null;
private delegate void BuildResourceDelegate([MarshalAs(UnmanagedType.LPWStr)]string resource);
private BuildResourceDelegate buildResource_ = null;
}
}
| |
using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using DNTProfiler.Common.Profiler;
using NHibernate.Impl;
namespace DNTProfiler.NHibernate.Core.Infrastructure
{
[System.ComponentModel.DesignerCategory("")]
public class ProfiledDbCommand : DbCommand, ICloneable
{
private readonly Guid _id = Guid.NewGuid();
private readonly IDbProfiler _profiler;
private DbConnection _connection;
private DbTransaction _transaction;
private readonly Stopwatch _stopwatch = Stopwatch.StartNew();
public ProfiledDbCommand(DbCommand command, DbConnection connection, IDbProfiler profiler)
{
if (command == null) throw new ArgumentNullException("command");
InternalCommand = command;
_connection = connection;
_profiler = profiler;
}
public int AffectedRows { set; get; }
public override string CommandText
{
get { return InternalCommand.CommandText; }
set { InternalCommand.CommandText = value; }
}
public override int CommandTimeout
{
get { return InternalCommand.CommandTimeout; }
set { InternalCommand.CommandTimeout = value; }
}
public override CommandType CommandType
{
get { return InternalCommand.CommandType; }
set { InternalCommand.CommandType = value; }
}
public DataTable DataRows { get; private set; }
public override bool DesignTimeVisible
{
get { return InternalCommand.DesignTimeVisible; }
set { InternalCommand.DesignTimeVisible = value; }
}
public Guid Id
{
get { return _id; }
}
public DbCommand InternalCommand { get; private set; }
public Guid? SessionId
{
get { return SessionIdLoggingContext.SessionId; }
}
public override UpdateRowSource UpdatedRowSource
{
get { return InternalCommand.UpdatedRowSource; }
set { InternalCommand.UpdatedRowSource = value; }
}
protected override DbConnection DbConnection
{
get
{
return _connection;
}
set
{
_connection = value;
var dbConnection = value as ProfiledDbConnection;
InternalCommand.Connection = dbConnection == null ? value : dbConnection.InnerConnection;
}
}
protected override DbParameterCollection DbParameterCollection
{
get { return InternalCommand.Parameters; }
}
protected override DbTransaction DbTransaction
{
get
{
return _transaction;
}
set
{
_transaction = value;
var awesomeTran = value as ProfiledDbTransaction;
InternalCommand.Transaction = awesomeTran == null ? value : awesomeTran.InnerTransaction;
}
}
public override void Cancel()
{
InternalCommand.Cancel();
}
public ProfiledDbCommand Clone()
{
var tail = InternalCommand as ICloneable;
if (tail == null) throw new NotSupportedException("Underlying " + InternalCommand.GetType().Name + " is not cloneable");
return new ProfiledDbCommand((DbCommand)tail.Clone(), _connection, _profiler);
}
public override int ExecuteNonQuery()
{
int result = 0;
var context = NHProfilerContextProvider.GetLoggedDbCommand(InternalCommand, null);
_profiler.NonQueryExecuting(InternalCommand, context);
_stopwatch.Restart();
try
{
result = InternalCommand.ExecuteNonQuery();
AffectedRows = result;
}
catch (Exception e)
{
context = NHProfilerContextProvider.GetLoggedDbCommand(InternalCommand, e);
_profiler.NonQueryExecuting(InternalCommand, context);
throw;
}
finally
{
_stopwatch.Stop();
context = NHProfilerContextProvider.GetLoggedResult(InternalCommand, null, result, _stopwatch.ElapsedMilliseconds, null);
_profiler.NonQueryExecuted(InternalCommand, context);
}
return result;
}
public override object ExecuteScalar()
{
object result = null;
var context = NHProfilerContextProvider.GetLoggedDbCommand(InternalCommand, null);
_profiler.ScalarExecuting(InternalCommand, context);
_stopwatch.Restart();
try
{
result = InternalCommand.ExecuteScalar();
}
catch (Exception e)
{
context = NHProfilerContextProvider.GetLoggedDbCommand(InternalCommand, e);
_profiler.ScalarExecuting(InternalCommand, context);
throw;
}
finally
{
_stopwatch.Stop();
context = NHProfilerContextProvider.GetLoggedResult(InternalCommand, null, result, _stopwatch.ElapsedMilliseconds, null);
_profiler.ScalarExecuted(InternalCommand, context);
}
return result;
}
object ICloneable.Clone()
{
return Clone();
}
public override void Prepare()
{
InternalCommand.Prepare();
}
protected override DbParameter CreateDbParameter()
{
return InternalCommand.CreateParameter();
}
protected override void Dispose(bool disposing)
{
if (disposing && InternalCommand != null)
{
InternalCommand.Dispose();
}
InternalCommand = null;
base.Dispose(disposing);
}
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
{
DbDataReader originalResult = null;
var context = NHProfilerContextProvider.GetLoggedDbCommand(InternalCommand, null);
_profiler.ReaderExecuting(InternalCommand, context);
_stopwatch.Restart();
try
{
originalResult = InternalCommand.ExecuteReader(behavior);
var dataSet = new DataSet { EnforceConstraints = false };
DataRows = new DataTable(tableName: Guid.NewGuid().ToString());
dataSet.Tables.Add(DataRows);
dataSet.Load(originalResult, LoadOption.OverwriteChanges, DataRows);
originalResult = DataRows.CreateDataReader();
}
catch (Exception e)
{
context = NHProfilerContextProvider.GetLoggedDbCommand(InternalCommand, e);
_profiler.ReaderExecuting(InternalCommand, context);
throw;
}
finally
{
_stopwatch.Stop();
context = NHProfilerContextProvider.GetLoggedResult(InternalCommand, null, originalResult, _stopwatch.ElapsedMilliseconds, DataRows);
_profiler.ReaderExecuted(InternalCommand, context);
}
return originalResult;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
using System.Text;
using ServiceStack.Text;
namespace ServiceStack.OrmLite
{
internal static class ReadExpressionCommandExtensions
{
internal static List<T> Select<T>(this IDbCommand dbCmd, SqlExpression<T> q)
{
string sql = q.SelectInto<T>();
return dbCmd.ExprConvertToList<T>(sql, q.Params, onlyFields: q.OnlyFields);
}
internal static List<T> Select<T>(this IDbCommand dbCmd, Expression<Func<T, bool>> predicate)
{
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
string sql = q.Where(predicate).SelectInto<T>();
return dbCmd.ExprConvertToList<T>(sql, q.Params);
}
internal static List<Tuple<T, T2>> SelectMulti<T, T2>(this IDbCommand dbCmd, SqlExpression<T> q)
{
q.SelectIfDistinct(q.CreateMultiSelect<T, T2, EOT, EOT, EOT, EOT, EOT>(dbCmd.GetDialectProvider()));
return dbCmd.ExprConvertToList<Tuple<T, T2>>(q.ToSelectStatement(), q.Params, onlyFields: q.OnlyFields);
}
internal static List<Tuple<T, T2, T3>> SelectMulti<T, T2, T3>(this IDbCommand dbCmd, SqlExpression<T> q)
{
q.SelectIfDistinct(q.CreateMultiSelect<T, T2, T3, EOT, EOT, EOT, EOT>(dbCmd.GetDialectProvider()));
return dbCmd.ExprConvertToList<Tuple<T, T2, T3>>(q.ToSelectStatement(), q.Params, onlyFields: q.OnlyFields);
}
internal static List<Tuple<T, T2, T3, T4>> SelectMulti<T, T2, T3, T4>(this IDbCommand dbCmd, SqlExpression<T> q)
{
q.SelectIfDistinct(q.CreateMultiSelect<T, T2, T3, T4, EOT, EOT, EOT>(dbCmd.GetDialectProvider()));
return dbCmd.ExprConvertToList<Tuple<T, T2, T3, T4>>(q.ToSelectStatement(), q.Params, onlyFields: q.OnlyFields);
}
internal static List<Tuple<T, T2, T3, T4, T5>> SelectMulti<T, T2, T3, T4, T5>(this IDbCommand dbCmd, SqlExpression<T> q)
{
q.SelectIfDistinct(q.CreateMultiSelect<T, T2, T3, T4, T5, EOT, EOT>(dbCmd.GetDialectProvider()));
return dbCmd.ExprConvertToList<Tuple<T, T2, T3, T4, T5>>(q.ToSelectStatement(), q.Params, onlyFields: q.OnlyFields);
}
internal static List<Tuple<T, T2, T3, T4, T5, T6>> SelectMulti<T, T2, T3, T4, T5, T6>(this IDbCommand dbCmd, SqlExpression<T> q)
{
q.SelectIfDistinct(q.CreateMultiSelect<T, T2, T3, T4, T5, T6, EOT>(dbCmd.GetDialectProvider()));
return dbCmd.ExprConvertToList<Tuple<T, T2, T3, T4, T5, T6>>(q.ToSelectStatement(), q.Params, onlyFields: q.OnlyFields);
}
internal static List<Tuple<T, T2, T3, T4, T5, T6, T7>> SelectMulti<T, T2, T3, T4, T5, T6, T7>(this IDbCommand dbCmd, SqlExpression<T> q)
{
q.SelectIfDistinct(q.CreateMultiSelect<T, T2, T3, T4, T5, T6, T7>(dbCmd.GetDialectProvider()));
return dbCmd.ExprConvertToList<Tuple<T, T2, T3, T4, T5, T6, T7>>(q.ToSelectStatement(), q.Params, onlyFields: q.OnlyFields);
}
internal static string CreateMultiSelect<T, T2, T3, T4, T5, T6, T7>(this SqlExpression<T> q, IOrmLiteDialectProvider dialectProvider)
{
var sb = StringBuilderCache.Allocate()
.Append($"{dialectProvider.GetQuotedTableName(typeof(T).GetModelDefinition())}.*, {Sql.EOT}");
if (typeof(T2) != typeof(EOT))
sb.Append($", {dialectProvider.GetQuotedTableName(typeof(T2).GetModelDefinition())}.*, {Sql.EOT}");
if (typeof(T3) != typeof(EOT))
sb.Append($", {dialectProvider.GetQuotedTableName(typeof(T3).GetModelDefinition())}.*, {Sql.EOT}");
if (typeof(T4) != typeof(EOT))
sb.Append($", {dialectProvider.GetQuotedTableName(typeof(T4).GetModelDefinition())}.*, {Sql.EOT}");
if (typeof(T5) != typeof(EOT))
sb.Append($", {dialectProvider.GetQuotedTableName(typeof(T5).GetModelDefinition())}.*, {Sql.EOT}");
if (typeof(T6) != typeof(EOT))
sb.Append($", {dialectProvider.GetQuotedTableName(typeof(T6).GetModelDefinition())}.*, {Sql.EOT}");
if (typeof(T7) != typeof(EOT))
sb.Append($", {dialectProvider.GetQuotedTableName(typeof(T7).GetModelDefinition())}.*, {Sql.EOT}");
return StringBuilderCache.ReturnAndFree(sb);
}
internal static string CreateMultiSelect(this ISqlExpression q, string[] tableSelects)
{
var sb = StringBuilderCache.Allocate();
foreach (var tableSelect in tableSelects)
{
if (sb.Length > 0)
sb.Append(", ");
sb.Append($"{tableSelect}, {Sql.EOT}");
}
return StringBuilderCache.ReturnAndFree(sb);
}
internal static List<Tuple<T, T2>> SelectMulti<T, T2>(this IDbCommand dbCmd, SqlExpression<T> q, string[] tableSelects)
{
return dbCmd.ExprConvertToList<Tuple<T, T2>>(q.Select(q.CreateMultiSelect(tableSelects)).ToSelectStatement(), q.Params, onlyFields: q.OnlyFields);
}
internal static List<Tuple<T, T2, T3>> SelectMulti<T, T2, T3>(this IDbCommand dbCmd, SqlExpression<T> q, string[] tableSelects)
{
return dbCmd.ExprConvertToList<Tuple<T, T2, T3>>(q.Select(q.CreateMultiSelect(tableSelects)).ToSelectStatement(), q.Params, onlyFields: q.OnlyFields);
}
internal static List<Tuple<T, T2, T3, T4>> SelectMulti<T, T2, T3, T4>(this IDbCommand dbCmd, SqlExpression<T> q, string[] tableSelects)
{
return dbCmd.ExprConvertToList<Tuple<T, T2, T3, T4>>(q.Select(q.CreateMultiSelect(tableSelects)).ToSelectStatement(), q.Params, onlyFields: q.OnlyFields);
}
internal static List<Tuple<T, T2, T3, T4, T5>> SelectMulti<T, T2, T3, T4, T5>(this IDbCommand dbCmd, SqlExpression<T> q, string[] tableSelects)
{
return dbCmd.ExprConvertToList<Tuple<T, T2, T3, T4, T5>>(q.Select(q.CreateMultiSelect(tableSelects)).ToSelectStatement(), q.Params, onlyFields: q.OnlyFields);
}
internal static List<Tuple<T, T2, T3, T4, T5, T6>> SelectMulti<T, T2, T3, T4, T5, T6>(this IDbCommand dbCmd, SqlExpression<T> q, string[] tableSelects)
{
return dbCmd.ExprConvertToList<Tuple<T, T2, T3, T4, T5, T6>>(q.Select(q.CreateMultiSelect(tableSelects)).ToSelectStatement(), q.Params, onlyFields: q.OnlyFields);
}
internal static List<Tuple<T, T2, T3, T4, T5, T6, T7>> SelectMulti<T, T2, T3, T4, T5, T6, T7>(this IDbCommand dbCmd, SqlExpression<T> q, string[] tableSelects)
{
return dbCmd.ExprConvertToList<Tuple<T, T2, T3, T4, T5, T6, T7>>(q.Select(q.CreateMultiSelect(tableSelects)).ToSelectStatement(), q.Params, onlyFields: q.OnlyFields);
}
internal static T Single<T>(this IDbCommand dbCmd, Expression<Func<T, bool>> predicate)
{
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
return Single(dbCmd, q.Where(predicate));
}
internal static T Single<T>(this IDbCommand dbCmd, SqlExpression<T> q)
{
string sql = q.Limit(1).SelectInto<T>();
return dbCmd.ExprConvertTo<T>(sql, q.Params, onlyFields:q.OnlyFields);
}
public static TKey Scalar<T, TKey>(this IDbCommand dbCmd, SqlExpression<T> expression)
{
var sql = expression.SelectInto<T>();
return dbCmd.Scalar<TKey>(sql, expression.Params);
}
public static TKey Scalar<T, TKey>(this IDbCommand dbCmd, Expression<Func<T, object>> field)
{
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
q.Select(field);
var sql = q.SelectInto<T>();
return dbCmd.Scalar<TKey>(sql, q.Params);
}
internal static TKey Scalar<T, TKey>(this IDbCommand dbCmd,
Expression<Func<T, object>> field, Expression<Func<T, bool>> predicate)
{
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
q.Select(field).Where(predicate);
string sql = q.SelectInto<T>();
return dbCmd.Scalar<TKey>(sql, q.Params);
}
internal static long Count<T>(this IDbCommand dbCmd)
{
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
var sql = q.ToCountStatement();
return GetCount(dbCmd, sql, q.Params);
}
internal static long Count<T>(this IDbCommand dbCmd, SqlExpression<T> expression)
{
var sql = expression.ToCountStatement();
return GetCount(dbCmd, sql, expression.Params);
}
internal static long Count<T>(this IDbCommand dbCmd, Expression<Func<T, bool>> predicate)
{
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
q.Where(predicate);
var sql = q.ToCountStatement();
return GetCount(dbCmd, sql, q.Params);
}
internal static long GetCount(this IDbCommand dbCmd, string sql)
{
return dbCmd.Column<long>(sql).Sum();
}
internal static long GetCount(this IDbCommand dbCmd, string sql, IEnumerable<IDbDataParameter> sqlParams)
{
return dbCmd.Column<long>(sql, sqlParams).Sum();
}
internal static long RowCount<T>(this IDbCommand dbCmd, SqlExpression<T> expression)
{
//ORDER BY throws when used in subselects in SQL Server. Removing OrderBy() clause since it doesn't impact results
var countExpr = expression.Clone().OrderBy();
return dbCmd.Scalar<long>(dbCmd.GetDialectProvider().ToRowCountStatement(countExpr.ToSelectStatement()), countExpr.Params);
}
internal static long RowCount(this IDbCommand dbCmd, string sql, object anonType)
{
if (anonType != null)
dbCmd.SetParameters(anonType.ToObjectDictionary(), excludeDefaults: false, sql:ref sql);
return dbCmd.Scalar<long>(dbCmd.GetDialectProvider().ToRowCountStatement(sql));
}
internal static long RowCount(this IDbCommand dbCmd, string sql, IEnumerable<IDbDataParameter> sqlParams)
{
return dbCmd.SetParameters(sqlParams).Scalar<long>(dbCmd.GetDialectProvider().ToRowCountStatement(sql));
}
internal static List<T> LoadSelect<T>(this IDbCommand dbCmd, SqlExpression<T> expression = null, IEnumerable<string> include = null)
{
return dbCmd.LoadListWithReferences<T, T>(expression, include);
}
internal static List<Into> LoadSelect<Into, From>(this IDbCommand dbCmd, SqlExpression<From> expression, IEnumerable<string> include = null)
{
return dbCmd.LoadListWithReferences<Into, From>(expression, include);
}
internal static List<T> LoadSelect<T>(this IDbCommand dbCmd, Expression<Func<T, bool>> predicate, IEnumerable<string> include = null)
{
var expr = dbCmd.GetDialectProvider().SqlExpression<T>().Where(predicate);
return dbCmd.LoadListWithReferences<T, T>(expr, include);
}
internal static DataTable GetSchemaTable(this IDbCommand dbCmd, string sql)
{
using (var reader = dbCmd.ExecReader(sql))
{
return reader.GetSchemaTable();
}
}
public static ColumnSchema[] GetTableColumns(this IDbCommand dbCmd, Type table) =>
dbCmd.GetTableColumns($"SELECT * FROM {dbCmd.GetDialectProvider().GetQuotedTableName(table.GetModelDefinition())}");
public static ColumnSchema[] GetTableColumns(this IDbCommand dbCmd, string sql) => dbCmd.GetSchemaTable(sql).ToColumnSchemas();
internal static ColumnSchema[] ToColumnSchemas(this DataTable dt)
{
var ret = new List<ColumnSchema>();
foreach (DataRow row in dt.Rows)
{
var obj = new Dictionary<string, object>();
foreach (DataColumn column in dt.Columns)
{
obj[column.ColumnName] = row[column.Ordinal];
}
var to = obj.FromObjectDictionary<ColumnSchema>();
ret.Add(to);
}
return ret.ToArray();
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Agent.Sdk;
using Microsoft.TeamFoundation.DistributedTask.Pipelines;
namespace Microsoft.VisualStudio.Services.Agent.Util
{
public static class RepositoryUtil
{
public static readonly string IsPrimaryRepository = "system.isprimaryrepository";
public static readonly string IsTriggeringRepository = "system.istriggeringrepository";
public static readonly string DefaultPrimaryRepositoryName = "self";
public static readonly string GitStandardBranchPrefix = "refs/heads/";
public static string TrimStandardBranchPrefix(string branchName)
{
if (!string.IsNullOrEmpty(branchName) && branchName.StartsWith(GitStandardBranchPrefix, StringComparison.OrdinalIgnoreCase))
{
return branchName.Substring(GitStandardBranchPrefix.Length);
}
return branchName;
}
/// <summary>
/// Returns true if the dictionary contains the 'HasMultipleCheckouts' key and the value is set to 'true'.
/// </summary>
public static bool HasMultipleCheckouts(Dictionary<string, string> jobSettings)
{
if (jobSettings != null && jobSettings.TryGetValue(WellKnownJobSettings.HasMultipleCheckouts, out string hasMultipleCheckoutsText))
{
return bool.TryParse(hasMultipleCheckoutsText, out bool hasMultipleCheckouts) && hasMultipleCheckouts;
}
return false;
}
/// <summary>
/// Returns true if the string matches the primary repository name (self)
/// </summary>
public static bool IsPrimaryRepositoryName(string repoAlias)
{
return string.Equals(repoAlias, DefaultPrimaryRepositoryName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// This method returns the repo from the list that is considered the primary repository.
/// If the list only contains 1 repo, then that is the primary repository.
/// If the list contains more than one, then we look for the repository marked as the primary repo.
/// It returns null, if no primary repository can be found.
/// </summary>
public static RepositoryResource GetPrimaryRepository(IList<RepositoryResource> repositories)
{
return GetWellKnownRepository(repositories, RepositoryUtil.IsPrimaryRepository);
}
/// <summary>
/// This method returns the repo from the list that is considered the triggering repository.
/// If the list only contains 1 repo, then that is the triggering repository.
/// If the list contains more than one, then we look for the repository marked as the triggering repo.
/// It returns null, if no triggering repository can be found.
/// </summary>
public static RepositoryResource GetTriggeringRepository(IList<RepositoryResource> repositories)
{
return GetWellKnownRepository(repositories, RepositoryUtil.IsTriggeringRepository);
}
private static RepositoryResource GetWellKnownRepository(IList<RepositoryResource> repositories, string repositoryFlagName)
{
if (repositories == null || !repositories.Any())
{
return null;
}
if (repositories.Count == 1)
{
return repositories.First();
}
// Look for any repository marked with the expected flag name
var repo = repositories.Where(r => r.Properties.Get<bool>(repositoryFlagName, false)).FirstOrDefault();
if (repo != null)
{
return repo;
}
else
{
// return the "self" repo or null
return GetRepository(repositories, DefaultPrimaryRepositoryName);
}
}
/// <summary>
/// This method returns the repository from the list that has a 'Path' that the localPath is parented to.
/// If the localPath is not part of any of the repo paths, null is returned.
/// </summary>
public static RepositoryResource GetRepositoryForLocalPath(IList<RepositoryResource> repositories, string localPath)
{
if (repositories == null || !repositories.Any() || String.IsNullOrEmpty(localPath))
{
return null;
}
if (repositories.Count == 1)
{
return repositories.First();
}
else
{
foreach (var repo in repositories)
{
var repoPath = repo.Properties.Get<string>(RepositoryPropertyNames.Path)?.TrimEnd(Path.DirectorySeparatorChar);
if (!string.IsNullOrEmpty(repoPath) &&
(localPath.Equals(repoPath, IOUtil.FilePathStringComparison)) ||
localPath.StartsWith(repoPath + Path.DirectorySeparatorChar, IOUtil.FilePathStringComparison))
{
return repo;
}
}
}
return null;
}
/// <summary>
/// This method returns the repo matching the repo alias passed.
/// It returns null if that repo can't be found.
/// </summary>
public static RepositoryResource GetRepository(IList<RepositoryResource> repositories, string repoAlias)
{
if (repositories == null)
{
return null;
}
return repositories.FirstOrDefault(r => string.Equals(r.Alias, repoAlias, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// We can fairly easily determine a cloud provider like GitHub, Azure DevOps, or BitBucket.
/// Other providers are not easily guessed, So we return Azure Repos (aka Git)
/// </summary>
public static string GuessRepositoryType(string repositoryUrl)
{
if (string.IsNullOrEmpty(repositoryUrl))
{
return string.Empty;
}
if (repositoryUrl.IndexOf("github.com", StringComparison.OrdinalIgnoreCase) >= 0)
{
return RepositoryTypes.GitHub;
}
else if (repositoryUrl.IndexOf(".visualstudio.com", StringComparison.OrdinalIgnoreCase) >= 0
|| repositoryUrl.IndexOf("dev.azure.com", StringComparison.OrdinalIgnoreCase) >= 0)
{
if (repositoryUrl.IndexOf("/_git/", StringComparison.OrdinalIgnoreCase) >= 0)
{
return RepositoryTypes.Git;
}
return RepositoryTypes.Tfvc;
}
else if (repositoryUrl.IndexOf("bitbucket.org", StringComparison.OrdinalIgnoreCase) >= 0)
{
return RepositoryTypes.Bitbucket;
}
// Don't assume anything
return string.Empty;
}
/// <summary>
/// Returns the folder name that would be created by calling 'git.exe clone'.
/// This is just the relative folder name not a full path.
/// The repo name is used if provided, then repo url, and finally repo alias.
/// </summary>
public static string GetCloneDirectory(RepositoryResource repository)
{
ArgUtil.NotNull(repository, nameof(repository));
string repoName =
repository.Properties.Get<string>(RepositoryPropertyNames.Name) ??
repository.Url?.AbsoluteUri ??
repository.Alias;
return GetCloneDirectory(repoName);
}
/// <summary>
/// Returns the folder name that would be created by calling 'git.exe clone'.
/// This is just the relative folder name not a full path.
/// This can take a repo full name, partial name, or url as input.
/// </summary>
public static string GetCloneDirectory(string repoName)
{
// The logic here was inspired by what git.exe does
// see https://github.com/git/git/blob/4c86140027f4a0d2caaa3ab4bd8bfc5ce3c11c8a/builtin/clone.c#L213
ArgUtil.NotNullOrEmpty(repoName, nameof(repoName));
const string schemeSeparator = "://";
// skip any kind of scheme
int startPosition = repoName.IndexOf(schemeSeparator);
if (startPosition < 0)
{
// There is no scheme
startPosition = 0;
}
else
{
startPosition += schemeSeparator.Length;
}
// skip any auth info (ends with @)
int endPosition = repoName.Length - 1;
startPosition = repoName.SkipLastIndexOf('@', startPosition, endPosition, out _);
// trim any slashes or ".git" extension
endPosition = TrimSlashesAndExtension(repoName, endPosition);
// skip everything before the last path segment (ends with /)
startPosition = repoName.SkipLastIndexOf('/', startPosition, endPosition, out bool slashFound);
if (!slashFound)
{
// No slashes means we only have a host name, remove any trailing port number
endPosition = TrimPortNumber(repoName, endPosition, startPosition);
}
// Colons can also be path separators, so skip past the last colon
startPosition = repoName.SkipLastIndexOf(':', startPosition, endPosition, out _);
return repoName.Substring(startPosition, endPosition - startPosition + 1);
}
private static int TrimPortNumber(string buffer, int endIndex, int startIndex)
{
int lastColon = buffer.FinalIndexOf(':', startIndex, endIndex);
// Trim the rest of the string after the colon if it is empty or is all digits
if (lastColon >= 0 && (lastColon == endIndex || buffer.SubstringIsNumber(lastColon + 1, endIndex)))
{
return lastColon - 1;
}
return endIndex;
}
private static int TrimSlashesAndExtension(string buffer, int endIndex)
{
if (buffer == null || endIndex < 0 || endIndex >= buffer.Length)
{
return endIndex;
}
// skip ending slashes or whitespace
while (endIndex > 0 && (buffer[endIndex] == '/' || char.IsWhiteSpace(buffer[endIndex])))
{
endIndex--;
}
const string gitExtension = ".git";
int possibleExtensionStart = endIndex - gitExtension.Length + 1;
if (possibleExtensionStart >= 0 && gitExtension.Equals(buffer.Substring(possibleExtensionStart, gitExtension.Length), StringComparison.OrdinalIgnoreCase))
{
// We found the .git extension
endIndex -= gitExtension.Length;
}
// skip ending slashes or whitespace
while (endIndex > 0 && (buffer[endIndex] == '/' || char.IsWhiteSpace(buffer[endIndex])))
{
endIndex--;
}
return endIndex;
}
private static int SkipLastIndexOf(this string buffer, char charToSearchFor, int startIndex, int endIndex, out bool charFound)
{
int index = buffer.FinalIndexOf(charToSearchFor, startIndex, endIndex);
if (index >= 0 && index < endIndex)
{
// Start after the char we found
charFound = true;
return index + 1;
}
charFound = false;
return startIndex;
}
private static int FinalIndexOf(this string buffer, char charToSearchFor, int startIndex, int endIndex)
{
if (buffer == null || startIndex < 0 || endIndex < 0 || startIndex >= buffer.Length || endIndex >= buffer.Length)
{
return -1;
}
return buffer.LastIndexOf(charToSearchFor, endIndex, endIndex - startIndex + 1);
}
private static bool SubstringIsNumber(this string buffer, int startIndex, int endIndex)
{
if (buffer == null || startIndex < 0 || endIndex < 0 || startIndex >= buffer.Length || endIndex >= buffer.Length || startIndex > endIndex)
{
return false;
}
for (int i = startIndex; i <= endIndex; i++)
{
if (!char.IsDigit(buffer[i]))
{
return false;
}
}
return true;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Configuration
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Client;
/// <summary>
/// Client connector configuration (ODBC, JDBC, Thin Client).
/// </summary>
public class ClientConnectorConfiguration
{
/// <summary>
/// Default port.
/// </summary>
public const int DefaultPort = 10800;
/// <summary>
/// Default port range.
/// </summary>
public const int DefaultPortRange = 100;
/// <summary>
/// Default socket buffer size.
/// </summary>
public const int DefaultSocketBufferSize = 0;
/// <summary>
/// Default value of <see cref="TcpNoDelay" /> property.
/// </summary>
public const bool DefaultTcpNoDelay = true;
/// <summary>
/// Default maximum number of open cursors per connection.
/// </summary>
public const int DefaultMaxOpenCursorsPerConnection = 128;
/// <summary>
/// Default SQL connector thread pool size.
/// </summary>
public static readonly int DefaultThreadPoolSize = IgniteConfiguration.DefaultThreadPoolSize;
/// <summary>
/// Default idle timeout.
/// </summary>
public static readonly TimeSpan DefaultIdleTimeout = TimeSpan.Zero;
/// <summary>
/// Default handshake timeout.
/// </summary>
public static readonly TimeSpan DefaultHandshakeTimeout = TimeSpan.FromSeconds(10);
/// <summary>
/// Default value for <see cref="ThinClientEnabled"/> property.
/// </summary>
public const bool DefaultThinClientEnabled = true;
/// <summary>
/// Default value for <see cref="JdbcEnabled"/> property.
/// </summary>
public const bool DefaultJdbcEnabled = true;
/// <summary>
/// Default value for <see cref="OdbcEnabled"/> property.
/// </summary>
public const bool DefaultOdbcEnabled = true;
/// <summary>
/// Initializes a new instance of the <see cref="ClientConnectorConfiguration"/> class.
/// </summary>
public ClientConnectorConfiguration()
{
Port = DefaultPort;
PortRange = DefaultPortRange;
SocketSendBufferSize = DefaultSocketBufferSize;
SocketReceiveBufferSize = DefaultSocketBufferSize;
TcpNoDelay = DefaultTcpNoDelay;
MaxOpenCursorsPerConnection = DefaultMaxOpenCursorsPerConnection;
ThreadPoolSize = DefaultThreadPoolSize;
IdleTimeout = DefaultIdleTimeout;
HandshakeTimeout = DefaultHandshakeTimeout;
ThinClientEnabled = DefaultThinClientEnabled;
OdbcEnabled = DefaultOdbcEnabled;
JdbcEnabled = DefaultJdbcEnabled;
}
/// <summary>
/// Initializes a new instance of the <see cref="ClientConnectorConfiguration"/> class.
/// </summary>
internal ClientConnectorConfiguration(ClientProtocolVersion ver, IBinaryRawReader reader)
{
Debug.Assert(reader != null);
Host = reader.ReadString();
Port = reader.ReadInt();
PortRange = reader.ReadInt();
SocketSendBufferSize = reader.ReadInt();
SocketReceiveBufferSize = reader.ReadInt();
TcpNoDelay = reader.ReadBoolean();
MaxOpenCursorsPerConnection = reader.ReadInt();
ThreadPoolSize = reader.ReadInt();
IdleTimeout = reader.ReadLongAsTimespan();
ThinClientEnabled = reader.ReadBoolean();
OdbcEnabled = reader.ReadBoolean();
JdbcEnabled = reader.ReadBoolean();
if (ver.CompareTo(ClientSocket.Ver130) >= 0) {
HandshakeTimeout = reader.ReadLongAsTimespan();
}
}
/// <summary>
/// Writes to the specified writer.
/// </summary>
internal void Write(ClientProtocolVersion ver, IBinaryRawWriter writer)
{
Debug.Assert(writer != null);
writer.WriteString(Host);
writer.WriteInt(Port);
writer.WriteInt(PortRange);
writer.WriteInt(SocketSendBufferSize);
writer.WriteInt(SocketReceiveBufferSize);
writer.WriteBoolean(TcpNoDelay);
writer.WriteInt(MaxOpenCursorsPerConnection);
writer.WriteInt(ThreadPoolSize);
writer.WriteTimeSpanAsLong(IdleTimeout);
writer.WriteBoolean(ThinClientEnabled);
writer.WriteBoolean(OdbcEnabled);
writer.WriteBoolean(JdbcEnabled);
if (ver.CompareTo(ClientSocket.Ver130) >= 0) {
writer.WriteTimeSpanAsLong(HandshakeTimeout);
}
}
/// <summary>
/// Gets or sets the host.
/// </summary>
public string Host { get; set; }
/// <summary>
/// Gets or sets the port.
/// </summary>
[DefaultValue(DefaultPort)]
public int Port { get; set; }
/// <summary>
/// Gets or sets the port range.
/// </summary>
[DefaultValue(DefaultPortRange)]
public int PortRange { get; set; }
/// <summary>
/// Gets or sets the size of the socket send buffer. When set to 0, operating system default is used.
/// </summary>
[DefaultValue(DefaultSocketBufferSize)]
public int SocketSendBufferSize { get; set; }
/// <summary>
/// Gets or sets the size of the socket receive buffer. When set to 0, operating system default is used.
/// </summary>
[DefaultValue(DefaultSocketBufferSize)]
public int SocketReceiveBufferSize { get; set; }
/// <summary>
/// Gets or sets the value for <c>TCP_NODELAY</c> socket option. Each
/// socket will be opened using provided value.
/// <para />
/// Setting this option to <c>true</c> disables Nagle's algorithm
/// for socket decreasing latency and delivery time for small messages.
/// <para />
/// For systems that work under heavy network load it is advisable to set this value to <c>false</c>.
/// </summary>
[DefaultValue(DefaultTcpNoDelay)]
public bool TcpNoDelay { get; set; }
/// <summary>
/// Gets or sets the maximum open cursors per connection.
/// </summary>
[DefaultValue(DefaultMaxOpenCursorsPerConnection)]
public int MaxOpenCursorsPerConnection { get; set; }
/// <summary>
/// Gets or sets the size of the thread pool.
/// </summary>
public int ThreadPoolSize { get; set; }
/// <summary>
/// Gets or sets idle timeout for client connections on the server side.
/// If no packets come within idle timeout, the connection is closed by the server.
/// Zero or negative means no timeout.
/// </summary>
public TimeSpan IdleTimeout { get; set; }
/// <summary>
/// Gets or sets handshake timeout for client connections on the server side.
/// If no successful handshake is performed within this timeout upon successful establishment of TCP connection
/// the connection is closed.
/// </summary>
public TimeSpan HandshakeTimeout { get; set; }
/// <summary>
/// Gets or sets a value indicating whether thin client connector is enabled.
/// </summary>
[DefaultValue(DefaultThinClientEnabled)]
public bool ThinClientEnabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether JDBC connector is enabled.
/// </summary>
[DefaultValue(DefaultJdbcEnabled)]
public bool JdbcEnabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether ODBC connector is enabled.
/// </summary>
[DefaultValue(DefaultOdbcEnabled)]
public bool OdbcEnabled { get; set; }
}
}
| |
// 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.Diagnostics;
using System.Globalization;
using System.Security.Principal;
using System.Security.Permissions;
using System.Collections.Generic;
using System.ComponentModel;
using System.Collections;
namespace System.DirectoryServices.AccountManagement
{
[System.Diagnostics.DebuggerDisplay("Name ( {Name} )")]
abstract public class Principal : IDisposable
{
//
// Public properties
//
[System.Security.SecurityCritical]
public override string ToString()
{
return Name;
}
// Context property
public PrincipalContext Context
{
[System.Security.SecuritySafeCritical]
get
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// The only way we can't have a PrincipalContext is if we're unpersisted
Debug.Assert(_ctx != null || this.unpersisted == true);
return _ctx;
}
}
// ContextType property
public ContextType ContextType
{
[System.Security.SecurityCritical]
get
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// The only way we can't have a PrincipalContext is if we're unpersisted
Debug.Assert(_ctx != null || this.unpersisted == true);
if (_ctx == null)
throw new InvalidOperationException(SR.PrincipalMustSetContextForProperty);
return _ctx.ContextType;
}
}
// Description property
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _description = null; // the actual property value
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _descriptionChanged = LoadState.NotSet; // change-tracking
public string Description
{
[System.Security.SecurityCritical]
get
{
return HandleGet<string>(ref _description, PropertyNames.PrincipalDescription, ref _descriptionChanged);
}
[System.Security.SecurityCritical]
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalDescription))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _description, value, ref _descriptionChanged, PropertyNames.PrincipalDescription);
}
}
// DisplayName property
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _displayName = null; // the actual property value
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _displayNameChanged = LoadState.NotSet; // change-tracking
public string DisplayName
{
[System.Security.SecurityCritical]
get
{
return HandleGet<string>(ref _displayName, PropertyNames.PrincipalDisplayName, ref _displayNameChanged);
}
[System.Security.SecurityCritical]
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalDisplayName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _displayName, value, ref _displayNameChanged, PropertyNames.PrincipalDisplayName);
}
}
//
// Convenience wrappers for the IdentityClaims property
// SAM Account Name
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _samName = null; // the actual property value
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _samNameChanged = LoadState.NotSet; // change-tracking
public string SamAccountName
{
[System.Security.SecurityCritical]
get
{
return HandleGet<string>(ref _samName, PropertyNames.PrincipalSamAccountName, ref _samNameChanged);
}
[System.Security.SecurityCritical]
set
{
if (null == value || 0 == value.Length)
throw new ArgumentNullException(String.Format(CultureInfo.CurrentCulture, SR.InvalidNullArgument, PropertyNames.PrincipalSamAccountName));
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalSamAccountName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _samName, value, ref _samNameChanged, PropertyNames.PrincipalSamAccountName);
}
}
// UPN
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _userPrincipalName = null; // the actual property value
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _userPrincipalNameChanged = LoadState.NotSet; // change-tracking
public string UserPrincipalName
{
[System.Security.SecurityCritical]
get
{
return HandleGet<string>(ref _userPrincipalName, PropertyNames.PrincipalUserPrincipalName, ref _userPrincipalNameChanged);
}
[System.Security.SecurityCritical]
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalUserPrincipalName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _userPrincipalName, value, ref _userPrincipalNameChanged, PropertyNames.PrincipalUserPrincipalName);
}
}
// SID
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private SecurityIdentifier _sid = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _sidChanged = LoadState.NotSet;
public SecurityIdentifier Sid
{
[System.Security.SecurityCritical]
get
{
return HandleGet<SecurityIdentifier>(ref _sid, PropertyNames.PrincipalSid, ref _sidChanged);
}
}
// GUID
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private Nullable<Guid> _guid = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _guidChanged = LoadState.NotSet;
public Nullable<Guid> Guid
{
[System.Security.SecurityCritical]
get
{
return HandleGet<Nullable<Guid>>(ref _guid, PropertyNames.PrincipalGuid, ref _guidChanged);
}
}
// DistinguishedName
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _distinguishedName = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _distinguishedNameChanged = LoadState.NotSet;
public string DistinguishedName
{
[System.Security.SecurityCritical]
get
{
return HandleGet<string>(ref _distinguishedName, PropertyNames.PrincipalDistinguishedName, ref _distinguishedNameChanged);
}
}
// DistinguishedName
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _structuralObjectClass = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _structuralObjectClassChanged = LoadState.NotSet;
public string StructuralObjectClass
{
[System.Security.SecurityCritical]
get
{
return HandleGet<string>(ref _structuralObjectClass, PropertyNames.PrincipalStructuralObjectClass, ref _structuralObjectClassChanged);
}
}
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _name = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _nameChanged = LoadState.NotSet;
public string Name
{
[System.Security.SecurityCritical]
get
{
// TODO Store should be mapping both to the same property already....
// TQ Special case to map name and SamAccountNAme to same cache variable.
// This should be removed in the future.
// Context type could be null for an unpersisted user.
// Default to the original domain behavior if a context is not set.
ContextType ct = (_ctx == null) ? ContextType.Domain : _ctx.ContextType;
if (ct == ContextType.Machine)
{
return HandleGet<string>(ref _samName, PropertyNames.PrincipalSamAccountName, ref _samNameChanged);
}
else
{
return HandleGet<string>(ref _name, PropertyNames.PrincipalName, ref _nameChanged);
}
}
[System.Security.SecurityCritical]
set
{
if (null == value || 0 == value.Length)
throw new ArgumentNullException(String.Format(CultureInfo.CurrentCulture, SR.InvalidNullArgument, PropertyNames.PrincipalName));
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
ContextType ct = (_ctx == null) ? ContextType.Domain : _ctx.ContextType;
if (ct == ContextType.Machine)
{
HandleSet<string>(ref _samName, value, ref _samNameChanged, PropertyNames.PrincipalSamAccountName);
}
else
{
HandleSet<string>(ref _name, value, ref _nameChanged, PropertyNames.PrincipalName);
}
}
}
private ExtensionHelper _extensionHelper;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal ExtensionHelper ExtensionHelper
{
get
{
if (null == _extensionHelper)
_extensionHelper = new ExtensionHelper(this);
return _extensionHelper;
}
}
//
// Public methods
//
[System.Security.SecurityCritical]
public static Principal FindByIdentity(PrincipalContext context, string identityValue)
{
return FindByIdentityWithType(context, typeof(Principal), identityValue);
}
[System.Security.SecurityCritical]
public static Principal FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
{
return FindByIdentityWithType(context, typeof(Principal), identityType, identityValue);
}
[System.Security.SecurityCritical]
public void Save()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Entering Save");
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
// We must have a PrincipalContext to save into. This should always be the case, unless we're unpersisted
// and they never set a PrincipalContext.
if (_ctx == null)
{
Debug.Assert(this.unpersisted == true);
throw new InvalidOperationException(SR.PrincipalMustSetContextForSave);
}
// Call the appropriate operation depending on whether this is an insert or update
StoreCtx storeCtxToUse = GetStoreCtxToUse();
Debug.Assert(storeCtxToUse != null); // since we know this.ctx isn't null
if (this.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save: inserting principal of type {0} using {1}", this.GetType(), storeCtxToUse.GetType());
Debug.Assert(storeCtxToUse == _ctx.ContextForType(this.GetType()));
storeCtxToUse.Insert(this);
this.unpersisted = false; // once we persist, we're no longer in the unpersisted state
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save: updating principal of type {0} using {1}", this.GetType(), storeCtxToUse.GetType());
Debug.Assert(storeCtxToUse == _ctx.QueryCtx);
storeCtxToUse.Update(this);
}
}
[System.Security.SecurityCritical]
public void Save(PrincipalContext context)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Entering Save(Context)");
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
if (context.ContextType == ContextType.Machine || _ctx.ContextType == ContextType.Machine)
{
throw new InvalidOperationException(SR.SaveToNotSupportedAgainstMachineStore);
}
// We must have a PrincipalContext to save into. This should always be the case, unless we're unpersisted
// and they never set a PrincipalContext.
if (context == null)
{
Debug.Assert(this.unpersisted == true);
throw new InvalidOperationException(SR.NullArguments);
}
// If the user is trying to save to the same context we are already set to then just save the changes
if (context == _ctx)
{
Save();
return;
}
// If we already have a context set on this object then make sure the new
// context is of the same type.
if (context.ContextType != _ctx.ContextType)
{
Debug.Assert(this.unpersisted == true);
throw new InvalidOperationException(SR.SaveToMustHaveSamecontextType);
}
StoreCtx originalStoreCtx = GetStoreCtxToUse();
_ctx = context;
// Call the appropriate operation depending on whether this is an insert or update
StoreCtx newStoreCtx = GetStoreCtxToUse();
Debug.Assert(newStoreCtx != null); // since we know this.ctx isn't null
Debug.Assert(originalStoreCtx != null); // since we know this.ctx isn't null
if (this.unpersisted)
{
// We have an unpersisted principal so we just want to create a principal in the new store.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save(context): inserting new principal of type {0} using {1}", this.GetType(), newStoreCtx.GetType());
Debug.Assert(newStoreCtx == _ctx.ContextForType(this.GetType()));
newStoreCtx.Insert(this);
this.unpersisted = false; // once we persist, we're no longer in the unpersisted state
}
else
{
// We have a principal that already exists. We need to move it to the new store.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save(context): Moving principal of type {0} using {1}", this.GetType(), newStoreCtx.GetType());
// we are now saving to a new store so this principal is unpersisted.
this.unpersisted = true;
// If the user has modified the name save away the current name so
// if the move succeeds and the update fails we will move the item back to the original
// store with the original name.
bool nameModified = _nameChanged == LoadState.Changed;
string previousName = null;
if (nameModified)
{
string newName = _name;
_ctx.QueryCtx.Load(this, PropertyNames.PrincipalName);
previousName = _name;
this.Name = newName;
}
newStoreCtx.Move(originalStoreCtx, this);
try
{
this.unpersisted = false; // once we persist, we're no longer in the unpersisted state
newStoreCtx.Update(this);
}
catch (System.SystemException e)
{
try
{
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Principal", "Save(context):, Update Failed (attempting to move back) Exception {0} ", e.Message);
if (nameModified)
this.Name = previousName;
originalStoreCtx.Move(newStoreCtx, this);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Move back succeeded");
}
catch (System.SystemException deleteFail)
{
// The move back failed. Just continue we will throw the original exception below.
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Principal", "Save(context):, Move back Failed {0} ", deleteFail.Message);
}
if (e is System.Runtime.InteropServices.COMException)
throw ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e);
else
throw e;
}
}
_ctx.QueryCtx = newStoreCtx; // so Updates go to the right StoreCtx
}
[System.Security.SecurityCritical]
public void Delete()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Entering Delete");
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
// If we're unpersisted, nothing to delete
if (this.unpersisted)
throw new InvalidOperationException(SR.PrincipalCantDeleteUnpersisted);
// Since we're not unpersisted, we must have come back from a query, and the query logic would
// have filled in a PrincipalContext on us.
Debug.Assert(_ctx != null);
_ctx.QueryCtx.Delete(this);
_isDeleted = true;
}
public override bool Equals(object o)
{
Principal that = o as Principal;
if (that == null)
return false;
if (Object.ReferenceEquals(this, that))
return true;
if ((_key != null) && (that._key != null) && (_key.Equals(that._key)))
return true;
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
[System.Security.SecurityCritical]
public object GetUnderlyingObject()
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
if (this.UnderlyingObject == null)
{
throw new InvalidOperationException(SR.PrincipalMustPersistFirst);
}
return this.UnderlyingObject;
}
[System.Security.SecurityCritical]
public Type GetUnderlyingObjectType()
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
if (this.unpersisted)
{
// If we're unpersisted, we can't determine the native type until our PrincipalContext has been set.
if (_ctx != null)
{
return _ctx.ContextForType(this.GetType()).NativeType(this);
}
else
{
throw new InvalidOperationException(SR.PrincipalMustSetContextForNative);
}
}
else
{
Debug.Assert(_ctx != null);
return _ctx.QueryCtx.NativeType(this);
}
}
[System.Security.SecurityCritical]
public PrincipalSearchResult<Principal> GetGroups()
{
return new PrincipalSearchResult<Principal>(GetGroupsHelper());
}
[System.Security.SecurityCritical]
public PrincipalSearchResult<Principal> GetGroups(PrincipalContext contextToQuery)
{
if (contextToQuery == null)
throw new ArgumentNullException("contextToQuery");
return new PrincipalSearchResult<Principal>(GetGroupsHelper(contextToQuery));
}
[System.Security.SecurityCritical]
public bool IsMemberOf(GroupPrincipal group)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
if (group == null)
throw new ArgumentNullException("group");
return group.Members.Contains(this);
}
[System.Security.SecurityCritical]
public bool IsMemberOf(PrincipalContext context, IdentityType identityType, string identityValue)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
if (context == null)
throw new ArgumentNullException("context");
if (identityValue == null)
throw new ArgumentNullException("identityValue");
GroupPrincipal g = GroupPrincipal.FindByIdentity(context, identityType, identityValue);
if (g != null)
{
return IsMemberOf(g);
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "IsMemberOf(urn/urn): no matching principal");
throw new NoMatchingPrincipalException(SR.NoMatchingGroupExceptionText);
}
}
//
// IDisposable
//
[System.Security.SecurityCritical]
public virtual void Dispose()
{
if (!_disposed)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Dispose: disposing");
if ((this.UnderlyingObject != null) && (this.UnderlyingObject is IDisposable))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Dispose: disposing underlying object");
((IDisposable)this.UnderlyingObject).Dispose();
}
if ((this.UnderlyingSearchObject != null) && (this.UnderlyingSearchObject is IDisposable))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Dispose: disposing underlying search object");
((IDisposable)this.UnderlyingSearchObject).Dispose();
}
_disposed = true;
GC.SuppressFinalize(this);
}
}
//
//
//
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
protected Principal()
{
}
//------------------------------------------------
// Protected functions for use by derived classes.
//------------------------------------------------
// Stores all values from derived classes for use at attributes or search filter.
private ExtensionCache _extensionCache = new ExtensionCache();
private LoadState _extensionCacheChanged = LoadState.NotSet;
[System.Security.SecurityCritical]
protected object[] ExtensionGet(string attribute)
{
if (null == attribute)
throw new ArgumentException(SR.NullArguments);
ExtensionCacheValue val;
if (_extensionCache.TryGetValue(attribute, out val))
{
if (val.Filter)
{
return null;
}
return val.Value;
}
else if (this.unpersisted)
{
return new object[0];
}
else
{
Debug.Assert(this.GetUnderlyingObjectType() == typeof(DirectoryEntry));
DirectoryEntry de = (DirectoryEntry)this.GetUnderlyingObject();
int valCount = de.Properties[attribute].Count;
if (valCount == 0)
return new object[0];
else
{
object[] objectArray = new object[valCount];
de.Properties[attribute].CopyTo(objectArray, 0);
return objectArray;
}
}
}
private void ValidateExtensionObject(object value)
{
if (value is object[])
{
if (((object[])value).Length == 0)
throw new ArgumentException(SR.InvalidExtensionCollectionType);
foreach (object o in (object[])value)
{
if (o is ICollection)
throw new ArgumentException(SR.InvalidExtensionCollectionType);
}
}
if (value is byte[])
{
if (((byte[])value).Length == 0)
{
throw new ArgumentException(SR.InvalidExtensionCollectionType);
}
}
else
{
if (value != null && value is ICollection)
{
ICollection collection = (ICollection)value;
if (collection.Count == 0)
throw new ArgumentException(SR.InvalidExtensionCollectionType);
foreach (object o in collection)
{
if (o is ICollection)
throw new ArgumentException(SR.InvalidExtensionCollectionType);
}
}
}
}
[System.Security.SecurityCritical]
protected void ExtensionSet(string attribute, object value)
{
if (null == attribute)
throw new ArgumentException(SR.NullArguments);
ValidateExtensionObject(value);
if (value is object[])
_extensionCache.properties[attribute] = new ExtensionCacheValue((object[])value);
else
_extensionCache.properties[attribute] = new ExtensionCacheValue(new object[] { value });
_extensionCacheChanged = LoadState.Changed;
}
[System.Security.SecurityCritical]
internal void AdvancedFilterSet(string attribute, object value, Type objectType, MatchType mt)
{
if (null == attribute)
throw new ArgumentException(SR.NullArguments);
ValidateExtensionObject(value);
if (value is object[])
_extensionCache.properties[attribute] = new ExtensionCacheValue((object[])value, objectType, mt);
else
_extensionCache.properties[attribute] = new ExtensionCacheValue(new object[] { value }, objectType, mt);
_extensionCacheChanged = LoadState.Changed; ;
}
//
// Internal implementation
//
// True indicates this is a new Principal object that has not yet been persisted to the store
internal bool unpersisted = false;
// True means our store object has been deleted
private bool _isDeleted = false;
// True means that StoreCtx.Load() has been called on this Principal to load in the values
// of all the delay-loaded properties.
private bool _loaded = false;
// True means this principal corresponds to one of the well-known SIDs that do not have a
// corresponding store object (e.g., NT AUTHORITY\NETWORK SERVICE). Such principals
// should be treated as read-only.
internal bool fakePrincipal = false;
// Directly corresponds to the Principal.PrincipalContext public property
[System.Security.SecuritySafeCritical]
private PrincipalContext _ctx = null;
internal bool Loaded
{
set
{
_loaded = value;
}
get
{
return _loaded;
}
}
// A low-level way for derived classes to access the ctx field. Note this is intended for internal use only,
// hence the LinkDemand.
[System.ComponentModel.Browsable(false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal protected PrincipalContext ContextRaw
{
//[StrongNameIdentityPermission(SecurityAction.LinkDemand, PublicKey = Microsoft.Internal.BuildInfo.WINDOWS_PUBLIC_KEY_STRING)]
[System.Security.SecurityCritical]
get
{ return _ctx; }
//[StrongNameIdentityPermission(SecurityAction.LinkDemand, PublicKey = Microsoft.Internal.BuildInfo.WINDOWS_PUBLIC_KEY_STRING)]
[System.Security.SecurityCritical]
set
{
// Verify that the passed context is not disposed.
if (value != null)
value.CheckDisposed();
_ctx = value;
}
}
static internal Principal MakePrincipal(PrincipalContext ctx, Type principalType)
{
Principal p = null;
System.Reflection.ConstructorInfo CI = principalType.GetConstructor(new Type[] { typeof(PrincipalContext) });
if (null == CI)
{
throw new NotSupportedException(SR.ExtensionInvalidClassDefinitionConstructor);
}
p = (Principal)CI.Invoke(new object[] { ctx });
if (null == p)
{
throw new NotSupportedException(SR.ExtensionInvalidClassDefinitionConstructor);
}
p.unpersisted = false;
return p;
}
// Depending on whether we're to-be-inserted or were retrieved from a query,
// returns the appropriate StoreCtx from the PrincipalContext that we should use for
// all StoreCtx-related operations.
// Returns null if no context has been set yet.
[System.Security.SecuritySafeCritical]
internal StoreCtx GetStoreCtxToUse()
{
if (_ctx == null)
{
Debug.Assert(this.unpersisted == true);
return null;
}
if (this.unpersisted)
{
return _ctx.ContextForType(this.GetType());
}
else
{
return _ctx.QueryCtx;
}
}
// The underlying object (e.g., DirectoryEntry, Item) corresponding to this Principal.
// Set by StoreCtx.GetAsPrincipal when this Principal was instantiated by it.
// If not set, this is a unpersisted principal and StoreCtx.PushChangesToNative()
// has not yet been called on it
private object _underlyingObject = null;
internal object UnderlyingObject
{
get
{
if (_underlyingObject != null)
return _underlyingObject;
return null;
}
set
{
_underlyingObject = value;
}
}
// The underlying search object (e.g., SearcResult, Item) corresponding to this Principal.
// Set by StoreCtx.GetAsPrincipal when this Principal was instantiated by it.
// If not set, this object was not created from a search. We need to store the searchresult until the object is persisted because
// we may need to load properties from it.
private object _underlyingSearchObject = null;
internal object UnderlyingSearchObject
{
get
{
if (_underlyingSearchObject != null)
return _underlyingSearchObject;
return null;
}
set
{
_underlyingSearchObject = value;
}
}
// Optional. This property exists entirely for the use of the StoreCtxs. When UnderlyingObject
// can correspond to more than one possible principal in the store (e.g., WinFS's "multiple principals
// per contact" model), the StoreCtx can use this to track and discern which principal in the
// UnderlyingObject this Principal object corresponds to. Set by GetAsPrincipal(), if set at all.
private object _discriminant = null;
internal object Discriminant
{
get { return _discriminant; }
set { _discriminant = value; }
}
// A store-specific key, used to determine if two CLR Principal objects represent the same store principal.
// Set by GetAsPrincipal when Principal is created from a query, or when a unpersisted Principal is persisted.
private StoreKey _key = null;
internal StoreKey Key
{
get { return _key; }
set { _key = value; }
}
private bool _disposed = false;
// Checks if the principal has been disposed or deleted, and throws an appropriate exception if it has.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Security.SecuritySafeCritical]
protected void CheckDisposedOrDeleted()
{
if (_disposed)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "CheckDisposedOrDeleted: accessing disposed object");
throw new ObjectDisposedException(this.GetType().ToString());
}
if (_isDeleted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "CheckDisposedOrDeleted: accessing deleted object");
throw new InvalidOperationException(SR.PrincipalDeleted);
}
}
[System.Security.SecurityCritical]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
protected static Principal FindByIdentityWithType(PrincipalContext context, Type principalType, string identityValue)
{
if (context == null)
throw new ArgumentNullException("context");
if (identityValue == null)
throw new ArgumentNullException("identityValue");
return FindByIdentityWithTypeHelper(context, principalType, null, identityValue, DateTime.UtcNow);
}
[System.Security.SecurityCritical]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
protected static Principal FindByIdentityWithType(PrincipalContext context, Type principalType, IdentityType identityType, string identityValue)
{
if (context == null)
throw new ArgumentNullException("context");
if (identityValue == null)
throw new ArgumentNullException("identityValue");
if ((identityType < IdentityType.SamAccountName) || (identityType > IdentityType.Guid))
throw new InvalidEnumArgumentException("identityType", (int)identityType, typeof(IdentityType));
return FindByIdentityWithTypeHelper(context, principalType, identityType, identityValue, DateTime.UtcNow);
}
[System.Security.SecurityCritical]
private static Principal FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable<IdentityType> identityType, string identityValue, DateTime refDate)
{
// Ask the store to find a Principal based on this IdentityReference info.
Principal p = context.QueryCtx.FindPrincipalByIdentRef(principalType, (identityType == null) ? null : (string)IdentMap.StringMap[(int)identityType, 1], identityValue, refDate);
// Did we find a match?
if (p != null)
{
// Given the native object, ask the StoreCtx to construct a Principal object for us.
return p;
}
else
{
// No match.
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "FindByIdentityWithTypeHelper: no match");
return null;
}
}
[System.Security.SecuritySafeCritical]
private ResultSet GetGroupsHelper()
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Unpersisted principals are not members of any group
if (this.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetGroupsHelper: returning empty set");
return new EmptySet();
}
StoreCtx storeCtx = GetStoreCtxToUse();
Debug.Assert(storeCtx != null);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetGroupsHelper: querying");
ResultSet resultSet = storeCtx.GetGroupsMemberOf(this);
return resultSet;
}
[System.Security.SecuritySafeCritical]
private ResultSet GetGroupsHelper(PrincipalContext contextToQuery)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
if (_ctx == null)
throw new InvalidOperationException(SR.UserMustSetContextForMethod);
StoreCtx storeCtx = GetStoreCtxToUse();
Debug.Assert(storeCtx != null);
return contextToQuery.QueryCtx.GetGroupsMemberOf(this, storeCtx);
}
// If we're the result of a query and our properties haven't been loaded yet, do so now
// We'd like this to be marked protected AND internal, but that's not possible, so we'll settle for
// internal and treat it as if it were also protected.
[System.Security.SecurityCritical]
internal void LoadIfNeeded(string principalPropertyName)
{
// Fake principals have nothing to load, since they have no store object.
// Just set the loaded flag.
if (this.fakePrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "LoadIfNeeded: not needed, fake principal");
Debug.Assert(this.unpersisted == false);
}
else if (!this.unpersisted)
{
// We came back from a query --> our PrincipalContext must be filled in
Debug.Assert(_ctx != null);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "LoadIfNeeded: loading");
// Just load the requested property...
_ctx.QueryCtx.Load(this, principalPropertyName);
}
}
// Checks if this is a fake principal, and throws an appropriate exception if so.
// We'd like this to be marked protected AND internal, but that's not possible, so we'll settle for
// internal and treat it as if it were also protected.
internal void CheckFakePrincipal()
{
if (this.fakePrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "CheckFakePrincipal: fake principal");
throw new InvalidOperationException(SR.PrincipalNotSupportedOnFakePrincipal);
}
}
// These methods implement the logic shared by all the get/set accessors for the public properties.
// We pass currentValue by ref, even though we don't directly modify it, because if the LoadIfNeeded()
// call causes the data to be loaded, we need to pick up the post-load value, not the (empty) value at the point
// HandleGet<T> was called.
//
// We'd like this to be marked protected AND internal, but that's not possible, so we'll settle for
// internal and treat it as if it were also protected.
[System.Security.SecurityCritical]
internal T HandleGet<T>(ref T currentValue, string name, ref LoadState state)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Check that we actually support this propery in our store
//CheckSupportedProperty(name);
if (state == LoadState.NotSet)
{
// Load in the value, if not yet done so
LoadIfNeeded(name);
state = LoadState.Loaded;
}
return currentValue;
}
// We'd like this to be marked protected AND internal, but that's not possible, so we'll settle for
// internal and treat it as if it were also protected.
[System.Security.SecurityCritical]
internal void HandleSet<T>(ref T currentValue, T newValue, ref LoadState state, string name)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Check that we actually support this propery in our store
//CheckSupportedProperty(name);
// Need to do this now so that newly-set value doesn't get overwritten by later load
// LoadIfNeeded(name);
currentValue = newValue;
state = LoadState.Changed;
}
//
// Load/Store implementation
//
//
// Loading with query results
//
// Given a property name like "Principal.DisplayName",
// writes the value into the internal field backing that property and
// resets the change-tracking for that property to "unchanged".
//
// If the property is a scalar property, then value is simply an object of the property type
// (e.g., a string for a string-valued property).
// If the property is an IdentityClaimCollection property, then value must be a List<IdentityClaim>.
// If the property is a ValueCollection<T>, then value must be a List<T>.
// If the property is a X509Certificate2Collection, then value must be a List<byte[]>, where
// each byte[] is a certificate.
// (The property can never be a PrincipalCollection, since such properties
// are not loaded by StoreCtx.Load()).
//[StrongNameIdentityPermission(SecurityAction.InheritanceDemand, PublicKey = Microsoft.Internal.BuildInfo.WINDOWS_PUBLIC_KEY_STRING)]
// ExtensionCache is never directly loaded by the store hence it does not exist in the switch
internal virtual void LoadValueIntoProperty(string propertyName, object value)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "LoadValueIntoProperty: name=" + propertyName + " value=" + (value == null ? "null" : value.ToString()));
switch (propertyName)
{
case PropertyNames.PrincipalDisplayName:
_displayName = (string)value;
_displayNameChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalDescription:
_description = (string)value;
_descriptionChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalSamAccountName:
_samName = (string)value;
_samNameChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalUserPrincipalName:
_userPrincipalName = (string)value;
_userPrincipalNameChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalSid:
SecurityIdentifier SID = (SecurityIdentifier)value;
_sid = SID;
_sidChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalGuid:
Guid PrincipalGuid = (Guid)value;
_guid = PrincipalGuid;
_guidChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalDistinguishedName:
_distinguishedName = (string)value;
_distinguishedNameChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalStructuralObjectClass:
_structuralObjectClass = (string)value;
_structuralObjectClassChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalName:
_name = (string)value;
_nameChanged = LoadState.Loaded;
break;
default:
// If we're here, we didn't find the property. They probably asked for a property we don't
// support (e.g., we're a Group, and they asked for PropertyNames.UserEmailAddress).
break;
}
}
//
// Getting changes to persist (or to build a query from a QBE filter)
//
// Given a property name, returns true if that property has changed since it was loaded, false otherwise.
//[StrongNameIdentityPermission(SecurityAction.InheritanceDemand, PublicKey = Microsoft.Internal.BuildInfo.WINDOWS_PUBLIC_KEY_STRING)]
[System.Security.SecuritySafeCritical]
internal virtual bool GetChangeStatusForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetChangeStatusForProperty: name=" + propertyName);
LoadState currentPropState;
switch (propertyName)
{
case PropertyNames.PrincipalDisplayName:
currentPropState = _displayNameChanged;
break;
case PropertyNames.PrincipalDescription:
currentPropState = _descriptionChanged;
break;
case PropertyNames.PrincipalSamAccountName:
currentPropState = _samNameChanged;
break;
case PropertyNames.PrincipalUserPrincipalName:
currentPropState = _userPrincipalNameChanged;
break;
case PropertyNames.PrincipalSid:
currentPropState = _sidChanged;
break;
case PropertyNames.PrincipalGuid:
currentPropState = _guidChanged;
break;
case PropertyNames.PrincipalDistinguishedName:
currentPropState = _distinguishedNameChanged;
break;
case PropertyNames.PrincipalStructuralObjectClass:
currentPropState = _structuralObjectClassChanged;
break;
case PropertyNames.PrincipalName:
currentPropState = _nameChanged;
break;
case PropertyNames.PrincipalExtensionCache:
currentPropState = _extensionCacheChanged;
break;
default:
// If we're here, we didn't find the property. They probably asked for a property we don't
// support (e.g., we're a User, and they asked for PropertyNames.GroupMembers). Since we don't
// have it, it didn't change.
currentPropState = LoadState.NotSet;
break;
}
return (currentPropState == LoadState.Changed);
}
// Given a property name, returns the current value for the property.
// Generally, this method is called only if GetChangeStatusForProperty indicates there are changes on the
// property specified.
//
// If the property is a scalar property, the return value is an object of the property type.
// If the property is an IdentityClaimCollection property, the return value is the IdentityClaimCollection
// itself.
// If the property is a ValueCollection<T>, the return value is the ValueCollection<T> itself.
// If the property is a X509Certificate2Collection, the return value is the X509Certificate2Collection itself.
// If the property is a PrincipalCollection, the return value is the PrincipalCollection itself.
//[StrongNameIdentityPermission(SecurityAction.InheritanceDemand, PublicKey = Microsoft.Internal.BuildInfo.WINDOWS_PUBLIC_KEY_STRING)]
internal virtual object GetValueForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetValueForProperty: name=" + propertyName);
switch (propertyName)
{
case PropertyNames.PrincipalDisplayName:
return _displayName;
case PropertyNames.PrincipalDescription:
return _description;
case PropertyNames.PrincipalSamAccountName:
return _samName;
case PropertyNames.PrincipalUserPrincipalName:
return _userPrincipalName;
case PropertyNames.PrincipalSid:
return _sid;
case PropertyNames.PrincipalGuid:
return _guid;
case PropertyNames.PrincipalDistinguishedName:
return _distinguishedName;
case PropertyNames.PrincipalStructuralObjectClass:
return _structuralObjectClass;
case PropertyNames.PrincipalName:
return _name;
case PropertyNames.PrincipalExtensionCache:
return _extensionCache;
default:
Debug.Fail(String.Format(CultureInfo.CurrentCulture, "Principal.GetValueForProperty: Ran off end of list looking for {0}", propertyName));
return null;
}
}
// Reset all change-tracking status for all properties on the object to "unchanged".
// This is used by StoreCtx.Insert() and StoreCtx.Update() to reset the change-tracking after they
// have persisted all current changes to the store.
//[StrongNameIdentityPermission(SecurityAction.InheritanceDemand, PublicKey = Microsoft.Internal.BuildInfo.WINDOWS_PUBLIC_KEY_STRING)]
internal virtual void ResetAllChangeStatus()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "ResetAllChangeStatus");
_displayNameChanged = (_displayNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_descriptionChanged = (_descriptionChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_samNameChanged = (_samNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_userPrincipalNameChanged = (_userPrincipalNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_sidChanged = (_sidChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_guidChanged = (_guidChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_distinguishedNameChanged = (_distinguishedNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_nameChanged = (_nameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_extensionCacheChanged = (_extensionCacheChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
}
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
namespace System.Collections.Immutable
{
/// <summary>
/// A set of initialization methods for instances of <see cref="ImmutableArray{T}"/>.
/// </summary>
public static class ImmutableArray
{
/// <summary>
/// A two element array useful for throwing exceptions the way LINQ does.
/// </summary>
internal static readonly byte[] TwoElementArray = new byte[2];
/// <summary>
/// Creates an empty <see cref="ImmutableArray{T}"/>.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <returns>An empty array.</returns>
[Pure]
public static ImmutableArray<T> Create<T>()
{
return ImmutableArray<T>.Empty;
}
/// <summary>
/// Creates an <see cref="ImmutableArray{T}"/> with the specified element as its only member.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="item">The element to store in the array.</param>
/// <returns>A 1-element array.</returns>
[Pure]
public static ImmutableArray<T> Create<T>(T item)
{
T[] array = new[] { item };
return new ImmutableArray<T>(array);
}
/// <summary>
/// Creates an <see cref="ImmutableArray{T}"/> with the specified elements.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="item1">The first element to store in the array.</param>
/// <param name="item2">The second element to store in the array.</param>
/// <returns>A 2-element array.</returns>
[Pure]
public static ImmutableArray<T> Create<T>(T item1, T item2)
{
T[] array = new[] { item1, item2 };
return new ImmutableArray<T>(array);
}
/// <summary>
/// Creates an <see cref="ImmutableArray{T}"/> with the specified elements.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="item1">The first element to store in the array.</param>
/// <param name="item2">The second element to store in the array.</param>
/// <param name="item3">The third element to store in the array.</param>
/// <returns>A 3-element array.</returns>
[Pure]
public static ImmutableArray<T> Create<T>(T item1, T item2, T item3)
{
T[] array = new[] { item1, item2, item3 };
return new ImmutableArray<T>(array);
}
/// <summary>
/// Creates an <see cref="ImmutableArray{T}"/> with the specified elements.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="item1">The first element to store in the array.</param>
/// <param name="item2">The second element to store in the array.</param>
/// <param name="item3">The third element to store in the array.</param>
/// <param name="item4">The fourth element to store in the array.</param>
/// <returns>A 4-element array.</returns>
[Pure]
public static ImmutableArray<T> Create<T>(T item1, T item2, T item3, T item4)
{
T[] array = new[] { item1, item2, item3, item4 };
return new ImmutableArray<T>(array);
}
/// <summary>
/// Creates an <see cref="ImmutableArray{T}"/> populated with the contents of the specified sequence.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="items">The elements to store in the array.</param>
/// <returns>An immutable array.</returns>
[Pure]
public static ImmutableArray<T> CreateRange<T>(IEnumerable<T> items)
{
Requires.NotNull(items, "items");
// As an optimization, if the provided enumerable is actually a
// boxed ImmutableArray<T> instance, reuse the underlying array if possible.
// Note that this allows for automatic upcasting and downcasting of arrays
// where the CLR allows it.
var immutableArray = items as IImmutableArray;
if (immutableArray != null)
{
immutableArray.ThrowInvalidOperationIfNotInitialized();
// immutableArray.Array must not be null at this point, and we know it's an
// ImmutableArray<T> or ImmutableArray<SomethingDerivedFromT> as they are
// the only types that could be both IEnumerable<T> and IImmutableArray.
// As such, we know that items is either an ImmutableArray<T> or
// ImmutableArray<TypeDerivedFromT>, and we can cast the array to T[].
return new ImmutableArray<T>((T[])immutableArray.Array);
}
// We don't recognize the source as an array that is safe to use.
// So clone the sequence into an array and return an immutable wrapper.
int count;
if (items.TryGetCount(out count))
{
if (count == 0)
{
// Return a wrapper around the singleton empty array.
return Create<T>();
}
else
{
// We know how long the sequence is. Linq's built-in ToArray extension method
// isn't as comprehensive in finding the length as we are, so call our own method
// to avoid reallocating arrays as the sequence is enumerated.
return new ImmutableArray<T>(items.ToArray(count));
}
}
else
{
return new ImmutableArray<T>(items.ToArray());
}
}
/// <summary>
/// Creates an empty <see cref="ImmutableArray{T}"/>.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="items">The elements to store in the array.</param>
/// <returns>An immutable array.</returns>
[Pure]
public static ImmutableArray<T> Create<T>(params T[] items)
{
if (items == null)
{
return Create<T>();
}
// We can't trust that the array passed in will never be mutated by the caller.
// The caller may have passed in an array explicitly (not relying on compiler params keyword)
// and could then change the array after the call, thereby violating the immutable
// guarantee provided by this struct. So we always copy the array to ensure it won't ever change.
return CreateDefensiveCopy(items);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The array to initialize the array with. A defensive copy is made.</param>
/// <param name="start">The index of the first element in the source array to include in the resulting array.</param>
/// <param name="length">The number of elements from the source array to include in the resulting array.</param>
/// <remarks>
/// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant
/// tax for copying an array when the new array is a segment of an existing array.
/// </remarks>
[Pure]
public static ImmutableArray<T> Create<T>(T[] items, int start, int length)
{
Requires.NotNull(items, "items");
Requires.Range(start >= 0 && start <= items.Length, "start");
Requires.Range(length >= 0 && start + length <= items.Length, "length");
if (length == 0)
{
// Avoid allocating an array.
return Create<T>();
}
var array = new T[length];
for (int i = 0; i < length; i++)
{
array[i] = items[start + i];
}
return new ImmutableArray<T>(array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The array to initialize the array with.
/// The selected array segment may be copied into a new array.</param>
/// <param name="start">The index of the first element in the source array to include in the resulting array.</param>
/// <param name="length">The number of elements from the source array to include in the resulting array.</param>
/// <remarks>
/// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant
/// tax for copying an array when the new array is a segment of an existing array.
/// </remarks>
[Pure]
public static ImmutableArray<T> Create<T>(ImmutableArray<T> items, int start, int length)
{
Requires.Range(start >= 0 && start <= items.Length, "start");
Requires.Range(length >= 0 && start + length <= items.Length, "length");
if (length == 0)
{
return Create<T>();
}
if (start == 0 && length == items.Length)
{
return items;
}
var array = new T[length];
Array.Copy(items.array, start, array, 0, length);
return new ImmutableArray<T>(array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The source array to initialize the resulting array with.</param>
/// <param name="selector">The function to apply to each element from the source array.</param>
/// <remarks>
/// This overload allows efficient creation of an <see cref="ImmutableArray{T}"/> based on an existing
/// <see cref="ImmutableArray{T}"/>, where a mapping function needs to be applied to each element from
/// the source array.
/// </remarks>
[Pure]
public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, Func<TSource, TResult> selector)
{
Requires.NotNull(selector, "selector");
int length = items.Length;
if (length == 0)
{
return Create<TResult>();
}
var array = new TResult[length];
for (int i = 0; i < length; i++)
{
array[i] = selector(items[i]);
}
return new ImmutableArray<TResult>(array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The source array to initialize the resulting array with.</param>
/// <param name="start">The index of the first element in the source array to include in the resulting array.</param>
/// <param name="length">The number of elements from the source array to include in the resulting array.</param>
/// <param name="selector">The function to apply to each element from the source array included in the resulting array.</param>
/// <remarks>
/// This overload allows efficient creation of an <see cref="ImmutableArray{T}"/> based on a slice of an existing
/// <see cref="ImmutableArray{T}"/>, where a mapping function needs to be applied to each element from the source array
/// included in the resulting array.
/// </remarks>
[Pure]
public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TResult> selector)
{
int itemsLength = items.Length;
Requires.Range(start >= 0 && start <= itemsLength, "start");
Requires.Range(length >= 0 && start + length <= itemsLength, "length");
Requires.NotNull(selector, "selector");
if (length == 0)
{
return Create<TResult>();
}
var array = new TResult[length];
for (int i = 0; i < length; i++)
{
array[i] = selector(items[i + start]);
}
return new ImmutableArray<TResult>(array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The source array to initialize the resulting array with.</param>
/// <param name="selector">The function to apply to each element from the source array.</param>
/// <param name="arg">An argument to be passed to the selector mapping function.</param>
/// <remarks>
/// This overload allows efficient creation of an <see cref="ImmutableArray{T}"/> based on an existing
/// <see cref="ImmutableArray{T}"/>, where a mapping function needs to be applied to each element from
/// the source array.
/// </remarks>
[Pure]
public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, Func<TSource, TArg, TResult> selector, TArg arg)
{
Requires.NotNull(selector, "selector");
int length = items.Length;
if (length == 0)
{
return Create<TResult>();
}
var array = new TResult[length];
for (int i = 0; i < length; i++)
{
array[i] = selector(items[i], arg);
}
return new ImmutableArray<TResult>(array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The source array to initialize the resulting array with.</param>
/// <param name="start">The index of the first element in the source array to include in the resulting array.</param>
/// <param name="length">The number of elements from the source array to include in the resulting array.</param>
/// <param name="selector">The function to apply to each element from the source array included in the resulting array.</param>
/// <param name="arg">An argument to be passed to the selector mapping function.</param>
/// <remarks>
/// This overload allows efficient creation of an <see cref="ImmutableArray{T}"/> based on a slice of an existing
/// <see cref="ImmutableArray{T}"/>, where a mapping function needs to be applied to each element from the source array
/// included in the resulting array.
/// </remarks>
[Pure]
public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TArg, TResult> selector, TArg arg)
{
int itemsLength = items.Length;
Requires.Range(start >= 0 && start <= itemsLength, "start");
Requires.Range(length >= 0 && start + length <= itemsLength, "length");
Requires.NotNull(selector, "selector");
if (length == 0)
{
return Create<TResult>();
}
var array = new TResult[length];
for (int i = 0; i < length; i++)
{
array[i] = selector(items[i + start], arg);
}
return new ImmutableArray<TResult>(array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}.Builder"/> class.
/// </summary>
/// <typeparam name="T">The type of elements stored in the array.</typeparam>
/// <returns>A new builder.</returns>
[Pure]
public static ImmutableArray<T>.Builder CreateBuilder<T>()
{
return Create<T>().ToBuilder();
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}.Builder"/> class.
/// </summary>
/// <typeparam name="T">The type of elements stored in the array.</typeparam>
/// <param name="initialCapacity">The size of the initial array backing the builder.</param>
/// <returns>A new builder.</returns>
[Pure]
public static ImmutableArray<T>.Builder CreateBuilder<T>(int initialCapacity)
{
return new ImmutableArray<T>.Builder(initialCapacity);
}
/// <summary>
/// Enumerates a sequence exactly once and produces an immutable array of its contents.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <param name="items">The sequence to enumerate.</param>
/// <returns>An immutable array.</returns>
[Pure]
public static ImmutableArray<TSource> ToImmutableArray<TSource>(this IEnumerable<TSource> items)
{
if (items is ImmutableArray<TSource>)
{
return (ImmutableArray<TSource>)items;
}
return CreateRange(items);
}
/// <summary>
/// Searches an entire one-dimensional sorted <see cref="ImmutableArray{T}"/> for a specific element,
/// using the <see cref="IComparable{T}"/> generic interface implemented by each element
/// of the <see cref="ImmutableArray{T}"/> and by the specified object.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="array">The sorted, one-dimensional array to search.</param>
/// <param name="value">The object to search for.</param>
/// <returns>
/// The index of the specified <paramref name="value"/> in the specified array, if <paramref name="value"/> is found.
/// If <paramref name="value"/> is not found and <paramref name="value"/> is less than one or more elements in array,
/// a negative number which is the bitwise complement of the index of the first
/// element that is larger than <paramref name="value"/>. If <paramref name="value"/> is not found and <paramref name="value"/> is greater
/// than any of the elements in array, a negative number which is the bitwise
/// complement of (the index of the last element plus 1).
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// <paramref name="value"/> does not implement the <see cref="IComparable{T}"/> generic interface, and
/// the search encounters an element that does not implement the <see cref="IComparable{T}"/>
/// generic interface.
/// </exception>
[Pure]
public static int BinarySearch<T>(this ImmutableArray<T> array, T value)
{
return Array.BinarySearch<T>(array.array, value);
}
/// <summary>
/// Searches an entire one-dimensional sorted <see cref="ImmutableArray{T}"/> for a value using
/// the specified <see cref="IComparer{T}"/> generic interface.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="array">The sorted, one-dimensional array to search.</param>
/// <param name="value">The object to search for.</param>
/// <param name="comparer">
/// The <see cref="IComparer{T}"/> implementation to use when comparing
/// elements; or null to use the <see cref="IComparable{T}"/> implementation of each
/// element.
/// </param>
/// <returns>
/// The index of the specified <paramref name="value"/> in the specified array, if <paramref name="value"/> is found.
/// If <paramref name="value"/> is not found and <paramref name="value"/> is less than one or more elements in array,
/// a negative number which is the bitwise complement of the index of the first
/// element that is larger than <paramref name="value"/>. If <paramref name="value"/> is not found and <paramref name="value"/> is greater
/// than any of the elements in array, a negative number which is the bitwise
/// complement of (the index of the last element plus 1).
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// <paramref name="comparer"/> is null, <paramref name="value"/> does not implement the <see cref="IComparable{T}"/> generic interface, and
/// the search encounters an element that does not implement the <see cref="IComparable{T}"/>
/// generic interface.
/// </exception>
[Pure]
public static int BinarySearch<T>(this ImmutableArray<T> array, T value, IComparer<T> comparer)
{
return Array.BinarySearch<T>(array.array, value, comparer);
}
/// <summary>
/// Searches a range of elements in a one-dimensional sorted <see cref="ImmutableArray{T}"/> for
/// a value, using the <see cref="IComparable{T}"/> generic interface implemented by
/// each element of the <see cref="ImmutableArray{T}"/> and by the specified value.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="array">The sorted, one-dimensional array to search.</param>
/// <param name="index">The starting index of the range to search.</param>
/// <param name="length">The length of the range to search.</param>
/// <param name="value">The object to search for.</param>
/// <returns>
/// The index of the specified <paramref name="value"/> in the specified <paramref name="array"/>, if <paramref name="value"/> is found.
/// If <paramref name="value"/> is not found and <paramref name="value"/> is less than one or more elements in <paramref name="array"/>,
/// a negative number which is the bitwise complement of the index of the first
/// element that is larger than <paramref name="value"/>. If <paramref name="value"/> is not found and <paramref name="value"/> is greater
/// than any of the elements in <paramref name="array"/>, a negative number which is the bitwise
/// complement of (the index of the last element plus 1).
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// <paramref name="value"/> does not implement the <see cref="IComparable{T}"/> generic interface, and
/// the search encounters an element that does not implement the <see cref="IComparable{T}"/>
/// generic interface.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="index"/> and <paramref name="length"/> do not specify a valid range in <paramref name="array"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than the lower bound of <paramref name="array"/>. -or- <paramref name="length"/> is less than zero.
/// </exception>
[Pure]
public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value)
{
return Array.BinarySearch<T>(array.array, index, length, value);
}
/// <summary>
/// Searches a range of elements in a one-dimensional sorted <see cref="ImmutableArray{T}"/> for
/// a value, using the specified <see cref="IComparer{T}"/> generic
/// interface.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="array">The sorted, one-dimensional array to search.</param>
/// <param name="index">The starting index of the range to search.</param>
/// <param name="length">The length of the range to search.</param>
/// <param name="value">The object to search for.</param>
/// <param name="comparer">
/// The <see cref="IComparer{T}"/> implementation to use when comparing
/// elements; or null to use the <see cref="IComparable{T}"/> implementation of each
/// element.
/// </param>
/// <returns>
/// The index of the specified <paramref name="value"/> in the specified <paramref name="array"/>, if <paramref name="value"/> is found.
/// If <paramref name="value"/> is not found and <paramref name="value"/> is less than one or more elements in <paramref name="array"/>,
/// a negative number which is the bitwise complement of the index of the first
/// element that is larger than <paramref name="value"/>. If <paramref name="value"/> is not found and <paramref name="value"/> is greater
/// than any of the elements in <paramref name="array"/>, a negative number which is the bitwise
/// complement of (the index of the last element plus 1).
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// <paramref name="comparer"/> is null, <paramref name="value"/> does not implement the <see cref="IComparable{T}"/> generic
/// interface, and the search encounters an element that does not implement the
/// <see cref="IComparable{T}"/> generic interface.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="index"/> and <paramref name="length"/> do not specify a valid range in <paramref name="array"/>.-or-<paramref name="comparer"/> is null,
/// and <paramref name="value"/> is of a type that is not compatible with the elements of <paramref name="array"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than the lower bound of <paramref name="array"/>. -or- <paramref name="length"/> is less than zero.
/// </exception>
[Pure]
public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value, IComparer<T> comparer)
{
return Array.BinarySearch<T>(array.array, index, length, value, comparer);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The array from which to copy.</param>
internal static ImmutableArray<T> CreateDefensiveCopy<T>(T[] items)
{
Debug.Assert(items != null);
if (items.Length == 0)
{
return ImmutableArray<T>.Empty; // use just a shared empty array, allowing the input array to be potentially GC'd
}
// defensive copy
var tmp = new T[items.Length];
Array.Copy(items, 0, tmp, 0, items.Length);
return new ImmutableArray<T>(tmp);
}
}
}
| |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using CoinSharp.Common;
using log4net;
namespace CoinSharp
{
/// <summary>
/// A NetworkConnection handles talking to a remote BitCoin peer at a low level. It understands how to read and write
/// messages off the network, but doesn't asynchronously communicate with the peer or handle the higher level details
/// of the protocol. After constructing a NetworkConnection, use a <see cref="Peer"/> to hand off communication to a
/// background thread.
/// </summary>
/// <remarks>
/// Construction is blocking whilst the protocol version is negotiated.
/// </remarks>
public class NetworkConnection : IDisposable
{
private static readonly ILog Log = Common.Logger.GetLoggerForDeclaringType();
private Socket _socket;
private Stream _out;
private Stream _in;
// The IP address to which we are connecting.
private readonly IPAddress remoteIp;
private readonly NetworkParameters _params;
private readonly VersionMessage versionMessage;
private readonly BitcoinSerializer serializer;
public NetworkConnection()
{
}
/// <summary>
/// Connect to the given IP address using the port specified as part of the network parameters. Once construction
/// is complete a functioning network channel is set up and running.
/// </summary>
/// <param name="peerAddress">IP address to connect to. IPv6 is not currently supported by BitCoin. If port is not positive the default port from params is used.</param>
/// <param name="networkParams">Defines which network to connect to and details of the protocol.</param>
/// <param name="bestHeight">How many blocks are in our best chain</param>
/// <param name="connectTimeout">Timeout in milliseconds when initially connecting to peer</param>
/// <exception cref="IOException">If there is a network related failure.</exception>
/// <exception cref="ProtocolException">If the version negotiation failed.</exception>
public NetworkConnection(PeerAddress peerAddress, NetworkParameters networkParams, uint bestHeight, int connectTimeout)
{
_params = networkParams;
remoteIp = peerAddress.Addr;
var port = (peerAddress.Port > 0) ? peerAddress.Port : networkParams.Port;
var address = new IPEndPoint(remoteIp, port);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(address);
_socket.SendTimeout = _socket.ReceiveTimeout = connectTimeout;
_out = new NetworkStream(_socket, FileAccess.Write);
_in = new NetworkStream(_socket, FileAccess.Read);
// the version message never uses check-summing. Update check-summing property after version is read.
serializer = new BitcoinSerializer(networkParams, true); // SDL: Checksuming now ALWAYS necessary
versionMessage = Handshake(networkParams, bestHeight);
// newer clients use check-summing
serializer.UseChecksumming(versionMessage.ClientVersion >= 209);
// Handshake is done!
}
private VersionMessage Handshake(NetworkParameters networkParams, uint bestHeight)
{
// Announce ourselves. This has to come first to connect to clients beyond v0.30.20.2 which wait to hear
// from us until they send their version message back.
WriteMessage(new VersionMessage(networkParams, bestHeight));
// When connecting, the remote peer sends us a version message with various bits of
// useful data in it. We need to know the peer protocol version before we can talk to it.
var versionMsg = (VersionMessage)ReadMessage();
// Now it's our turn ...
// Send an ACK message stating we accept the peers protocol version.
WriteMessage(new VersionAck());
// And get one back ...
ReadMessage();
// Switch to the new protocol version.
Log.InfoFormat("Connected to peer: version={0}, subVer='{1}', services=0x{2:X}, time={3}, blocks={4}",
versionMsg.ClientVersion,
versionMsg.SubVer,
versionMsg.LocalServices,
UnixTime.FromUnixTime(versionMsg.Time),
versionMsg.BestHeight);
// BitCoinSharp is a client mode implementation. That means there's not much point in us talking to other client
// mode nodes because we can't download the data from them we need to find/verify transactions.
if (!versionMsg.HasBlockChain())
{
// Shut down the socket
try
{
Shutdown();
}
catch (IOException)
{
// ignore exceptions while aborting
}
throw new ProtocolException("Peer does not have a copy of the block chain.");
}
return versionMsg;
}
/// <exception cref="IOException"/>
/// <exception cref="ProtocolException"/>
public NetworkConnection(IPAddress inetAddress, NetworkParameters networkParams, uint bestHeight, int connectTimeout)
: this(new PeerAddress(inetAddress), networkParams, bestHeight, connectTimeout)
{
}
/// <summary>
/// Sends a "ping" message to the remote node. The protocol doesn't presently use this feature much.
/// </summary>
/// <exception cref="IOException"/>
public void Ping()
{
WriteMessage(new Ping());
}
/// <summary>
/// Shuts down the network socket. Note that there's no way to wait for a socket to be fully flushed out to the
/// wire, so if you call this immediately after sending a message it might not get sent.
/// </summary>
/// <exception cref="IOException"/>
public virtual void Shutdown()
{
_socket.Disconnect(false);
_socket.Close();
}
public override string ToString()
{
return "[" + remoteIp + "]:" + _params.Port + " (" + (_socket.Connected ? "connected" : "disconnected") + ")";
}
/// <summary>
/// Reads a network message from the wire, blocking until the message is fully received.
/// </summary>
/// <returns>An instance of a Message subclass</returns>
/// <exception cref="ProtocolException">If the message is badly formatted, failed checksum or there was a TCP failure.</exception>
/// <exception cref="IOException"/>
public virtual Message ReadMessage()
{
return serializer.Deserialize(_in);
}
/// <summary>
/// Writes the given message out over the network using the protocol tag. For a Transaction
/// this should be "tx" for example. It's safe to call this from multiple threads simultaneously,
/// the actual writing will be serialized.
/// </summary>
/// <exception cref="IOException"/>
public virtual void WriteMessage(Message message)
{
lock (_out)
{
serializer.Serialize(message, _out);
}
}
/// <summary>
/// Returns the version message received from the other end of the connection during the handshake.
/// </summary>
public virtual VersionMessage VersionMessage
{
get { return versionMessage; }
}
#region IDisposable Members
public void Dispose()
{
if (_in != null)
{
_in.Dispose();
_in = null;
}
if (_out != null)
{
_out.Dispose();
_out = null;
}
if (_socket != null)
{
((IDisposable)_socket).Dispose();
_socket = null;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class.
/// </content>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableDictionary<TKey, TValue>
{
/// <summary>
/// A dictionary that mutates with little or no memory allocations,
/// can produce and/or build on immutable dictionary instances very efficiently.
/// </summary>
/// <remarks>
/// <para>
/// While <see cref="ImmutableDictionary{TKey, TValue}.AddRange(IEnumerable{KeyValuePair{TKey, TValue}})"/>
/// and other bulk change methods already provide fast bulk change operations on the collection, this class allows
/// multiple combinations of changes to be made to a set with equal efficiency.
/// </para>
/// <para>
/// Instance members of this class are <em>not</em> thread-safe.
/// </para>
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableDictionaryBuilderDebuggerProxy<,>))]
public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary
{
/// <summary>
/// The root of the binary tree that stores the collection. Contents are typically not entirely frozen.
/// </summary>
private SortedInt32KeyNode<HashBucket> _root = SortedInt32KeyNode<HashBucket>.EmptyNode;
/// <summary>
/// The comparers.
/// </summary>
private Comparers _comparers;
/// <summary>
/// The number of elements in this collection.
/// </summary>
private int _count;
/// <summary>
/// Caches an immutable instance that represents the current state of the collection.
/// </summary>
/// <value>Null if no immutable view has been created for the current version.</value>
private ImmutableDictionary<TKey, TValue> _immutable;
/// <summary>
/// A number that increments every time the builder changes its contents.
/// </summary>
private int _version;
/// <summary>
/// The object callers may use to synchronize access to this collection.
/// </summary>
private object _syncRoot;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class.
/// </summary>
/// <param name="map">The map that serves as the basis for this Builder.</param>
internal Builder(ImmutableDictionary<TKey, TValue> map)
{
Requires.NotNull(map, "map");
_root = map._root;
_count = map._count;
_comparers = map._comparers;
_immutable = map;
}
/// <summary>
/// Gets or sets the key comparer.
/// </summary>
/// <value>
/// The key comparer.
/// </value>
public IEqualityComparer<TKey> KeyComparer
{
get
{
return _comparers.KeyComparer;
}
set
{
Requires.NotNull(value, "value");
if (value != this.KeyComparer)
{
var comparers = Comparers.Get(value, this.ValueComparer);
var input = new MutationInput(SortedInt32KeyNode<HashBucket>.EmptyNode, comparers, 0);
var result = ImmutableDictionary<TKey, TValue>.AddRange(this, input);
_immutable = null;
_comparers = comparers;
_count = result.CountAdjustment; // offset from 0
this.Root = result.Root;
}
}
}
/// <summary>
/// Gets or sets the value comparer.
/// </summary>
/// <value>
/// The value comparer.
/// </value>
public IEqualityComparer<TValue> ValueComparer
{
get
{
return _comparers.ValueComparer;
}
set
{
Requires.NotNull(value, "value");
if (value != this.ValueComparer)
{
// When the key comparer is the same but the value comparer is different, we don't need a whole new tree
// because the structure of the tree does not depend on the value comparer.
// We just need a new root node to store the new value comparer.
_comparers = _comparers.WithValueComparer(value);
_immutable = null; // invalidate cached immutable
}
}
}
#region IDictionary<TKey, TValue> Properties
/// <summary>
/// Gets the number of elements contained in the <see cref="ICollection{T}"/>.
/// </summary>
/// <returns>The number of elements contained in the <see cref="ICollection{T}"/>.</returns>
public int Count
{
get { return _count; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.</returns>
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// See <see cref="IReadOnlyDictionary{TKey, TValue}"/>
/// </summary>
public IEnumerable<TKey> Keys
{
get
{
foreach (KeyValuePair<TKey, TValue> item in this)
{
yield return item.Key;
}
}
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns>
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return this.Keys.ToArray(this.Count); }
}
/// <summary>
/// See <see cref="IReadOnlyDictionary{TKey, TValue}"/>
/// </summary>
public IEnumerable<TValue> Values
{
get
{
foreach (KeyValuePair<TKey, TValue> item in this)
{
yield return item.Value;
}
}
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns>
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return this.Values.ToArray(this.Count); }
}
#endregion
#region IDictionary Properties
/// <summary>
/// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size.
/// </summary>
/// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns>
bool IDictionary.IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool IDictionary.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Keys
{
get { return this.Keys.ToArray(this.Count); }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Values
{
get { return this.Values.ToArray(this.Count); }
}
#endregion
#region ICollection Properties
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get { return false; }
}
#endregion
#region IDictionary Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param>
void IDictionary.Add(object key, object value)
{
this.Add((TKey)key, (TValue)value);
}
/// <summary>
/// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param>
/// <returns>
/// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false.
/// </returns>
bool IDictionary.Contains(object key)
{
return this.ContainsKey((TKey)key);
}
/// <summary>
/// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </summary>
/// <returns>
/// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </returns>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator());
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
void IDictionary.Remove(object key)
{
this.Remove((TKey)key);
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
object IDictionary.this[object key]
{
get { return this[(TKey)key]; }
set { this[(TKey)key] = (TValue)value; }
}
#endregion
#region ICollection methods
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int arrayIndex)
{
Requires.NotNull(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex");
Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex");
foreach (var item in this)
{
array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++);
}
}
#endregion
/// <summary>
/// Gets the current version of the contents of this builder.
/// </summary>
internal int Version
{
get { return _version; }
}
/// <summary>
/// Gets the initial data to pass to a query or mutation method.
/// </summary>
private MutationInput Origin
{
get { return new MutationInput(this.Root, _comparers, _count); }
}
/// <summary>
/// Gets or sets the root of this data structure.
/// </summary>
private SortedInt32KeyNode<HashBucket> Root
{
get
{
return _root;
}
set
{
// We *always* increment the version number because some mutations
// may not create a new value of root, although the existing root
// instance may have mutated.
_version++;
if (_root != value)
{
_root = value;
// Clear any cached value for the immutable view since it is now invalidated.
_immutable = null;
}
}
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <returns>The element with the specified key.</returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception>
/// <exception cref="KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.</exception>
/// <exception cref="NotSupportedException">The property is set and the <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception>
public TValue this[TKey key]
{
get
{
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
throw new KeyNotFoundException();
}
set
{
var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.SetValue, this.Origin);
this.Apply(result);
}
}
#region Public Methods
/// <summary>
/// Adds a sequence of values to this collection.
/// </summary>
/// <param name="items">The items.</param>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var result = ImmutableDictionary<TKey, TValue>.AddRange(items, this.Origin);
this.Apply(result);
}
/// <summary>
/// Removes any entries from the dictionaries with keys that match those found in the specified sequence.
/// </summary>
/// <param name="keys">The keys for entries to remove from the dictionary.</param>
public void RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, "keys");
foreach (var key in keys)
{
this.Remove(key);
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator(_root, this);
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <returns>The value for the key, or the default value of type <typeparamref name="TValue"/> if no matching key was found.</returns>
[Pure]
public TValue GetValueOrDefault(TKey key)
{
return this.GetValueOrDefault(key, default(TValue));
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param>
/// <returns>
/// The value for the key, or <paramref name="defaultValue"/> if no matching key was found.
/// </returns>
[Pure]
public TValue GetValueOrDefault(TKey key, TValue defaultValue)
{
Requires.NotNullAllowStructs(key, "key");
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
return defaultValue;
}
/// <summary>
/// Creates an immutable dictionary based on the contents of this instance.
/// </summary>
/// <returns>An immutable map.</returns>
/// <remarks>
/// This method is an O(n) operation, and approaches O(1) time as the number of
/// actual mutations to the set since the last call to this method approaches 0.
/// </remarks>
public ImmutableDictionary<TKey, TValue> ToImmutable()
{
// Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
if (_immutable == null)
{
_immutable = ImmutableDictionary<TKey, TValue>.Wrap(_root, _comparers, _count);
}
return _immutable;
}
#endregion
#region IDictionary<TKey, TValue> Members
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception>
/// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="IDictionary{TKey, TValue}"/>.</exception>
/// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception>
public void Add(TKey key, TValue value)
{
var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, this.Origin);
this.Apply(result);
}
/// <summary>
/// Determines whether the <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="IDictionary{TKey, TValue}"/>.</param>
/// <returns>
/// true if the <see cref="IDictionary{TKey, TValue}"/> contains an element with the key; otherwise, false.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception>
public bool ContainsKey(TKey key)
{
return ImmutableDictionary<TKey, TValue>.ContainsKey(key, this.Origin);
}
/// <summary>
/// Determines whether the <see cref="ImmutableDictionary{TKey, TValue}"/>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the <see cref="ImmutableDictionary{TKey, TValue}"/>.
/// The value can be null for reference types.
/// </param>
/// <returns>
/// true if the <see cref="ImmutableDictionary{TKey, TValue}"/> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
public bool ContainsValue(TValue value)
{
foreach (KeyValuePair<TKey, TValue> item in this)
{
if (this.ValueComparer.Equals(value, item.Value))
{
return true;
}
}
return false;
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception>
///
/// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception>
public bool Remove(TKey key)
{
var result = ImmutableDictionary<TKey, TValue>.Remove(key, this.Origin);
return this.Apply(result);
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key whose value to get.</param>
/// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value of the type <typeparamref name="TValue"/>. This parameter is passed uninitialized.</param>
/// <returns>
/// true if the object that implements <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key; otherwise, false.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception>
public bool TryGetValue(TKey key, out TValue value)
{
return ImmutableDictionary<TKey, TValue>.TryGetValue(key, this.Origin, out value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
return ImmutableDictionary<TKey, TValue>.TryGetKey(equalKey, this.Origin, out actualKey);
}
/// <summary>
/// Adds an item to the <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param>
/// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception>
public void Add(KeyValuePair<TKey, TValue> item)
{
this.Add(item.Key, item.Value);
}
/// <summary>
/// Removes all items from the <see cref="ICollection{T}"/>.
/// </summary>
/// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only. </exception>
public void Clear()
{
this.Root = SortedInt32KeyNode<HashBucket>.EmptyNode;
_count = 0;
}
/// <summary>
/// Determines whether the <see cref="ICollection{T}"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false.
/// </returns>
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return ImmutableDictionary<TKey, TValue>.Contains(item, this.Origin);
}
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
Requires.NotNull(array, "array");
foreach (var item in this)
{
array[arrayIndex++] = item;
}
}
#endregion
#region ICollection<KeyValuePair<TKey, TValue>> Members
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="ICollection{T}"/>.</param>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="ICollection{T}"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="ICollection{T}"/>.
/// </returns>
/// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception>
public bool Remove(KeyValuePair<TKey, TValue> item)
{
// Before removing based on the key, check that the key (if it exists) has the value given in the parameter as well.
if (this.Contains(item))
{
return this.Remove(item.Key);
}
return false;
}
#endregion
#region IEnumerator<T> methods
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Applies the result of some mutation operation to this instance.
/// </summary>
/// <param name="result">The result.</param>
private bool Apply(MutationResult result)
{
this.Root = result.Root;
_count += result.CountAdjustment;
return result.CountAdjustment != 0;
}
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
internal class ImmutableDictionaryBuilderDebuggerProxy<TKey, TValue>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableDictionary<TKey, TValue>.Builder _map;
/// <summary>
/// The simple view of the collection.
/// </summary>
private KeyValuePair<TKey, TValue>[] _contents;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableDictionaryBuilderDebuggerProxy{TKey, TValue}"/> class.
/// </summary>
/// <param name="map">The collection to display in the debugger</param>
public ImmutableDictionaryBuilderDebuggerProxy(ImmutableDictionary<TKey, TValue>.Builder map)
{
Requires.NotNull(map, "map");
_map = map;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Contents
{
get
{
if (_contents == null)
{
_contents = _map.ToArray(_map.Count);
}
return _contents;
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* 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.
*/
#endregion
using System.Collections;
using System.Data;
using Common.Logging;
using Spring.Dao;
using Spring.Data.Common;
using Spring.Objects.Factory;
namespace Spring.Data.Objects
{
/// <summary>
/// Abstract base class providing common functionality for generic and non
/// generic implementations of "AdoOperation" subclasses.
/// </summary>
/// <author>Mark Pollack (.NET)</author>
public abstract class AbstractAdoOperation : IInitializingObject
{
#region Logging Definition
protected readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion
#region Fields
private string sql;
private CommandType commandType = CommandType.Text;
private IDbParameters declaredParameters;
/// <summary>
/// Has this operation been compiled? Compilation means at
/// least checking that a IDbProvider and sql have been provided,
/// but subclasses may also implement their own custom validation.
/// </summary>
private bool compiled;
/// <summary>
/// Object enabling us to create IDbCommands
/// efficiently, based on this class's declared parameters.
/// </summary>
private IDbCommandCreatorFactory commandFactory;
#endregion
#region Properties
/// <summary>
/// Gets or sets the type of the command.
/// </summary>
/// <value>The type of the command.</value>
public CommandType CommandType
{
get { return commandType; }
set { commandType = value; }
}
/// <summary>
/// Gets or sets the db provider.
/// </summary>
/// <value>The db provider.</value>
public abstract IDbProvider DbProvider
{
get; set;
}
/// <summary>
/// Gets or sets the SQL to execute
/// </summary>
/// <value>The SQL.</value>
public string Sql
{
get
{
return sql;
}
set
{
sql = value;
}
}
/// <summary>
/// Gets or sets the declared parameters.
/// </summary>
/// <value>The declared parameters.</value>
public IDbParameters DeclaredParameters
{
get
{
return declaredParameters;
}
set
{
if (Compiled)
{
throw new InvalidDataAccessApiUsageException("Cannot add parameters once operation is compiled");
}
declaredParameters = value;
}
}
/// <summary>
/// Gets a value indicating whether this <see cref="AdoOperation"/> is compiled.
/// </summary>
/// <remarks>Compilation means that the operation is fully configured,
/// and ready to use. The exact meaning of compilation will vary between subclasses.</remarks>
/// <value><c>true</c> if compiled; otherwise, <c>false</c>.</value>
public bool Compiled
{
get { return compiled; }
protected set { compiled = value; }
}
/// <summary>
/// Sets the command timeout for IDbCommands that this AdoTemplate executes.
/// </summary>
/// <remarks>Default is 0, indicating to use the database provider's default.
/// Any timeout specified here will be overridden by the remaining
/// transaction timeout when executing within a transaction that has a
/// timeout specified at the transaction level.
/// </remarks>
/// <value>The command timeout.</value>
public abstract int CommandTimeout
{
set;
}
#endregion
#region Methods
/// <summary>
/// Ensures compilation if used in an IApplicationContext
/// </summary>
public void AfterPropertiesSet()
{
Compile();
}
/// <summary>
/// Compiles this operation. Ignores subsequent attempts to compile.
/// </summary>
public abstract void Compile();
/// <summary>
/// Check whether this operation has been compiled already;
/// lazily compile it if not already compiled.
/// </summary>
/// <remarks>Automatically called by ValidateParameters and ValidateNamedParameters</remarks>
protected void CheckCompiled()
{
if (!Compiled)
{
log.Debug("ADO operation not compiled before execution - invoking compile");
Compile();
}
}
protected virtual void ValidateParameters(params object[] inParamValues)
{
CheckCompiled();
int declaredInParameters = 0;
if (DeclaredParameters != null)
{
for (int i = 0; i < declaredParameters.Count; i++)
{
IDataParameter declaredParameter = DeclaredParameters[i];
if (IsInputParameter(declaredParameter))
{
declaredInParameters++;
}
}
}
if (inParamValues != null)
{
if (DeclaredParameters == null)
{
throw new InvalidDataAccessApiUsageException(
"Didn't expect any parameters: none were declared");
}
if (inParamValues.Length < declaredInParameters)
{
throw new InvalidDataAccessApiUsageException(
inParamValues.Length + " parameters were supplied, but " +
declaredInParameters + " in parameters were declared in class [" +
GetType().AssemblyQualifiedName + "]");
}
if (inParamValues.Length > declaredInParameters)
{
throw new InvalidDataAccessApiUsageException(
inParamValues.Length + " parameters were supplied, but " +
DeclaredParameters.Count + " parameters were declared " +
"in class [" + GetType().AssemblyQualifiedName + "]");
}
}
else
{
// No parameters were supplied
if (DeclaredParameters != null && !(DeclaredParameters.Count == 0))
{
throw new InvalidDataAccessApiUsageException(
DeclaredParameters.Count + " parameters must be supplied");
}
}
}
protected virtual bool IsInputParameter(IDataParameter parameter)
{
return (parameter.Direction == ParameterDirection.Input
|| parameter.Direction == ParameterDirection.InputOutput);
}
/// <summary>
/// Validates the named parameters passed to an AdoTemplate ExecuteXXX method based on
/// declared parameters.
/// </summary>
/// <remarks>
/// Subclasses should invoke this method very every ExecuteXXX method.
/// </remarks>
/// <param name="parameters">The parameter dictionary supplied. May by null.</param>
protected virtual void ValidateNamedParameters(IDictionary parameters)
{
CheckCompiled();
IDictionary paramsToUse = (parameters != null ? parameters : new Hashtable());
if (declaredParameters != null)
{
for (int i = 0; i < declaredParameters.Count; i++)
{
IDataParameter declaredParameter = DeclaredParameters[i];
if (declaredParameter.ParameterName == null)
{
throw new InvalidDataAccessApiUsageException(
"All parameters must have name specified when using the methods " +
"dedicated to named parameter support");
}
if (IsInputParameter(declaredParameter) && !paramsToUse.Contains(declaredParameter.ParameterName))
{
throw new InvalidDataAccessApiUsageException(
"The parameter named '" + declaredParameter +
"' was not among the parameters supplied: " + paramsToUse.Keys);
}
}
}
if (DeclaredParameters != null && DeclaredParameters.Count > 0)
{
if (DeclaredParameters == null)
{
throw new InvalidDataAccessApiUsageException(
"Didn't expect any parameters: none were declared");
}
}
else
{
// No parameters were supplied
if (DeclaredParameters != null && !(DeclaredParameters.Count == 0))
{
throw new InvalidDataAccessApiUsageException(
"Parameters must be supplied");
}
}
}
/// <summary>
/// Subclasses must implement to perform their own compilation.
/// Invoked after this class's compilation is complete.
/// Subclasses can assume that SQL has been supplied and that
/// a IDbProvider has been supplied.
/// </summary>
protected virtual void CompileInternal()
{
commandFactory = new IDbCommandCreatorFactory(DbProvider, CommandType, Sql, DeclaredParameters);
OnCompileInternal();
}
/// <summary>
/// Hook method that subclasses may override to react to compilation.
/// This implementation does nothing.
/// </summary>
protected virtual void OnCompileInternal()
{
}
protected virtual IDbCommandCreator NewCommandCreator(IDictionary inParams)
{
return commandFactory.NewDbCommandCreator(inParams);
}
protected virtual IDbCommandCreator NewCommandCreatorWithParamValues(params object[] inParams)
{
return commandFactory.NewDbCommandCreatorWithParamValues(inParams);
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;
using System.Collections.Generic;
using System.Threading;
using System.Globalization;
using CommandLine;
using NLog;
using Wox.Core;
using Wox.Core.Configuration;
using Wox.Core.Plugin;
using Wox.Core.Resource;
using Wox.Helper;
using Wox.Infrastructure;
using Wox.Infrastructure.Http;
using Wox.Image;
using Wox.Infrastructure.Logger;
using Wox.Infrastructure.UserSettings;
using Wox.ViewModel;
using Stopwatch = Wox.Infrastructure.Stopwatch;
using Wox.Infrastructure.Exception;
using Sentry;
namespace Wox
{
public partial class App : IDisposable, ISingleInstanceApp
{
public static PublicAPIInstance API { get; private set; }
private const string Unique = "Wox_Unique_Application_Mutex";
private static bool _disposed;
private MainViewModel _mainVM;
private SettingWindowViewModel _settingsVM;
private readonly Portable _portable = new Portable();
private StringMatcher _stringMatcher;
private static string _systemLanguage;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private class Options
{
[Option('q', "query", Required = false, HelpText = "Specify text to query on startup.")]
public string QueryText { get; set; }
}
private void ParseCommandLineArgs(IList<string> args)
{
if (args == null)
return;
Parser.Default.ParseArguments<Options>(args)
.WithParsed(o =>
{
if (o.QueryText != null && _mainVM != null)
_mainVM.ChangeQueryText(o.QueryText);
});
}
[STAThread]
public static void Main()
{
_systemLanguage = CultureInfo.CurrentUICulture.Name;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
using (ErrorReporting.InitializedSentry(_systemLanguage))
{
if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
{
using (var application = new App())
{
application.InitializeComponent();
application.Run();
}
}
}
}
private void OnStartup(object sender, StartupEventArgs e)
{
Logger.StopWatchNormal("Startup cost", () =>
{
RegisterAppDomainExceptions();
RegisterDispatcherUnhandledException();
Logger.WoxInfo("Begin Wox startup----------------------------------------------------");
Settings.Initialize();
ExceptionFormatter.Initialize(_systemLanguage, Settings.Instance.Language);
InsertWoxLanguageIntoLog();
Logger.WoxInfo(ExceptionFormatter.RuntimeInfo());
_portable.PreStartCleanUpAfterPortabilityUpdate();
ImageLoader.Initialize();
_settingsVM = new SettingWindowViewModel(_portable);
_stringMatcher = new StringMatcher();
StringMatcher.Instance = _stringMatcher;
_stringMatcher.UserSettingSearchPrecision = Settings.Instance.QuerySearchPrecision;
PluginManager.LoadPlugins(Settings.Instance.PluginSettings);
_mainVM = new MainViewModel();
var window = new MainWindow(_mainVM);
API = new PublicAPIInstance(_settingsVM, _mainVM);
PluginManager.InitializePlugins(API);
Current.MainWindow = window;
Current.MainWindow.Title = Constant.Wox;
// todo temp fix for instance code logic
// load plugin before change language, because plugin language also needs be changed
InternationalizationManager.Instance.Settings = Settings.Instance;
InternationalizationManager.Instance.ChangeLanguage(Settings.Instance.Language);
// main windows needs initialized before theme change because of blur settings
ThemeManager.Instance.ChangeTheme(Settings.Instance.Theme);
Http.Proxy = Settings.Instance.Proxy;
RegisterExitEvents();
AutoStartup();
ParseCommandLineArgs(SingleInstance<App>.CommandLineArgs);
_mainVM.MainWindowVisibility = Settings.Instance.HideOnStartup ? Visibility.Hidden : Visibility.Visible;
Logger.WoxInfo($"SDK Info: {ExceptionFormatter.SDKInfo()}");
Logger.WoxInfo("End Wox startup ---------------------------------------------------- ");
});
}
private static void InsertWoxLanguageIntoLog()
{
Log.updateSettingsInfo(Settings.Instance.Language);
Settings.Instance.PropertyChanged += (s, ev) =>
{
if (ev.PropertyName == nameof(Settings.Instance.Language))
{
Log.updateSettingsInfo(Settings.Instance.Language);
}
};
}
private void AutoStartup()
{
if (Settings.Instance.StartWoxOnSystemStartup)
{
if (!SettingWindow.StartupSet())
{
SettingWindow.SetStartup();
}
}
}
private void RegisterExitEvents()
{
AppDomain.CurrentDomain.ProcessExit += (s, e) => Dispose();
Current.Exit += (s, e) => Dispose();
Current.SessionEnding += (s, e) => Dispose();
}
/// <summary>
/// let exception throw as normal is better for Debug
/// </summary>
//[Conditional("RELEASE")]
private void RegisterDispatcherUnhandledException()
{
DispatcherUnhandledException += ErrorReporting.DispatcherUnhandledException;
}
/// <summary>
/// let exception throw as normal is better for Debug
/// </summary>
//[Conditional("RELEASE")]
private static void RegisterAppDomainExceptions()
{
AppDomain.CurrentDomain.UnhandledException += ErrorReporting.UnhandledExceptionHandleMain;
}
public void Dispose()
{
Logger.WoxInfo("Wox Start Displose");
// if sessionending is called, exit proverbially be called when log off / shutdown
// but if sessionending is not called, exit won't be called when log off / shutdown
if (!_disposed)
{
API?.SaveAppAllSettings();
_disposed = true;
// todo temp fix to exist application
// should notify child thread programmaly
Environment.Exit(0);
}
Logger.WoxInfo("Wox End Displose");
}
public void OnSecondAppStarted(IList<string> args)
{
ParseCommandLineArgs(args);
Current.MainWindow.Visibility = Visibility.Visible;
}
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2010 Leopold Bushkin. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MoreLinq.Test
{
using System;
using NUnit.Framework;
using Tuple = System.ValueTuple;
[TestFixture]
public class PartitionTest
{
[Test]
public void Partition()
{
var (evens, odds) =
Enumerable.Range(0, 10)
.Partition(x => x % 2 == 0);
Assert.That(evens, Is.EqualTo(new[] { 0, 2, 4, 6, 8 }));
Assert.That(odds, Is.EqualTo(new[] { 1, 3, 5, 7, 9 }));
}
[Test]
public void PartitionWithEmptySequence()
{
var (evens, odds) =
Enumerable.Empty<int>()
.Partition(x => x % 2 == 0);
Assert.That(evens, Is.Empty);
Assert.That(odds, Is.Empty);
}
[Test]
public void PartitionWithResultSelector()
{
var (evens, odds) =
Enumerable.Range(0, 10)
.Partition(x => x % 2 == 0, Tuple.Create);
Assert.That(evens, Is.EqualTo(new[] { 0, 2, 4, 6, 8 }));
Assert.That(odds, Is.EqualTo(new[] { 1, 3, 5, 7, 9 }));
}
[Test]
public void PartitionBooleanGrouping()
{
var (evens, odds) =
Enumerable.Range(0, 10)
.GroupBy(x => x % 2 == 0)
.Partition((t, f) => Tuple.Create(t, f));
Assert.That(evens, Is.EqualTo(new[] { 0, 2, 4, 6, 8 }));
Assert.That(odds, Is.EqualTo(new[] { 1, 3, 5, 7, 9 }));
}
[Test]
public void PartitionNullableBooleanGrouping()
{
var xs = new int?[] { 1, 2, 3, null, 5, 6, 7, null, 9, 10 };
var (lt5, gte5, nils) =
xs.GroupBy(x => x != null ? x < 5 : (bool?) null)
.Partition((t, f, n) => Tuple.Create(t, f, n));
Assert.That(lt5, Is.EqualTo(new[] { 1, 2, 3 }));
Assert.That(gte5, Is.EqualTo(new[] { 5, 6, 7, 9, 10 }));
Assert.That(nils, Is.EqualTo(new int?[] { null, null }));
}
[Test]
public void PartitionBooleanGroupingWithSingleKey()
{
var (m3, etc) =
Enumerable.Range(0, 10)
.GroupBy(x => x % 3)
.Partition(0, Tuple.Create);
Assert.That(m3, Is.EqualTo(new[] { 0, 3, 6, 9 }));
using var r = etc.Read();
var r1 = r.Read();
Assert.That(r1.Key, Is.EqualTo(1));
Assert.That(r1, Is.EqualTo(new[] { 1, 4, 7 }));
var r2 = r.Read();
Assert.That(r2.Key, Is.EqualTo(2));
Assert.That(r2, Is.EqualTo(new[] { 2, 5, 8 }));
r.ReadEnd();
}
[Test]
public void PartitionBooleanGroupingWitTwoKeys()
{
var (ms, r1, etc) =
Enumerable.Range(0, 10)
.GroupBy(x => x % 3)
.Partition(0, 1, Tuple.Create);
Assert.That(ms, Is.EqualTo(new[] { 0, 3, 6, 9 }));
Assert.That(r1, Is.EqualTo(new[] { 1, 4, 7 }));
using var r = etc.Read();
var r2 = r.Read();
Assert.That(r2.Key, Is.EqualTo(2));
Assert.That(r2, Is.EqualTo(new[] { 2, 5, 8 }));
r.ReadEnd();
}
[Test]
public void PartitionBooleanGroupingWitThreeKeys()
{
var (ms, r1, r2, etc) =
Enumerable.Range(0, 10)
.GroupBy(x => x % 3)
.Partition(0, 1, 2, Tuple.Create);
Assert.That(ms, Is.EqualTo(new[] { 0, 3, 6, 9 }));
Assert.That(r1, Is.EqualTo(new[] { 1, 4, 7 }));
Assert.That(r2, Is.EqualTo(new[] { 2, 5, 8 }));
Assert.That(etc, Is.Empty);
}
[Test]
public void PartitionBooleanGroupingWithSingleKeyWithComparer()
{
var words =
new[] { "foo", "bar", "FOO", "Bar" };
var (foo, etc) =
words.GroupBy(s => s, StringComparer.OrdinalIgnoreCase)
.Partition("foo", StringComparer.OrdinalIgnoreCase, Tuple.Create);
Assert.That(foo, Is.EqualTo(new[] { "foo", "FOO" }));
using var r = etc.Read();
var bar = r.Read();
Assert.That(bar, Is.EqualTo(new[] { "bar", "Bar" }));
r.ReadEnd();
}
[Test]
public void PartitionBooleanGroupingWithTwoKeysWithComparer()
{
var words =
new[] { "foo", "bar", "FOO", "Bar", "baz", "QUx", "bAz", "QuX" };
var (foos, bar, etc) =
words.GroupBy(s => s, StringComparer.OrdinalIgnoreCase)
.Partition("foo", "bar", StringComparer.OrdinalIgnoreCase, Tuple.Create);
Assert.That(foos, Is.EqualTo(new[] { "foo", "FOO" }));
Assert.That(bar, Is.EqualTo(new[] { "bar", "Bar" }));
using var r = etc.Read();
var baz = r.Read();
Assert.That(baz.Key, Is.EqualTo("baz"));
Assert.That(baz, Is.EqualTo(new[] { "baz", "bAz" }));
var qux = r.Read();
Assert.That(qux.Key, Is.EqualTo("QUx"));
Assert.That(qux, Is.EqualTo(new[] { "QUx", "QuX" }));
r.ReadEnd();
}
[Test]
public void PartitionBooleanGroupingWithThreeKeysWithComparer()
{
var words =
new[] { "foo", "bar", "FOO", "Bar", "baz", "QUx", "bAz", "QuX" };
var (foos, bar, baz, etc) =
words.GroupBy(s => s, StringComparer.OrdinalIgnoreCase)
.Partition("foo", "bar", "baz", StringComparer.OrdinalIgnoreCase, Tuple.Create);
Assert.That(foos, Is.EqualTo(new[] { "foo", "FOO" }));
Assert.That(bar, Is.EqualTo(new[] { "bar", "Bar" }));
Assert.That(baz, Is.EqualTo(new[] { "baz", "bAz" }));
using var r = etc.Read();
var qux = r.Read();
Assert.That(qux.Key, Is.EqualTo("QUx"));
Assert.That(qux, Is.EqualTo(new[] { "QUx", "QuX" }));
r.ReadEnd();
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: Border.cs
//
// Description: Contains the Decorator class.
// Spec at http://avalon/layout/Specs/Decorator.xml
//
// History:
// 06/12/2003 : greglett - Added to WCP branch
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.Controls;
using MS.Utility;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Threading;
using System.Windows.Media;
using System.Windows.Markup; // IAddChild, ContentPropertyAttribute
namespace System.Windows.Controls
{
/// <summary>
/// Decorator is a base class for elements that apply effects onto or around a single child.
/// </summary>
[Localizability(LocalizationCategory.Ignore, Readability = Readability.Unreadable)]
[ContentProperty("Child")]
public class Decorator : FrameworkElement, IAddChild
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
/// <summary>
/// Default DependencyObject constructor
/// </summary>
/// <remarks>
/// Automatic determination of current Dispatcher. Use alternative constructor
/// that accepts a Dispatcher for best performance.
/// </remarks>
public Decorator() : base()
{
}
#endregion
//-------------------------------------------------------------------
//
// Public Methods
//
//-------------------------------------------------------------------
#region Public Methods
///<summary>
/// This method is called to Add the object as a child of the Decorator. This method is used primarily
/// by the parser; a more direct way of adding a child to a Decorator is to use the <see cref="Child" />
/// property.
///</summary>
///<param name="value">
/// The object to add as a child; it must be a UIElement.
///</param>
void IAddChild.AddChild (Object value)
{
if (!(value is UIElement))
{
throw new ArgumentException (SR.Get(SRID.UnexpectedParameterType, value.GetType(), typeof(UIElement)), "value");
}
if (this.Child != null)
{
throw new ArgumentException(SR.Get(SRID.CanOnlyHaveOneChild, this.GetType(), value.GetType()));
}
this.Child = (UIElement)value;
}
///<summary>
/// This method is called by the parser when text appears under the tag in markup.
/// As Decorators do not support text, calling this method has no effect if the text
/// is all whitespace. For non-whitespace text, throw an exception.
///</summary>
///<param name="text">
/// Text to add as a child.
///</param>
void IAddChild.AddText (string text)
{
XamlSerializerUtil.ThrowIfNonWhiteSpaceInAddText(text, this);
}
#endregion
//-------------------------------------------------------------------
//
// Public Properties
//
//-------------------------------------------------------------------
#region Public Properties
/// <summary>
/// The single child of a <see cref="System.Windows.Controls.Decorator" />
/// </summary>
[DefaultValue(null)]
public virtual UIElement Child
{
get
{
return _child;
}
set
{
if(_child != value)
{
// notify the visual layer that the old child has been removed.
RemoveVisualChild(_child);
//need to remove old element from logical tree
RemoveLogicalChild(_child);
_child = value;
AddLogicalChild(value);
// notify the visual layer about the new child.
AddVisualChild(value);
InvalidateMeasure();
}
}
}
/// <summary>
/// Returns enumerator to logical children.
/// </summary>
protected internal override IEnumerator LogicalChildren
{
get
{
if (_child == null)
{
return EmptyEnumerator.Instance;
}
return new SingleChildEnumerator(_child);
}
}
#endregion
//-------------------------------------------------------------------
//
// Protected Methods
//
//-------------------------------------------------------------------
#region Protected Methods
/// <summary>
/// Returns the Visual children count.
/// </summary>
protected override int VisualChildrenCount
{
get { return (_child == null) ? 0 : 1; }
}
/// <summary>
/// Returns the child at the specified index.
/// </summary>
protected override Visual GetVisualChild(int index)
{
if ( (_child == null)
|| (index != 0))
{
throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange));
}
return _child;
}
/// <summary>
/// Updates DesiredSize of the Decorator. Called by parent UIElement. This is the first pass of layout.
/// </summary>
/// <remarks>
/// Decorator determines a desired size it needs from the child's sizing properties, margin, and requested size.
/// </remarks>
/// <param name="constraint">Constraint size is an "upper limit" that the return value should not exceed.</param>
/// <returns>The Decorator's desired size.</returns>
protected override Size MeasureOverride(Size constraint)
{
UIElement child = Child;
if (child != null)
{
child.Measure(constraint);
return (child.DesiredSize);
}
return (new Size());
}
/// <summary>
/// Decorator computes the position of its single child inside child's Margin and calls Arrange
/// on the child.
/// </summary>
/// <param name="arrangeSize">Size the Decorator will assume.</param>
protected override Size ArrangeOverride(Size arrangeSize)
{
UIElement child = Child;
if (child != null)
{
child.Arrange(new Rect(arrangeSize));
}
return (arrangeSize);
}
#endregion
#region Internal Properties
internal UIElement IntChild
{
get { return _child; }
set { _child = value; }
}
#endregion
#region Private Members
UIElement _child;
#endregion Private Members
}
}
| |
// <copyright file="DummyClient.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace GooglePlayGames.BasicApi
{
using System;
using GooglePlayGames.BasicApi.Multiplayer;
using GooglePlayGames.OurUtils;
using UnityEngine.SocialPlatforms;
/// <summary>
/// Dummy client used in Editor.
/// </summary>
/// <remarks>Google Play Game Services are not supported in the Editor
/// environment, so this client is used as a placeholder.
/// </remarks>
public class DummyClient : IPlayGamesClient
{
/// <summary>
/// Starts the authentication process.
/// </summary>
/// <remarks> If silent == true, no UIs will be shown
/// (if UIs are needed, it will fail rather than show them). If silent == false,
/// this may show UIs, consent dialogs, etc.
/// At the end of the process, callback will be invoked to notify of the result.
/// Once the callback returns true, the user is considered to be authenticated
/// forever after.
/// </remarks>
/// <param name="callback">Callback when completed.</param>
/// <param name="silent">If set to <c>true</c> silent.</param>
public void Authenticate(Action<bool> callback, bool silent)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Returns whether or not user is authenticated.
/// </summary>
/// <returns>true if authenticated</returns>
/// <c>false</c>
public bool IsAuthenticated()
{
LogUsage();
return false;
}
/// <summary>
/// Signs the user out.
/// </summary>
public void SignOut()
{
LogUsage();
}
/// <summary>
/// Returns an access token.
/// </summary>
/// <returns>The access token.</returns>
public string GetAccessToken()
{
LogUsage();
return "DummyAccessToken";
}
/// <summary>
/// Retrieves an id token, which can be verified server side, if they are logged in.
/// </summary>
/// <param name="idTokenCallback">The callback invoked with the token</param>
/// <returns>The identifier token.</returns>
public void GetIdToken(Action<string> idTokenCallback)
{
LogUsage();
if (idTokenCallback != null) {
idTokenCallback("DummyIdToken");
}
}
/// <summary>
/// Returns the authenticated user's ID. Note that this value may change if a user signs
/// on and signs in with a different account.
/// </summary>
/// <returns>The user identifier.</returns>
public string GetUserId()
{
LogUsage();
return "DummyID";
}
/// <summary>
/// Retrieves an OAuth 2.0 bearer token for the client.
/// </summary>
/// <returns>A string representing the bearer token.</returns>
public string GetToken()
{
return "DummyToken";
}
/// <summary>
/// Asynchronously retrieves the server auth code for this client.
/// </summary>
/// <remarks>
/// Note: This function is only implemented for Android.
/// </remarks>
/// <param name="serverClientId">The Client ID.</param>
/// <param name="callback">Callback for response.</param>
public void GetServerAuthCode(string serverClientId, Action<CommonStatusCodes, string> callback)
{
LogUsage();
if (callback != null)
{
callback(CommonStatusCodes.ApiNotConnected, "DummyServerAuthCode");
}
}
/// <summary>
/// Gets the user email.
/// </summary>
/// <returns>The user email or null if not authenticated or the permission is
/// not available.</returns>
public string GetUserEmail()
{
return string.Empty;
}
/// <summary>
/// Gets the player stats.
/// </summary>
/// <param name="callback">Callback for response.</param>
public void GetPlayerStats(Action<CommonStatusCodes, PlayerStats> callback)
{
LogUsage();
callback(CommonStatusCodes.ApiNotConnected, new PlayerStats());
}
/// <summary>
/// Returns a human readable name for the user, if they are logged in.
/// </summary>
/// <returns>The user display name.</returns>
public string GetUserDisplayName()
{
LogUsage();
return "Player";
}
/// <summary>
/// Returns the user's avatar url, if they are logged in and have an avatar.
/// </summary>
/// <returns>The user image URL.</returns>
public string GetUserImageUrl()
{
LogUsage();
return null;
}
/// <summary>
/// Loads the players specified.
/// </summary>
/// <remarks> This is mainly used by the leaderboard
/// APIs to get the information of a high scorer.
/// </remarks>
/// <param name="userIds">User identifiers.</param>
/// <param name="callback">Callback to invoke when completed.</param>
public void LoadUsers(string[] userIds, Action<IUserProfile[]> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(null);
}
}
/// <summary>
/// Loads the achievements for the current player.
/// </summary>
/// <param name="callback">Callback to invoke when completed.</param>
public void LoadAchievements(Action<Achievement[]> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(null);
}
}
/// <summary>
/// Returns the achievement corresponding to the passed achievement identifier.
/// </summary>
/// <returns>The achievement.</returns>
/// <param name="achId">Achievement identifier.</param>
public Achievement GetAchievement(string achId)
{
LogUsage();
return null;
}
/// <summary>
/// Unlocks the achievement.
/// </summary>
/// <param name="achId">Achievement identifier.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void UnlockAchievement(string achId, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Reveals the achievement.
/// </summary>
/// <param name="achId">Achievement identifier.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void RevealAchievement(string achId, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Increments the achievement.
/// </summary>
/// <param name="achId">Achievement identifier.</param>
/// <param name="steps">Steps to increment by..</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void IncrementAchievement(string achId, int steps, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Set an achievement to have at least the given number of steps completed.
/// </summary>
/// <remarks>
/// Calling this method while the achievement already has more steps than
/// the provided value is a no-op. Once the achievement reaches the
/// maximum number of steps, the achievement is automatically unlocked,
/// and any further mutation operations are ignored.
/// </remarks>
/// <param name="achId">Achievement identifier.</param>
/// <param name="steps">Steps to increment to at least.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void SetStepsAtLeast(string achId, int steps, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Shows the achievements UI
/// </summary>
/// <param name="callback">Callback to invoke when complete.</param>
public void ShowAchievementsUI(Action<UIStatus> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(UIStatus.VersionUpdateRequired);
}
}
/// <summary>
/// Shows the leaderboard UI
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="span">Timespan to display.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void ShowLeaderboardUI(
string leaderboardId,
LeaderboardTimeSpan span,
Action<UIStatus> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(UIStatus.VersionUpdateRequired);
}
}
/// <summary>
/// Returns the max number of scores returned per call.
/// </summary>
/// <returns>The max results.</returns>
public int LeaderboardMaxResults()
{
return 25;
}
/// <summary>
/// Loads the score data for the given leaderboard.
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="start">Start indicating the top scores or player centric</param>
/// <param name="rowCount">Row count.</param>
/// <param name="collection">Collection to display.</param>
/// <param name="timeSpan">Time span.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void LoadScores(
string leaderboardId,
LeaderboardStart start,
int rowCount,
LeaderboardCollection collection,
LeaderboardTimeSpan timeSpan,
Action<LeaderboardScoreData> callback)
{
LogUsage();
if (callback != null)
{
callback(new LeaderboardScoreData(
leaderboardId,
ResponseStatus.LicenseCheckFailed));
}
}
/// <summary>
/// Loads the more scores for the leaderboard.
/// </summary>
/// <remarks>The token is accessed
/// by calling LoadScores() with a positive row count.
/// </remarks>
/// <param name="token">Token used to start loading scores.</param>
/// <param name="rowCount">Max number of scores to return.
/// This can be limited by the SDK.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void LoadMoreScores(
ScorePageToken token,
int rowCount,
Action<LeaderboardScoreData> callback)
{
LogUsage();
if (callback != null)
{
callback(new LeaderboardScoreData(
token.LeaderboardId,
ResponseStatus.LicenseCheckFailed));
}
}
/// <summary>
/// Submits the score.
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="score">Score to submit.</param>
/// <param name="callback">Callback to invoke when complete.</param>
public void SubmitScore(string leaderboardId, long score, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Submits the score for the currently signed-in player
/// to the leaderboard associated with a specific id
/// and metadata (such as something the player did to earn the score).
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="score">Score value to submit.</param>
/// <param name="metadata">Metadata about the score.</param>
/// <param name="callback">Callback upon completion.</param>
public void SubmitScore(
string leaderboardId,
long score,
string metadata,
Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
/// <summary>
/// Returns a real-time multiplayer client.
/// </summary>
/// <seealso cref="GooglePlayGames.Multiplayer.IRealTimeMultiplayerClient"></seealso>
/// <returns>The rtmp client.</returns>
public IRealTimeMultiplayerClient GetRtmpClient()
{
LogUsage();
return null;
}
/// <summary>
/// Returns a turn-based multiplayer client.
/// </summary>
/// <returns>The tbmp client.</returns>
public ITurnBasedMultiplayerClient GetTbmpClient()
{
LogUsage();
return null;
}
/// <summary>
/// Gets the saved game client.
/// </summary>
/// <returns>The saved game client.</returns>
public SavedGame.ISavedGameClient GetSavedGameClient()
{
LogUsage();
return null;
}
/// <summary>
/// Gets the events client.
/// </summary>
/// <returns>The events client.</returns>
public GooglePlayGames.BasicApi.Events.IEventsClient GetEventsClient()
{
LogUsage();
return null;
}
/// <summary>
/// Gets the quests client.
/// </summary>
/// <returns>The quests client.</returns>
public GooglePlayGames.BasicApi.Quests.IQuestsClient GetQuestsClient()
{
LogUsage();
return null;
}
/// <summary>
/// Registers the invitation delegate.
/// </summary>
/// <param name="invitationDelegate">Invitation delegate.</param>
public void RegisterInvitationDelegate(InvitationReceivedDelegate invitationDelegate)
{
LogUsage();
}
/// <summary>
/// Gets the invitation from notification.
/// </summary>
/// <returns>The invitation from notification.</returns>
public Invitation GetInvitationFromNotification()
{
LogUsage();
return null;
}
/// <summary>
/// Determines whether this instance has invitation from notification.
/// </summary>
/// <returns><c>true</c> if this instance has invitation from notification; otherwise, <c>false</c>.</returns>
public bool HasInvitationFromNotification()
{
LogUsage();
return false;
}
/// <summary>
/// Load friends of the authenticated user
/// </summary>
/// <param name="callback">Callback invoked when complete. bool argument
/// indicates success.</param>
public void LoadFriends(Action<bool> callback)
{
LogUsage();
callback(false);
}
/// <summary>
/// Gets the friends.
/// </summary>
/// <returns>The friends.</returns>
public IUserProfile[] GetFriends()
{
LogUsage();
return new IUserProfile[0];
}
/// <summary>
/// Gets the Android API client. Returns null on non-Android players.
/// </summary>
/// <returns>The API client.</returns>
public IntPtr GetApiClient()
{
LogUsage();
return IntPtr.Zero;
}
/// <summary>
/// Logs the usage.
/// </summary>
private static void LogUsage()
{
Logger.d("Received method call on DummyClient - using stub implementation.");
}
}
}
| |
using UnityEngine;
using UnityEngine.Serialization;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus
{
[ExecuteInEditMode]
[RequireComponent(typeof(Flowchart))]
[AddComponentMenu("")]
public class Block : Node
{
public enum ExecutionState
{
Idle,
Executing,
}
[NonSerialized]
public ExecutionState executionState;
[HideInInspector]
public int itemId = -1; // Invalid flowchart item id
[FormerlySerializedAs("sequenceName")]
[Tooltip("The name of the block node as displayed in the Flowchart window")]
public string blockName = "New Block";
[TextArea(2, 5)]
[Tooltip("Description text to display under the block node")]
public string description = "";
[Tooltip("An optional Event Handler which can execute the block when an event occurs")]
public EventHandler eventHandler;
[HideInInspector]
[System.NonSerialized]
public Command activeCommand;
// Index of last command executed before the current one
// -1 indicates no previous command
[HideInInspector]
[System.NonSerialized]
public int previousActiveCommandIndex = -1;
[HideInInspector]
[System.NonSerialized]
public float executingIconTimer;
[HideInInspector]
public List<Command> commandList = new List<Command>();
protected int executionCount;
/**
* Duration of fade for executing icon displayed beside blocks & commands.
*/
public const float executingIconFadeTime = 0.5f;
/**
* Controls the next command to execute in the block execution coroutine.
*/
[NonSerialized]
public int jumpToCommandIndex = -1;
protected virtual void Awake()
{
// Give each child command a reference back to its parent block
// and tell each command its index in the list.
int index = 0;
foreach (Command command in commandList)
{
if (command == null)
{
continue;
}
command.parentBlock = this;
command.commandIndex = index++;
}
}
#if UNITY_EDITOR
// The user can modify the command list order while playing in the editor,
// so we keep the command indices updated every frame. There's no need to
// do this in player builds so we compile this bit out for those builds.
void Update()
{
int index = 0;
foreach (Command command in commandList)
{
if (command == null) // Null entry will be deleted automatically later
{
continue;
}
command.commandIndex = index++;
}
}
#endif
public virtual Flowchart GetFlowchart()
{
return GetComponent<Flowchart>();
}
public virtual bool HasError()
{
foreach (Command command in commandList)
{
if (command.errorMessage.Length > 0)
{
return true;
}
}
return false;
}
public virtual bool IsExecuting()
{
return (executionState == ExecutionState.Executing);
}
public virtual int GetExecutionCount()
{
return executionCount;
}
public virtual bool Execute(Action onComplete = null)
{
if (executionState != ExecutionState.Idle)
{
return false;
}
executionCount++;
StartCoroutine(ExecuteBlock(onComplete));
return true;
}
protected virtual IEnumerator ExecuteBlock(Action onComplete = null)
{
Flowchart flowchart = GetFlowchart();
executionState = ExecutionState.Executing;
#if UNITY_EDITOR
// Select the executing block & the first command
flowchart.selectedBlock = this;
if (commandList.Count > 0)
{
flowchart.ClearSelectedCommands();
flowchart.AddSelectedCommand(commandList[0]);
}
#endif
int i = 0;
while (true)
{
// Executing commands specify the next command to skip to by setting jumpToCommandIndex using Command.Continue()
if (jumpToCommandIndex > -1)
{
i = jumpToCommandIndex;
jumpToCommandIndex = -1;
}
// Skip disabled commands, comments and labels
while (i < commandList.Count &&
(!commandList[i].enabled ||
commandList[i].GetType() == typeof(Comment) ||
commandList[i].GetType() == typeof(Label)))
{
i = commandList[i].commandIndex + 1;
}
if (i >= commandList.Count)
{
break;
}
// The previous active command is needed for if / else / else if commands
if (activeCommand == null)
{
previousActiveCommandIndex = -1;
}
else
{
previousActiveCommandIndex = activeCommand.commandIndex;
}
Command command = commandList[i];
activeCommand = command;
if (flowchart.gameObject.activeInHierarchy)
{
// Auto select a command in some situations
if ((flowchart.selectedCommands.Count == 0 && i == 0) ||
(flowchart.selectedCommands.Count == 1 && flowchart.selectedCommands[0].commandIndex == previousActiveCommandIndex))
{
flowchart.ClearSelectedCommands();
flowchart.AddSelectedCommand(commandList[i]);
}
}
command.isExecuting = true;
// This icon timer is managed by the FlowchartWindow class, but we also need to
// set it here in case a command starts and finishes execution before the next window update.
command.executingIconTimer = Time.realtimeSinceStartup + executingIconFadeTime;
command.Execute();
// Wait until the executing command sets another command to jump to via Command.Continue()
while (jumpToCommandIndex == -1)
{
yield return null;
}
#if UNITY_EDITOR
if (flowchart.stepPause > 0f)
{
yield return new WaitForSeconds(flowchart.stepPause);
}
#endif
command.isExecuting = false;
}
executionState = ExecutionState.Idle;
activeCommand = null;
if (onComplete != null)
{
onComplete();
}
}
public virtual void Stop()
{
// This will cause the execution loop to break on the next iteration
jumpToCommandIndex = int.MaxValue;
}
public virtual List<Block> GetConnectedBlocks()
{
List<Block> connectedBlocks = new List<Block>();
foreach (Command command in commandList)
{
if (command != null)
{
command.GetConnectedBlocks(ref connectedBlocks);
}
}
return connectedBlocks;
}
public virtual System.Type GetPreviousActiveCommandType()
{
if (previousActiveCommandIndex >= 0 &&
previousActiveCommandIndex < commandList.Count)
{
return commandList[previousActiveCommandIndex].GetType();
}
return null;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.