context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Rest.Wireless.V1;
namespace Twilio.Tests.Rest.Wireless.V1
{
[TestFixture]
public class CommandTest : TwilioTest
{
[Test]
public void TestFetchRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.Wireless,
"/v1/Commands/DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CommandResource.Fetch("DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestFetchCommandSmsResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"command\": \"command\",\"command_mode\": \"text\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"delivery_receipt_requested\": true,\"sim_sid\": \"DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"direction\": \"from_sim\",\"sid\": \"DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\": \"queued\",\"transport\": \"sms\",\"url\": \"https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = CommandResource.Fetch("DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestFetchCommandIpResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"command\": \"command\",\"command_mode\": \"text\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"delivery_receipt_requested\": false,\"sim_sid\": \"DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"direction\": \"to_sim\",\"sid\": \"DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\": \"queued\",\"transport\": \"ip\",\"url\": \"https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = CommandResource.Fetch("DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestReadRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.Wireless,
"/v1/Commands",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CommandResource.Read(client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestReadEmptyResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"commands\": [],\"meta\": {\"first_page_url\": \"https://wireless.twilio.com/v1/Commands?Status=queued&Direction=from_sim&Sim=sim&PageSize=50&Page=0\",\"key\": \"commands\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://wireless.twilio.com/v1/Commands?Status=queued&Direction=from_sim&Sim=sim&PageSize=50&Page=0\"}}"
));
var response = CommandResource.Read(client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestReadFullResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"commands\": [{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"command\": \"command\",\"command_mode\": \"text\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"delivery_receipt_requested\": true,\"sim_sid\": \"DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"direction\": \"from_sim\",\"sid\": \"DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\": \"queued\",\"transport\": \"sms\",\"url\": \"https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"meta\": {\"first_page_url\": \"https://wireless.twilio.com/v1/Commands?Status=queued&Direction=from_sim&Sim=sim&PageSize=50&Page=0\",\"key\": \"commands\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://wireless.twilio.com/v1/Commands?Status=queued&Direction=from_sim&Sim=sim&PageSize=50&Page=0\"}}"
));
var response = CommandResource.Read(client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestReadIpResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"commands\": [{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"command\": \"command\",\"command_mode\": \"binary\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"delivery_receipt_requested\": true,\"sim_sid\": \"DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"direction\": \"to_sim\",\"sid\": \"DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\": \"queued\",\"transport\": \"ip\",\"url\": \"https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"meta\": {\"first_page_url\": \"https://wireless.twilio.com/v1/Commands?Status=queued&Direction=to_sim&Transport=ip&Sim=sim&PageSize=50&Page=0\",\"key\": \"commands\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://wireless.twilio.com/v1/Commands?Status=queued&Direction=to_sim&Transport=ip&Sim=sim&PageSize=50&Page=0\"}}"
));
var response = CommandResource.Read(client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestCreateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.Wireless,
"/v1/Commands",
""
);
request.AddPostParam("Command", Serialize("command"));
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CommandResource.Create("command", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestCreateCommandSmsResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.Created,
"{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"command\": \"command\",\"command_mode\": \"text\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"delivery_receipt_requested\": true,\"sim_sid\": \"DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"direction\": \"from_sim\",\"sid\": \"DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\": \"queued\",\"transport\": \"sms\",\"url\": \"https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = CommandResource.Create("command", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestCreateCommandIpResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.Created,
"{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"command\": \"command\",\"command_mode\": \"binary\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"delivery_receipt_requested\": true,\"direction\": \"to_sim\",\"sid\": \"DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sim_sid\": \"DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\": \"queued\",\"transport\": \"ip\",\"url\": \"https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = CommandResource.Create("command", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestDeleteRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Delete,
Twilio.Rest.Domain.Wireless,
"/v1/Commands/DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CommandResource.Delete("DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestDeleteResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.NoContent,
"null"
));
var response = CommandResource.Delete("DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
}
}
| |
// This file was automatically generated by the PetaPoco T4 Template
// Do not make changes directly to this file - edit the template instead
//
// The following connection settings were used to generate this file
//
// Connection String Name: `Postgres`
// Provider: `Npgsql`
// Connection String: `server=192.168.10.40;Port=5432;Database=openlawoffice;User Id=postgres;password=**zapped**;`
// Schema: ``
// Include Views: `False`
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PetaPoco;
namespace OpenLawOffice.Data.DbModels
{
internal partial class PostgresDB : Database
{
internal PostgresDB()
: base("Postgres")
{
CommonConstruct();
}
internal PostgresDB(string connectionStringName)
: base(connectionStringName)
{
CommonConstruct();
}
partial void CommonConstruct();
internal interface IFactory
{
PostgresDB GetInstance();
}
internal static IFactory Factory { get; set; }
internal static PostgresDB GetInstance()
{
if (_instance!=null)
return _instance;
if (Factory!=null)
return Factory.GetInstance();
else
return new PostgresDB();
}
[ThreadStatic] static PostgresDB _instance;
public override void OnBeginTransaction()
{
if (_instance==null)
_instance=this;
}
public override void OnEndTransaction()
{
if (_instance==this)
_instance=null;
}
internal class Record<T> where T:new()
{
internal static PostgresDB repo { get { return PostgresDB.GetInstance(); } }
internal bool IsNew() { return repo.IsNew(this); }
internal object Insert() { return repo.Insert(this); }
internal void Save() { repo.Save(this); }
internal int Update() { return repo.Update(this); }
internal int Update(IEnumerable<string> columns) { return repo.Update(this, columns); }
internal static int Update(string sql, params object[] args) { return repo.Update<T>(sql, args); }
internal static int Update(Sql sql) { return repo.Update<T>(sql); }
internal int Delete() { return repo.Delete(this); }
internal static int Delete(string sql, params object[] args) { return repo.Delete<T>(sql, args); }
internal static int Delete(Sql sql) { return repo.Delete<T>(sql); }
internal static int Delete(object primaryKey) { return repo.Delete<T>(primaryKey); }
internal static bool Exists(object primaryKey) { return repo.Exists<T>(primaryKey); }
internal static bool Exists(string sql, params object[] args) { return repo.Exists<T>(sql, args); }
internal static T SingleOrDefault(object primaryKey) { return repo.SingleOrDefault<T>(primaryKey); }
internal static T SingleOrDefault(string sql, params object[] args) { return repo.SingleOrDefault<T>(sql, args); }
internal static T SingleOrDefault(Sql sql) { return repo.SingleOrDefault<T>(sql); }
internal static T FirstOrDefault(string sql, params object[] args) { return repo.FirstOrDefault<T>(sql, args); }
internal static T FirstOrDefault(Sql sql) { return repo.FirstOrDefault<T>(sql); }
internal static T Single(object primaryKey) { return repo.Single<T>(primaryKey); }
internal static T Single(string sql, params object[] args) { return repo.Single<T>(sql, args); }
internal static T Single(Sql sql) { return repo.Single<T>(sql); }
internal static T First(string sql, params object[] args) { return repo.First<T>(sql, args); }
internal static T First(Sql sql) { return repo.First<T>(sql); }
internal static List<T> Fetch(string sql, params object[] args) { return repo.Fetch<T>(sql, args); }
internal static List<T> Fetch(Sql sql) { return repo.Fetch<T>(sql); }
internal static List<T> Fetch(long page, long itemsPerPage, string sql, params object[] args) { return repo.Fetch<T>(page, itemsPerPage, sql, args); }
internal static List<T> Fetch(long page, long itemsPerPage, Sql sql) { return repo.Fetch<T>(page, itemsPerPage, sql); }
internal static List<T> SkipTake(long skip, long take, string sql, params object[] args) { return repo.SkipTake<T>(skip, take, sql, args); }
internal static List<T> SkipTake(long skip, long take, Sql sql) { return repo.SkipTake<T>(skip, take, sql); }
internal static Page<T> Page(long page, long itemsPerPage, string sql, params object[] args) { return repo.Page<T>(page, itemsPerPage, sql, args); }
internal static Page<T> Page(long page, long itemsPerPage, Sql sql) { return repo.Page<T>(page, itemsPerPage, sql); }
internal static IEnumerable<T> Query(string sql, params object[] args) { return repo.Query<T>(sql, args); }
internal static IEnumerable<T> Query(Sql sql) { return repo.Query<T>(sql); }
}
}
[TableName("task_time")]
[PrimaryKey("id", autoIncrement=false)]
[ExplicitColumns]
internal partial class TaskTime : PostgresDB.Record<TaskTime>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("time_id")] internal string TimeId { get; set; }
[Column("task_id")] internal long TaskId { get; set; }
[Column("id")] internal string Id { get; set; }
}
[TableName("time")]
[PrimaryKey("id", autoIncrement=false)]
[ExplicitColumns]
internal partial class Time : PostgresDB.Record<Time>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("worker_contact_id")] internal int WorkerContactId { get; set; }
[Column("stop")] internal DateTime Stop { get; set; }
[Column("start")] internal DateTime Start { get; set; }
[Column("id")] internal string Id { get; set; }
}
[TableName("task_tag")]
[PrimaryKey("id", autoIncrement=false)]
[ExplicitColumns]
internal partial class TaskTag : PostgresDB.Record<TaskTag>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("tag")] internal string Tag { get; set; }
[Column("tag_category_id")] internal int? TagCategoryId { get; set; }
[Column("task_id")] internal long TaskId { get; set; }
[Column("id")] internal string Id { get; set; }
}
[TableName("task")]
[PrimaryKey("id")]
[ExplicitColumns]
internal partial class Task : PostgresDB.Record<Task>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("sequential_predecessor_id")] internal long? SequentialPredecessorId { get; set; }
[Column("is_grouping_task")] internal string IsGroupingTask { get; set; }
[Column("parent_id")] internal long? ParentId { get; set; }
[Column("actual_end")] internal DateTime? ActualEnd { get; set; }
[Column("projected_end")] internal DateTime? ProjectedEnd { get; set; }
[Column("due_date")] internal DateTime? DueDate { get; set; }
[Column("projected_start")] internal DateTime? ProjectedStart { get; set; }
[Column("description")] internal string Description { get; set; }
[Column("title")] internal string Title { get; set; }
[Column("id")] internal long Id { get; set; }
}
[TableName("task_responsible_user")]
[PrimaryKey("id", autoIncrement=false)]
[ExplicitColumns]
internal partial class TaskResponsibleUser : PostgresDB.Record<TaskResponsibleUser>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("responsibility")] internal string Responsibility { get; set; }
[Column("user_id")] internal int UserId { get; set; }
[Column("task_id")] internal long TaskId { get; set; }
[Column("id")] internal string Id { get; set; }
}
[TableName("matter_contact")]
[PrimaryKey("id")]
[ExplicitColumns]
internal partial class MatterContact : PostgresDB.Record<MatterContact>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("role")] internal string Role { get; set; }
[Column("contact_id")] internal int ContactId { get; set; }
[Column("matter_id")] internal string MatterId { get; set; }
[Column("id")] internal int Id { get; set; }
}
[TableName("task_assigned_contact")]
[PrimaryKey("id", autoIncrement=false)]
[ExplicitColumns]
internal partial class TaskAssignedContact : PostgresDB.Record<TaskAssignedContact>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("assignment_type")] internal short AssignmentType { get; set; }
[Column("contact_id")] internal int ContactId { get; set; }
[Column("task_id")] internal long TaskId { get; set; }
[Column("id")] internal string Id { get; set; }
}
[TableName("contact")]
[PrimaryKey("id")]
[ExplicitColumns]
internal partial class Contact : PostgresDB.Record<Contact>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("referred_by_name")] internal string ReferredByName { get; set; }
[Column("gender")] internal string Gender { get; set; }
[Column("business_home_page")] internal string BusinessHomePage { get; set; }
[Column("personal_home_page")] internal string PersonalHomePage { get; set; }
[Column("instant_messaging_address")] internal string InstantMessagingAddress { get; set; }
[Column("language")] internal string Language { get; set; }
[Column("spouse_name")] internal string SpouseName { get; set; }
[Column("profession")] internal string Profession { get; set; }
[Column("assistant_name")] internal string AssistantName { get; set; }
[Column("manager_name")] internal string ManagerName { get; set; }
[Column("office_location")] internal string OfficeLocation { get; set; }
[Column("department_name")] internal string DepartmentName { get; set; }
[Column("company_name")] internal string CompanyName { get; set; }
[Column("title")] internal string Title { get; set; }
[Column("wedding")] internal DateTime? Wedding { get; set; }
[Column("birthday")] internal DateTime? Birthday { get; set; }
[Column("telephone10_telephone_number")] internal string Telephone10TelephoneNumber { get; set; }
[Column("telephone10_display_name")] internal string Telephone10DisplayName { get; set; }
[Column("telephone9_telephone_number")] internal string Telephone9TelephoneNumber { get; set; }
[Column("telephone9_display_name")] internal string Telephone9DisplayName { get; set; }
[Column("telephone8_telephone_number")] internal string Telephone8TelephoneNumber { get; set; }
[Column("telephone8_display_name")] internal string Telephone8DisplayName { get; set; }
[Column("telephone7_telephone_number")] internal string Telephone7TelephoneNumber { get; set; }
[Column("telephone7_display_name")] internal string Telephone7DisplayName { get; set; }
[Column("telephone6_telephone_number")] internal string Telephone6TelephoneNumber { get; set; }
[Column("telephone6_display_name")] internal string Telephone6DisplayName { get; set; }
[Column("telephone5_telephone_number")] internal string Telephone5TelephoneNumber { get; set; }
[Column("telephone5_display_name")] internal string Telephone5DisplayName { get; set; }
[Column("telephone4_telephone_number")] internal string Telephone4TelephoneNumber { get; set; }
[Column("telephone4_display_name")] internal string Telephone4DisplayName { get; set; }
[Column("telephone3_telephone_number")] internal string Telephone3TelephoneNumber { get; set; }
[Column("telephone3_display_name")] internal string Telephone3DisplayName { get; set; }
[Column("telephone2_telephone_number")] internal string Telephone2TelephoneNumber { get; set; }
[Column("telephone2_display_name")] internal string Telephone2DisplayName { get; set; }
[Column("telephone1_telephone_number")] internal string Telephone1TelephoneNumber { get; set; }
[Column("telephone1_display_name")] internal string Telephone1DisplayName { get; set; }
[Column("address3_address_post_office_box")] internal string Address3AddressPostOfficeBox { get; set; }
[Column("address3_address_country_code")] internal string Address3AddressCountryCode { get; set; }
[Column("address3_address_country")] internal string Address3AddressCountry { get; set; }
[Column("address3_address_postal_code")] internal string Address3AddressPostalCode { get; set; }
[Column("address3_address_state_or_province")] internal string Address3AddressStateOrProvince { get; set; }
[Column("address3_address_city")] internal string Address3AddressCity { get; set; }
[Column("address3_address_street")] internal string Address3AddressStreet { get; set; }
[Column("address3_display_name")] internal string Address3DisplayName { get; set; }
[Column("address2_address_post_office_box")] internal string Address2AddressPostOfficeBox { get; set; }
[Column("address2_address_country_code")] internal string Address2AddressCountryCode { get; set; }
[Column("address2_address_country")] internal string Address2AddressCountry { get; set; }
[Column("address2_address_postal_code")] internal string Address2AddressPostalCode { get; set; }
[Column("address2_address_state_or_province")] internal string Address2AddressStateOrProvince { get; set; }
[Column("address2_address_city")] internal string Address2AddressCity { get; set; }
[Column("address2_address_street")] internal string Address2AddressStreet { get; set; }
[Column("address2_display_name")] internal string Address2DisplayName { get; set; }
[Column("address1_address_post_office_box")] internal string Address1AddressPostOfficeBox { get; set; }
[Column("address1_address_country_code")] internal string Address1AddressCountryCode { get; set; }
[Column("address1_address_country")] internal string Address1AddressCountry { get; set; }
[Column("address1_address_postal_code")] internal string Address1AddressPostalCode { get; set; }
[Column("address1_address_state_or_province")] internal string Address1AddressStateOrProvince { get; set; }
[Column("address1_address_city")] internal string Address1AddressCity { get; set; }
[Column("address1_address_street")] internal string Address1AddressStreet { get; set; }
[Column("address1_display_name")] internal string Address1DisplayName { get; set; }
[Column("fax3_fax_number")] internal string Fax3FaxNumber { get; set; }
[Column("fax3_display_name")] internal string Fax3DisplayName { get; set; }
[Column("fax2_fax_number")] internal string Fax2FaxNumber { get; set; }
[Column("fax2_display_name")] internal string Fax2DisplayName { get; set; }
[Column("fax1_fax_number")] internal string Fax1FaxNumber { get; set; }
[Column("fax1_display_name")] internal string Fax1DisplayName { get; set; }
[Column("email3_email_address")] internal string Email3EmailAddress { get; set; }
[Column("email3_display_name")] internal string Email3DisplayName { get; set; }
[Column("email2_email_address")] internal string Email2EmailAddress { get; set; }
[Column("email2_display_name")] internal string Email2DisplayName { get; set; }
[Column("email1_email_address")] internal string Email1EmailAddress { get; set; }
[Column("email1_display_name")] internal string Email1DisplayName { get; set; }
[Column("display_name")] internal string DisplayName { get; set; }
[Column("initials")] internal string Initials { get; set; }
[Column("given_name")] internal string GivenName { get; set; }
[Column("middle_name")] internal string MiddleName { get; set; }
[Column("surname")] internal string Surname { get; set; }
[Column("display_name_prefix")] internal string DisplayNamePrefix { get; set; }
[Column("generation")] internal string Generation { get; set; }
[Column("nickname")] internal string Nickname { get; set; }
[Column("is_organization")] internal bool IsOrganization { get; set; }
[Column("id")] internal int Id { get; set; }
}
[TableName("task_matter")]
[PrimaryKey("id", autoIncrement=false)]
[ExplicitColumns]
internal partial class TaskMatter : PostgresDB.Record<TaskMatter>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("matter_id")] internal string MatterId { get; set; }
[Column("task_id")] internal long TaskId { get; set; }
[Column("id")] internal string Id { get; set; }
}
[TableName("responsible_user")]
[PrimaryKey("id")]
[ExplicitColumns]
internal partial class ResponsibleUser : PostgresDB.Record<ResponsibleUser>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("responsibility")] internal string Responsibility { get; set; }
[Column("user_id")] internal int UserId { get; set; }
[Column("matter_id")] internal string MatterId { get; set; }
[Column("id")] internal int Id { get; set; }
}
[TableName("matter_tag")]
[PrimaryKey("id", autoIncrement=false)]
[ExplicitColumns]
internal partial class MatterTag : PostgresDB.Record<MatterTag>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("tag")] internal string Tag { get; set; }
[Column("tag_category_id")] internal int? TagCategoryId { get; set; }
[Column("matter_id")] internal string MatterId { get; set; }
[Column("id")] internal string Id { get; set; }
}
[TableName("user")]
[PrimaryKey("id")]
[ExplicitColumns]
internal partial class User : PostgresDB.Record<User>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("user_auth_token_expiry")] internal DateTime? UserAuthTokenExpiry { get; set; }
[Column("user_auth_token")] internal string UserAuthToken { get; set; }
[Column("password_salt")] internal string PasswordSalt { get; set; }
[Column("password")] internal string Password { get; set; }
[Column("username")] internal string Username { get; set; }
[Column("id")] internal int Id { get; set; }
}
[TableName("tag_category")]
[PrimaryKey("id")]
[ExplicitColumns]
internal partial class TagCategory : PostgresDB.Record<TagCategory>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("name")] internal string Name { get; set; }
[Column("id")] internal int Id { get; set; }
}
[TableName("secured_resource")]
[PrimaryKey("id", autoIncrement=false)]
[ExplicitColumns]
internal partial class SecuredResource : PostgresDB.Record<SecuredResource>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("id")] internal string Id { get; set; }
}
[TableName("area")]
[PrimaryKey("id")]
[ExplicitColumns]
internal partial class Area : PostgresDB.Record<Area>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("description")] internal string Description { get; set; }
[Column("name")] internal string Name { get; set; }
[Column("parent_id")] internal int? ParentId { get; set; }
[Column("id")] internal int Id { get; set; }
}
[TableName("matter")]
[PrimaryKey("id", autoIncrement=false)]
[ExplicitColumns]
internal partial class Matter : PostgresDB.Record<Matter>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("id")] internal string Id { get; set; }
[Column("synopsis")] internal string Synopsis { get; set; }
[Column("parent_id")] internal string ParentId { get; set; }
[Column("title")] internal string Title { get; set; }
}
[TableName("secured_resource_acl")]
[PrimaryKey("id", autoIncrement=false)]
[ExplicitColumns]
internal partial class SecuredResourceAcl : PostgresDB.Record<SecuredResourceAcl>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("deny_flags")] internal int DenyFlags { get; set; }
[Column("allow_flags")] internal int AllowFlags { get; set; }
[Column("user_id")] internal int UserId { get; set; }
[Column("secured_resource_id")] internal string SecuredResourceId { get; set; }
[Column("id")] internal string Id { get; set; }
}
[TableName("area_acl")]
[PrimaryKey("id")]
[ExplicitColumns]
internal partial class AreaAcl : PostgresDB.Record<AreaAcl>
{
[Column("utc_disabled")] internal DateTime? UtcDisabled { get; set; }
[Column("utc_modified")] internal DateTime UtcModified { get; set; }
[Column("utc_created")] internal DateTime UtcCreated { get; set; }
[Column("disabled_by_user_id")] internal int? DisabledByUserId { get; set; }
[Column("modified_by_user_id")] internal int ModifiedByUserId { get; set; }
[Column("created_by_user_id")] internal int CreatedByUserId { get; set; }
[Column("deny_flags")] internal int DenyFlags { get; set; }
[Column("allow_flags")] internal int AllowFlags { get; set; }
[Column("user_id")] internal int UserId { get; set; }
[Column("security_area_id")] internal int SecurityAreaId { get; set; }
[Column("id")] internal int Id { get; set; }
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GraphInterpreterSpecKit.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;
using System.Collections.Generic;
using System.Linq;
using Akka.Actor;
using Akka.Configuration;
using Akka.Event;
using Akka.Streams.Implementation;
using Akka.Streams.Implementation.Fusing;
using Akka.Streams.Stage;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using Xunit.Abstractions;
namespace Akka.Streams.Tests.Implementation.Fusing
{
public class GraphInterpreterSpecKit : AkkaSpec
{
public GraphInterpreterSpecKit(ITestOutputHelper output = null, Config config = null) : base(output, config)
{
}
public abstract class BaseBuilder
{
private GraphInterpreter _interpreter;
private readonly ILoggingAdapter _logger;
protected BaseBuilder(ActorSystem system)
{
_logger = Logging.GetLogger(system, "InterpreterSpecKit");
}
public GraphInterpreter Interpreter => _interpreter;
public void StepAll()
{
Interpreter.Execute(int.MaxValue);
}
public virtual void Step()
{
Interpreter.Execute(1);
}
public class Upstream : GraphInterpreter.UpstreamBoundaryStageLogic
{
private readonly Outlet<int> _out;
public Upstream()
{
_out = new Outlet<int>("up") { Id = 0 };
}
public override Outlet Out => _out;
}
public class Downstream : GraphInterpreter.DownstreamBoundaryStageLogic
{
private readonly Inlet<int> _in;
public Downstream()
{
_in = new Inlet<int>("up") { Id = 0 };
}
public override Inlet In => _in;
}
public class AssemblyBuilder
{
private readonly ILoggingAdapter _logger;
private readonly Action<GraphInterpreter> _interpreterSetter;
private readonly IList<IGraphStageWithMaterializedValue<Shape, object>> _stages;
private readonly IList<Tuple<GraphInterpreter.UpstreamBoundaryStageLogic, Inlet>> _upstreams =
new List<Tuple<GraphInterpreter.UpstreamBoundaryStageLogic, Inlet>>();
private readonly IList<Tuple<Outlet, GraphInterpreter.DownstreamBoundaryStageLogic>> _downstreams =
new List<Tuple<Outlet, GraphInterpreter.DownstreamBoundaryStageLogic>>();
private readonly IList<Tuple<Outlet, Inlet>> _connections = new List<Tuple<Outlet, Inlet>>();
public AssemblyBuilder(ILoggingAdapter logger, Action<GraphInterpreter> interpreterSetter, IEnumerable<IGraphStageWithMaterializedValue<Shape, object>> stages)
{
_logger = logger;
_interpreterSetter = interpreterSetter;
_stages = stages.ToArray();
}
public AssemblyBuilder Connect<T>(GraphInterpreter.UpstreamBoundaryStageLogic upstream, Inlet<T> inlet)
{
_upstreams.Add(new Tuple<GraphInterpreter.UpstreamBoundaryStageLogic, Inlet>(upstream, inlet));
return this;
}
public AssemblyBuilder Connect<T>(Outlet<T> outlet, GraphInterpreter.DownstreamBoundaryStageLogic downstream)
{
_downstreams.Add(new Tuple<Outlet, GraphInterpreter.DownstreamBoundaryStageLogic>(outlet, downstream));
return this;
}
public AssemblyBuilder Connect<T>(Outlet<T> outlet, Inlet<T> inlet)
{
_connections.Add(new Tuple<Outlet, Inlet>(outlet, inlet));
return this;
}
public GraphAssembly BuildAssembly()
{
var ins = _upstreams.Select(u => u.Item2).Concat(_connections.Select(c => c.Item2)).ToArray();
var outs = _connections.Select(c => c.Item1).Concat(_downstreams.Select(d => d.Item1)).ToArray();
var inOwners =
ins.Select(
inlet =>
_stages.Select((s, i) => new {Stage = s, Index = i})
.First(s => s.Stage.Shape.Inlets.Contains(inlet))
.Index).ToArray();
var outOwners =
outs.Select(
outlet =>
_stages.Select((s, i) => new {Stage = s, Index = i})
.First(s => s.Stage.Shape.Outlets.Contains(outlet))
.Index);
return new GraphAssembly(_stages.ToArray(),
Enumerable.Repeat(Attributes.None, _stages.Count).ToArray(),
ins.Concat(Enumerable.Repeat<Inlet>(null, _downstreams.Count)).ToArray(),
inOwners.Concat(Enumerable.Repeat(-1, _downstreams.Count)).ToArray(),
Enumerable.Repeat<Outlet>(null, _upstreams.Count).Concat(outs).ToArray(),
Enumerable.Repeat(-1, _upstreams.Count).Concat(outOwners).ToArray());
}
public void Init()
{
var assembly = BuildAssembly();
var mat = assembly.Materialize(Attributes.None, assembly.Stages.Select(s => s.Module).ToArray(),
new Dictionary<IModule, object>(), s => { });
var connections = mat.Item1;
var logics = mat.Item2;
var interpreter = new GraphInterpreter(assembly, NoMaterializer.Instance, _logger, logics, connections, (l, o, a) => {}, false, null);
var i = 0;
foreach (var upstream in _upstreams)
{
interpreter.AttachUpstreamBoundary(connections[i++], upstream.Item1);
}
i = 0;
foreach (var downstream in _downstreams)
{
interpreter.AttachDownstreamBoundary(connections[i++ + _upstreams.Count + _connections.Count], downstream.Item2);
}
interpreter.Init(null);
_interpreterSetter(interpreter);
}
}
public void ManualInit(GraphAssembly assembly)
{
var mat = assembly.Materialize(Attributes.None, assembly.Stages.Select(s => s.Module).ToArray(),
new Dictionary<IModule, object>(), s => { });
var connections = mat.Item1;
var logics = mat.Item2;
_interpreter = new GraphInterpreter(assembly, NoMaterializer.Instance, _logger, logics, connections, (l, o, a) => {}, false, null);
}
public AssemblyBuilder Builder(params IGraphStageWithMaterializedValue<Shape, object>[] stages)
{
return new AssemblyBuilder(_logger, interpreter => _interpreter = interpreter, stages);
}
}
public class BaseBuilderSetup<T> : BaseBuilder
{
public BaseBuilderSetup(ActorSystem system) : base(system)
{
}
public GraphInterpreter Build(GraphInterpreter.UpstreamBoundaryStageLogic upstream, GraphStage<FlowShape<T, T>>[] ops, GraphInterpreter.DownstreamBoundaryStageLogic downstream)
{
var b = Builder(ops).Connect(upstream, ops[0].Shape.Inlet);
for (var i = 0; i < ops.Length - 1; i++)
b.Connect(ops[i].Shape.Outlet, ops[i + 1].Shape.Inlet);
b.Connect(ops[ops.Length - 1].Shape.Outlet, downstream);
b.Init();
return Interpreter;
}
}
public class TestSetup : BaseBuilder
{
#region Test Events
public interface ITestEvent
{
GraphStageLogic Source { get; }
}
public class OnComplete : ITestEvent
{
public GraphStageLogic Source { get; }
public OnComplete(GraphStageLogic source)
{
Source = source;
}
protected bool Equals(OnComplete other)
{
return Equals(Source, other.Source);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((OnComplete) obj);
}
public override int GetHashCode()
{
return Source?.GetHashCode() ?? 0;
}
}
public class Cancel : ITestEvent
{
public GraphStageLogic Source { get; }
public Cancel(GraphStageLogic source)
{
Source = source;
}
protected bool Equals(Cancel other)
{
return Equals(Source, other.Source);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((Cancel) obj);
}
public override int GetHashCode()
{
return Source?.GetHashCode() ?? 0;
}
}
public class OnError : ITestEvent
{
public GraphStageLogic Source { get; }
public Exception Cause { get; }
public OnError(GraphStageLogic source, Exception cause)
{
Source = source;
Cause = cause;
}
protected bool Equals(OnError other)
{
return Equals(Source, other.Source) && Equals(Cause, other.Cause);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((OnError) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((Source?.GetHashCode() ?? 0)*397) ^ (Cause?.GetHashCode() ?? 0);
}
}
}
public class OnNext : ITestEvent
{
public GraphStageLogic Source { get; }
public object Element { get; }
public OnNext(GraphStageLogic source, object element)
{
Source = source;
Element = element;
}
protected bool Equals(OnNext other)
{
return Equals(Source, other.Source) && Equals(Element, other.Element);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((OnNext) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((Source?.GetHashCode() ?? 0)*397) ^ (Element?.GetHashCode() ?? 0);
}
}
}
public class RequestOne : ITestEvent
{
public GraphStageLogic Source { get; }
public RequestOne(GraphStageLogic source)
{
Source = source;
}
protected bool Equals(RequestOne other)
{
return Equals(Source, other.Source);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((RequestOne) obj);
}
public override int GetHashCode()
{
return Source?.GetHashCode() ?? 0;
}
}
public class RequestAnother : ITestEvent
{
public GraphStageLogic Source { get; }
public RequestAnother(GraphStageLogic source)
{
Source = source;
}
protected bool Equals(RequestAnother other)
{
return Equals(Source, other.Source);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((RequestAnother) obj);
}
public override int GetHashCode()
{
return Source?.GetHashCode() ?? 0;
}
}
public class PreStart : ITestEvent
{
public GraphStageLogic Source { get; }
public PreStart(GraphStageLogic source)
{
Source = source;
}
protected bool Equals(PreStart other)
{
return Equals(Source, other.Source);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((PreStart) obj);
}
public override int GetHashCode()
{
return Source?.GetHashCode() ?? 0;
}
}
public class PostStop : ITestEvent
{
public GraphStageLogic Source { get; }
public PostStop(GraphStageLogic source)
{
Source = source;
}
protected bool Equals(PostStop other)
{
return Equals(Source, other.Source);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((PostStop) obj);
}
public override int GetHashCode()
{
return Source?.GetHashCode() ?? 0;
}
}
#endregion
public TestSetup(ActorSystem system) : base(system)
{
}
public ISet<ITestEvent> LastEvent = new HashSet<ITestEvent>();
public ISet<ITestEvent> LastEvents()
{
var result = LastEvent;
ClearEvents();
return result;
}
public void ClearEvents()
{
LastEvent = new HashSet<ITestEvent>();
}
public UpstreamProbe<T> NewUpstreamProbe<T>(string name)
{
return new UpstreamProbe<T>(this, name);
}
public DownstreamProbe<T> NewDownstreamProbe<T>(string name)
{
return new DownstreamProbe<T>(this, name);
}
public class UpstreamProbe<T> : GraphInterpreter.UpstreamBoundaryStageLogic
{
private readonly string _name;
public UpstreamProbe(TestSetup setup, string name)
{
_name = name;
Out = new Outlet<T>("out") {Id = 0};
var probe = this;
SetHandler(Out, () => setup.LastEvent.Add(new RequestOne(probe)), () => setup.LastEvent.Add(new Cancel(probe)));
}
public sealed override Outlet Out { get; }
public void OnNext(T element, int eventLimit = int.MaxValue)
{
if (GraphInterpreter.IsDebug)
Console.WriteLine($"----- NEXT: {this} {element}");
Push(Out, element);
Interpreter.Execute(eventLimit);
}
public void OnComplete(int eventLimit = int.MaxValue)
{
if (GraphInterpreter.IsDebug)
Console.WriteLine($"----- COMPLETE: {this}");
Complete(Out);
Interpreter.Execute(eventLimit);
}
public void OnFailure(int eventLimit = int.MaxValue, Exception ex = null)
{
if (GraphInterpreter.IsDebug)
Console.WriteLine($"----- FAIL: {this}");
Fail(Out, ex);
Interpreter.Execute(eventLimit);
}
public override string ToString()
{
return _name;
}
}
public class DownstreamProbe<T> : GraphInterpreter.DownstreamBoundaryStageLogic
{
private readonly string _name;
public DownstreamProbe(TestSetup setup, string name)
{
_name = name;
In = new Inlet<T>("in") {Id = 0};
var probe = this;
SetHandler(In, () => setup.LastEvent.Add(new OnNext(probe, Grab<T>(In))),
() => setup.LastEvent.Add(new OnComplete(probe)),
ex => setup.LastEvent.Add(new OnError(probe, ex)));
}
public sealed override Inlet In { get; }
public void RequestOne(int eventLimit = int.MaxValue)
{
if (GraphInterpreter.IsDebug)
Console.WriteLine($"----- REQ: {this}");
Pull(In);
Interpreter.Execute(eventLimit);
}
public void Cancel(int eventLimit = int.MaxValue)
{
if (GraphInterpreter.IsDebug)
Console.WriteLine($"----- CANCEL: {this}");
Cancel(In);
Interpreter.Execute(eventLimit);
}
public override string ToString()
{
return _name;
}
}
}
public class PortTestSetup : TestSetup
{
private readonly bool _chasing;
public UpstreamPortProbe<int> Out { get; }
public DownstreamPortProbe<int> In { get; }
private readonly GraphAssembly _assembly;
public PortTestSetup(ActorSystem system, bool chasing = false) : base(system)
{
_chasing = chasing;
var propagateStage = new EventPropagateStage();
_assembly = !chasing
? new GraphAssembly(new IGraphStageWithMaterializedValue<Shape, object>[0], new Attributes[0],
new Inlet[] {null}, new[] {-1}, new Outlet[] {null}, new[] {-1})
: new GraphAssembly(new[] {propagateStage}, new[] {Attributes.None},
new Inlet[] {propagateStage.In, null}, new[] {0, -1}, new Outlet[] {null, propagateStage.Out},
new[] {-1, 0});
Out = new UpstreamPortProbe<int>(this);
In = new DownstreamPortProbe<int>(this);
ManualInit(_assembly);
Interpreter.AttachDownstreamBoundary(Interpreter.Connections[chasing ? 1 : 0], In);
Interpreter.AttachUpstreamBoundary(Interpreter.Connections[0], Out);
Interpreter.Init(null);
}
public class EventPropagateStage : GraphStage<FlowShape<int, int>>
{
private sealed class Logic : GraphStageLogic, IInHandler, IOutHandler
{
private readonly EventPropagateStage _stage;
public Logic(EventPropagateStage stage) :base(stage.Shape)
{
_stage = stage;
SetHandler(stage.In, this);
SetHandler(stage.Out, this);
}
public void OnPush() => Push(_stage.Out, Grab(_stage.In));
public void OnUpstreamFinish() => Complete(_stage.Out);
public void OnUpstreamFailure(Exception e) => Fail(_stage.Out, e);
public void OnPull() => Pull(_stage.In);
public void OnDownstreamFinish() => Cancel(_stage.In);
}
public EventPropagateStage()
{
Shape = new FlowShape<int, int>(In, Out);
}
public Inlet<int> In { get; } = new Inlet<int>("Propagate.in");
public Outlet<int> Out { get; } = new Outlet<int>("Propagate.out");
public override FlowShape<int, int> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
// Step() means different depending whether we have a stage between the two probes or not
public override void Step() => Interpreter.Execute(!_chasing ? 1 : 2);
public class UpstreamPortProbe<T> : UpstreamProbe<T>
{
public UpstreamPortProbe(TestSetup setup) : base(setup, "upstreamPort")
{
}
public bool IsAvailable() => IsAvailable(Out);
public bool IsClosed() => IsClosed(Out);
public void Push(T element) => Push(Out, element);
public void Complete() => Complete(Out);
public void Fail(Exception ex) => Fail(Out, ex);
}
public class DownstreamPortProbe<T> : DownstreamProbe<T>
{
public DownstreamPortProbe(TestSetup setup) : base(setup, "downstreamPort")
{
var probe = this;
SetHandler(In, () =>
{
// Modified onPush that does not Grab() automatically the element. This access some internals.
var internalEvent = PortToConn[In.Id].Slot;
if (internalEvent is GraphInterpreter.Failed)
((PortTestSetup) setup).LastEvent.Add(new OnNext(probe,
((GraphInterpreter.Failed) internalEvent).PreviousElement));
else
((PortTestSetup) setup).LastEvent.Add(new OnNext(probe, internalEvent));
},
() => ((PortTestSetup) setup).LastEvent.Add(new OnComplete(probe)),
ex => ((PortTestSetup) setup).LastEvent.Add(new OnError(probe, ex))
);
}
public bool IsAvailable() => IsAvailable(In);
public bool HasBeenPulled() => HasBeenPulled(In);
public bool IsClosed() => IsClosed(In);
public void Pull() => Pull(In);
public void Cancel() => Cancel(In);
public T Grab() => Grab<T>(In);
}
}
public class FailingStageSetup : TestSetup
{
public new UpstreamPortProbe<int> Upstream { get; }
public new DownstreamPortProbe<int> Downstream { get; }
private bool _failOnNextEvent;
private bool _failOnPostStop;
private readonly Inlet<int> _stageIn;
private readonly Outlet<int> _stageOut;
private readonly FlowShape<int, int> _stageShape;
// Must be lazy because I turned this stage "inside-out" therefore changing initialization order
// to make tests a bit more readable
public Lazy<GraphStageLogic> Stage { get; }
public FailingStageSetup(ActorSystem system, bool initFailOnNextEvent = false) : base(system)
{
Upstream = new UpstreamPortProbe<int>(this);
Downstream = new DownstreamPortProbe<int>(this);
_failOnNextEvent = initFailOnNextEvent;
_failOnPostStop = false;
_stageIn = new Inlet<int>("sandwitch.in");
_stageOut = new Outlet<int>("sandwitch.out");
_stageShape = new FlowShape<int, int>(_stageIn, _stageOut);
Stage = new Lazy<GraphStageLogic>(() => new FailingGraphStageLogic(this, _stageShape));
GraphStage<FlowShape<int, int>> sandwitchStage = new SandwitchStage(this);
Builder(sandwitchStage)
.Connect(Upstream, _stageIn)
.Connect(_stageOut, Downstream)
.Init();
}
public void FailOnNextEvent()
{
_failOnNextEvent = true;
}
public void FailOnPostStop()
{
_failOnPostStop = true;
}
public Exception TestException()
{
return new TestException("test");
}
public class FailingGraphStageLogic : GraphStageLogic
{
private readonly FailingStageSetup _setup;
public FailingGraphStageLogic(FailingStageSetup setup, Shape shape) : base(shape)
{
_setup = setup;
SetHandler(setup._stageIn,
() => MayFail(() => Push(setup._stageOut, Grab(setup._stageIn))),
() => MayFail(CompleteStage),
ex => MayFail(() => FailStage(ex)));
SetHandler(setup._stageOut,
() => MayFail(() => Pull(setup._stageIn)),
() => MayFail(CompleteStage));
}
private void MayFail(Action task)
{
if (!_setup._failOnNextEvent)
task();
else
{
_setup._failOnNextEvent = false;
throw _setup.TestException();
}
}
public override void PreStart()
{
MayFail(() => _setup.LastEvent.Add(new PreStart(this)));
}
public override void PostStop()
{
if (!_setup._failOnPostStop)
_setup.LastEvent.Add(new PostStop(this));
else throw _setup.TestException();
}
public override string ToString()
{
return "stage";
}
}
public class SandwitchStage : GraphStage<FlowShape<int, int>>
{
private readonly FailingStageSetup _setup;
public SandwitchStage(FailingStageSetup setup)
{
_setup = setup;
}
public override FlowShape<int, int> Shape => _setup._stageShape;
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes)
{
return _setup.Stage.Value;
}
public override string ToString()
{
return "stage";
}
}
public class UpstreamPortProbe<T> : UpstreamProbe<T>
{
public UpstreamPortProbe(TestSetup setup) : base(setup, "upstreamPort")
{
}
public void Push(T element)
{
Push(Out, element);
}
public void Complete()
{
Complete(Out);
}
public void Fail(Exception ex)
{
Fail(Out, ex);
}
}
public class DownstreamPortProbe<T> : DownstreamProbe<T>
{
public DownstreamPortProbe(TestSetup setup) : base(setup, "downstreamPort")
{
}
public void Pull()
{
Pull(In);
}
public void Cancel()
{
Cancel(In);
}
}
}
public abstract class OneBoundedSetup : BaseBuilder
{
#region Test Events
public interface ITestEvent
{
}
public class OnComplete : ITestEvent
{
protected bool Equals(OnComplete other)
{
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (OnComplete)) return false;
return Equals((OnComplete) obj);
}
public override int GetHashCode()
{
return 0;
}
}
public class Cancel : ITestEvent
{
protected bool Equals(Cancel other)
{
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Cancel)) return false;
return Equals((Cancel) obj);
}
public override int GetHashCode()
{
return 0;
}
}
public class OnError : ITestEvent
{
public Exception Cause { get; }
public OnError(Exception cause)
{
Cause = cause;
}
protected bool Equals(OnError other)
{
return Equals(Cause, other.Cause);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((OnError) obj);
}
public override int GetHashCode()
{
return Cause?.GetHashCode() ?? 0;
}
}
public class OnNext : ITestEvent
{
public object Element { get; }
public OnNext(object element)
{
Element = element;
}
protected bool Equals(OnNext other)
{
return Element is IEnumerable
? ((IEnumerable) Element).Cast<object>().SequenceEqual(((IEnumerable) other.Element).Cast<object>())
: Equals(Element, other.Element);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((OnNext) obj);
}
public override int GetHashCode()
{
return Element?.GetHashCode() ?? 0;
}
}
public class RequestOne : ITestEvent
{
protected bool Equals(RequestOne other)
{
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (RequestOne)) return false;
return Equals((RequestOne) obj);
}
public override int GetHashCode()
{
return 0;
}
}
public class RequestAnother : ITestEvent
{
protected bool Equals(RequestAnother other)
{
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (RequestAnother)) return false;
return Equals((RequestAnother) obj);
}
public override int GetHashCode()
{
return 0;
}
}
#endregion
protected OneBoundedSetup(ActorSystem system) : base(system)
{
}
protected ISet<ITestEvent> LastEvent { get; private set; } = new HashSet<ITestEvent>();
public ISet<ITestEvent> LastEvents()
{
var events = LastEvent;
LastEvent = new HashSet<ITestEvent>();
return events;
}
protected abstract void Run();
public class UpstreamOneBoundedProbe<T> : GraphInterpreter.UpstreamBoundaryStageLogic
{
private readonly OneBoundedSetup _setup;
public UpstreamOneBoundedProbe(OneBoundedSetup setup)
{
_setup = setup;
Out = new Outlet<T>("out") {Id = 0};
SetHandler(Out, () =>
{
if (setup.LastEvent.OfType<RequestOne>().Any())
setup.LastEvent.Add(new RequestAnother());
else
setup.LastEvent.Add(new RequestOne());
}, () => setup.LastEvent.Add(new Cancel()));
}
public override Outlet Out { get; }
public void OnNext(T element)
{
Push(Out, element);
_setup.Run();
}
public void OnComplete()
{
Complete(Out);
_setup.Run();
}
public void OnNextAndComplete(T element)
{
Push(Out, element);
Complete(Out);
_setup.Run();
}
public void OnError(Exception ex)
{
Fail(Out, ex);
_setup.Run();
}
}
public class DownstreamOneBoundedPortProbe<T> : GraphInterpreter.DownstreamBoundaryStageLogic
{
private readonly OneBoundedSetup _setup;
public DownstreamOneBoundedPortProbe(OneBoundedSetup setup)
{
_setup = setup;
In = new Inlet<T>("in") {Id = 0};
SetHandler(In, () =>
{
setup.LastEvent.Add(new OnNext(Grab<object>(In)));
},
() => setup.LastEvent.Add(new OnComplete()),
ex => setup.LastEvent.Add(new OnError(ex)));
}
public override Inlet In { get; }
public void RequestOne()
{
Pull(In);
_setup.Run();
}
public void Cancel()
{
Cancel(In);
_setup.Run();
}
}
}
public class OneBoundedSetup<TIn, TOut> : OneBoundedSetup
{
public OneBoundedSetup(ActorSystem system, params IGraphStageWithMaterializedValue<Shape, object>[] ops) : base(system)
{
Ops = ops;
Upstream = new UpstreamOneBoundedProbe<TIn>(this);
Downstream = new DownstreamOneBoundedPortProbe<TOut>(this);
Initialize();
Run(); // Detached stages need the prefetch
}
public IGraphStageWithMaterializedValue<Shape, object>[] Ops { get; }
public new UpstreamOneBoundedProbe<TIn> Upstream { get; }
public new DownstreamOneBoundedPortProbe<TOut> Downstream { get; }
protected sealed override void Run()
{
Interpreter.Execute(int.MaxValue);
}
private void Initialize()
{
var attributes = Enumerable.Repeat(Attributes.None, Ops.Length).ToArray();
var ins = new Inlet[Ops.Length + 1];
var inOwners = new int[Ops.Length + 1];
var outs = new Outlet[Ops.Length + 1];
var outOwners = new int[Ops.Length + 1];
ins[Ops.Length] = null;
inOwners[Ops.Length] = GraphInterpreter.Boundary;
outs[0] = null;
outOwners[0] = GraphInterpreter.Boundary;
for (int i = 0; i < Ops.Length; i++)
{
var shape = (IFlowShape) Ops[i].Shape;
ins[i] = shape.Inlet;
inOwners[i] = i;
outs[i + 1] = shape.Outlet;
outOwners[i + 1] = i;
}
ManualInit(new GraphAssembly(Ops, attributes, ins, inOwners, outs, outOwners));
Interpreter.AttachUpstreamBoundary(0, Upstream);
Interpreter.AttachDownstreamBoundary(Ops.Length, Downstream);
Interpreter.Init(null);
}
}
public class OneBoundedSetup<T> : OneBoundedSetup<T, T>
{
public OneBoundedSetup(ActorSystem system, params IGraphStageWithMaterializedValue<Shape, object>[] ops) : base(system, ops)
{
}
}
public PushPullGraphStage<TIn, TOut> ToGraphStage<TIn, TOut>(IStage<TIn, TOut> stage)
{
var s = stage;
return new PushPullGraphStage<TIn, TOut>(_ => s, Attributes.None);
}
public IGraphStageWithMaterializedValue<Shape, object>[] ToGraphStage<TIn, TOut>(IStage<TIn, TOut>[] stages)
{
return stages.Select(ToGraphStage).Cast<IGraphStageWithMaterializedValue<Shape, object>>().ToArray();
}
public void WithTestSetup(Action<TestSetup, Func<ISet<TestSetup.ITestEvent>>> spec)
{
var setup = new TestSetup(Sys);
spec(setup, setup.LastEvents);
}
public void WithTestSetup(
Action
<TestSetup, Func<IGraphStageWithMaterializedValue<Shape, object>, BaseBuilder.AssemblyBuilder>,
Func<ISet<TestSetup.ITestEvent>>> spec)
{
var setup = new TestSetup(Sys);
spec(setup, g => setup.Builder(g), setup.LastEvents);
}
public void WithTestSetup(
Action
<TestSetup, Func<IGraphStageWithMaterializedValue<Shape, object>[], BaseBuilder.AssemblyBuilder>,
Func<ISet<TestSetup.ITestEvent>>> spec)
{
var setup = new TestSetup(Sys);
spec(setup, setup.Builder, setup.LastEvents);
}
public void WithOneBoundedSetup<T>(IStage<T, T> op,
Action
<Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<T>,
OneBoundedSetup.DownstreamOneBoundedPortProbe<T>> spec)
{
WithOneBoundedSetup<T>(ToGraphStage(op), spec);
}
public void WithOneBoundedSetup<T>(IStage<T, T>[] ops,
Action
<Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<T>,
OneBoundedSetup.DownstreamOneBoundedPortProbe<T>> spec)
{
WithOneBoundedSetup<T>(ToGraphStage(ops), spec);
}
public void WithOneBoundedSetup<T>(IGraphStageWithMaterializedValue<Shape, object> op,
Action
<Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<T>,
OneBoundedSetup.DownstreamOneBoundedPortProbe<T>>
spec)
{
WithOneBoundedSetup<T>(new[] {op}, spec);
}
public void WithOneBoundedSetup<T>(IGraphStageWithMaterializedValue<Shape, object>[] ops,
Action
<Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<T>, OneBoundedSetup.DownstreamOneBoundedPortProbe<T>>
spec)
{
var setup = new OneBoundedSetup<T>(Sys, ops);
spec(setup.LastEvents, setup.Upstream, setup.Downstream);
}
public void WithOneBoundedSetup<TIn, TOut>(IGraphStageWithMaterializedValue<Shape, object> op,
Action
<Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<TIn>,
OneBoundedSetup.DownstreamOneBoundedPortProbe<TOut>>
spec)
{
WithOneBoundedSetup(new[] {op}, spec);
}
public void WithOneBoundedSetup<TIn, TOut>(IGraphStageWithMaterializedValue<Shape, object>[] ops,
Action
<Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<TIn>, OneBoundedSetup.DownstreamOneBoundedPortProbe<TOut>>
spec)
{
var setup = new OneBoundedSetup<TIn, TOut>(Sys, ops);
spec(setup.LastEvents, setup.Upstream, setup.Downstream);
}
public void WithOneBoundedSetup<TIn, TOut>(IGraphStageWithMaterializedValue<FlowShape<TIn, TOut>, object> op,
Action
<Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<TIn>, OneBoundedSetup.DownstreamOneBoundedPortProbe<TOut>>
spec)
{
WithOneBoundedSetup(new[] { op }, spec);
}
public void WithOneBoundedSetup<TIn, TOut>(IGraphStageWithMaterializedValue<FlowShape<TIn, TOut>, object>[] ops,
Action
<Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<TIn>, OneBoundedSetup.DownstreamOneBoundedPortProbe<TOut>>
spec)
{
var setup = new OneBoundedSetup<TIn, TOut>(Sys, ops);
spec(setup.LastEvents, setup.Upstream, setup.Downstream);
}
public void WithBaseBuilderSetup<T>(GraphStage<FlowShape<T, T>>[] ops, Action<GraphInterpreter> spec)
{
var interpreter = new BaseBuilderSetup<T>(Sys).Build(new BaseBuilder.Upstream(), ops, new BaseBuilder.Downstream());
spec(interpreter);
}
}
}
| |
namespace SimpleECS
{
using System;
using System.Collections;
using System.Collections.Generic;
using Internal;
/// <summary>
/// stores component data of entities that matches the archetype's type signature
/// </summary>
public struct Archetype : IEquatable<Archetype>, IEnumerable<Entity>
{
internal Archetype(World world, int index, int version)
{
this.world = world; this.index = index; this.version = version;
}
/// <summary>
/// returns a copy of archetype's type signature
/// </summary>
public TypeSignature GetTypeSignature()
=> this.TryGetArchetypeInfo(out var archetype_Info) ? new TypeSignature(archetype_Info.signature) : new TypeSignature();
/// <summary>
/// returns a copy of component types in this archetype
/// </summary>
public Type[] GetTypes()
=> this.TryGetArchetypeInfo(out var archetype_Info) ? archetype_Info.GetComponentTypes() : new Type[0];
/// <summary>
/// the world this archetype belongs to
/// </summary>
public readonly World world;
/// <summary>
/// the index and version create a unique identifier for the archetype
/// </summary>
public readonly int index;
/// <summary>
/// the index and version create a unique identifier for the archetype
/// </summary>
public readonly int version;
/// <summary>
/// [structural]
/// creates an entity that matches this archetype
/// </summary>
public Entity CreateEntity()
{
if (this.TryGetArchetypeInfo(out var world_info, out var archetype_info))
return world_info.StructureEvents.CreateEntity(archetype_info);
return default;
}
/// <summary>
/// returns a copy of all the entities stored in the archetype
/// </summary>
public Entity[] GetEntities()
{
Entity[] entities = new Entity[EntityCount];
if (this.TryGetArchetypeInfo(out var archetype_info))
for (int i = 0; i < archetype_info.entity_count; ++i)
entities[i] = archetype_info.entities[i];
return entities;
}
/// <summary>
/// returns the total amount of entities stored in the archetype
/// </summary>
public int EntityCount => this.TryGetArchetypeInfo(out var archetype_Info) ? archetype_Info.entity_count : 0;
/// <summary>
/// returns false if the archetype is invalid or destroyed.
/// outputs the raw entity storage buffer.
/// should be treated as readonly as changing values will break the ecs.
/// only entities up to archetype's EntityCount are valid, DO NOT use the length of the array
/// </summary>
public bool TryGetEntityBuffer(out Entity[] entity_buffer)
{
if (this.TryGetArchetypeInfo(out var data))
{
entity_buffer = data.entities;
return true;
}
entity_buffer = default;
return false;
}
/// <summary>
/// returns false if the archetype is invalid or does not store the component buffer
/// outputs the raw component storage buffer.
/// only components up to archetype's EntityCount are valid
/// entities in the entity buffer that share the same index as the component in the component buffer own that component
/// </summary>
public bool TryGetComponentBuffer<Component>(out Component[] comp_buffer)
{
if (this.TryGetArchetypeInfo(out var data))
return data.TryGetArray(out comp_buffer);
comp_buffer = default;
return false;
}
/// <summary>
/// [structural]
/// destroys the archetype along with all the entities within it
/// </summary>
public void Destroy()
{
if (world.IsValid())
World_Info.All[world.index].data.StructureEvents.DestroyArchetype(this);
}
/// <summary>
/// [structural]
/// resizes the archetype's backing arrays to the minimum number of 2 needed to store the entities
/// </summary>
public void ResizeBackingArrays()
{
if (world.IsValid())
World_Info.All[world.index].data.StructureEvents.ResizeBackingArrays(this);
}
bool IEquatable<Archetype>.Equals(Archetype other)
=> world == other.world && index == other.index && version == other.version;
/// <summary>
/// returns true if the archetype is not null or destroyed
/// </summary>
public bool IsValid()
=> world.TryGetWorldInfo(out var info) && info.archetypes[index].version == version;
public static implicit operator bool(Archetype archetype) => archetype.IsValid();
public override bool Equals(object obj) => obj is Archetype a ? a == this : false;
public static implicit operator int(Archetype a) => a.index;
public static bool operator ==(Archetype a, Archetype b) => a.world == b.world && a.index == b.index && a.version == b.version;
public static bool operator !=(Archetype a, Archetype b) => !(a == b);
public override int GetHashCode() => index;
public override string ToString() => $"{(IsValid() ? "" : "~")}Arch [{GetTypeString()}]";
string GetTypeString()
{
string val = "";
if (this.TryGetArchetypeInfo(out var archetype_info))
{
for(int i = 0; i < archetype_info.component_count; ++ i)
{
val += $" {TypeID.Get(archetype_info.component_buffers[i].type_id).Name}";
}
}
return val;
}
IEnumerator<Entity> IEnumerable<Entity>.GetEnumerator()
{
if (this.TryGetArchetypeInfo(out var info))
for(int i = 0; i < info.entity_count; ++ i)
yield return info.entities[i];
}
IEnumerator IEnumerable.GetEnumerator()
{
if (this.TryGetArchetypeInfo(out var info))
for(int i = 0; i < info.entity_count; ++ i)
yield return info.entities[i];
}
}
}
namespace SimpleECS.Internal
{
using System;
using System.Collections;
public static partial class Extensions
{
public static bool TryGetArchetypeInfo(this Archetype archetype, out World_Info world_info, out Archetype_Info arch_info)
{
if (archetype.world.TryGetWorldInfo(out world_info))
{
var arch = world_info.archetypes[archetype.index];
if (arch.version == archetype.version)
{
arch_info = arch.data;
return true;
}
}
arch_info = default;
world_info = default;
return false;
}
public static bool TryGetArchetypeInfo(this Archetype archetype, out Archetype_Info arch_info)
{
if (archetype.world.TryGetWorldInfo(out var world_info))
{
var arch = world_info.archetypes[archetype.index];
if (arch.version == archetype.version)
{
arch_info = arch.data;
return true;
}
}
arch_info = default;
return false;
}
}
public class Archetype_Info
{
public Archetype_Info(World_Info world, TypeSignature signature, int arch_index, int arch_version)
{
this.world_info = world;
this.signature = signature;
this.archetype = new Archetype(world.world, arch_index, arch_version);
component_buffers = new CompBufferData[signature.Count == 0 ? 1 : signature.Count];
component_count = signature.Count;
for (int i = 0; i < component_buffers.Length; ++i)
component_buffers[i].next = -1;
// add components into empty bucket, skip if bucket is occupied
for(int i = 0 ; i < component_count; ++ i)
{
var type = signature.Types[i];
var type_id = TypeID.Get(type);
var index = type_id % component_buffers.Length;
ref var buffer_data = ref component_buffers[index];
if (buffer_data.type_id == 0)
{
buffer_data.type_id = type_id;
buffer_data.buffer = CreatePool(type);
}
}
// add skipped components into buckets not filled in first pass
// hopefully this minimizes lookup time
for(int i = 0; i < component_count; ++ i)
{
var type = signature.Types[i];
var type_id = TypeID.Get(type);
if (ContainsType(type_id)) continue;
var index = GetEmptyIndex(type_id%component_buffers.Length);
ref var buffer_data = ref component_buffers[index];
buffer_data.type_id = type_id;
buffer_data.buffer = CreatePool(type);
}
bool ContainsType(int type_id)
{
foreach(var val in component_buffers)
if (val.type_id == type_id) return true;
return false;
}
// if current index is filled, will return an empty index with a way to get to that index from the provided one
int GetEmptyIndex(int current_index)
{
if (component_buffers[current_index].type_id == 0)
return current_index;
while (component_buffers[current_index].next >= 0)
{
current_index = component_buffers[current_index].next;
}
for (int i = 0; i < component_count; ++i)
if (component_buffers[i].type_id == 0)
{
component_buffers[current_index].next = i;
return i;
}
throw new Exception("FRAMEWORK BUG: not enough components in archetype");
}
CompBuffer CreatePool(Type type)
=> Activator.CreateInstance(typeof(CompBuffer<>).MakeGenericType(type)) as CompBuffer;
}
public int entity_count;
public Entity[] entities = new Entity[8];
public World_Info world_info;
public TypeSignature signature;
public readonly Archetype archetype;
public readonly int component_count;
public CompBufferData[] component_buffers;
public struct CompBufferData
{
public int next;
public int type_id;
public CompBuffer buffer;
}
/// <summary>
/// resizes all backing arrays to minimum power of 2
/// </summary>
public void ResizeBackingArrays()
{
int size = 8;
while (size <= entity_count)
size *= 2;
System.Array.Resize(ref entities, size);
for(int i = 0; i < component_count; ++ i)
component_buffers[i].buffer.Resize(size);
}
public void EnsureCapacity(int capacity)
{
if (capacity >= entities.Length)
{
int size = entities.Length;
while (capacity >= size)
size *= 2;
System.Array.Resize(ref entities, size);
for (int i = 0; i < component_count; ++i)
component_buffers[i].buffer.Resize(size);
}
}
public bool Has(int type_id)
{
var data = component_buffers[type_id % component_buffers.Length];
if (data.type_id == type_id)
return true;
while (data.next >= 0)
{
data = component_buffers[data.next];
if (data.type_id == type_id)
return true;
}
return false;
}
public bool TryGetArray<Component>(out Component[] components)
{
int type_id = TypeID<Component>.Value;
var data = component_buffers[type_id % component_buffers.Length];
if (data.type_id == type_id)
{
components = (Component[])data.buffer.array;
return true;
}
while (data.next >= 0)
{
data = component_buffers[data.next];
if (data.type_id == type_id)
{
components = (Component[])data.buffer.array;
return true;
}
}
components = default;
return false;
}
public bool TryGetCompBuffer(int type_id, out CompBuffer buffer)
{
var data = component_buffers[type_id % component_buffers.Length];
if (data.type_id == type_id)
{
buffer = data.buffer;
return true;
}
while (data.next >= 0)
{
data = component_buffers[data.next];
if (data.type_id == type_id)
{
buffer = data.buffer;
return true;
}
}
buffer = default;
return false;
}
public object[] GetAllComponents(int entity_arch_index)
{
object[] components = new object[component_count];
for (int i = 0; i < component_count; ++i)
components[i] = component_buffers[i].buffer.array[entity_arch_index];
return components;
}
public Type[] GetComponentTypes()
{
Type[] components = new Type[component_count];
for (int i = 0; i < component_count; ++i)
components[i] = TypeID.Get(component_buffers[i].type_id);
return components;
}
public abstract class CompBuffer //handles component data
{
public IList array;
public abstract void Resize(int capacity);
/// <summary>
/// returns removed component
/// </summary>
public abstract object Remove(int entity_arch_index, int last);
public abstract void Move(int entity_arch_index, int last_entity_index, Archetype_Info target_archetype, int target_index);
public abstract void Move(int entity_arch_index, int last_entity_index, object buffer, int target_index);
}
public sealed class CompBuffer<Component> : CompBuffer
{
public CompBuffer()
{
array = components;
}
public Component[] components = new Component[8];
public override void Resize(int capacity)
{
System.Array.Resize(ref components, capacity);
array = components;
}
public override object Remove(int entity_arch_index, int last)
{
var comp = components[entity_arch_index];
components[entity_arch_index] = components[last];
components[last] = default;
return comp;
}
public override void Move(int entity_arch_index, int last_entity_index, Archetype_Info target_archetype, int target_index)
{
if (target_archetype.TryGetArray<Component>(out var target_array))
{
target_array[target_index] = components[entity_arch_index];
}
components[entity_arch_index] = components[last_entity_index];
components[last_entity_index] = default;
}
public override void Move(int entity_arch_index, int last_entity_index, object buffer, int target_index)
{
((Component[])buffer)[target_index] = components[entity_arch_index];
components[entity_arch_index] = components[last_entity_index];
components[last_entity_index] = default;
}
}
}
}
| |
// 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 Microsoft.Azure.Management.Network.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Network;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Network security rule.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class SecurityRule : SubResource
{
/// <summary>
/// Initializes a new instance of the SecurityRule class.
/// </summary>
public SecurityRule()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SecurityRule class.
/// </summary>
/// <param name="protocol">Network protocol this rule applies to.
/// Possible values are 'Tcp', 'Udp', and '*'. Possible values include:
/// 'Tcp', 'Udp', '*'</param>
/// <param name="sourceAddressPrefix">The CIDR or source IP range.
/// Asterix '*' can also be used to match all source IPs. Default tags
/// such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can
/// also be used. If this is an ingress rule, specifies where network
/// traffic originates from. </param>
/// <param name="destinationAddressPrefix">The destination address
/// prefix. CIDR or destination IP range. Asterix '*' can also be used
/// to match all source IPs. Default tags such as 'VirtualNetwork',
/// 'AzureLoadBalancer' and 'Internet' can also be used.</param>
/// <param name="access">The network traffic is allowed or denied.
/// Possible values are: 'Allow' and 'Deny'. Possible values include:
/// 'Allow', 'Deny'</param>
/// <param name="direction">The direction of the rule. The direction
/// specifies if rule will be evaluated on incoming or outcoming
/// traffic. Possible values are: 'Inbound' and 'Outbound'. Possible
/// values include: 'Inbound', 'Outbound'</param>
/// <param name="id">Resource ID.</param>
/// <param name="description">A description for this rule. Restricted
/// to 140 chars.</param>
/// <param name="sourcePortRange">The source port or range. Integer or
/// range between 0 and 65535. Asterix '*' can also be used to match
/// all ports.</param>
/// <param name="destinationPortRange">The destination port or range.
/// Integer or range between 0 and 65535. Asterix '*' can also be used
/// to match all ports.</param>
/// <param name="sourceAddressPrefixes">The CIDR or source IP
/// ranges.</param>
/// <param name="destinationAddressPrefixes">The destination address
/// prefixes. CIDR or destination IP ranges.</param>
/// <param name="sourcePortRanges">The source port ranges.</param>
/// <param name="destinationPortRanges">The destination port
/// ranges.</param>
/// <param name="priority">The priority of the rule. The value can be
/// between 100 and 4096. The priority number must be unique for each
/// rule in the collection. The lower the priority number, the higher
/// the priority of the rule.</param>
/// <param name="provisioningState">The provisioning state of the
/// public IP resource. Possible values are: 'Updating', 'Deleting',
/// and 'Failed'.</param>
/// <param name="name">The name of the resource that is unique within a
/// resource group. This name can be used to access the
/// resource.</param>
/// <param name="etag">A unique read-only string that changes whenever
/// the resource is updated.</param>
public SecurityRule(string protocol, string sourceAddressPrefix, string destinationAddressPrefix, string access, string direction, string id = default(string), string description = default(string), string sourcePortRange = default(string), string destinationPortRange = default(string), IList<string> sourceAddressPrefixes = default(IList<string>), IList<string> destinationAddressPrefixes = default(IList<string>), IList<string> sourcePortRanges = default(IList<string>), IList<string> destinationPortRanges = default(IList<string>), int? priority = default(int?), string provisioningState = default(string), string name = default(string), string etag = default(string))
: base(id)
{
Description = description;
Protocol = protocol;
SourcePortRange = sourcePortRange;
DestinationPortRange = destinationPortRange;
SourceAddressPrefix = sourceAddressPrefix;
SourceAddressPrefixes = sourceAddressPrefixes;
DestinationAddressPrefix = destinationAddressPrefix;
DestinationAddressPrefixes = destinationAddressPrefixes;
SourcePortRanges = sourcePortRanges;
DestinationPortRanges = destinationPortRanges;
Access = access;
Priority = priority;
Direction = direction;
ProvisioningState = provisioningState;
Name = name;
Etag = etag;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets a description for this rule. Restricted to 140 chars.
/// </summary>
[JsonProperty(PropertyName = "properties.description")]
public string Description { get; set; }
/// <summary>
/// Gets or sets network protocol this rule applies to. Possible values
/// are 'Tcp', 'Udp', and '*'. Possible values include: 'Tcp', 'Udp',
/// '*'
/// </summary>
[JsonProperty(PropertyName = "properties.protocol")]
public string Protocol { get; set; }
/// <summary>
/// Gets or sets the source port or range. Integer or range between 0
/// and 65535. Asterix '*' can also be used to match all ports.
/// </summary>
[JsonProperty(PropertyName = "properties.sourcePortRange")]
public string SourcePortRange { get; set; }
/// <summary>
/// Gets or sets the destination port or range. Integer or range
/// between 0 and 65535. Asterix '*' can also be used to match all
/// ports.
/// </summary>
[JsonProperty(PropertyName = "properties.destinationPortRange")]
public string DestinationPortRange { get; set; }
/// <summary>
/// Gets or sets the CIDR or source IP range. Asterix '*' can also be
/// used to match all source IPs. Default tags such as
/// 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be
/// used. If this is an ingress rule, specifies where network traffic
/// originates from.
/// </summary>
[JsonProperty(PropertyName = "properties.sourceAddressPrefix")]
public string SourceAddressPrefix { get; set; }
/// <summary>
/// Gets or sets the CIDR or source IP ranges.
/// </summary>
[JsonProperty(PropertyName = "properties.sourceAddressPrefixes")]
public IList<string> SourceAddressPrefixes { get; set; }
/// <summary>
/// Gets or sets the destination address prefix. CIDR or destination IP
/// range. Asterix '*' can also be used to match all source IPs.
/// Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and
/// 'Internet' can also be used.
/// </summary>
[JsonProperty(PropertyName = "properties.destinationAddressPrefix")]
public string DestinationAddressPrefix { get; set; }
/// <summary>
/// Gets or sets the destination address prefixes. CIDR or destination
/// IP ranges.
/// </summary>
[JsonProperty(PropertyName = "properties.destinationAddressPrefixes")]
public IList<string> DestinationAddressPrefixes { get; set; }
/// <summary>
/// Gets or sets the source port ranges.
/// </summary>
[JsonProperty(PropertyName = "properties.sourcePortRanges")]
public IList<string> SourcePortRanges { get; set; }
/// <summary>
/// Gets or sets the destination port ranges.
/// </summary>
[JsonProperty(PropertyName = "properties.destinationPortRanges")]
public IList<string> DestinationPortRanges { get; set; }
/// <summary>
/// Gets or sets the network traffic is allowed or denied. Possible
/// values are: 'Allow' and 'Deny'. Possible values include: 'Allow',
/// 'Deny'
/// </summary>
[JsonProperty(PropertyName = "properties.access")]
public string Access { get; set; }
/// <summary>
/// Gets or sets the priority of the rule. The value can be between 100
/// and 4096. The priority number must be unique for each rule in the
/// collection. The lower the priority number, the higher the priority
/// of the rule.
/// </summary>
[JsonProperty(PropertyName = "properties.priority")]
public int? Priority { get; set; }
/// <summary>
/// Gets or sets the direction of the rule. The direction specifies if
/// rule will be evaluated on incoming or outcoming traffic. Possible
/// values are: 'Inbound' and 'Outbound'. Possible values include:
/// 'Inbound', 'Outbound'
/// </summary>
[JsonProperty(PropertyName = "properties.direction")]
public string Direction { get; set; }
/// <summary>
/// Gets or sets the provisioning state of the public IP resource.
/// Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public string ProvisioningState { get; set; }
/// <summary>
/// Gets or sets the name of the resource that is unique within a
/// resource group. This name can be used to access the resource.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets a unique read-only string that changes whenever the
/// resource is updated.
/// </summary>
[JsonProperty(PropertyName = "etag")]
public string Etag { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Protocol == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Protocol");
}
if (SourceAddressPrefix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "SourceAddressPrefix");
}
if (DestinationAddressPrefix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "DestinationAddressPrefix");
}
if (Access == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Access");
}
if (Direction == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Direction");
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticmapreduce-2009-03-31.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.ElasticMapReduce
{
/// <summary>
/// Constants used for properties of type ActionOnFailure.
/// </summary>
public class ActionOnFailure : ConstantClass
{
/// <summary>
/// Constant CANCEL_AND_WAIT for ActionOnFailure
/// </summary>
public static readonly ActionOnFailure CANCEL_AND_WAIT = new ActionOnFailure("CANCEL_AND_WAIT");
/// <summary>
/// Constant CONTINUE for ActionOnFailure
/// </summary>
public static readonly ActionOnFailure CONTINUE = new ActionOnFailure("CONTINUE");
/// <summary>
/// Constant TERMINATE_CLUSTER for ActionOnFailure
/// </summary>
public static readonly ActionOnFailure TERMINATE_CLUSTER = new ActionOnFailure("TERMINATE_CLUSTER");
/// <summary>
/// Constant TERMINATE_JOB_FLOW for ActionOnFailure
/// </summary>
public static readonly ActionOnFailure TERMINATE_JOB_FLOW = new ActionOnFailure("TERMINATE_JOB_FLOW");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ActionOnFailure(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ActionOnFailure FindValue(string value)
{
return FindValue<ActionOnFailure>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ActionOnFailure(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ClusterState.
/// </summary>
public class ClusterState : ConstantClass
{
/// <summary>
/// Constant BOOTSTRAPPING for ClusterState
/// </summary>
public static readonly ClusterState BOOTSTRAPPING = new ClusterState("BOOTSTRAPPING");
/// <summary>
/// Constant RUNNING for ClusterState
/// </summary>
public static readonly ClusterState RUNNING = new ClusterState("RUNNING");
/// <summary>
/// Constant STARTING for ClusterState
/// </summary>
public static readonly ClusterState STARTING = new ClusterState("STARTING");
/// <summary>
/// Constant TERMINATED for ClusterState
/// </summary>
public static readonly ClusterState TERMINATED = new ClusterState("TERMINATED");
/// <summary>
/// Constant TERMINATED_WITH_ERRORS for ClusterState
/// </summary>
public static readonly ClusterState TERMINATED_WITH_ERRORS = new ClusterState("TERMINATED_WITH_ERRORS");
/// <summary>
/// Constant TERMINATING for ClusterState
/// </summary>
public static readonly ClusterState TERMINATING = new ClusterState("TERMINATING");
/// <summary>
/// Constant WAITING for ClusterState
/// </summary>
public static readonly ClusterState WAITING = new ClusterState("WAITING");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ClusterState(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ClusterState FindValue(string value)
{
return FindValue<ClusterState>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ClusterState(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ClusterStateChangeReasonCode.
/// </summary>
public class ClusterStateChangeReasonCode : ConstantClass
{
/// <summary>
/// Constant ALL_STEPS_COMPLETED for ClusterStateChangeReasonCode
/// </summary>
public static readonly ClusterStateChangeReasonCode ALL_STEPS_COMPLETED = new ClusterStateChangeReasonCode("ALL_STEPS_COMPLETED");
/// <summary>
/// Constant BOOTSTRAP_FAILURE for ClusterStateChangeReasonCode
/// </summary>
public static readonly ClusterStateChangeReasonCode BOOTSTRAP_FAILURE = new ClusterStateChangeReasonCode("BOOTSTRAP_FAILURE");
/// <summary>
/// Constant INSTANCE_FAILURE for ClusterStateChangeReasonCode
/// </summary>
public static readonly ClusterStateChangeReasonCode INSTANCE_FAILURE = new ClusterStateChangeReasonCode("INSTANCE_FAILURE");
/// <summary>
/// Constant INTERNAL_ERROR for ClusterStateChangeReasonCode
/// </summary>
public static readonly ClusterStateChangeReasonCode INTERNAL_ERROR = new ClusterStateChangeReasonCode("INTERNAL_ERROR");
/// <summary>
/// Constant STEP_FAILURE for ClusterStateChangeReasonCode
/// </summary>
public static readonly ClusterStateChangeReasonCode STEP_FAILURE = new ClusterStateChangeReasonCode("STEP_FAILURE");
/// <summary>
/// Constant USER_REQUEST for ClusterStateChangeReasonCode
/// </summary>
public static readonly ClusterStateChangeReasonCode USER_REQUEST = new ClusterStateChangeReasonCode("USER_REQUEST");
/// <summary>
/// Constant VALIDATION_ERROR for ClusterStateChangeReasonCode
/// </summary>
public static readonly ClusterStateChangeReasonCode VALIDATION_ERROR = new ClusterStateChangeReasonCode("VALIDATION_ERROR");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ClusterStateChangeReasonCode(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ClusterStateChangeReasonCode FindValue(string value)
{
return FindValue<ClusterStateChangeReasonCode>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ClusterStateChangeReasonCode(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type InstanceGroupState.
/// </summary>
public class InstanceGroupState : ConstantClass
{
/// <summary>
/// Constant ARRESTED for InstanceGroupState
/// </summary>
public static readonly InstanceGroupState ARRESTED = new InstanceGroupState("ARRESTED");
/// <summary>
/// Constant BOOTSTRAPPING for InstanceGroupState
/// </summary>
public static readonly InstanceGroupState BOOTSTRAPPING = new InstanceGroupState("BOOTSTRAPPING");
/// <summary>
/// Constant ENDED for InstanceGroupState
/// </summary>
public static readonly InstanceGroupState ENDED = new InstanceGroupState("ENDED");
/// <summary>
/// Constant PROVISIONING for InstanceGroupState
/// </summary>
public static readonly InstanceGroupState PROVISIONING = new InstanceGroupState("PROVISIONING");
/// <summary>
/// Constant RESIZING for InstanceGroupState
/// </summary>
public static readonly InstanceGroupState RESIZING = new InstanceGroupState("RESIZING");
/// <summary>
/// Constant RUNNING for InstanceGroupState
/// </summary>
public static readonly InstanceGroupState RUNNING = new InstanceGroupState("RUNNING");
/// <summary>
/// Constant SHUTTING_DOWN for InstanceGroupState
/// </summary>
public static readonly InstanceGroupState SHUTTING_DOWN = new InstanceGroupState("SHUTTING_DOWN");
/// <summary>
/// Constant SUSPENDED for InstanceGroupState
/// </summary>
public static readonly InstanceGroupState SUSPENDED = new InstanceGroupState("SUSPENDED");
/// <summary>
/// Constant TERMINATED for InstanceGroupState
/// </summary>
public static readonly InstanceGroupState TERMINATED = new InstanceGroupState("TERMINATED");
/// <summary>
/// Constant TERMINATING for InstanceGroupState
/// </summary>
public static readonly InstanceGroupState TERMINATING = new InstanceGroupState("TERMINATING");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public InstanceGroupState(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static InstanceGroupState FindValue(string value)
{
return FindValue<InstanceGroupState>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator InstanceGroupState(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type InstanceGroupStateChangeReasonCode.
/// </summary>
public class InstanceGroupStateChangeReasonCode : ConstantClass
{
/// <summary>
/// Constant CLUSTER_TERMINATED for InstanceGroupStateChangeReasonCode
/// </summary>
public static readonly InstanceGroupStateChangeReasonCode CLUSTER_TERMINATED = new InstanceGroupStateChangeReasonCode("CLUSTER_TERMINATED");
/// <summary>
/// Constant INSTANCE_FAILURE for InstanceGroupStateChangeReasonCode
/// </summary>
public static readonly InstanceGroupStateChangeReasonCode INSTANCE_FAILURE = new InstanceGroupStateChangeReasonCode("INSTANCE_FAILURE");
/// <summary>
/// Constant INTERNAL_ERROR for InstanceGroupStateChangeReasonCode
/// </summary>
public static readonly InstanceGroupStateChangeReasonCode INTERNAL_ERROR = new InstanceGroupStateChangeReasonCode("INTERNAL_ERROR");
/// <summary>
/// Constant VALIDATION_ERROR for InstanceGroupStateChangeReasonCode
/// </summary>
public static readonly InstanceGroupStateChangeReasonCode VALIDATION_ERROR = new InstanceGroupStateChangeReasonCode("VALIDATION_ERROR");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public InstanceGroupStateChangeReasonCode(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static InstanceGroupStateChangeReasonCode FindValue(string value)
{
return FindValue<InstanceGroupStateChangeReasonCode>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator InstanceGroupStateChangeReasonCode(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type InstanceGroupType.
/// </summary>
public class InstanceGroupType : ConstantClass
{
/// <summary>
/// Constant CORE for InstanceGroupType
/// </summary>
public static readonly InstanceGroupType CORE = new InstanceGroupType("CORE");
/// <summary>
/// Constant MASTER for InstanceGroupType
/// </summary>
public static readonly InstanceGroupType MASTER = new InstanceGroupType("MASTER");
/// <summary>
/// Constant TASK for InstanceGroupType
/// </summary>
public static readonly InstanceGroupType TASK = new InstanceGroupType("TASK");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public InstanceGroupType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static InstanceGroupType FindValue(string value)
{
return FindValue<InstanceGroupType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator InstanceGroupType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type InstanceRoleType.
/// </summary>
public class InstanceRoleType : ConstantClass
{
/// <summary>
/// Constant CORE for InstanceRoleType
/// </summary>
public static readonly InstanceRoleType CORE = new InstanceRoleType("CORE");
/// <summary>
/// Constant MASTER for InstanceRoleType
/// </summary>
public static readonly InstanceRoleType MASTER = new InstanceRoleType("MASTER");
/// <summary>
/// Constant TASK for InstanceRoleType
/// </summary>
public static readonly InstanceRoleType TASK = new InstanceRoleType("TASK");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public InstanceRoleType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static InstanceRoleType FindValue(string value)
{
return FindValue<InstanceRoleType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator InstanceRoleType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type InstanceState.
/// </summary>
public class InstanceState : ConstantClass
{
/// <summary>
/// Constant AWAITING_FULFILLMENT for InstanceState
/// </summary>
public static readonly InstanceState AWAITING_FULFILLMENT = new InstanceState("AWAITING_FULFILLMENT");
/// <summary>
/// Constant BOOTSTRAPPING for InstanceState
/// </summary>
public static readonly InstanceState BOOTSTRAPPING = new InstanceState("BOOTSTRAPPING");
/// <summary>
/// Constant PROVISIONING for InstanceState
/// </summary>
public static readonly InstanceState PROVISIONING = new InstanceState("PROVISIONING");
/// <summary>
/// Constant RUNNING for InstanceState
/// </summary>
public static readonly InstanceState RUNNING = new InstanceState("RUNNING");
/// <summary>
/// Constant TERMINATED for InstanceState
/// </summary>
public static readonly InstanceState TERMINATED = new InstanceState("TERMINATED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public InstanceState(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static InstanceState FindValue(string value)
{
return FindValue<InstanceState>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator InstanceState(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type InstanceStateChangeReasonCode.
/// </summary>
public class InstanceStateChangeReasonCode : ConstantClass
{
/// <summary>
/// Constant BOOTSTRAP_FAILURE for InstanceStateChangeReasonCode
/// </summary>
public static readonly InstanceStateChangeReasonCode BOOTSTRAP_FAILURE = new InstanceStateChangeReasonCode("BOOTSTRAP_FAILURE");
/// <summary>
/// Constant CLUSTER_TERMINATED for InstanceStateChangeReasonCode
/// </summary>
public static readonly InstanceStateChangeReasonCode CLUSTER_TERMINATED = new InstanceStateChangeReasonCode("CLUSTER_TERMINATED");
/// <summary>
/// Constant INSTANCE_FAILURE for InstanceStateChangeReasonCode
/// </summary>
public static readonly InstanceStateChangeReasonCode INSTANCE_FAILURE = new InstanceStateChangeReasonCode("INSTANCE_FAILURE");
/// <summary>
/// Constant INTERNAL_ERROR for InstanceStateChangeReasonCode
/// </summary>
public static readonly InstanceStateChangeReasonCode INTERNAL_ERROR = new InstanceStateChangeReasonCode("INTERNAL_ERROR");
/// <summary>
/// Constant VALIDATION_ERROR for InstanceStateChangeReasonCode
/// </summary>
public static readonly InstanceStateChangeReasonCode VALIDATION_ERROR = new InstanceStateChangeReasonCode("VALIDATION_ERROR");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public InstanceStateChangeReasonCode(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static InstanceStateChangeReasonCode FindValue(string value)
{
return FindValue<InstanceStateChangeReasonCode>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator InstanceStateChangeReasonCode(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type JobFlowExecutionState.
/// </summary>
public class JobFlowExecutionState : ConstantClass
{
/// <summary>
/// Constant BOOTSTRAPPING for JobFlowExecutionState
/// </summary>
public static readonly JobFlowExecutionState BOOTSTRAPPING = new JobFlowExecutionState("BOOTSTRAPPING");
/// <summary>
/// Constant COMPLETED for JobFlowExecutionState
/// </summary>
public static readonly JobFlowExecutionState COMPLETED = new JobFlowExecutionState("COMPLETED");
/// <summary>
/// Constant FAILED for JobFlowExecutionState
/// </summary>
public static readonly JobFlowExecutionState FAILED = new JobFlowExecutionState("FAILED");
/// <summary>
/// Constant RUNNING for JobFlowExecutionState
/// </summary>
public static readonly JobFlowExecutionState RUNNING = new JobFlowExecutionState("RUNNING");
/// <summary>
/// Constant SHUTTING_DOWN for JobFlowExecutionState
/// </summary>
public static readonly JobFlowExecutionState SHUTTING_DOWN = new JobFlowExecutionState("SHUTTING_DOWN");
/// <summary>
/// Constant STARTING for JobFlowExecutionState
/// </summary>
public static readonly JobFlowExecutionState STARTING = new JobFlowExecutionState("STARTING");
/// <summary>
/// Constant TERMINATED for JobFlowExecutionState
/// </summary>
public static readonly JobFlowExecutionState TERMINATED = new JobFlowExecutionState("TERMINATED");
/// <summary>
/// Constant WAITING for JobFlowExecutionState
/// </summary>
public static readonly JobFlowExecutionState WAITING = new JobFlowExecutionState("WAITING");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public JobFlowExecutionState(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static JobFlowExecutionState FindValue(string value)
{
return FindValue<JobFlowExecutionState>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator JobFlowExecutionState(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type MarketType.
/// </summary>
public class MarketType : ConstantClass
{
/// <summary>
/// Constant ON_DEMAND for MarketType
/// </summary>
public static readonly MarketType ON_DEMAND = new MarketType("ON_DEMAND");
/// <summary>
/// Constant SPOT for MarketType
/// </summary>
public static readonly MarketType SPOT = new MarketType("SPOT");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public MarketType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static MarketType FindValue(string value)
{
return FindValue<MarketType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator MarketType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type StepExecutionState.
/// </summary>
public class StepExecutionState : ConstantClass
{
/// <summary>
/// Constant CANCELLED for StepExecutionState
/// </summary>
public static readonly StepExecutionState CANCELLED = new StepExecutionState("CANCELLED");
/// <summary>
/// Constant COMPLETED for StepExecutionState
/// </summary>
public static readonly StepExecutionState COMPLETED = new StepExecutionState("COMPLETED");
/// <summary>
/// Constant CONTINUE for StepExecutionState
/// </summary>
public static readonly StepExecutionState CONTINUE = new StepExecutionState("CONTINUE");
/// <summary>
/// Constant FAILED for StepExecutionState
/// </summary>
public static readonly StepExecutionState FAILED = new StepExecutionState("FAILED");
/// <summary>
/// Constant INTERRUPTED for StepExecutionState
/// </summary>
public static readonly StepExecutionState INTERRUPTED = new StepExecutionState("INTERRUPTED");
/// <summary>
/// Constant PENDING for StepExecutionState
/// </summary>
public static readonly StepExecutionState PENDING = new StepExecutionState("PENDING");
/// <summary>
/// Constant RUNNING for StepExecutionState
/// </summary>
public static readonly StepExecutionState RUNNING = new StepExecutionState("RUNNING");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public StepExecutionState(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static StepExecutionState FindValue(string value)
{
return FindValue<StepExecutionState>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator StepExecutionState(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type StepState.
/// </summary>
public class StepState : ConstantClass
{
/// <summary>
/// Constant CANCELLED for StepState
/// </summary>
public static readonly StepState CANCELLED = new StepState("CANCELLED");
/// <summary>
/// Constant COMPLETED for StepState
/// </summary>
public static readonly StepState COMPLETED = new StepState("COMPLETED");
/// <summary>
/// Constant FAILED for StepState
/// </summary>
public static readonly StepState FAILED = new StepState("FAILED");
/// <summary>
/// Constant INTERRUPTED for StepState
/// </summary>
public static readonly StepState INTERRUPTED = new StepState("INTERRUPTED");
/// <summary>
/// Constant PENDING for StepState
/// </summary>
public static readonly StepState PENDING = new StepState("PENDING");
/// <summary>
/// Constant RUNNING for StepState
/// </summary>
public static readonly StepState RUNNING = new StepState("RUNNING");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public StepState(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static StepState FindValue(string value)
{
return FindValue<StepState>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator StepState(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type StepStateChangeReasonCode.
/// </summary>
public class StepStateChangeReasonCode : ConstantClass
{
/// <summary>
/// Constant NONE for StepStateChangeReasonCode
/// </summary>
public static readonly StepStateChangeReasonCode NONE = new StepStateChangeReasonCode("NONE");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public StepStateChangeReasonCode(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static StepStateChangeReasonCode FindValue(string value)
{
return FindValue<StepStateChangeReasonCode>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator StepStateChangeReasonCode(string value)
{
return FindValue(value);
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.XPath;
namespace System.Xml.Xsl.Xslt
{
using T = XmlQueryTypeFactory;
internal class XPathPatternBuilder : XPathPatternParser.IPatternBuilder
{
private XPathPredicateEnvironment _predicateEnvironment;
private XPathBuilder _predicateBuilder;
private bool _inTheBuild;
private XPathQilFactory _f;
private QilNode _fixupNode;
private IXPathEnvironment _environment;
public XPathPatternBuilder(IXPathEnvironment environment)
{
Debug.Assert(environment != null);
_environment = environment;
_f = environment.Factory;
_predicateEnvironment = new XPathPredicateEnvironment(environment);
_predicateBuilder = new XPathBuilder(_predicateEnvironment);
_fixupNode = _f.Unknown(T.NodeNotRtfS);
}
public QilNode FixupNode
{
get { return _fixupNode; }
}
public virtual void StartBuild()
{
Debug.Assert(!_inTheBuild, "XPathBuilder is busy!");
_inTheBuild = true;
return;
}
[Conditional("DEBUG")]
public void AssertFilter(QilLoop filter)
{
Debug.Assert(filter.NodeType == QilNodeType.Filter, "XPathPatternBuilder expected to generate list of Filters on top level");
Debug.Assert(filter.Variable.XmlType.IsSubtypeOf(T.NodeNotRtf));
Debug.Assert(filter.Variable.Binding.NodeType == QilNodeType.Unknown); // fixupNode
Debug.Assert(filter.Body.XmlType.IsSubtypeOf(T.Boolean));
}
private void FixupFilterBinding(QilLoop filter, QilNode newBinding)
{
AssertFilter(filter);
filter.Variable.Binding = newBinding;
}
public virtual QilNode EndBuild(QilNode result)
{
Debug.Assert(_inTheBuild, "StartBuild() wasn't called");
if (result == null)
{
// Special door to clean builder state in exception handlers
}
// All these variables will be positive for "false() and (. = position() + last())"
// since QilPatternFactory eliminates the right operand of 'and'
Debug.Assert(_predicateEnvironment.numFixupCurrent >= 0, "Context fixup error");
Debug.Assert(_predicateEnvironment.numFixupPosition >= 0, "Context fixup error");
Debug.Assert(_predicateEnvironment.numFixupLast >= 0, "Context fixup error");
_inTheBuild = false;
return result;
}
public QilNode Operator(XPathOperator op, QilNode left, QilNode right)
{
Debug.Assert(op == XPathOperator.Union);
Debug.Assert(left != null);
Debug.Assert(right != null);
// It is important to not create nested lists here
Debug.Assert(right.NodeType == QilNodeType.Filter, "LocationPathPattern must be compiled into a filter");
if (left.NodeType == QilNodeType.Sequence)
{
((QilList)left).Add(right);
return left;
}
else
{
Debug.Assert(left.NodeType == QilNodeType.Filter, "LocationPathPattern must be compiled into a filter");
return _f.Sequence(left, right);
}
}
private static QilLoop BuildAxisFilter(QilPatternFactory f, QilIterator itr, XPathAxis xpathAxis, XPathNodeType nodeType, string name, string nsUri)
{
QilNode nameTest = (
name != null && nsUri != null ? f.Eq(f.NameOf(itr), f.QName(name, nsUri)) : // ns:bar || bar
nsUri != null ? f.Eq(f.NamespaceUriOf(itr), f.String(nsUri)) : // ns:*
name != null ? f.Eq(f.LocalNameOf(itr), f.String(name)) : // *:foo
/*name == nsUri == null*/ f.True() // *
);
XmlNodeKindFlags intersection = XPathBuilder.AxisTypeMask(itr.XmlType.NodeKinds, nodeType, xpathAxis);
QilNode typeTest = (
intersection == 0 ? f.False() : // input & required doesn't intersect
intersection == itr.XmlType.NodeKinds ? f.True() : // input is subset of required
/*else*/ f.IsType(itr, T.NodeChoice(intersection))
);
QilLoop filter = f.BaseFactory.Filter(itr, f.And(typeTest, nameTest));
filter.XmlType = T.PrimeProduct(T.NodeChoice(intersection), filter.XmlType.Cardinality);
return filter;
}
public QilNode Axis(XPathAxis xpathAxis, XPathNodeType nodeType, string prefix, string name)
{
Debug.Assert(
xpathAxis == XPathAxis.Child ||
xpathAxis == XPathAxis.Attribute ||
xpathAxis == XPathAxis.DescendantOrSelf ||
xpathAxis == XPathAxis.Root
);
QilLoop result;
double priority;
switch (xpathAxis)
{
case XPathAxis.DescendantOrSelf:
Debug.Assert(nodeType == XPathNodeType.All && prefix == null && name == null, " // is the only d-o-s axes that we can have in pattern");
return _f.Nop(_fixupNode); // We using Nop as a flag that DescendantOrSelf exis was used between steps.
case XPathAxis.Root:
QilIterator i;
result = _f.BaseFactory.Filter(i = _f.For(_fixupNode), _f.IsType(i, T.Document));
priority = 0.5;
break;
default:
string nsUri = prefix == null ? null : _environment.ResolvePrefix(prefix);
result = BuildAxisFilter(_f, _f.For(_fixupNode), xpathAxis, nodeType, name, nsUri);
switch (nodeType)
{
case XPathNodeType.Element:
case XPathNodeType.Attribute:
if (name != null)
{
priority = 0;
}
else
{
if (prefix != null)
{
priority = -0.25;
}
else
{
priority = -0.5;
}
}
break;
case XPathNodeType.ProcessingInstruction:
priority = name != null ? 0 : -0.5;
break;
default:
priority = -0.5;
break;
}
break;
}
SetPriority(result, priority);
SetLastParent(result, result);
return result;
}
// a/b/c -> self::c[parent::b[parent::a]]
// a/b//c -> self::c[ancestor::b[parent::a]]
// a/b -> self::b[parent::a]
// -> JoinStep(Axis('a'), Axis('b'))
// -> Filter('b' & Parent(Filter('a')))
// a//b
// -> JoinStep(Axis('a'), JoingStep(Axis(DescendantOrSelf), Axis('b')))
// -> JoinStep(Filter('a'), JoingStep(Nop(null), Filter('b')))
// -> JoinStep(Filter('a'), Nop(Filter('b')))
// -> Filter('b' & Ancestor(Filter('a')))
public QilNode JoinStep(QilNode left, QilNode right)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
if (left.NodeType == QilNodeType.Nop)
{
QilUnary nop = (QilUnary)left;
Debug.Assert(nop.Child == _fixupNode);
nop.Child = right; // We use Nop as a flag that DescendantOrSelf axis was used between steps.
return nop;
}
Debug.Assert(GetLastParent(left) == left, "Left is always single axis and never the step");
Debug.Assert(left.NodeType == QilNodeType.Filter);
CleanAnnotation(left);
QilLoop parentFilter = (QilLoop)left;
bool ancestor = false;
{
if (right.NodeType == QilNodeType.Nop)
{
ancestor = true;
QilUnary nop = (QilUnary)right;
Debug.Assert(nop.Child != null);
right = nop.Child;
}
}
Debug.Assert(right.NodeType == QilNodeType.Filter);
QilLoop lastParent = GetLastParent(right);
FixupFilterBinding(parentFilter, ancestor ? _f.Ancestor(lastParent.Variable) : _f.Parent(lastParent.Variable));
lastParent.Body = _f.And(lastParent.Body, _f.Not(_f.IsEmpty(parentFilter)));
SetPriority(right, 0.5);
SetLastParent(right, parentFilter);
return right;
}
QilNode IXPathBuilder<QilNode>.Predicate(QilNode node, QilNode condition, bool isReverseStep)
{
Debug.Assert(false, "Should not call to this function.");
return null;
}
//The structure of result is a Filter, variable is current node, body is the match condition.
//Previous predicate build logic in XPathPatternBuilder is match from right to left, which have 2^n complexiy when have lots of position predicates. TFS #368771
//Now change the logic to: If predicates contains position/last predicates, given the current node, filter out all the nodes that match the predicates,
//and then check if current node is in the result set.
public QilNode BuildPredicates(QilNode nodeset, List<QilNode> predicates)
{
//convert predicates to boolean type
List<QilNode> convertedPredicates = new List<QilNode>(predicates.Count);
foreach (var predicate in predicates)
{
convertedPredicates.Add(XPathBuilder.PredicateToBoolean(predicate, _f, _predicateEnvironment));
}
QilLoop nodeFilter = (QilLoop)nodeset;
QilIterator current = nodeFilter.Variable;
//If no last() and position() in predicates, use nodeFilter.Variable to fixup current
//because all the predicates only based on the input variable, no matter what other predicates are.
if (_predicateEnvironment.numFixupLast == 0 && _predicateEnvironment.numFixupPosition == 0)
{
foreach (var predicate in convertedPredicates)
{
nodeFilter.Body = _f.And(nodeFilter.Body, predicate);
}
nodeFilter.Body = _predicateEnvironment.fixupVisitor.Fixup(nodeFilter.Body, current, null);
}
//If any preidcate contains last() or position() node, then the current node is based on previous predicates,
//for instance, a[...][2] is match second node after filter 'a[...]' instead of second 'a'.
else
{
//filter out the siblings
QilIterator parentIter = _f.For(_f.Parent(current));
QilNode sibling = _f.Content(parentIter);
//generate filter based on input filter
QilLoop siblingFilter = (QilLoop)nodeset.DeepClone(_f.BaseFactory);
siblingFilter.Variable.Binding = sibling;
siblingFilter = (QilLoop)_f.Loop(parentIter, siblingFilter);
//build predicates from left to right to get all the matching nodes
QilNode matchingSet = siblingFilter;
foreach (var predicate in convertedPredicates)
{
matchingSet = XPathBuilder.BuildOnePredicate(matchingSet, predicate, /*isReverseStep*/false,
_f, _predicateEnvironment.fixupVisitor,
ref _predicateEnvironment.numFixupCurrent, ref _predicateEnvironment.numFixupPosition, ref _predicateEnvironment.numFixupLast);
}
//check if the matching nodes contains the current node
QilIterator matchNodeIter = _f.For(matchingSet);
QilNode filterCurrent = _f.Filter(matchNodeIter, _f.Is(matchNodeIter, current));
nodeFilter.Body = _f.Not(_f.IsEmpty(filterCurrent));
//for passing type check, explicit say the result is target type
nodeFilter.Body = _f.And(_f.IsType(current, nodeFilter.XmlType), nodeFilter.Body);
}
SetPriority(nodeset, 0.5);
return nodeset;
}
public QilNode Function(string prefix, string name, IList<QilNode> args)
{
Debug.Assert(prefix.Length == 0);
QilIterator i = _f.For(_fixupNode);
QilNode matches;
if (name == "id")
{
Debug.Assert(
args.Count == 1 && args[0].NodeType == QilNodeType.LiteralString,
"Function id() must have one literal string argument"
);
matches = _f.Id(i, args[0]);
}
else
{
Debug.Assert(name == "key", "Unexpected function");
Debug.Assert(
args.Count == 2 &&
args[0].NodeType == QilNodeType.LiteralString && args[1].NodeType == QilNodeType.LiteralString,
"Function key() must have two literal string arguments"
);
matches = _environment.ResolveFunction(prefix, name, args, new XsltFunctionFocus(i));
}
QilIterator j;
QilLoop result = _f.BaseFactory.Filter(i, _f.Not(_f.IsEmpty(_f.Filter(j = _f.For(matches), _f.Is(j, i)))));
SetPriority(result, 0.5);
SetLastParent(result, result);
return result;
}
public QilNode String(string value) { return _f.String(value); } // As argument of id() or key() function
public QilNode Number(double value)
{
//Internal Error: Literal number is not allowed in XSLT pattern outside of predicate.
throw new XmlException(SR.Xml_InternalError);
}
public QilNode Variable(string prefix, string name)
{
//Internal Error: Variable is not allowed in XSLT pattern outside of predicate.
throw new XmlException(SR.Xml_InternalError);
}
// -------------------------------------- Priority / Parent ---------------------------------------
private class Annotation
{
public double Priority;
public QilLoop Parent;
}
public static void SetPriority(QilNode node, double priority)
{
Annotation ann = (Annotation)node.Annotation ?? new Annotation();
ann.Priority = priority;
node.Annotation = ann;
}
public static double GetPriority(QilNode node)
{
return ((Annotation)node.Annotation).Priority;
}
private static void SetLastParent(QilNode node, QilLoop parent)
{
Debug.Assert(parent.NodeType == QilNodeType.Filter);
Annotation ann = (Annotation)node.Annotation ?? new Annotation();
ann.Parent = parent;
node.Annotation = ann;
}
private static QilLoop GetLastParent(QilNode node)
{
return ((Annotation)node.Annotation).Parent;
}
public static void CleanAnnotation(QilNode node)
{
node.Annotation = null;
}
// -------------------------------------- GetPredicateBuilder() ---------------------------------------
public IXPathBuilder<QilNode> GetPredicateBuilder(QilNode ctx)
{
QilLoop context = (QilLoop)ctx;
Debug.Assert(context != null, "Predicate always has step so it can't have context == null");
Debug.Assert(context.Variable.NodeType == QilNodeType.For, "It shouldn't be Let, becaus predicates in PatternBuilder don't produce cached tuples.");
return _predicateBuilder;
}
private class XPathPredicateEnvironment : IXPathEnvironment
{
private readonly IXPathEnvironment _baseEnvironment;
private readonly XPathQilFactory _f;
public readonly XPathBuilder.FixupVisitor fixupVisitor;
private readonly QilNode _fixupCurrent, _fixupPosition, _fixupLast;
// Number of unresolved fixup nodes
public int numFixupCurrent, numFixupPosition, numFixupLast;
public XPathPredicateEnvironment(IXPathEnvironment baseEnvironment)
{
_baseEnvironment = baseEnvironment;
_f = baseEnvironment.Factory;
_fixupCurrent = _f.Unknown(T.NodeNotRtf);
_fixupPosition = _f.Unknown(T.DoubleX);
_fixupLast = _f.Unknown(T.DoubleX);
this.fixupVisitor = new XPathBuilder.FixupVisitor(_f, _fixupCurrent, _fixupPosition, _fixupLast);
}
/* ----------------------------------------------------------------------------
IXPathEnvironment interface
*/
public XPathQilFactory Factory { get { return _f; } }
public QilNode ResolveVariable(string prefix, string name)
{
return _baseEnvironment.ResolveVariable(prefix, name);
}
public QilNode ResolveFunction(string prefix, string name, IList<QilNode> args, IFocus env)
{
return _baseEnvironment.ResolveFunction(prefix, name, args, env);
}
public string ResolvePrefix(string prefix)
{
return _baseEnvironment.ResolvePrefix(prefix);
}
public QilNode GetCurrent() { numFixupCurrent++; return _fixupCurrent; }
public QilNode GetPosition() { numFixupPosition++; return _fixupPosition; }
public QilNode GetLast() { numFixupLast++; return _fixupLast; }
}
private class XsltFunctionFocus : IFocus
{
private QilIterator _current;
public XsltFunctionFocus(QilIterator current)
{
Debug.Assert(current != null);
_current = current;
}
/* ----------------------------------------------------------------------------
IFocus interface
*/
public QilNode GetCurrent()
{
return _current;
}
public QilNode GetPosition()
{
Debug.Fail("GetPosition() must not be called");
return null;
}
public QilNode GetLast()
{
Debug.Fail("GetLast() must not be called");
return null;
}
}
}
}
| |
//
// nullable.cs: Nullable types support
//
// Authors: Martin Baulig (martin@ximian.com)
// Miguel de Icaza (miguel@ximian.com)
// Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
// Copyright 2004-2008 Novell, Inc
//
using System;
#if STATIC
using IKVM.Reflection.Emit;
#else
using System.Reflection.Emit;
#endif
namespace Mono.CSharp.Nullable
{
public class NullableType : TypeExpr
{
TypeExpr underlying;
public NullableType (TypeExpr underlying, Location l)
{
this.underlying = underlying;
loc = l;
eclass = ExprClass.Type;
}
public NullableType (TypeSpec type, Location loc)
: this (new TypeExpression (type, loc), loc)
{ }
protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
{
var type = ec.Module.PredefinedTypes.Nullable.Resolve (loc);
if (type == null)
return null;
TypeArguments args = new TypeArguments (underlying);
GenericTypeExpr ctype = new GenericTypeExpr (type, args, loc);
return ctype.ResolveAsTypeTerminal (ec, false);
}
}
static class NullableInfo
{
public static MethodSpec GetConstructor (TypeSpec nullableType)
{
return TypeManager.GetPredefinedConstructor (nullableType, Location.Null, GetUnderlyingType (nullableType));
}
public static MethodSpec GetHasValue (TypeSpec nullableType)
{
return (MethodSpec) MemberCache.FindMember (nullableType,
MemberFilter.Method ("get_HasValue", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
}
public static MethodSpec GetGetValueOrDefault (TypeSpec nullableType)
{
return (MethodSpec) MemberCache.FindMember (nullableType,
MemberFilter.Method ("GetValueOrDefault", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
}
public static MethodSpec GetValue (TypeSpec nullableType)
{
return (MethodSpec) MemberCache.FindMember (nullableType,
MemberFilter.Method ("get_Value", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
}
public static TypeSpec GetUnderlyingType (TypeSpec nullableType)
{
return ((InflatedTypeSpec) nullableType).TypeArguments[0];
}
public static bool IsNullableType (TypeSpec type)
{
throw new NotImplementedException ("net");
}
}
public class Unwrap : Expression, IMemoryLocation, IAssignMethod
{
Expression expr;
LocalTemporary temp;
readonly bool useDefaultValue;
Unwrap (Expression expr, bool useDefaultValue)
{
this.expr = expr;
this.loc = expr.Location;
this.useDefaultValue = useDefaultValue;
type = NullableInfo.GetUnderlyingType (expr.Type);
eclass = expr.eclass;
}
public static Expression Create (Expression expr)
{
//
// Avoid unwraping and wraping of same type
//
Wrap wrap = expr as Wrap;
if (wrap != null)
return wrap.Child;
return Create (expr, false);
}
public static Unwrap Create (Expression expr, bool useDefaultValue)
{
return new Unwrap (expr, useDefaultValue);
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
return expr.CreateExpressionTree (ec);
}
protected override Expression DoResolve (ResolveContext ec)
{
return this;
}
public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
{
expr = expr.DoResolveLValue (ec, right_side);
return this;
}
public override void Emit (EmitContext ec)
{
Store (ec);
if (useDefaultValue)
Invocation.EmitCall (ec, this, NullableInfo.GetGetValueOrDefault (expr.Type), null, loc);
else
Invocation.EmitCall (ec, this, NullableInfo.GetValue (expr.Type), null, loc);
}
public void EmitCheck (EmitContext ec)
{
Store (ec);
Invocation.EmitCall (ec, this, NullableInfo.GetHasValue (expr.Type), null, loc);
}
public override bool Equals (object obj)
{
Unwrap uw = obj as Unwrap;
return uw != null && expr.Equals (uw.expr);
}
public Expression Original {
get {
return expr;
}
}
public override int GetHashCode ()
{
return expr.GetHashCode ();
}
public override bool IsNull {
get {
return expr.IsNull;
}
}
void Store (EmitContext ec)
{
if (expr is VariableReference)
return;
if (temp != null)
return;
expr.Emit (ec);
LocalVariable.Store (ec);
}
public void Load (EmitContext ec)
{
if (expr is VariableReference)
expr.Emit (ec);
else
LocalVariable.Emit (ec);
}
public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
{
return expr.MakeExpression (ctx);
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
IMemoryLocation ml = expr as VariableReference;
if (ml != null)
ml.AddressOf (ec, mode);
else
LocalVariable.AddressOf (ec, mode);
}
//
// Keeps result of non-variable expression
//
LocalTemporary LocalVariable {
get {
if (temp == null)
temp = new LocalTemporary (expr.Type);
return temp;
}
}
public void Emit (EmitContext ec, bool leave_copy)
{
if (leave_copy)
Load (ec);
Emit (ec);
}
public void EmitAssign (EmitContext ec, Expression source,
bool leave_copy, bool prepare_for_load)
{
InternalWrap wrap = new InternalWrap (source, expr.Type, loc);
((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
}
class InternalWrap : Expression
{
public Expression expr;
public InternalWrap (Expression expr, TypeSpec type, Location loc)
{
this.expr = expr;
this.loc = loc;
this.type = type;
eclass = ExprClass.Value;
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
throw new NotSupportedException ("ET");
}
protected override Expression DoResolve (ResolveContext ec)
{
return this;
}
public override void Emit (EmitContext ec)
{
expr.Emit (ec);
ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
}
}
}
//
// Calls get_Value method on nullable expression
//
public class UnwrapCall : CompositeExpression
{
public UnwrapCall (Expression expr)
: base (expr)
{
}
protected override Expression DoResolve (ResolveContext rc)
{
base.DoResolve (rc);
if (type != null)
type = NullableInfo.GetUnderlyingType (type);
return this;
}
public override void Emit (EmitContext ec)
{
Invocation.EmitCall (ec, Child, NullableInfo.GetValue (Child.Type), null, loc);
}
}
public class Wrap : TypeCast
{
private Wrap (Expression expr, TypeSpec type)
: base (expr, type)
{
eclass = ExprClass.Value;
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
TypeCast child_cast = child as TypeCast;
if (child_cast != null) {
child.Type = type;
return child_cast.CreateExpressionTree (ec);
}
return base.CreateExpressionTree (ec);
}
public static Expression Create (Expression expr, TypeSpec type)
{
//
// Avoid unwraping and wraping of the same type
//
Unwrap unwrap = expr as Unwrap;
if (unwrap != null && expr.Type == NullableInfo.GetUnderlyingType (type))
return unwrap.Original;
return new Wrap (expr, type);
}
public override void Emit (EmitContext ec)
{
child.Emit (ec);
ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
}
}
//
// Represents null literal lifted to nullable type
//
public class LiftedNull : NullConstant, IMemoryLocation
{
private LiftedNull (TypeSpec nullable_type, Location loc)
: base (nullable_type, loc)
{
eclass = ExprClass.Value;
}
public static Constant Create (TypeSpec nullable, Location loc)
{
return new LiftedNull (nullable, loc);
}
public static Constant CreateFromExpression (ResolveContext ec, Expression e)
{
ec.Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
TypeManager.CSharpName (e.Type));
return ReducedExpression.Create (Create (e.Type, e.Location), e);
}
public override void Emit (EmitContext ec)
{
// TODO: generate less temporary variables
LocalTemporary value_target = new LocalTemporary (type);
value_target.AddressOf (ec, AddressOp.Store);
ec.Emit (OpCodes.Initobj, type);
value_target.Emit (ec);
}
public void AddressOf (EmitContext ec, AddressOp Mode)
{
LocalTemporary value_target = new LocalTemporary (type);
value_target.AddressOf (ec, AddressOp.Store);
ec.Emit (OpCodes.Initobj, type);
((IMemoryLocation) value_target).AddressOf (ec, Mode);
}
}
//
// Generic lifting expression, supports all S/S? -> T/T? cases
//
public class Lifted : Expression, IMemoryLocation
{
Expression expr, null_value;
Unwrap unwrap;
public Lifted (Expression expr, Unwrap unwrap, TypeSpec type)
{
this.expr = expr;
this.unwrap = unwrap;
this.loc = expr.Location;
this.type = type;
}
public Lifted (Expression expr, Expression unwrap, TypeSpec type)
: this (expr, unwrap as Unwrap, type)
{
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
return expr.CreateExpressionTree (ec);
}
protected override Expression DoResolve (ResolveContext ec)
{
//
// It's null when lifting non-nullable type
//
if (unwrap == null) {
// S -> T? is wrap only
if (TypeManager.IsNullableType (type))
return Wrap.Create (expr, type);
// S -> T can be simplified
return expr;
}
// Wrap target for T?
if (TypeManager.IsNullableType (type)) {
expr = Wrap.Create (expr, type);
if (expr == null)
return null;
null_value = LiftedNull.Create (type, loc);
} else if (TypeManager.IsValueType (type)) {
null_value = LiftedNull.Create (type, loc);
} else {
null_value = new NullConstant (type, loc);
}
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
Label is_null_label = ec.DefineLabel ();
Label end_label = ec.DefineLabel ();
unwrap.EmitCheck (ec);
ec.Emit (OpCodes.Brfalse, is_null_label);
expr.Emit (ec);
ec.Emit (OpCodes.Br, end_label);
ec.MarkLabel (is_null_label);
null_value.Emit (ec);
ec.MarkLabel (end_label);
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
unwrap.AddressOf (ec, mode);
}
}
public class LiftedUnaryOperator : Unary, IMemoryLocation
{
Unwrap unwrap;
Expression user_operator;
public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
: base (op, expr, loc)
{
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
unwrap.AddressOf (ec, mode);
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
if (user_operator != null)
return user_operator.CreateExpressionTree (ec);
if (Oper == Operator.UnaryPlus)
return Expr.CreateExpressionTree (ec);
return base.CreateExpressionTree (ec);
}
protected override Expression DoResolve (ResolveContext ec)
{
unwrap = Unwrap.Create (Expr, false);
if (unwrap == null)
return null;
Expression res = base.ResolveOperator (ec, unwrap);
if (res != this) {
if (user_operator == null)
return res;
} else {
res = Expr = LiftExpression (ec, Expr);
}
if (res == null)
return null;
eclass = ExprClass.Value;
type = res.Type;
return this;
}
public override void Emit (EmitContext ec)
{
Label is_null_label = ec.DefineLabel ();
Label end_label = ec.DefineLabel ();
unwrap.EmitCheck (ec);
ec.Emit (OpCodes.Brfalse, is_null_label);
if (user_operator != null) {
user_operator.Emit (ec);
} else {
EmitOperator (ec, NullableInfo.GetUnderlyingType (type));
}
ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
ec.Emit (OpCodes.Br_S, end_label);
ec.MarkLabel (is_null_label);
LiftedNull.Create (type, loc).Emit (ec);
ec.MarkLabel (end_label);
}
Expression LiftExpression (ResolveContext ec, Expression expr)
{
TypeExpr lifted_type = new NullableType (expr.Type, expr.Location);
lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
if (lifted_type == null)
return null;
expr.Type = lifted_type.Type;
return expr;
}
protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr)
{
expr = base.ResolveEnumOperator (ec, expr);
if (expr == null)
return null;
Expr = LiftExpression (ec, Expr);
return LiftExpression (ec, expr);
}
protected override Expression ResolveUserOperator (ResolveContext ec, Expression expr)
{
expr = base.ResolveUserOperator (ec, expr);
if (expr == null)
return null;
//
// When a user operator is of non-nullable type
//
if (Expr is Unwrap) {
user_operator = LiftExpression (ec, expr);
return user_operator;
}
return expr;
}
}
public class LiftedBinaryOperator : Binary
{
Unwrap left_unwrap, right_unwrap;
Expression left_orig, right_orig;
Expression user_operator;
MethodSpec wrap_ctor;
public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right, Location loc)
: base (op, left, right, loc)
{
}
bool IsBitwiseBoolean {
get {
return (Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) &&
((left_unwrap != null && left_unwrap.Type == TypeManager.bool_type) ||
(right_unwrap != null && right_unwrap.Type == TypeManager.bool_type));
}
}
bool IsLeftNullLifted {
get {
return (state & State.LeftNullLifted) != 0;
}
}
bool IsRightNullLifted {
get {
return (state & State.RightNullLifted) != 0;
}
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
if (user_operator != null)
return user_operator.CreateExpressionTree (ec);
return base.CreateExpressionTree (ec);
}
//
// CSC 2 has this behavior, it allows structs to be compared
// with the null literal *outside* of a generics context and
// inlines that as true or false.
//
Constant CreateNullConstant (ResolveContext ec, Expression expr)
{
// FIXME: Handle side effect constants
Constant c = new BoolConstant (Oper == Operator.Inequality, loc).Resolve (ec);
if ((Oper & Operator.EqualityMask) != 0) {
ec.Report.Warning (472, 2, loc, "The result of comparing value type `{0}' with null is `{1}'",
TypeManager.CSharpName (expr.Type), c.GetValueAsLiteral ());
} else {
ec.Report.Warning (464, 2, loc, "The result of comparing type `{0}' with null is always `{1}'",
TypeManager.CSharpName (expr.Type), c.GetValueAsLiteral ());
}
return ReducedExpression.Create (c, this);
}
protected override Expression DoResolve (ResolveContext ec)
{
if ((Oper & Operator.LogicalMask) != 0) {
Error_OperatorCannotBeApplied (ec, left, right);
return null;
}
bool use_default_call = (Oper & (Operator.BitwiseMask | Operator.EqualityMask)) != 0;
left_orig = left;
if (TypeManager.IsNullableType (left.Type)) {
left = left_unwrap = Unwrap.Create (left, use_default_call);
if (left == null)
return null;
}
right_orig = right;
if (TypeManager.IsNullableType (right.Type)) {
right = right_unwrap = Unwrap.Create (right, use_default_call);
if (right == null)
return null;
}
//
// Some details are in 6.4.2, 7.2.7
// Arguments can be lifted for equal operators when the return type is bool and both
// arguments are of same type
//
if (left_orig is NullLiteral) {
left = right;
state |= State.LeftNullLifted;
type = TypeManager.bool_type;
}
if (right_orig.IsNull) {
if ((Oper & Operator.ShiftMask) != 0)
right = new EmptyExpression (TypeManager.int32_type);
else
right = left;
state |= State.RightNullLifted;
type = TypeManager.bool_type;
}
eclass = ExprClass.Value;
return DoResolveCore (ec, left_orig, right_orig);
}
void EmitBitwiseBoolean (EmitContext ec)
{
Label load_left = ec.DefineLabel ();
Label load_right = ec.DefineLabel ();
Label end_label = ec.DefineLabel ();
// null & value, null | value
if (left_unwrap == null) {
left_unwrap = right_unwrap;
right_unwrap = null;
right = left;
}
left_unwrap.Emit (ec);
ec.Emit (OpCodes.Brtrue_S, load_right);
// value & null, value | null
if (right_unwrap != null) {
right_unwrap.Emit (ec);
ec.Emit (OpCodes.Brtrue_S, load_left);
}
left_unwrap.EmitCheck (ec);
ec.Emit (OpCodes.Brfalse_S, load_right);
// load left
ec.MarkLabel (load_left);
if (Oper == Operator.BitwiseAnd) {
left_unwrap.Load (ec);
} else {
if (right_unwrap == null) {
right.Emit (ec);
if (right is EmptyConstantCast || right is EmptyCast)
ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
} else {
right_unwrap.Load (ec);
right_unwrap = left_unwrap;
}
}
ec.Emit (OpCodes.Br_S, end_label);
// load right
ec.MarkLabel (load_right);
if (right_unwrap == null) {
if (Oper == Operator.BitwiseAnd) {
right.Emit (ec);
if (right is EmptyConstantCast || right is EmptyCast)
ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
} else {
left_unwrap.Load (ec);
}
} else {
right_unwrap.Load (ec);
}
ec.MarkLabel (end_label);
}
//
// Emits optimized equality or inequality operator when possible
//
void EmitEquality (EmitContext ec)
{
//
// Either left or right is null
//
if (left_unwrap != null && (IsRightNullLifted || right.IsNull)) {
left_unwrap.EmitCheck (ec);
if (Oper == Binary.Operator.Equality) {
ec.Emit (OpCodes.Ldc_I4_0);
ec.Emit (OpCodes.Ceq);
}
return;
}
if (right_unwrap != null && (IsLeftNullLifted || left.IsNull)) {
right_unwrap.EmitCheck (ec);
if (Oper == Binary.Operator.Equality) {
ec.Emit (OpCodes.Ldc_I4_0);
ec.Emit (OpCodes.Ceq);
}
return;
}
Label dissimilar_label = ec.DefineLabel ();
Label end_label = ec.DefineLabel ();
if (user_operator != null) {
user_operator.Emit (ec);
ec.Emit (Oper == Operator.Equality ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, dissimilar_label);
} else {
left.Emit (ec);
right.Emit (ec);
ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
}
if (left_unwrap != null)
left_unwrap.EmitCheck (ec);
if (right_unwrap != null)
right_unwrap.EmitCheck (ec);
if (left_unwrap != null && right_unwrap != null) {
if (Oper == Operator.Inequality)
ec.Emit (OpCodes.Xor);
else
ec.Emit (OpCodes.Ceq);
} else {
if (Oper == Operator.Inequality) {
ec.Emit (OpCodes.Ldc_I4_0);
ec.Emit (OpCodes.Ceq);
}
}
ec.Emit (OpCodes.Br_S, end_label);
ec.MarkLabel (dissimilar_label);
if (Oper == Operator.Inequality)
ec.Emit (OpCodes.Ldc_I4_1);
else
ec.Emit (OpCodes.Ldc_I4_0);
ec.MarkLabel (end_label);
}
public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
{
Emit (ec);
ec.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
}
public override void Emit (EmitContext ec)
{
//
// Optimize same expression operation
//
if (right_unwrap != null && right.Equals (left))
right_unwrap = left_unwrap;
if (user_operator == null && IsBitwiseBoolean) {
EmitBitwiseBoolean (ec);
return;
}
if ((Oper & Operator.EqualityMask) != 0) {
EmitEquality (ec);
return;
}
Label is_null_label = ec.DefineLabel ();
Label end_label = ec.DefineLabel ();
if (left_unwrap != null) {
left_unwrap.EmitCheck (ec);
ec.Emit (OpCodes.Brfalse, is_null_label);
}
//
// Don't emit HasValue check when left and right expressions are same
//
if (right_unwrap != null && !left.Equals (right)) {
right_unwrap.EmitCheck (ec);
ec.Emit (OpCodes.Brfalse, is_null_label);
}
EmitOperator (ec, left.Type);
if (wrap_ctor != null)
ec.Emit (OpCodes.Newobj, wrap_ctor);
ec.Emit (OpCodes.Br_S, end_label);
ec.MarkLabel (is_null_label);
if ((Oper & Operator.ComparisonMask) != 0) {
ec.Emit (OpCodes.Ldc_I4_0);
} else {
LiftedNull.Create (type, loc).Emit (ec);
}
ec.MarkLabel (end_label);
}
protected override void EmitOperator (EmitContext ec, TypeSpec l)
{
if (user_operator != null) {
user_operator.Emit (ec);
return;
}
if (TypeManager.IsNullableType (l))
l = TypeManager.GetTypeArguments (l) [0];
base.EmitOperator (ec, l);
}
Expression LiftResult (ResolveContext ec, Expression res_expr)
{
TypeExpr lifted_type;
//
// Avoid double conversion
//
if (left_unwrap == null || IsLeftNullLifted || left_unwrap.Type != left.Type || (left_unwrap != null && IsRightNullLifted)) {
lifted_type = new NullableType (left.Type, loc);
lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
if (lifted_type == null)
return null;
if (left is UserCast || left is TypeCast)
left.Type = lifted_type.Type;
else
left = EmptyCast.Create (left, lifted_type.Type);
}
if (left != right && (right_unwrap == null || IsRightNullLifted || right_unwrap.Type != right.Type || (right_unwrap != null && IsLeftNullLifted))) {
lifted_type = new NullableType (right.Type, loc);
lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
if (lifted_type == null)
return null;
var r = right;
if (r is ReducedExpression)
r = ((ReducedExpression) r).OriginalExpression;
if (r is UserCast || r is TypeCast)
r.Type = lifted_type.Type;
else
right = EmptyCast.Create (right, lifted_type.Type);
}
if ((Oper & Operator.ComparisonMask) == 0) {
lifted_type = new NullableType (res_expr.Type, loc);
lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
if (lifted_type == null)
return null;
wrap_ctor = NullableInfo.GetConstructor (lifted_type.Type);
type = res_expr.Type = lifted_type.Type;
}
if (IsLeftNullLifted) {
left = LiftedNull.Create (right.Type, left.Location);
//
// Special case for bool?, the result depends on both null right side and left side value
//
if ((Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) && NullableInfo.GetUnderlyingType (type) == TypeManager.bool_type) {
return res_expr;
}
if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0)
return LiftedNull.CreateFromExpression (ec, res_expr);
//
// Value types and null comparison
//
if (right_unwrap == null || (Oper & Operator.RelationalMask) != 0)
return CreateNullConstant (ec, right_orig).Resolve (ec);
}
if (IsRightNullLifted) {
right = LiftedNull.Create (left.Type, right.Location);
//
// Special case for bool?, the result depends on both null right side and left side value
//
if ((Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) && NullableInfo.GetUnderlyingType (type) == TypeManager.bool_type) {
return res_expr;
}
if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0)
return LiftedNull.CreateFromExpression (ec, res_expr);
//
// Value types and null comparison
//
if (left_unwrap == null || (Oper & Operator.RelationalMask) != 0)
return CreateNullConstant (ec, left_orig);
}
return res_expr;
}
protected override Expression ResolveOperatorPredefined (ResolveContext ec, Binary.PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
{
Expression e = base.ResolveOperatorPredefined (ec, operators, primitives_only, enum_type);
if (e == this || enum_type != null)
return LiftResult (ec, e);
//
// 7.9.9 Equality operators and null
//
// The == and != operators permit one operand to be a value of a nullable type and
// the other to be the null literal, even if no predefined or user-defined operator
// (in unlifted or lifted form) exists for the operation.
//
if (e == null && (Oper & Operator.EqualityMask) != 0) {
if ((IsLeftNullLifted && right_unwrap != null) || (IsRightNullLifted && left_unwrap != null))
return LiftResult (ec, this);
}
return e;
}
protected override Expression ResolveUserOperator (ResolveContext ec, Expression left, Expression right)
{
//
// Try original types first for exact match without unwrapping
//
Expression expr = base.ResolveUserOperator (ec, left_orig, right_orig);
if (expr != null)
return expr;
State orig_state = state;
//
// One side is a nullable type, try to match underlying types
//
if (left_unwrap != null || right_unwrap != null || (state & (State.RightNullLifted | State.LeftNullLifted)) != 0) {
expr = base.ResolveUserOperator (ec, left, right);
}
if (expr == null)
return null;
//
// Lift the result in the case it can be null and predefined or user operator
// result type is of a value type
//
if (!TypeManager.IsValueType (expr.Type))
return null;
if (state != orig_state)
return expr;
expr = LiftResult (ec, expr);
if (expr is Constant)
return expr;
type = expr.Type;
user_operator = expr;
return this;
}
}
public class NullCoalescingOperator : Expression
{
Expression left, right;
Unwrap unwrap;
public NullCoalescingOperator (Expression left, Expression right, Location loc)
{
this.left = left;
this.right = right;
this.loc = loc;
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
if (left is NullLiteral)
ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
UserCast uc = left as UserCast;
Expression conversion = null;
if (uc != null) {
left = uc.Source;
Arguments c_args = new Arguments (2);
c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
c_args.Add (new Argument (left.CreateExpressionTree (ec)));
conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
}
Arguments args = new Arguments (3);
args.Add (new Argument (left.CreateExpressionTree (ec)));
args.Add (new Argument (right.CreateExpressionTree (ec)));
if (conversion != null)
args.Add (new Argument (conversion));
return CreateExpressionFactoryCall (ec, "Coalesce", args);
}
Expression ConvertExpression (ResolveContext ec)
{
// TODO: ImplicitConversionExists should take care of this
if (left.eclass == ExprClass.MethodGroup)
return null;
TypeSpec ltype = left.Type;
//
// If left is a nullable type and an implicit conversion exists from right to underlying type of left,
// the result is underlying type of left
//
if (TypeManager.IsNullableType (ltype)) {
unwrap = Unwrap.Create (left, false);
if (unwrap == null)
return null;
//
// Reduce (left ?? null) to left
//
if (right.IsNull)
return ReducedExpression.Create (left, this);
if (Convert.ImplicitConversionExists (ec, right, unwrap.Type)) {
left = unwrap;
ltype = left.Type;
//
// If right is a dynamic expression, the result type is dynamic
//
if (right.Type == InternalType.Dynamic) {
type = right.Type;
// Need to box underlying value type
left = Convert.ImplicitBoxingConversion (left, ltype, type);
return this;
}
right = Convert.ImplicitConversion (ec, right, ltype, loc);
type = ltype;
return this;
}
} else if (TypeManager.IsReferenceType (ltype)) {
if (Convert.ImplicitConversionExists (ec, right, ltype)) {
//
// If right is a dynamic expression, the result type is dynamic
//
if (right.Type == InternalType.Dynamic) {
type = right.Type;
return this;
}
//
// Reduce ("foo" ?? expr) to expression
//
Constant lc = left as Constant;
if (lc != null && !lc.IsDefaultValue)
return ReducedExpression.Create (lc, this).Resolve (ec);
//
// Reduce (left ?? null) to left OR (null-constant ?? right) to right
//
if (right.IsNull || lc != null)
return ReducedExpression.Create (lc != null ? right : left, this).Resolve (ec);
right = Convert.ImplicitConversion (ec, right, ltype, loc);
type = ltype;
return this;
}
} else {
return null;
}
TypeSpec rtype = right.Type;
if (!Convert.ImplicitConversionExists (ec, unwrap != null ? unwrap : left, rtype) || right.eclass == ExprClass.MethodGroup)
return null;
//
// Reduce (null ?? right) to right
//
if (left.IsNull)
return ReducedExpression.Create (right, this).Resolve (ec);
left = Convert.ImplicitConversion (ec, unwrap != null ? unwrap : left, rtype, loc);
type = rtype;
return this;
}
protected override Expression DoResolve (ResolveContext ec)
{
left = left.Resolve (ec);
right = right.Resolve (ec);
if (left == null || right == null)
return null;
eclass = ExprClass.Value;
Expression e = ConvertExpression (ec);
if (e == null) {
Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
return null;
}
return e;
}
public override void Emit (EmitContext ec)
{
Label end_label = ec.DefineLabel ();
if (unwrap != null) {
Label is_null_label = ec.DefineLabel ();
unwrap.EmitCheck (ec);
ec.Emit (OpCodes.Brfalse, is_null_label);
left.Emit (ec);
ec.Emit (OpCodes.Br, end_label);
ec.MarkLabel (is_null_label);
right.Emit (ec);
ec.MarkLabel (end_label);
return;
}
left.Emit (ec);
ec.Emit (OpCodes.Dup);
// Only to make verifier happy
if (left.Type.IsGenericParameter)
ec.Emit (OpCodes.Box, left.Type);
ec.Emit (OpCodes.Brtrue, end_label);
ec.Emit (OpCodes.Pop);
right.Emit (ec);
ec.MarkLabel (end_label);
}
protected override void CloneTo (CloneContext clonectx, Expression t)
{
NullCoalescingOperator target = (NullCoalescingOperator) t;
target.left = left.Clone (clonectx);
target.right = right.Clone (clonectx);
}
}
public class LiftedUnaryMutator : ExpressionStatement
{
public readonly UnaryMutator.Mode Mode;
Expression expr;
UnaryMutator underlying;
Unwrap unwrap;
public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
{
this.expr = expr;
this.Mode = mode;
this.loc = loc;
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
return new SimpleAssign (this, this).CreateExpressionTree (ec);
}
protected override Expression DoResolve (ResolveContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return null;
unwrap = Unwrap.Create (expr, false);
if (unwrap == null)
return null;
underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
if (underlying == null)
return null;
eclass = ExprClass.Value;
type = expr.Type;
return this;
}
void DoEmit (EmitContext ec, bool is_expr)
{
Label is_null_label = ec.DefineLabel ();
Label end_label = ec.DefineLabel ();
unwrap.EmitCheck (ec);
ec.Emit (OpCodes.Brfalse, is_null_label);
if (is_expr) {
underlying.Emit (ec);
ec.Emit (OpCodes.Br_S, end_label);
} else {
underlying.EmitStatement (ec);
}
ec.MarkLabel (is_null_label);
if (is_expr)
LiftedNull.Create (type, loc).Emit (ec);
ec.MarkLabel (end_label);
}
public override void Emit (EmitContext ec)
{
DoEmit (ec, true);
}
public override void EmitStatement (EmitContext ec)
{
DoEmit (ec, false);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Newtonsoft.Json.Utilities;
using System.Globalization;
#if HAVE_DYNAMIC
using System.Dynamic;
using System.Linq.Expressions;
#endif
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a value in JSON (string, integer, date, etc).
/// </summary>
public partial class JValue : JToken, IEquatable<JValue>, IFormattable, IComparable, IComparable<JValue>
#if HAVE_ICONVERTIBLE
, IConvertible
#endif
{
private JTokenType _valueType;
private object _value;
internal JValue(object value, JTokenType type)
{
_value = value;
_valueType = type;
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class from another <see cref="JValue"/> object.
/// </summary>
/// <param name="other">A <see cref="JValue"/> object to copy from.</param>
public JValue(JValue other)
: this(other.Value, other.Type)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(long value)
: this(value, JTokenType.Integer)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(decimal value)
: this(value, JTokenType.Float)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(char value)
: this(value, JTokenType.String)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
[CLSCompliant(false)]
public JValue(ulong value)
: this(value, JTokenType.Integer)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(double value)
: this(value, JTokenType.Float)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(float value)
: this(value, JTokenType.Float)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(DateTime value)
: this(value, JTokenType.Date)
{
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(DateTimeOffset value)
: this(value, JTokenType.Date)
{
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(bool value)
: this(value, JTokenType.Boolean)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(string value)
: this(value, JTokenType.String)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(Guid value)
: this(value, JTokenType.Guid)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(Uri value)
: this(value, (value != null) ? JTokenType.Uri : JTokenType.Null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(TimeSpan value)
: this(value, JTokenType.TimeSpan)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(object value)
: this(value, GetValueType(null, value))
{
}
internal override bool DeepEquals(JToken node)
{
if (!(node is JValue other))
{
return false;
}
if (other == this)
{
return true;
}
return ValuesEquals(this, other);
}
/// <summary>
/// Gets a value indicating whether this token has child tokens.
/// </summary>
/// <value>
/// <c>true</c> if this token has child values; otherwise, <c>false</c>.
/// </value>
public override bool HasValues => false;
#if HAVE_BIG_INTEGER
private static int CompareBigInteger(BigInteger i1, object i2)
{
int result = i1.CompareTo(ConvertUtils.ToBigInteger(i2));
if (result != 0)
{
return result;
}
// converting a fractional number to a BigInteger will lose the fraction
// check for fraction if result is two numbers are equal
if (i2 is decimal d1)
{
return (0m).CompareTo(Math.Abs(d1 - Math.Truncate(d1)));
}
else if (i2 is double || i2 is float)
{
double d = Convert.ToDouble(i2, CultureInfo.InvariantCulture);
return (0d).CompareTo(Math.Abs(d - Math.Truncate(d)));
}
return result;
}
#endif
internal static int Compare(JTokenType valueType, object objA, object objB)
{
if (objA == objB)
{
return 0;
}
if (objB == null)
{
return 1;
}
if (objA == null)
{
return -1;
}
switch (valueType)
{
case JTokenType.Integer:
{
#if HAVE_BIG_INTEGER
if (objA is BigInteger integerA)
{
return CompareBigInteger(integerA, objB);
}
if (objB is BigInteger integerB)
{
return -CompareBigInteger(integerB, objA);
}
#endif
if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
{
return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
}
else if (objA is float || objB is float || objA is double || objB is double)
{
return CompareFloat(objA, objB);
}
else
{
return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
}
}
case JTokenType.Float:
{
#if HAVE_BIG_INTEGER
if (objA is BigInteger integerA)
{
return CompareBigInteger(integerA, objB);
}
if (objB is BigInteger integerB)
{
return -CompareBigInteger(integerB, objA);
}
#endif
if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
{
return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
}
return CompareFloat(objA, objB);
}
case JTokenType.Comment:
case JTokenType.String:
case JTokenType.Raw:
string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);
return string.CompareOrdinal(s1, s2);
case JTokenType.Boolean:
bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);
return b1.CompareTo(b2);
case JTokenType.Date:
#if HAVE_DATE_TIME_OFFSET
if (objA is DateTime dateA)
{
#else
DateTime dateA = (DateTime)objA;
#endif
DateTime dateB;
#if HAVE_DATE_TIME_OFFSET
if (objB is DateTimeOffset offsetB)
{
dateB = offsetB.DateTime;
}
else
#endif
{
dateB = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);
}
return dateA.CompareTo(dateB);
#if HAVE_DATE_TIME_OFFSET
}
else
{
DateTimeOffset offsetA = (DateTimeOffset)objA;
if (!(objB is DateTimeOffset offsetB))
{
offsetB = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture));
}
return offsetA.CompareTo(offsetB);
}
#endif
case JTokenType.Bytes:
if (!(objB is byte[] bytesB))
{
throw new ArgumentException("Object must be of type byte[].");
}
byte[] bytesA = objA as byte[];
Debug.Assert(bytesA != null);
return MiscellaneousUtils.ByteArrayCompare(bytesA, bytesB);
case JTokenType.Guid:
if (!(objB is Guid))
{
throw new ArgumentException("Object must be of type Guid.");
}
Guid guid1 = (Guid)objA;
Guid guid2 = (Guid)objB;
return guid1.CompareTo(guid2);
case JTokenType.Uri:
Uri uri2 = objB as Uri;
if (uri2 == null)
{
throw new ArgumentException("Object must be of type Uri.");
}
Uri uri1 = (Uri)objA;
return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
case JTokenType.TimeSpan:
if (!(objB is TimeSpan))
{
throw new ArgumentException("Object must be of type TimeSpan.");
}
TimeSpan ts1 = (TimeSpan)objA;
TimeSpan ts2 = (TimeSpan)objB;
return ts1.CompareTo(ts2);
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(valueType), valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
}
}
private static int CompareFloat(object objA, object objB)
{
double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture);
double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture);
// take into account possible floating point errors
if (MathUtils.ApproxEquals(d1, d2))
{
return 0;
}
return d1.CompareTo(d2);
}
#if HAVE_EXPRESSIONS
private static bool Operation(ExpressionType operation, object objA, object objB, out object result)
{
if (objA is string || objB is string)
{
if (operation == ExpressionType.Add || operation == ExpressionType.AddAssign)
{
result = objA?.ToString() + objB?.ToString();
return true;
}
}
#if HAVE_BIG_INTEGER
if (objA is BigInteger || objB is BigInteger)
{
if (objA == null || objB == null)
{
result = null;
return true;
}
// not that this will lose the fraction
// BigInteger doesn't have operators with non-integer types
BigInteger i1 = ConvertUtils.ToBigInteger(objA);
BigInteger i2 = ConvertUtils.ToBigInteger(objB);
switch (operation)
{
case ExpressionType.Add:
case ExpressionType.AddAssign:
result = i1 + i2;
return true;
case ExpressionType.Subtract:
case ExpressionType.SubtractAssign:
result = i1 - i2;
return true;
case ExpressionType.Multiply:
case ExpressionType.MultiplyAssign:
result = i1 * i2;
return true;
case ExpressionType.Divide:
case ExpressionType.DivideAssign:
result = i1 / i2;
return true;
}
}
else
#endif
if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
{
if (objA == null || objB == null)
{
result = null;
return true;
}
decimal d1 = Convert.ToDecimal(objA, CultureInfo.InvariantCulture);
decimal d2 = Convert.ToDecimal(objB, CultureInfo.InvariantCulture);
switch (operation)
{
case ExpressionType.Add:
case ExpressionType.AddAssign:
result = d1 + d2;
return true;
case ExpressionType.Subtract:
case ExpressionType.SubtractAssign:
result = d1 - d2;
return true;
case ExpressionType.Multiply:
case ExpressionType.MultiplyAssign:
result = d1 * d2;
return true;
case ExpressionType.Divide:
case ExpressionType.DivideAssign:
result = d1 / d2;
return true;
}
}
else if (objA is float || objB is float || objA is double || objB is double)
{
if (objA == null || objB == null)
{
result = null;
return true;
}
double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture);
double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture);
switch (operation)
{
case ExpressionType.Add:
case ExpressionType.AddAssign:
result = d1 + d2;
return true;
case ExpressionType.Subtract:
case ExpressionType.SubtractAssign:
result = d1 - d2;
return true;
case ExpressionType.Multiply:
case ExpressionType.MultiplyAssign:
result = d1 * d2;
return true;
case ExpressionType.Divide:
case ExpressionType.DivideAssign:
result = d1 / d2;
return true;
}
}
else if (objA is int || objA is uint || objA is long || objA is short || objA is ushort || objA is sbyte || objA is byte ||
objB is int || objB is uint || objB is long || objB is short || objB is ushort || objB is sbyte || objB is byte)
{
if (objA == null || objB == null)
{
result = null;
return true;
}
long l1 = Convert.ToInt64(objA, CultureInfo.InvariantCulture);
long l2 = Convert.ToInt64(objB, CultureInfo.InvariantCulture);
switch (operation)
{
case ExpressionType.Add:
case ExpressionType.AddAssign:
result = l1 + l2;
return true;
case ExpressionType.Subtract:
case ExpressionType.SubtractAssign:
result = l1 - l2;
return true;
case ExpressionType.Multiply:
case ExpressionType.MultiplyAssign:
result = l1 * l2;
return true;
case ExpressionType.Divide:
case ExpressionType.DivideAssign:
result = l1 / l2;
return true;
}
}
result = null;
return false;
}
#endif
internal override JToken CloneToken()
{
return new JValue(this);
}
/// <summary>
/// Creates a <see cref="JValue"/> comment with the given value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>A <see cref="JValue"/> comment with the given value.</returns>
public static JValue CreateComment(string value)
{
return new JValue(value, JTokenType.Comment);
}
/// <summary>
/// Creates a <see cref="JValue"/> string with the given value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>A <see cref="JValue"/> string with the given value.</returns>
public static JValue CreateString(string value)
{
return new JValue(value, JTokenType.String);
}
/// <summary>
/// Creates a <see cref="JValue"/> null value.
/// </summary>
/// <returns>A <see cref="JValue"/> null value.</returns>
public static JValue CreateNull()
{
return new JValue(null, JTokenType.Null);
}
/// <summary>
/// Creates a <see cref="JValue"/> undefined value.
/// </summary>
/// <returns>A <see cref="JValue"/> undefined value.</returns>
public static JValue CreateUndefined()
{
return new JValue(null, JTokenType.Undefined);
}
private static JTokenType GetValueType(JTokenType? current, object value)
{
if (value == null)
{
return JTokenType.Null;
}
#if HAVE_ADO_NET
else if (value == DBNull.Value)
{
return JTokenType.Null;
}
#endif
else if (value is string)
{
return GetStringValueType(current);
}
else if (value is long || value is int || value is short || value is sbyte
|| value is ulong || value is uint || value is ushort || value is byte)
{
return JTokenType.Integer;
}
else if (value is Enum)
{
return JTokenType.Integer;
}
#if HAVE_BIG_INTEGER
else if (value is BigInteger)
{
return JTokenType.Integer;
}
#endif
else if (value is double || value is float || value is decimal)
{
return JTokenType.Float;
}
else if (value is DateTime)
{
return JTokenType.Date;
}
#if HAVE_DATE_TIME_OFFSET
else if (value is DateTimeOffset)
{
return JTokenType.Date;
}
#endif
else if (value is byte[])
{
return JTokenType.Bytes;
}
else if (value is bool)
{
return JTokenType.Boolean;
}
else if (value is Guid)
{
return JTokenType.Guid;
}
else if (value is Uri)
{
return JTokenType.Uri;
}
else if (value is TimeSpan)
{
return JTokenType.TimeSpan;
}
throw new ArgumentException("Could not determine JSON object type for type {0}.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
private static JTokenType GetStringValueType(JTokenType? current)
{
if (current == null)
{
return JTokenType.String;
}
switch (current.GetValueOrDefault())
{
case JTokenType.Comment:
case JTokenType.String:
case JTokenType.Raw:
return current.GetValueOrDefault();
default:
return JTokenType.String;
}
}
/// <summary>
/// Gets the node type for this <see cref="JToken"/>.
/// </summary>
/// <value>The type.</value>
public override JTokenType Type => _valueType;
/// <summary>
/// Gets or sets the underlying token value.
/// </summary>
/// <value>The underlying token value.</value>
public object Value
{
get => _value;
set
{
Type currentType = _value?.GetType();
Type newType = value?.GetType();
if (currentType != newType)
{
_valueType = GetValueType(_valueType, value);
}
_value = value;
}
}
/// <summary>
/// Writes this token to a <see cref="JsonWriter"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/>s which will be used when writing the token.</param>
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{
if (converters != null && converters.Length > 0 && _value != null)
{
JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType());
if (matchingConverter != null && matchingConverter.CanWrite)
{
matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault());
return;
}
}
switch (_valueType)
{
case JTokenType.Comment:
writer.WriteComment(_value?.ToString());
return;
case JTokenType.Raw:
writer.WriteRawValue(_value?.ToString());
return;
case JTokenType.Null:
writer.WriteNull();
return;
case JTokenType.Undefined:
writer.WriteUndefined();
return;
case JTokenType.Integer:
if (_value is int i)
{
writer.WriteValue(i);
}
else if (_value is long l)
{
writer.WriteValue(l);
}
else if (_value is ulong ul)
{
writer.WriteValue(ul);
}
#if HAVE_BIG_INTEGER
else if (_value is BigInteger integer)
{
writer.WriteValue(integer);
}
#endif
else
{
writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture));
}
return;
case JTokenType.Float:
if (_value is decimal dec)
{
writer.WriteValue(dec);
}
else if (_value is double d)
{
writer.WriteValue(d);
}
else if (_value is float f)
{
writer.WriteValue(f);
}
else
{
writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture));
}
return;
case JTokenType.String:
writer.WriteValue(_value?.ToString());
return;
case JTokenType.Boolean:
writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture));
return;
case JTokenType.Date:
#if HAVE_DATE_TIME_OFFSET
if (_value is DateTimeOffset offset)
{
writer.WriteValue(offset);
}
else
#endif
{
writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture));
}
return;
case JTokenType.Bytes:
writer.WriteValue((byte[])_value);
return;
case JTokenType.Guid:
writer.WriteValue((_value != null) ? (Guid?)_value : null);
return;
case JTokenType.TimeSpan:
writer.WriteValue((_value != null) ? (TimeSpan?)_value : null);
return;
case JTokenType.Uri:
writer.WriteValue((Uri)_value);
return;
}
throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(Type), _valueType, "Unexpected token type.");
}
internal override int GetDeepHashCode()
{
int valueHashCode = (_value != null) ? _value.GetHashCode() : 0;
// GetHashCode on an enum boxes so cast to int
return ((int)_valueType).GetHashCode() ^ valueHashCode;
}
private static bool ValuesEquals(JValue v1, JValue v2)
{
return (v1 == v2 || (v1._valueType == v2._valueType && Compare(v1._valueType, v1._value, v2._value) == 0));
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// <c>true</c> if the current object is equal to the <paramref name="other"/> parameter; otherwise, <c>false</c>.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(JValue other)
{
if (other == null)
{
return false;
}
return ValuesEquals(this, other);
}
/// <summary>
/// Determines whether the specified <see cref="Object"/> is equal to the current <see cref="Object"/>.
/// </summary>
/// <param name="obj">The <see cref="Object"/> to compare with the current <see cref="Object"/>.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="Object"/> is equal to the current <see cref="Object"/>; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return Equals(obj as JValue);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="Object"/>.
/// </returns>
public override int GetHashCode()
{
if (_value == null)
{
return 0;
}
return _value.GetHashCode();
}
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public override string ToString()
{
if (_value == null)
{
return string.Empty;
}
return _value.ToString();
}
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <param name="formatProvider">The format provider.</param>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public string ToString(IFormatProvider formatProvider)
{
return ToString(null, formatProvider);
}
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="formatProvider">The format provider.</param>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
{
if (_value == null)
{
return string.Empty;
}
if (_value is IFormattable formattable)
{
return formattable.ToString(format, formatProvider);
}
else
{
return _value.ToString();
}
}
#if HAVE_DYNAMIC
/// <summary>
/// Returns the <see cref="DynamicMetaObject"/> responsible for binding operations performed on this object.
/// </summary>
/// <param name="parameter">The expression tree representation of the runtime value.</param>
/// <returns>
/// The <see cref="DynamicMetaObject"/> to bind this object.
/// </returns>
protected override DynamicMetaObject GetMetaObject(Expression parameter)
{
return new DynamicProxyMetaObject<JValue>(parameter, this, new JValueDynamicProxy());
}
private class JValueDynamicProxy : DynamicProxy<JValue>
{
public override bool TryConvert(JValue instance, ConvertBinder binder, out object result)
{
if (binder.Type == typeof(JValue) || binder.Type == typeof(JToken))
{
result = instance;
return true;
}
object value = instance.Value;
if (value == null)
{
result = null;
return ReflectionUtils.IsNullable(binder.Type);
}
result = ConvertUtils.Convert(value, CultureInfo.InvariantCulture, binder.Type);
return true;
}
public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, out object result)
{
object compareValue = arg is JValue value ? value.Value : arg;
switch (binder.Operation)
{
case ExpressionType.Equal:
result = (Compare(instance.Type, instance.Value, compareValue) == 0);
return true;
case ExpressionType.NotEqual:
result = (Compare(instance.Type, instance.Value, compareValue) != 0);
return true;
case ExpressionType.GreaterThan:
result = (Compare(instance.Type, instance.Value, compareValue) > 0);
return true;
case ExpressionType.GreaterThanOrEqual:
result = (Compare(instance.Type, instance.Value, compareValue) >= 0);
return true;
case ExpressionType.LessThan:
result = (Compare(instance.Type, instance.Value, compareValue) < 0);
return true;
case ExpressionType.LessThanOrEqual:
result = (Compare(instance.Type, instance.Value, compareValue) <= 0);
return true;
case ExpressionType.Add:
case ExpressionType.AddAssign:
case ExpressionType.Subtract:
case ExpressionType.SubtractAssign:
case ExpressionType.Multiply:
case ExpressionType.MultiplyAssign:
case ExpressionType.Divide:
case ExpressionType.DivideAssign:
if (Operation(binder.Operation, instance.Value, compareValue, out result))
{
result = new JValue(result);
return true;
}
break;
}
result = null;
return false;
}
}
#endif
int IComparable.CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
JTokenType comparisonType;
object otherValue;
if (obj is JValue value)
{
otherValue = value.Value;
comparisonType = (_valueType == JTokenType.String && _valueType != value._valueType)
? value._valueType
: _valueType;
}
else
{
otherValue = obj;
comparisonType = _valueType;
}
return Compare(comparisonType, _value, otherValue);
}
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings:
/// Value
/// Meaning
/// Less than zero
/// This instance is less than <paramref name="obj"/>.
/// Zero
/// This instance is equal to <paramref name="obj"/>.
/// Greater than zero
/// This instance is greater than <paramref name="obj"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="obj"/> is not of the same type as this instance.
/// </exception>
public int CompareTo(JValue obj)
{
if (obj == null)
{
return 1;
}
JTokenType comparisonType = (_valueType == JTokenType.String && _valueType != obj._valueType)
? obj._valueType
: _valueType;
return Compare(comparisonType, _value, obj._value);
}
#if HAVE_ICONVERTIBLE
TypeCode IConvertible.GetTypeCode()
{
if (_value == null)
{
return TypeCode.Empty;
}
if (_value is IConvertible convertable)
{
return convertable.GetTypeCode();
}
return TypeCode.Object;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return (bool)this;
}
char IConvertible.ToChar(IFormatProvider provider)
{
return (char)this;
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return (sbyte)this;
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return (byte)this;
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return (short)this;
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return (ushort)this;
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return (int)this;
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return (uint)this;
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return (long)this;
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return (ulong)this;
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return (float)this;
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return (double)this;
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return (decimal)this;
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return (DateTime)this;
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return ToObject(conversionType);
}
#endif
}
}
| |
// Unzip class for .NET 3.5 Client Profile or Mono 2.10
// Written by Alexey Yakovlev <yallie@yandex.ru>
// https://github.com/yallie/unzip
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
namespace Internals
{
/// <summary>
/// Unzip helper class.
/// </summary>
internal class Unzip : IDisposable
{
private const int EntrySignature = 0x02014B50;
private const int FileSignature = 0x04034b50;
private const int DirectorySignature = 0x06054B50;
private const int BufferSize = 16 * 1024;
/// <summary>
/// Zip archive entry.
/// </summary>
public class Entry
{
/// <summary>
/// Gets or sets the name of a file or a directory.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the comment.
/// </summary>
public string Comment { get; set; }
/// <summary>
/// Gets or sets the CRC32.
/// </summary>
public int Crc32 { get; set; }
/// <summary>
/// Gets or sets the compressed size of the file.
/// </summary>
public int CompressedSize { get; set; }
/// <summary>
/// Gets or sets the original size of the file.
/// </summary>
public int OriginalSize { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Entry" /> is deflated.
/// </summary>
public bool Deflated { get; set; }
/// <summary>
/// Gets a value indicating whether this <see cref="Entry" /> is a directory.
/// </summary>
public bool IsDirectory { get { return Name.EndsWith("/"); } }
/// <summary>
/// Gets or sets the timestamp.
/// </summary>
public DateTime Timestamp { get; set; }
/// <summary>
/// Gets a value indicating whether this <see cref="Entry" /> is a file.
/// </summary>
public bool IsFile { get { return !IsDirectory; } }
[EditorBrowsable(EditorBrowsableState.Never)]
public int HeaderOffset { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
public int DataOffset { get; set; }
}
/// <summary>
/// Initializes a new instance of the <see cref="Unzip" /> class.
/// </summary>
/// <param name="fileName">Name of the file.</param>
public Unzip(string fileName)
: this(File.OpenRead(fileName))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Unzip" /> class.
/// </summary>
/// <param name="stream">The stream.</param>
public Unzip(Stream stream)
{
Stream = stream;
Reader = new BinaryReader(Stream);
}
private Stream Stream { get; set; }
private BinaryReader Reader { get; set; }
/// <summary>
/// Performs application-defined tasks associated with
/// freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (Stream != null)
{
Stream.Dispose();
Stream = null;
}
if (Reader != null)
{
Reader.Close();
Reader = null;
}
}
/// <summary>
/// Extracts the contents of the zip file to the given directory.
/// </summary>
/// <param name="directoryName">Name of the directory.</param>
public void ExtractToDirectory(string directoryName)
{
foreach (var entry in Entries.Where(e => !e.IsDirectory))
{
// create target directory for the file
var fileName = Path.Combine(directoryName, entry.Name);
var dirName = Path.GetDirectoryName(fileName);
Directory.CreateDirectory(dirName);
// save file
Extract(entry.Name, fileName);
}
}
/// <summary>
/// Extracts the specified file to the specified name.
/// </summary>
/// <param name="fileName">Name of the file in zip archive.</param>
/// <param name="outputFileName">Name of the output file.</param>
public void Extract(string fileName, string outputFileName)
{
var entry = GetEntry(fileName);
using (var outStream = File.Create(outputFileName))
{
Extract(entry, outStream);
}
File.SetLastWriteTime(outputFileName, entry.Timestamp);
}
private Entry GetEntry(string fileName)
{
fileName = fileName.Replace("\\", "/").Trim().TrimStart('/');
var entry = Entries.Where(e => e.Name == fileName).FirstOrDefault();
if (entry == null)
{
throw new FileNotFoundException("File not found in the archive: " + fileName);
}
return entry;
}
/// <summary>
/// Extracts the specified file to the output <see cref="Stream"/>.
/// </summary>
/// <param name="fileName">Name of the file in zip archive.</param>
/// <param name="outputStream">The output stream.</param>
public void Extract(string fileName, Stream outputStream)
{
Extract(GetEntry(fileName), outputStream);
}
/// <summary>
/// Extracts the specified entry.
/// </summary>
/// <param name="entry">Zip file entry to extract.</param>
/// <param name="outputStream">The stream to write the data to.</param>
/// <exception cref="System.InvalidOperationException"> is thrown when the file header signature doesn't match.</exception>
public void Extract(Entry entry, Stream outputStream)
{
// check file signature
Stream.Seek(entry.HeaderOffset, SeekOrigin.Begin);
if (Reader.ReadInt32() != FileSignature)
{
throw new InvalidOperationException("File signature doesn't match.");
}
// move to file data
Stream.Seek(entry.DataOffset, SeekOrigin.Begin);
var inputStream = Stream;
if (entry.Deflated)
{
inputStream = new DeflateStream(Stream, CompressionMode.Decompress, true);
}
// allocate buffer
var count = entry.OriginalSize;
var bufferSize = Math.Min(BufferSize, entry.OriginalSize);
var buffer = new byte[bufferSize];
while (count > 0)
{
// decompress data
var read = inputStream.Read(buffer, 0, bufferSize);
if (read == 0)
{
break;
}
// copy to the output stream
outputStream.Write(buffer, 0, read);
count -= read;
}
}
/// <summary>
/// Gets the file names.
/// </summary>
public IEnumerable<string> FileNames
{
get
{
return Entries.Select(e => e.Name).Where(f => !f.EndsWith("/")).OrderBy(f => f);
}
}
private Entry[] entries;
/// <summary>
/// Gets zip file entries.
/// </summary>
public IEnumerable<Entry> Entries
{
get
{
if (entries == null)
{
entries = ReadZipEntries().ToArray();
}
return entries;
}
}
private IEnumerable<Entry> ReadZipEntries()
{
if (Stream.Length < 22)
{
yield break;
}
Stream.Seek(-22, SeekOrigin.End);
// find directory signature
while (Reader.ReadInt32() != DirectorySignature)
{
if (Stream.Position <= 5)
{
yield break;
}
// move 1 byte back
Stream.Seek(-5, SeekOrigin.Current);
}
// read directory properties
Stream.Seek(6, SeekOrigin.Current);
var entries = Reader.ReadUInt16();
var difSize = Reader.ReadInt32();
var dirOffset = Reader.ReadUInt32();
Stream.Seek(dirOffset, SeekOrigin.Begin);
// read directory entries
for (int i = 0; i < entries; i++)
{
if (Reader.ReadInt32() != EntrySignature)
{
continue;
}
// read file properties
Reader.ReadInt32();
bool utf8 = (Reader.ReadInt16() & 0x0800) != 0;
short method = Reader.ReadInt16();
int timestamp = Reader.ReadInt32();
int crc32 = Reader.ReadInt32();
int compressedSize = Reader.ReadInt32();
int fileSize = Reader.ReadInt32();
short fileNameSize = Reader.ReadInt16();
short extraSize = Reader.ReadInt16();
short commentSize = Reader.ReadInt16();
int headerOffset = Reader.ReadInt32();
Reader.ReadInt32();
int fileHeaderOffset = Reader.ReadInt32();
var fileNameBytes = Reader.ReadBytes(fileNameSize);
Stream.Seek(extraSize, SeekOrigin.Current);
var fileCommentBytes = Reader.ReadBytes(commentSize);
var fileDataOffset = CalculateFileDataOffset(fileHeaderOffset);
// decode zip file entry
var encoder = utf8 ? Encoding.UTF8 : Encoding.Default;
yield return new Entry
{
Name = encoder.GetString(fileNameBytes),
Comment = encoder.GetString(fileCommentBytes),
Crc32 = crc32,
CompressedSize = compressedSize,
OriginalSize = fileSize,
HeaderOffset = fileHeaderOffset,
DataOffset = fileDataOffset,
Deflated = method == 8,
Timestamp = ConvertToDateTime(timestamp)
};
}
}
private int CalculateFileDataOffset(int fileHeaderOffset)
{
var position = Stream.Position;
Stream.Seek(fileHeaderOffset + 26, SeekOrigin.Begin);
var fileNameSize = Reader.ReadInt16();
var extraSize = Reader.ReadInt16();
var fileOffset = (int)Stream.Position + fileNameSize + extraSize;
Stream.Seek(position, SeekOrigin.Begin);
return fileOffset;
}
/// <summary>
/// Converts DOS timestamp to a <see cref="DateTime"/> instance.
/// </summary>
/// <param name="dosTimestamp">The dos timestamp.</param>
/// <returns>The <see cref="DateTime"/> instance.</returns>
public static DateTime ConvertToDateTime(int dosTimestamp)
{
return new DateTime((dosTimestamp >> 25) + 1980, (dosTimestamp >> 21) & 15, (dosTimestamp >> 16) & 31,
(dosTimestamp >> 11) & 31, (dosTimestamp >> 5) & 63, (dosTimestamp & 31) * 2);
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
// Timeouts for corpse deletion.
$CorpseTimeoutValue = 45 * 1000;
// // Damage Rate for entering Liquid
// $DamageLava = 0.01;
// $DamageHotLava = 0.01;
// $DamageCrustyLava = 0.01;
// Death Animations
$PlayerDeathAnim::TorsoFrontFallForward = 1;
$PlayerDeathAnim::TorsoFrontFallBack = 2;
$PlayerDeathAnim::TorsoBackFallForward = 3;
$PlayerDeathAnim::TorsoLeftSpinDeath = 4;
$PlayerDeathAnim::TorsoRightSpinDeath = 5;
$PlayerDeathAnim::LegsLeftGimp = 6;
$PlayerDeathAnim::LegsRightGimp = 7;
$PlayerDeathAnim::TorsoBackFallForward = 8;
$PlayerDeathAnim::HeadFrontDirect = 9;
$PlayerDeathAnim::HeadBackFallForward = 10;
$PlayerDeathAnim::ExplosionBlowBack = 11;
//----------------------------------------------------------------------------
// Armor Datablock methods
//----------------------------------------------------------------------------
function Armor::onAdd(%this, %obj)
{
// Vehicle timeout
%obj.mountVehicle = true;
// Default dynamic armor stats
%obj.setRechargeRate(%this.rechargeRate);
%obj.setRepairRate(0);
// Set the numerical Health HUD
//%obj.updateHealth();
// Calling updateHealth() must be delayed now... for some reason
%obj.schedule(50, "updateHealth");
}
function Armor::onRemove(%this, %obj)
{
if (%obj.client.player == %obj)
%obj.client.player = 0;
}
function Armor::onNewDataBlock(%this, %obj)
{
}
//----------------------------------------------------------------------------
function Armor::onMount(%this, %obj, %vehicle, %node)
{
// Node 0 is the pilot's position, we need to dismount his weapon.
if (%node == 0)
{
%obj.setTransform("0 0 0 0 0 1 0");
%obj.setActionThread(%vehicle.getDatablock().mountPose[%node], true, true);
%obj.lastWeapon = %obj.getMountedImage($WeaponSlot);
%obj.unmountImage($WeaponSlot);
%obj.setControlObject(%vehicle);
if(%obj.getClassName() $= "Player")
commandToClient(%obj.client, 'toggleVehicleMap', true);
}
else
{
if (%vehicle.getDataBlock().mountPose[%node] !$= "")
%obj.setActionThread(%vehicle.getDatablock().mountPose[%node]);
else
%obj.setActionThread("root", true);
}
}
function Armor::onUnmount(%this, %obj, %vehicle, %node)
{
if (%node == 0)
{
%obj.mountImage(%obj.lastWeapon, $WeaponSlot);
%obj.setControlObject("");
}
}
function Armor::doDismount(%this, %obj, %forced)
{
//echo("\c4Armor::doDismount(" @ %this @", "@ %obj.client.nameBase @", "@ %forced @")");
// This function is called by player.cc when the jump trigger
// is true while mounted
%vehicle = %obj.mVehicle;
if (!%obj.isMounted() || !isObject(%vehicle))
return;
// Vehicle must be at rest!
if ((VectorLen(%vehicle.getVelocity()) <= %vehicle.getDataBlock().maxDismountSpeed ) || %forced)
{
// Position above dismount point
%pos = getWords(%obj.getTransform(), 0, 2);
%rot = getWords(%obj.getTransform(), 3, 6);
%oldPos = %pos;
%vec[0] = " -1 0 0";
%vec[1] = " 0 0 1";
%vec[2] = " 0 0 -1";
%vec[3] = " 1 0 0";
%vec[4] = "0 -1 0";
%impulseVec = "0 0 0";
%vec[0] = MatrixMulVector(%obj.getTransform(), %vec[0]);
// Make sure the point is valid
%pos = "0 0 0";
%numAttempts = 5;
%success = -1;
for (%i = 0; %i < %numAttempts; %i++)
{
%pos = VectorAdd(%oldPos, VectorScale(%vec[%i], 3));
if (%obj.checkDismountPoint(%oldPos, %pos))
{
%success = %i;
%impulseVec = %vec[%i];
break;
}
}
if (%forced && %success == -1)
%pos = %oldPos;
%obj.mountVehicle = false;
%obj.schedule(4000, "mountVehicles", true);
// Position above dismount point
%obj.unmount();
%obj.setTransform(%pos SPC %rot);//%obj.setTransform(%pos);
//%obj.playAudio(0, UnmountVehicleSound);
%obj.applyImpulse(%pos, VectorScale(%impulseVec, %obj.getDataBlock().mass));
// Set player velocity when ejecting
%vel = %obj.getVelocity();
%vec = vectorDot( %vel, vectorNormalize(%vel));
if(%vec > 50)
{
%scale = 50 / %vec;
%obj.setVelocity(VectorScale(%vel, %scale));
}
//%obj.vehicleTurret = "";
}
else
messageClient(%obj.client, 'msgUnmount', '\c2Cannot exit %1 while moving.', %vehicle.getDataBlock().nameTag);
}
//----------------------------------------------------------------------------
function Armor::onCollision(%this, %obj, %col)
{
if (!isObject(%col) || %obj.getState() $= "Dead")
return;
// Try and pickup all items
if (%col.getClassName() $= "Item")
{
%obj.pickup(%col);
return;
}
// Mount vehicles
if (%col.getType() & $TypeMasks::GameBaseObjectType)
{
%db = %col.getDataBlock();
if ((%db.getClassName() $= "WheeledVehicleData" ) && %obj.mountVehicle && %obj.getState() $= "Move" && %col.mountable)
{
// Only mount drivers for now.
ServerConnection.setFirstPerson(0);
// For this specific example, only one person can fit
// into a vehicle
%mount = %col.getMountNodeObject(0);
if(%mount)
return;
// For this specific FPS Example, always mount the player
// to node 0
%node = 0;
%col.mountObject(%obj, %node);
%obj.mVehicle = %col;
}
}
}
function Armor::onImpact(%this, %obj, %collidedObject, %vec, %vecLen)
{
%obj.damage(0, VectorAdd(%obj.getPosition(), %vec), %vecLen * %this.speedDamageScale, "Impact");
}
//----------------------------------------------------------------------------
function Armor::damage(%this, %obj, %sourceObject, %position, %damage, %damageType)
{
if (!isObject(%obj) || %obj.getState() $= "Dead")
return;
%obj.applyDamage(%damage);
%location = "Body";
// Update the numerical Health HUD
%obj.updateHealth();
// Deal with client callbacks here because we don't have this
// information in the onDamage or onDisable methods
%client = %obj.client;
%sourceClient = %sourceObject ? %sourceObject.client : 0;
if (%obj.getState() $= "Dead" && isObject(%client))
%client.onDeath(%sourceObject, %sourceClient, %damageType, %location);
}
function Armor::onDamage(%this, %obj, %delta)
{
// This method is invoked by the ShapeBase code whenever the
// object's damage level changes.
if (%delta > 0 && %obj.getState() !$= "Dead")
{
// Apply a damage flash
%obj.setDamageFlash(1);
// If the pain is excessive, let's hear about it.
if (%delta > 10)
%obj.playPain();
}
}
// ----------------------------------------------------------------------------
// The player object sets the "disabled" state when damage exceeds it's
// maxDamage value. This is method is invoked by ShapeBase state mangement code.
// If we want to deal with the damage information that actually caused this
// death, then we would have to move this code into the script "damage" method.
function Armor::onDisabled(%this, %obj, %state)
{
// Release the main weapon trigger
%obj.setImageTrigger(0, false);
// Toss current mounted weapon and ammo if any
%item = %obj.getMountedImage($WeaponSlot).item;
if (isObject(%item))
{
%amount = %obj.getInventory(%item.image.ammo);
if(%amount)
%obj.throw(%item.image.ammo, %amount);
%obj.throw(%item, 1);
}
// Toss out a health patch
%obj.tossPatch();
%obj.playDeathCry();
%obj.playDeathAnimation();
//%obj.setDamageFlash(0.75);
// Schedule corpse removal. Just keeping the place clean.
%obj.schedule($CorpseTimeoutValue - 1000, "startFade", 1000, 0, true);
%obj.schedule($CorpseTimeoutValue, "delete");
}
//-----------------------------------------------------------------------------
function Armor::onLeaveMissionArea(%this, %obj)
{
//echo("\c4Leaving Mission Area at POS:"@ %obj.getPosition());
// Inform the client
%obj.client.onLeaveMissionArea();
// Damage over time and kill the coward!
//%obj.setDamageDt(0.2, "MissionAreaDamage");
}
function Armor::onEnterMissionArea(%this, %obj)
{
//echo("\c4Entering Mission Area at POS:"@ %obj.getPosition());
// Inform the client
%obj.client.onEnterMissionArea();
// Stop the punishment
//%obj.clearDamageDt();
}
//-----------------------------------------------------------------------------
function Armor::onEnterLiquid(%this, %obj, %coverage, %type)
{
//echo("\c4this:"@ %this @" object:"@ %obj @" just entered water of type:"@ %type @" for "@ %coverage @"coverage");
}
function Armor::onLeaveLiquid(%this, %obj, %type)
{
//
}
//-----------------------------------------------------------------------------
function Armor::onTrigger(%this, %obj, %triggerNum, %val)
{
// This method is invoked when the player receives a trigger move event.
// The player automatically triggers slot 0 and slot one off of triggers #
// 0 & 1. Trigger # 2 is also used as the jump key.
}
//-----------------------------------------------------------------------------
// Player methods
//-----------------------------------------------------------------------------
//----------------------------------------------------------------------------
function Player::kill(%this, %damageType)
{
%this.damage(0, %this.getPosition(), 10000, %damageType);
}
//----------------------------------------------------------------------------
function Player::mountVehicles(%this, %bool)
{
// If set to false, this variable disables vehicle mounting.
%this.mountVehicle = %bool;
}
function Player::isPilot(%this)
{
%vehicle = %this.getObjectMount();
// There are two "if" statements to avoid a script warning.
if (%vehicle)
if (%vehicle.getMountNodeObject(0) == %this)
return true;
return false;
}
//----------------------------------------------------------------------------
function Player::playDeathAnimation(%this)
{
if (isObject(%this.client))
{
if (%this.client.deathIdx++ > 11)
%this.client.deathIdx = 1;
%this.setActionThread("Death" @ %this.client.deathIdx);
}
else
{
%rand = getRandom(1, 11);
%this.setActionThread("Death" @ %rand);
}
}
function Player::playCelAnimation(%this, %anim)
{
if (%this.getState() !$= "Dead")
%this.setActionThread("cel"@%anim);
}
//----------------------------------------------------------------------------
function Player::playDeathCry(%this)
{
%this.playAudio(0, DeathCrySound);
}
function Player::playPain(%this)
{
%this.playAudio(0, PainCrySound);
}
// ----------------------------------------------------------------------------
// Numerical Health Counter
// ----------------------------------------------------------------------------
function Player::updateHealth(%player)
{
//echo("\c4Player::updateHealth() -> Player Health changed, updating HUD!");
// Calcualte player health
%maxDamage = %player.getDatablock().maxDamage;
%damageLevel = %player.getDamageLevel();
%curHealth = %maxDamage - %damageLevel;
%curHealth = mceil(%curHealth);
// Send the player object's current health level to the client, where it
// will Update the numericalHealth HUD.
commandToClient(%player.client, 'setNumericalHealthHUD', %curHealth);
}
function Player::use(%player, %data)
{
// No mounting/using weapons when you're driving!
if (%player.isPilot())
return(false);
Parent::use(%player, %data);
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace pltkw3msInventoryCatalog.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// 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.IO;
using Test.IO.Streams;
using Xunit;
namespace System.Security.Cryptography.Rsa.Tests
{
public class SignVerify
{
public static bool BadKeyFormatDoesntThrow => !PlatformDetection.IsFullFramework || PlatformDetection.IsNetfx462OrNewer();
public static bool InvalidKeySizeDoesntThrow => !PlatformDetection.IsFullFramework || PlatformDetection.IsNetfx462OrNewer();
[Fact]
public static void InvalidKeySize_DoesNotInvalidateKey()
{
using (RSA rsa = RSAFactory.Create())
{
byte[] signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
// A 2049-bit key is hard to describe, none of the providers support it.
Assert.ThrowsAny<CryptographicException>(() => rsa.KeySize = 2049);
Assert.True(rsa.VerifyData(TestData.HelloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1));
}
}
[Fact]
public static void PublicKey_CannotSign()
{
using (RSA rsa = RSAFactory.Create())
using (RSA rsaPub = RSAFactory.Create())
{
rsaPub.ImportParameters(rsa.ExportParameters(false));
Assert.ThrowsAny<CryptographicException>(
() => rsaPub.SignData(TestData.HelloBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
}
}
[Fact]
public static void SignEmptyHash()
{
using (RSA rsa = RSAFactory.Create())
{
Assert.ThrowsAny<CryptographicException>(
() => rsa.SignHash(Array.Empty<byte>(), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1));
}
}
[Fact]
public static void SignNullHash()
{
using (RSA rsa = RSAFactory.Create())
{
Assert.ThrowsAny<ArgumentNullException>(
() => rsa.SignHash(null, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1));
}
}
[ConditionalFact(nameof(InvalidKeySizeDoesntThrow))]
public static void ExpectedSignature_SHA1_384()
{
byte[] expectedSignature =
{
0x79, 0xD9, 0x3C, 0xBF, 0x54, 0xFA, 0x55, 0x8C,
0x44, 0xC3, 0xC3, 0x83, 0x85, 0xBB, 0x78, 0x44,
0xCD, 0x0F, 0x5A, 0x8E, 0x71, 0xC9, 0xC2, 0x68,
0x68, 0x0A, 0x33, 0x93, 0x19, 0x37, 0x02, 0x06,
0xE2, 0xF7, 0x67, 0x97, 0x3C, 0x67, 0xB3, 0xF4,
0x11, 0xE0, 0x6E, 0xD2, 0x22, 0x75, 0xE7, 0x7C,
};
try
{
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA1", TestData.RSA384Parameters);
Assert.True(RSAFactory.Supports384PrivateKey, "RSAFactory.Supports384PrivateKey");
}
catch (CryptographicException)
{
// If the provider is not known to fail loading a 384-bit key, let the exception be the
// test failure. (If it is known to fail loading that key, we've now suppressed the throw,
// and the test will pass.)
if (RSAFactory.Supports384PrivateKey)
{
throw;
}
}
}
[ConditionalFact(nameof(InvalidKeySizeDoesntThrow))]
public static void ExpectedSignature_SHA1_1032()
{
byte[] expectedSignature =
{
0x49, 0xBC, 0x1C, 0xBE, 0x72, 0xEF, 0x83, 0x6E,
0x2D, 0xFA, 0xE7, 0xFA, 0xEB, 0xBC, 0xF0, 0x16,
0xF7, 0x2C, 0x07, 0x6D, 0x9F, 0xA6, 0x68, 0x71,
0xDC, 0x78, 0x9C, 0xA3, 0x42, 0x9E, 0xBB, 0xF5,
0x72, 0xE0, 0xAB, 0x4B, 0x4B, 0x6A, 0xE7, 0x3C,
0xE2, 0xC8, 0x1F, 0xA2, 0x07, 0xED, 0xD3, 0x98,
0xE9, 0xDF, 0x9A, 0x7A, 0x86, 0xB8, 0x06, 0xED,
0x97, 0x46, 0xF9, 0x8A, 0xED, 0x53, 0x1D, 0x90,
0xC3, 0x57, 0x7E, 0x5A, 0xE4, 0x7C, 0xEC, 0xB9,
0x45, 0x95, 0xAB, 0xCC, 0xBA, 0x9B, 0x2C, 0x1A,
0x64, 0xC2, 0x2C, 0xA0, 0x36, 0x7C, 0x56, 0xF0,
0x78, 0x77, 0x0B, 0x27, 0xB8, 0x1C, 0xCA, 0x7D,
0xD4, 0x71, 0x37, 0xBF, 0xC6, 0x4C, 0x64, 0x76,
0xBC, 0x8A, 0x87, 0xA0, 0x81, 0xF9, 0x4A, 0x94,
0x7B, 0xAA, 0x80, 0x95, 0x47, 0x51, 0xF9, 0x02,
0xA3, 0x44, 0x5C, 0x56, 0x60, 0xFB, 0x94, 0xA8,
0x52,
};
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA1", TestData.RSA1032Parameters);
}
[Fact]
public static void ExpectedSignature_SHA1_2048()
{
byte[] expectedSignature = new byte[]
{
0xA1, 0xFC, 0x74, 0x67, 0x49, 0x91, 0xF4, 0x28,
0xB0, 0xF6, 0x2B, 0xB8, 0x5E, 0x5F, 0x2E, 0x0F,
0xD8, 0xBC, 0xB4, 0x6E, 0x0A, 0xF7, 0x11, 0xC2,
0x65, 0x35, 0x5C, 0x1B, 0x1B, 0xC1, 0x20, 0xC0,
0x7D, 0x5B, 0x98, 0xAF, 0xB4, 0xC1, 0x6A, 0x25,
0x17, 0x47, 0x2C, 0x7F, 0x20, 0x2A, 0xDD, 0xF0,
0x5F, 0xDF, 0x6F, 0x5B, 0x7D, 0xEE, 0xAA, 0x4B,
0x9E, 0x8B, 0xA6, 0x0D, 0x81, 0x54, 0x93, 0x6E,
0xB2, 0x86, 0xC8, 0x14, 0x4F, 0xE7, 0x4A, 0xCC,
0xBE, 0x51, 0x2D, 0x0B, 0x9B, 0x46, 0xF1, 0x39,
0x80, 0x1D, 0xD0, 0x07, 0xBA, 0x46, 0x48, 0xFC,
0x7A, 0x50, 0x17, 0xC9, 0x7F, 0xEF, 0xDD, 0x42,
0xC5, 0x8B, 0x69, 0x38, 0x67, 0xAB, 0xBD, 0x39,
0xA6, 0xF4, 0x02, 0x34, 0x88, 0x56, 0x50, 0x05,
0xEA, 0x95, 0x24, 0x7D, 0x34, 0xD9, 0x9F, 0xB1,
0x05, 0x39, 0x6A, 0x42, 0x9E, 0x5E, 0xEB, 0xC9,
0x90, 0xC1, 0x93, 0x63, 0x29, 0x0C, 0xC5, 0xBC,
0xC8, 0x65, 0xB0, 0xFA, 0x63, 0x61, 0x77, 0xD9,
0x16, 0x59, 0xF0, 0xAD, 0x28, 0xC7, 0x98, 0x3C,
0x53, 0xF1, 0x6C, 0x91, 0x7E, 0x36, 0xC3, 0x3A,
0x23, 0x87, 0xA7, 0x3A, 0x18, 0x18, 0xBF, 0xD2,
0x3E, 0x51, 0x9E, 0xAB, 0x9E, 0x4C, 0x65, 0xBA,
0x43, 0xC0, 0x7E, 0xA2, 0x6B, 0xCF, 0x69, 0x7C,
0x8F, 0xAB, 0x22, 0x28, 0xD6, 0xF1, 0x65, 0x0B,
0x4A, 0x5B, 0x9B, 0x1F, 0xD4, 0xAA, 0xEF, 0x35,
0xA2, 0x42, 0x32, 0x00, 0x9F, 0x42, 0xBB, 0x19,
0x99, 0x49, 0x6D, 0xB8, 0x03, 0x3D, 0x35, 0x96,
0x0C, 0x57, 0xBB, 0x6B, 0x07, 0xA4, 0xB9, 0x7F,
0x9B, 0xEC, 0x78, 0x90, 0xB7, 0xC8, 0x5E, 0x7F,
0x3B, 0xAB, 0xC1, 0xB6, 0x0C, 0x84, 0x3C, 0xBC,
0x7F, 0x04, 0x79, 0xB7, 0x9C, 0xC0, 0xFE, 0xB0,
0xAE, 0xBD, 0xA5, 0x57, 0x2C, 0xEC, 0x3D, 0x0D,
};
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void ExpectedSignature_SHA256_1024()
{
byte[] expectedSignature = new byte[]
{
0x5C, 0x2F, 0x00, 0xA9, 0xE4, 0x63, 0xD7, 0xB7,
0x94, 0x93, 0xCE, 0xA8, 0x7E, 0x71, 0xAE, 0x97,
0xC2, 0x6B, 0x37, 0x31, 0x5B, 0xB8, 0xE3, 0x30,
0xDF, 0x77, 0xF8, 0xBB, 0xB5, 0xBF, 0x41, 0x9F,
0x14, 0x6A, 0x61, 0x26, 0x2E, 0x80, 0xE5, 0xE6,
0x8A, 0xEA, 0xC7, 0x60, 0x0B, 0xAE, 0x2B, 0xB2,
0x18, 0xD8, 0x5D, 0xC8, 0x58, 0x86, 0x5E, 0x23,
0x62, 0x44, 0x72, 0xEA, 0x3B, 0xF7, 0x70, 0xC6,
0x4C, 0x2B, 0x54, 0x5B, 0xF4, 0x24, 0xA1, 0xE5,
0x63, 0xDD, 0x50, 0x3A, 0x29, 0x26, 0x84, 0x06,
0xEF, 0x13, 0xD0, 0xCE, 0xCC, 0xA1, 0x05, 0xB4,
0x72, 0x81, 0x0A, 0x2E, 0x33, 0xF6, 0x2F, 0xD1,
0xEA, 0x41, 0xB0, 0xB3, 0x93, 0x4C, 0xF3, 0x0F,
0x6F, 0x21, 0x3E, 0xD7, 0x5F, 0x57, 0x2E, 0xC7,
0x5F, 0xF5, 0x28, 0x89, 0xB8, 0x07, 0xDB, 0xAC,
0x70, 0x95, 0x25, 0x49, 0x8A, 0x1A, 0xD7, 0xFC,
};
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void ExpectedSignature_SHA256_2048()
{
byte[] expectedSignature = new byte[]
{
0x2C, 0x74, 0x98, 0x23, 0xF4, 0x38, 0x7F, 0x49,
0x82, 0xB6, 0x55, 0xCF, 0xC3, 0x25, 0x4F, 0xE3,
0x4B, 0x17, 0xE7, 0xED, 0xEA, 0x58, 0x1E, 0x63,
0x57, 0x58, 0xCD, 0xB5, 0x06, 0xD6, 0xCA, 0x13,
0x28, 0x81, 0xE6, 0xE0, 0x8B, 0xDC, 0xC6, 0x05,
0x35, 0x35, 0x40, 0x73, 0x76, 0x61, 0x67, 0x42,
0x94, 0xF7, 0x54, 0x0E, 0xB6, 0x30, 0x9A, 0x70,
0xC3, 0x06, 0xC1, 0x59, 0xA7, 0x89, 0x66, 0x38,
0x02, 0x5C, 0x52, 0x02, 0x17, 0x4E, 0xEC, 0x21,
0xE9, 0x24, 0x85, 0xCB, 0x56, 0x42, 0xAB, 0x21,
0x3A, 0x19, 0xC3, 0x95, 0x06, 0xBA, 0xDB, 0xD9,
0x89, 0x7C, 0xB9, 0xEC, 0x1D, 0x8B, 0x5A, 0x64,
0x87, 0xAF, 0x36, 0x71, 0xAC, 0x0A, 0x2B, 0xC7,
0x7D, 0x2F, 0x44, 0xAA, 0xB4, 0x1C, 0xBE, 0x0B,
0x0A, 0x4E, 0xEA, 0xF8, 0x75, 0x40, 0xD9, 0x4A,
0x82, 0x1C, 0x82, 0x81, 0x97, 0xC2, 0xF1, 0xC8,
0xA7, 0x4B, 0x45, 0x9A, 0x66, 0x8E, 0x35, 0x2E,
0xE5, 0x1A, 0x2B, 0x0B, 0xF9, 0xAB, 0xC4, 0x2A,
0xE0, 0x47, 0x72, 0x2A, 0xC2, 0xD8, 0xC6, 0xFD,
0x91, 0x30, 0xD2, 0x45, 0xA4, 0x7F, 0x0F, 0x39,
0x80, 0xBC, 0xA9, 0xBD, 0xEC, 0xA5, 0x03, 0x6F,
0x01, 0xF6, 0x19, 0xD5, 0x2B, 0xD9, 0x40, 0xCD,
0x7F, 0xEF, 0x0F, 0x9D, 0x93, 0x02, 0xCD, 0x89,
0xB8, 0x2C, 0xC7, 0xD6, 0xFD, 0xAA, 0x12, 0x6E,
0x4C, 0x06, 0x35, 0x08, 0x61, 0x79, 0x27, 0xE1,
0xEA, 0x46, 0x75, 0x08, 0x5B, 0x51, 0xA1, 0x80,
0x78, 0x02, 0xEA, 0x3E, 0xEC, 0x29, 0xD2, 0x8B,
0xC5, 0x9E, 0x7D, 0xA4, 0x85, 0x8D, 0xAD, 0x73,
0x39, 0x17, 0x64, 0x82, 0x46, 0x4A, 0xA4, 0x34,
0xF0, 0xCC, 0x2F, 0x9F, 0x55, 0xA4, 0xEA, 0xEC,
0xC9, 0xA7, 0xAB, 0xBA, 0xA8, 0x84, 0x14, 0x62,
0x6B, 0x9B, 0x97, 0x2D, 0x8C, 0xB2, 0x1C, 0x16,
};
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA256", TestData.RSA2048Params);
}
[Fact]
public static void ExpectSignature_SHA256_1024_Stream()
{
byte[] expectedSignature = new byte[]
{
0x78, 0x6F, 0x42, 0x00, 0xF4, 0x5A, 0xDB, 0x09,
0x72, 0xB9, 0xCD, 0xBE, 0xB8, 0x46, 0x54, 0xE0,
0xCF, 0x02, 0xB5, 0xA1, 0xF1, 0x7C, 0xA7, 0x5A,
0xCF, 0x09, 0x60, 0xB6, 0xFF, 0x6B, 0x8A, 0x92,
0x8E, 0xB4, 0xD5, 0x2C, 0x64, 0x90, 0x3E, 0x38,
0x8B, 0x1D, 0x7D, 0x0E, 0xE8, 0x3C, 0xF0, 0xB9,
0xBB, 0xEF, 0x90, 0x49, 0x7E, 0x6A, 0x1C, 0xEC,
0x51, 0xB9, 0x13, 0x9B, 0x02, 0x02, 0x66, 0x59,
0xC6, 0xB1, 0x51, 0xBD, 0x17, 0x2E, 0x03, 0xEC,
0x93, 0x2B, 0xE9, 0x41, 0x28, 0x57, 0x8C, 0xB2,
0x42, 0x60, 0xDE, 0xB4, 0x18, 0x85, 0x81, 0x55,
0xAE, 0x09, 0xD9, 0xC4, 0x87, 0x57, 0xD1, 0x90,
0xB3, 0x18, 0xD2, 0x96, 0x18, 0x91, 0x2D, 0x38,
0x98, 0x0E, 0x68, 0x3C, 0xA6, 0x2E, 0xFE, 0x0D,
0xD0, 0x50, 0x18, 0x55, 0x75, 0xA9, 0x85, 0x40,
0xAB, 0x72, 0xE6, 0x7F, 0x9F, 0xDC, 0x30, 0xB9,
};
byte[] signature;
using (Stream stream = new PositionValueStream(10))
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA1024Params);
signature = rsa.SignData(stream, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
Assert.Equal(expectedSignature, signature);
}
[ConditionalFact(nameof(InvalidKeySizeDoesntThrow))]
public static void VerifySignature_SHA1_384()
{
byte[] signature =
{
0x79, 0xD9, 0x3C, 0xBF, 0x54, 0xFA, 0x55, 0x8C,
0x44, 0xC3, 0xC3, 0x83, 0x85, 0xBB, 0x78, 0x44,
0xCD, 0x0F, 0x5A, 0x8E, 0x71, 0xC9, 0xC2, 0x68,
0x68, 0x0A, 0x33, 0x93, 0x19, 0x37, 0x02, 0x06,
0xE2, 0xF7, 0x67, 0x97, 0x3C, 0x67, 0xB3, 0xF4,
0x11, 0xE0, 0x6E, 0xD2, 0x22, 0x75, 0xE7, 0x7C,
};
VerifySignature(signature, TestData.HelloBytes, "SHA1", TestData.RSA384Parameters);
}
[ConditionalFact(nameof(InvalidKeySizeDoesntThrow))]
public static void VerifySignature_SHA1_1032()
{
byte[] signature =
{
0x49, 0xBC, 0x1C, 0xBE, 0x72, 0xEF, 0x83, 0x6E,
0x2D, 0xFA, 0xE7, 0xFA, 0xEB, 0xBC, 0xF0, 0x16,
0xF7, 0x2C, 0x07, 0x6D, 0x9F, 0xA6, 0x68, 0x71,
0xDC, 0x78, 0x9C, 0xA3, 0x42, 0x9E, 0xBB, 0xF5,
0x72, 0xE0, 0xAB, 0x4B, 0x4B, 0x6A, 0xE7, 0x3C,
0xE2, 0xC8, 0x1F, 0xA2, 0x07, 0xED, 0xD3, 0x98,
0xE9, 0xDF, 0x9A, 0x7A, 0x86, 0xB8, 0x06, 0xED,
0x97, 0x46, 0xF9, 0x8A, 0xED, 0x53, 0x1D, 0x90,
0xC3, 0x57, 0x7E, 0x5A, 0xE4, 0x7C, 0xEC, 0xB9,
0x45, 0x95, 0xAB, 0xCC, 0xBA, 0x9B, 0x2C, 0x1A,
0x64, 0xC2, 0x2C, 0xA0, 0x36, 0x7C, 0x56, 0xF0,
0x78, 0x77, 0x0B, 0x27, 0xB8, 0x1C, 0xCA, 0x7D,
0xD4, 0x71, 0x37, 0xBF, 0xC6, 0x4C, 0x64, 0x76,
0xBC, 0x8A, 0x87, 0xA0, 0x81, 0xF9, 0x4A, 0x94,
0x7B, 0xAA, 0x80, 0x95, 0x47, 0x51, 0xF9, 0x02,
0xA3, 0x44, 0x5C, 0x56, 0x60, 0xFB, 0x94, 0xA8,
0x52,
};
VerifySignature(signature, TestData.HelloBytes, "SHA1", TestData.RSA1032Parameters);
}
[Fact]
public static void VerifySignature_SHA1_2048()
{
byte[] signature = new byte[]
{
0xA1, 0xFC, 0x74, 0x67, 0x49, 0x91, 0xF4, 0x28,
0xB0, 0xF6, 0x2B, 0xB8, 0x5E, 0x5F, 0x2E, 0x0F,
0xD8, 0xBC, 0xB4, 0x6E, 0x0A, 0xF7, 0x11, 0xC2,
0x65, 0x35, 0x5C, 0x1B, 0x1B, 0xC1, 0x20, 0xC0,
0x7D, 0x5B, 0x98, 0xAF, 0xB4, 0xC1, 0x6A, 0x25,
0x17, 0x47, 0x2C, 0x7F, 0x20, 0x2A, 0xDD, 0xF0,
0x5F, 0xDF, 0x6F, 0x5B, 0x7D, 0xEE, 0xAA, 0x4B,
0x9E, 0x8B, 0xA6, 0x0D, 0x81, 0x54, 0x93, 0x6E,
0xB2, 0x86, 0xC8, 0x14, 0x4F, 0xE7, 0x4A, 0xCC,
0xBE, 0x51, 0x2D, 0x0B, 0x9B, 0x46, 0xF1, 0x39,
0x80, 0x1D, 0xD0, 0x07, 0xBA, 0x46, 0x48, 0xFC,
0x7A, 0x50, 0x17, 0xC9, 0x7F, 0xEF, 0xDD, 0x42,
0xC5, 0x8B, 0x69, 0x38, 0x67, 0xAB, 0xBD, 0x39,
0xA6, 0xF4, 0x02, 0x34, 0x88, 0x56, 0x50, 0x05,
0xEA, 0x95, 0x24, 0x7D, 0x34, 0xD9, 0x9F, 0xB1,
0x05, 0x39, 0x6A, 0x42, 0x9E, 0x5E, 0xEB, 0xC9,
0x90, 0xC1, 0x93, 0x63, 0x29, 0x0C, 0xC5, 0xBC,
0xC8, 0x65, 0xB0, 0xFA, 0x63, 0x61, 0x77, 0xD9,
0x16, 0x59, 0xF0, 0xAD, 0x28, 0xC7, 0x98, 0x3C,
0x53, 0xF1, 0x6C, 0x91, 0x7E, 0x36, 0xC3, 0x3A,
0x23, 0x87, 0xA7, 0x3A, 0x18, 0x18, 0xBF, 0xD2,
0x3E, 0x51, 0x9E, 0xAB, 0x9E, 0x4C, 0x65, 0xBA,
0x43, 0xC0, 0x7E, 0xA2, 0x6B, 0xCF, 0x69, 0x7C,
0x8F, 0xAB, 0x22, 0x28, 0xD6, 0xF1, 0x65, 0x0B,
0x4A, 0x5B, 0x9B, 0x1F, 0xD4, 0xAA, 0xEF, 0x35,
0xA2, 0x42, 0x32, 0x00, 0x9F, 0x42, 0xBB, 0x19,
0x99, 0x49, 0x6D, 0xB8, 0x03, 0x3D, 0x35, 0x96,
0x0C, 0x57, 0xBB, 0x6B, 0x07, 0xA4, 0xB9, 0x7F,
0x9B, 0xEC, 0x78, 0x90, 0xB7, 0xC8, 0x5E, 0x7F,
0x3B, 0xAB, 0xC1, 0xB6, 0x0C, 0x84, 0x3C, 0xBC,
0x7F, 0x04, 0x79, 0xB7, 0x9C, 0xC0, 0xFE, 0xB0,
0xAE, 0xBD, 0xA5, 0x57, 0x2C, 0xEC, 0x3D, 0x0D,
};
VerifySignature(signature, TestData.HelloBytes, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void VerifySignature_SHA256_1024()
{
byte[] signature = new byte[]
{
0x5C, 0x2F, 0x00, 0xA9, 0xE4, 0x63, 0xD7, 0xB7,
0x94, 0x93, 0xCE, 0xA8, 0x7E, 0x71, 0xAE, 0x97,
0xC2, 0x6B, 0x37, 0x31, 0x5B, 0xB8, 0xE3, 0x30,
0xDF, 0x77, 0xF8, 0xBB, 0xB5, 0xBF, 0x41, 0x9F,
0x14, 0x6A, 0x61, 0x26, 0x2E, 0x80, 0xE5, 0xE6,
0x8A, 0xEA, 0xC7, 0x60, 0x0B, 0xAE, 0x2B, 0xB2,
0x18, 0xD8, 0x5D, 0xC8, 0x58, 0x86, 0x5E, 0x23,
0x62, 0x44, 0x72, 0xEA, 0x3B, 0xF7, 0x70, 0xC6,
0x4C, 0x2B, 0x54, 0x5B, 0xF4, 0x24, 0xA1, 0xE5,
0x63, 0xDD, 0x50, 0x3A, 0x29, 0x26, 0x84, 0x06,
0xEF, 0x13, 0xD0, 0xCE, 0xCC, 0xA1, 0x05, 0xB4,
0x72, 0x81, 0x0A, 0x2E, 0x33, 0xF6, 0x2F, 0xD1,
0xEA, 0x41, 0xB0, 0xB3, 0x93, 0x4C, 0xF3, 0x0F,
0x6F, 0x21, 0x3E, 0xD7, 0x5F, 0x57, 0x2E, 0xC7,
0x5F, 0xF5, 0x28, 0x89, 0xB8, 0x07, 0xDB, 0xAC,
0x70, 0x95, 0x25, 0x49, 0x8A, 0x1A, 0xD7, 0xFC,
};
VerifySignature(signature, TestData.HelloBytes, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void VerifySignature_SHA256_2048()
{
byte[] signature = new byte[]
{
0x2C, 0x74, 0x98, 0x23, 0xF4, 0x38, 0x7F, 0x49,
0x82, 0xB6, 0x55, 0xCF, 0xC3, 0x25, 0x4F, 0xE3,
0x4B, 0x17, 0xE7, 0xED, 0xEA, 0x58, 0x1E, 0x63,
0x57, 0x58, 0xCD, 0xB5, 0x06, 0xD6, 0xCA, 0x13,
0x28, 0x81, 0xE6, 0xE0, 0x8B, 0xDC, 0xC6, 0x05,
0x35, 0x35, 0x40, 0x73, 0x76, 0x61, 0x67, 0x42,
0x94, 0xF7, 0x54, 0x0E, 0xB6, 0x30, 0x9A, 0x70,
0xC3, 0x06, 0xC1, 0x59, 0xA7, 0x89, 0x66, 0x38,
0x02, 0x5C, 0x52, 0x02, 0x17, 0x4E, 0xEC, 0x21,
0xE9, 0x24, 0x85, 0xCB, 0x56, 0x42, 0xAB, 0x21,
0x3A, 0x19, 0xC3, 0x95, 0x06, 0xBA, 0xDB, 0xD9,
0x89, 0x7C, 0xB9, 0xEC, 0x1D, 0x8B, 0x5A, 0x64,
0x87, 0xAF, 0x36, 0x71, 0xAC, 0x0A, 0x2B, 0xC7,
0x7D, 0x2F, 0x44, 0xAA, 0xB4, 0x1C, 0xBE, 0x0B,
0x0A, 0x4E, 0xEA, 0xF8, 0x75, 0x40, 0xD9, 0x4A,
0x82, 0x1C, 0x82, 0x81, 0x97, 0xC2, 0xF1, 0xC8,
0xA7, 0x4B, 0x45, 0x9A, 0x66, 0x8E, 0x35, 0x2E,
0xE5, 0x1A, 0x2B, 0x0B, 0xF9, 0xAB, 0xC4, 0x2A,
0xE0, 0x47, 0x72, 0x2A, 0xC2, 0xD8, 0xC6, 0xFD,
0x91, 0x30, 0xD2, 0x45, 0xA4, 0x7F, 0x0F, 0x39,
0x80, 0xBC, 0xA9, 0xBD, 0xEC, 0xA5, 0x03, 0x6F,
0x01, 0xF6, 0x19, 0xD5, 0x2B, 0xD9, 0x40, 0xCD,
0x7F, 0xEF, 0x0F, 0x9D, 0x93, 0x02, 0xCD, 0x89,
0xB8, 0x2C, 0xC7, 0xD6, 0xFD, 0xAA, 0x12, 0x6E,
0x4C, 0x06, 0x35, 0x08, 0x61, 0x79, 0x27, 0xE1,
0xEA, 0x46, 0x75, 0x08, 0x5B, 0x51, 0xA1, 0x80,
0x78, 0x02, 0xEA, 0x3E, 0xEC, 0x29, 0xD2, 0x8B,
0xC5, 0x9E, 0x7D, 0xA4, 0x85, 0x8D, 0xAD, 0x73,
0x39, 0x17, 0x64, 0x82, 0x46, 0x4A, 0xA4, 0x34,
0xF0, 0xCC, 0x2F, 0x9F, 0x55, 0xA4, 0xEA, 0xEC,
0xC9, 0xA7, 0xAB, 0xBA, 0xA8, 0x84, 0x14, 0x62,
0x6B, 0x9B, 0x97, 0x2D, 0x8C, 0xB2, 0x1C, 0x16,
};
VerifySignature(signature, TestData.HelloBytes, "SHA256", TestData.RSA2048Params);
}
[Fact]
public static void SignAndVerify_SHA1_1024()
{
SignAndVerify(TestData.HelloBytes, "SHA1", TestData.RSA1024Params);
}
[Fact]
public static void SignAndVerify_SHA1_2048()
{
SignAndVerify(TestData.HelloBytes, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void SignAndVerify_SHA256_1024()
{
SignAndVerify(TestData.HelloBytes, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void NegativeVerify_WrongAlgorithm()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA2048Params);
byte[] signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
bool signatureMatched = rsa.VerifyData(TestData.HelloBytes, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
Assert.False(signatureMatched);
}
}
[Fact]
public static void NegativeVerify_WrongSignature()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA2048Params);
byte[] signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
// Invalidate the signature.
signature[0] = unchecked((byte)~signature[0]);
bool signatureMatched = rsa.VerifyData(TestData.HelloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.False(signatureMatched);
}
}
[Fact]
public static void NegativeVerify_TamperedData()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA2048Params);
byte[] signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
bool signatureMatched = rsa.VerifyData(Array.Empty<byte>(), signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.False(signatureMatched);
}
}
[ConditionalFact(nameof(BadKeyFormatDoesntThrow))]
public static void NegativeVerify_BadKeysize()
{
byte[] signature;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA2048Params);
signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
}
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA1024Params);
bool signatureMatched = rsa.VerifyData(TestData.HelloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.False(signatureMatched);
}
}
[Fact]
public static void ExpectedHashSignature_SHA1_2048()
{
byte[] expectedHashSignature = new byte[]
{
0xA1, 0xFC, 0x74, 0x67, 0x49, 0x91, 0xF4, 0x28,
0xB0, 0xF6, 0x2B, 0xB8, 0x5E, 0x5F, 0x2E, 0x0F,
0xD8, 0xBC, 0xB4, 0x6E, 0x0A, 0xF7, 0x11, 0xC2,
0x65, 0x35, 0x5C, 0x1B, 0x1B, 0xC1, 0x20, 0xC0,
0x7D, 0x5B, 0x98, 0xAF, 0xB4, 0xC1, 0x6A, 0x25,
0x17, 0x47, 0x2C, 0x7F, 0x20, 0x2A, 0xDD, 0xF0,
0x5F, 0xDF, 0x6F, 0x5B, 0x7D, 0xEE, 0xAA, 0x4B,
0x9E, 0x8B, 0xA6, 0x0D, 0x81, 0x54, 0x93, 0x6E,
0xB2, 0x86, 0xC8, 0x14, 0x4F, 0xE7, 0x4A, 0xCC,
0xBE, 0x51, 0x2D, 0x0B, 0x9B, 0x46, 0xF1, 0x39,
0x80, 0x1D, 0xD0, 0x07, 0xBA, 0x46, 0x48, 0xFC,
0x7A, 0x50, 0x17, 0xC9, 0x7F, 0xEF, 0xDD, 0x42,
0xC5, 0x8B, 0x69, 0x38, 0x67, 0xAB, 0xBD, 0x39,
0xA6, 0xF4, 0x02, 0x34, 0x88, 0x56, 0x50, 0x05,
0xEA, 0x95, 0x24, 0x7D, 0x34, 0xD9, 0x9F, 0xB1,
0x05, 0x39, 0x6A, 0x42, 0x9E, 0x5E, 0xEB, 0xC9,
0x90, 0xC1, 0x93, 0x63, 0x29, 0x0C, 0xC5, 0xBC,
0xC8, 0x65, 0xB0, 0xFA, 0x63, 0x61, 0x77, 0xD9,
0x16, 0x59, 0xF0, 0xAD, 0x28, 0xC7, 0x98, 0x3C,
0x53, 0xF1, 0x6C, 0x91, 0x7E, 0x36, 0xC3, 0x3A,
0x23, 0x87, 0xA7, 0x3A, 0x18, 0x18, 0xBF, 0xD2,
0x3E, 0x51, 0x9E, 0xAB, 0x9E, 0x4C, 0x65, 0xBA,
0x43, 0xC0, 0x7E, 0xA2, 0x6B, 0xCF, 0x69, 0x7C,
0x8F, 0xAB, 0x22, 0x28, 0xD6, 0xF1, 0x65, 0x0B,
0x4A, 0x5B, 0x9B, 0x1F, 0xD4, 0xAA, 0xEF, 0x35,
0xA2, 0x42, 0x32, 0x00, 0x9F, 0x42, 0xBB, 0x19,
0x99, 0x49, 0x6D, 0xB8, 0x03, 0x3D, 0x35, 0x96,
0x0C, 0x57, 0xBB, 0x6B, 0x07, 0xA4, 0xB9, 0x7F,
0x9B, 0xEC, 0x78, 0x90, 0xB7, 0xC8, 0x5E, 0x7F,
0x3B, 0xAB, 0xC1, 0xB6, 0x0C, 0x84, 0x3C, 0xBC,
0x7F, 0x04, 0x79, 0xB7, 0x9C, 0xC0, 0xFE, 0xB0,
0xAE, 0xBD, 0xA5, 0x57, 0x2C, 0xEC, 0x3D, 0x0D,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA1.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
ExpectHashSignature(expectedHashSignature, dataHash, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void ExpectedHashSignature_SHA256_1024()
{
byte[] expectedHashSignature = new byte[]
{
0x5C, 0x2F, 0x00, 0xA9, 0xE4, 0x63, 0xD7, 0xB7,
0x94, 0x93, 0xCE, 0xA8, 0x7E, 0x71, 0xAE, 0x97,
0xC2, 0x6B, 0x37, 0x31, 0x5B, 0xB8, 0xE3, 0x30,
0xDF, 0x77, 0xF8, 0xBB, 0xB5, 0xBF, 0x41, 0x9F,
0x14, 0x6A, 0x61, 0x26, 0x2E, 0x80, 0xE5, 0xE6,
0x8A, 0xEA, 0xC7, 0x60, 0x0B, 0xAE, 0x2B, 0xB2,
0x18, 0xD8, 0x5D, 0xC8, 0x58, 0x86, 0x5E, 0x23,
0x62, 0x44, 0x72, 0xEA, 0x3B, 0xF7, 0x70, 0xC6,
0x4C, 0x2B, 0x54, 0x5B, 0xF4, 0x24, 0xA1, 0xE5,
0x63, 0xDD, 0x50, 0x3A, 0x29, 0x26, 0x84, 0x06,
0xEF, 0x13, 0xD0, 0xCE, 0xCC, 0xA1, 0x05, 0xB4,
0x72, 0x81, 0x0A, 0x2E, 0x33, 0xF6, 0x2F, 0xD1,
0xEA, 0x41, 0xB0, 0xB3, 0x93, 0x4C, 0xF3, 0x0F,
0x6F, 0x21, 0x3E, 0xD7, 0x5F, 0x57, 0x2E, 0xC7,
0x5F, 0xF5, 0x28, 0x89, 0xB8, 0x07, 0xDB, 0xAC,
0x70, 0x95, 0x25, 0x49, 0x8A, 0x1A, 0xD7, 0xFC,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA256.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
ExpectHashSignature(expectedHashSignature, dataHash, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void ExpectedHashSignature_SHA256_2048()
{
byte[] expectedHashSignature = new byte[]
{
0x2C, 0x74, 0x98, 0x23, 0xF4, 0x38, 0x7F, 0x49,
0x82, 0xB6, 0x55, 0xCF, 0xC3, 0x25, 0x4F, 0xE3,
0x4B, 0x17, 0xE7, 0xED, 0xEA, 0x58, 0x1E, 0x63,
0x57, 0x58, 0xCD, 0xB5, 0x06, 0xD6, 0xCA, 0x13,
0x28, 0x81, 0xE6, 0xE0, 0x8B, 0xDC, 0xC6, 0x05,
0x35, 0x35, 0x40, 0x73, 0x76, 0x61, 0x67, 0x42,
0x94, 0xF7, 0x54, 0x0E, 0xB6, 0x30, 0x9A, 0x70,
0xC3, 0x06, 0xC1, 0x59, 0xA7, 0x89, 0x66, 0x38,
0x02, 0x5C, 0x52, 0x02, 0x17, 0x4E, 0xEC, 0x21,
0xE9, 0x24, 0x85, 0xCB, 0x56, 0x42, 0xAB, 0x21,
0x3A, 0x19, 0xC3, 0x95, 0x06, 0xBA, 0xDB, 0xD9,
0x89, 0x7C, 0xB9, 0xEC, 0x1D, 0x8B, 0x5A, 0x64,
0x87, 0xAF, 0x36, 0x71, 0xAC, 0x0A, 0x2B, 0xC7,
0x7D, 0x2F, 0x44, 0xAA, 0xB4, 0x1C, 0xBE, 0x0B,
0x0A, 0x4E, 0xEA, 0xF8, 0x75, 0x40, 0xD9, 0x4A,
0x82, 0x1C, 0x82, 0x81, 0x97, 0xC2, 0xF1, 0xC8,
0xA7, 0x4B, 0x45, 0x9A, 0x66, 0x8E, 0x35, 0x2E,
0xE5, 0x1A, 0x2B, 0x0B, 0xF9, 0xAB, 0xC4, 0x2A,
0xE0, 0x47, 0x72, 0x2A, 0xC2, 0xD8, 0xC6, 0xFD,
0x91, 0x30, 0xD2, 0x45, 0xA4, 0x7F, 0x0F, 0x39,
0x80, 0xBC, 0xA9, 0xBD, 0xEC, 0xA5, 0x03, 0x6F,
0x01, 0xF6, 0x19, 0xD5, 0x2B, 0xD9, 0x40, 0xCD,
0x7F, 0xEF, 0x0F, 0x9D, 0x93, 0x02, 0xCD, 0x89,
0xB8, 0x2C, 0xC7, 0xD6, 0xFD, 0xAA, 0x12, 0x6E,
0x4C, 0x06, 0x35, 0x08, 0x61, 0x79, 0x27, 0xE1,
0xEA, 0x46, 0x75, 0x08, 0x5B, 0x51, 0xA1, 0x80,
0x78, 0x02, 0xEA, 0x3E, 0xEC, 0x29, 0xD2, 0x8B,
0xC5, 0x9E, 0x7D, 0xA4, 0x85, 0x8D, 0xAD, 0x73,
0x39, 0x17, 0x64, 0x82, 0x46, 0x4A, 0xA4, 0x34,
0xF0, 0xCC, 0x2F, 0x9F, 0x55, 0xA4, 0xEA, 0xEC,
0xC9, 0xA7, 0xAB, 0xBA, 0xA8, 0x84, 0x14, 0x62,
0x6B, 0x9B, 0x97, 0x2D, 0x8C, 0xB2, 0x1C, 0x16,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA256.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
ExpectHashSignature(expectedHashSignature, dataHash, "SHA256", TestData.RSA2048Params);
}
[Fact]
public static void VerifyHashSignature_SHA1_2048()
{
byte[] hashSignature = new byte[]
{
0xA1, 0xFC, 0x74, 0x67, 0x49, 0x91, 0xF4, 0x28,
0xB0, 0xF6, 0x2B, 0xB8, 0x5E, 0x5F, 0x2E, 0x0F,
0xD8, 0xBC, 0xB4, 0x6E, 0x0A, 0xF7, 0x11, 0xC2,
0x65, 0x35, 0x5C, 0x1B, 0x1B, 0xC1, 0x20, 0xC0,
0x7D, 0x5B, 0x98, 0xAF, 0xB4, 0xC1, 0x6A, 0x25,
0x17, 0x47, 0x2C, 0x7F, 0x20, 0x2A, 0xDD, 0xF0,
0x5F, 0xDF, 0x6F, 0x5B, 0x7D, 0xEE, 0xAA, 0x4B,
0x9E, 0x8B, 0xA6, 0x0D, 0x81, 0x54, 0x93, 0x6E,
0xB2, 0x86, 0xC8, 0x14, 0x4F, 0xE7, 0x4A, 0xCC,
0xBE, 0x51, 0x2D, 0x0B, 0x9B, 0x46, 0xF1, 0x39,
0x80, 0x1D, 0xD0, 0x07, 0xBA, 0x46, 0x48, 0xFC,
0x7A, 0x50, 0x17, 0xC9, 0x7F, 0xEF, 0xDD, 0x42,
0xC5, 0x8B, 0x69, 0x38, 0x67, 0xAB, 0xBD, 0x39,
0xA6, 0xF4, 0x02, 0x34, 0x88, 0x56, 0x50, 0x05,
0xEA, 0x95, 0x24, 0x7D, 0x34, 0xD9, 0x9F, 0xB1,
0x05, 0x39, 0x6A, 0x42, 0x9E, 0x5E, 0xEB, 0xC9,
0x90, 0xC1, 0x93, 0x63, 0x29, 0x0C, 0xC5, 0xBC,
0xC8, 0x65, 0xB0, 0xFA, 0x63, 0x61, 0x77, 0xD9,
0x16, 0x59, 0xF0, 0xAD, 0x28, 0xC7, 0x98, 0x3C,
0x53, 0xF1, 0x6C, 0x91, 0x7E, 0x36, 0xC3, 0x3A,
0x23, 0x87, 0xA7, 0x3A, 0x18, 0x18, 0xBF, 0xD2,
0x3E, 0x51, 0x9E, 0xAB, 0x9E, 0x4C, 0x65, 0xBA,
0x43, 0xC0, 0x7E, 0xA2, 0x6B, 0xCF, 0x69, 0x7C,
0x8F, 0xAB, 0x22, 0x28, 0xD6, 0xF1, 0x65, 0x0B,
0x4A, 0x5B, 0x9B, 0x1F, 0xD4, 0xAA, 0xEF, 0x35,
0xA2, 0x42, 0x32, 0x00, 0x9F, 0x42, 0xBB, 0x19,
0x99, 0x49, 0x6D, 0xB8, 0x03, 0x3D, 0x35, 0x96,
0x0C, 0x57, 0xBB, 0x6B, 0x07, 0xA4, 0xB9, 0x7F,
0x9B, 0xEC, 0x78, 0x90, 0xB7, 0xC8, 0x5E, 0x7F,
0x3B, 0xAB, 0xC1, 0xB6, 0x0C, 0x84, 0x3C, 0xBC,
0x7F, 0x04, 0x79, 0xB7, 0x9C, 0xC0, 0xFE, 0xB0,
0xAE, 0xBD, 0xA5, 0x57, 0x2C, 0xEC, 0x3D, 0x0D,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA1.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
VerifyHashSignature(hashSignature, dataHash, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void VerifyHashSignature_SHA256_1024()
{
byte[] hashSignature = new byte[]
{
0x5C, 0x2F, 0x00, 0xA9, 0xE4, 0x63, 0xD7, 0xB7,
0x94, 0x93, 0xCE, 0xA8, 0x7E, 0x71, 0xAE, 0x97,
0xC2, 0x6B, 0x37, 0x31, 0x5B, 0xB8, 0xE3, 0x30,
0xDF, 0x77, 0xF8, 0xBB, 0xB5, 0xBF, 0x41, 0x9F,
0x14, 0x6A, 0x61, 0x26, 0x2E, 0x80, 0xE5, 0xE6,
0x8A, 0xEA, 0xC7, 0x60, 0x0B, 0xAE, 0x2B, 0xB2,
0x18, 0xD8, 0x5D, 0xC8, 0x58, 0x86, 0x5E, 0x23,
0x62, 0x44, 0x72, 0xEA, 0x3B, 0xF7, 0x70, 0xC6,
0x4C, 0x2B, 0x54, 0x5B, 0xF4, 0x24, 0xA1, 0xE5,
0x63, 0xDD, 0x50, 0x3A, 0x29, 0x26, 0x84, 0x06,
0xEF, 0x13, 0xD0, 0xCE, 0xCC, 0xA1, 0x05, 0xB4,
0x72, 0x81, 0x0A, 0x2E, 0x33, 0xF6, 0x2F, 0xD1,
0xEA, 0x41, 0xB0, 0xB3, 0x93, 0x4C, 0xF3, 0x0F,
0x6F, 0x21, 0x3E, 0xD7, 0x5F, 0x57, 0x2E, 0xC7,
0x5F, 0xF5, 0x28, 0x89, 0xB8, 0x07, 0xDB, 0xAC,
0x70, 0x95, 0x25, 0x49, 0x8A, 0x1A, 0xD7, 0xFC,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA256.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
VerifyHashSignature(hashSignature, dataHash, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void VerifyHashSignature_SHA256_2048()
{
byte[] hashSignature = new byte[]
{
0x2C, 0x74, 0x98, 0x23, 0xF4, 0x38, 0x7F, 0x49,
0x82, 0xB6, 0x55, 0xCF, 0xC3, 0x25, 0x4F, 0xE3,
0x4B, 0x17, 0xE7, 0xED, 0xEA, 0x58, 0x1E, 0x63,
0x57, 0x58, 0xCD, 0xB5, 0x06, 0xD6, 0xCA, 0x13,
0x28, 0x81, 0xE6, 0xE0, 0x8B, 0xDC, 0xC6, 0x05,
0x35, 0x35, 0x40, 0x73, 0x76, 0x61, 0x67, 0x42,
0x94, 0xF7, 0x54, 0x0E, 0xB6, 0x30, 0x9A, 0x70,
0xC3, 0x06, 0xC1, 0x59, 0xA7, 0x89, 0x66, 0x38,
0x02, 0x5C, 0x52, 0x02, 0x17, 0x4E, 0xEC, 0x21,
0xE9, 0x24, 0x85, 0xCB, 0x56, 0x42, 0xAB, 0x21,
0x3A, 0x19, 0xC3, 0x95, 0x06, 0xBA, 0xDB, 0xD9,
0x89, 0x7C, 0xB9, 0xEC, 0x1D, 0x8B, 0x5A, 0x64,
0x87, 0xAF, 0x36, 0x71, 0xAC, 0x0A, 0x2B, 0xC7,
0x7D, 0x2F, 0x44, 0xAA, 0xB4, 0x1C, 0xBE, 0x0B,
0x0A, 0x4E, 0xEA, 0xF8, 0x75, 0x40, 0xD9, 0x4A,
0x82, 0x1C, 0x82, 0x81, 0x97, 0xC2, 0xF1, 0xC8,
0xA7, 0x4B, 0x45, 0x9A, 0x66, 0x8E, 0x35, 0x2E,
0xE5, 0x1A, 0x2B, 0x0B, 0xF9, 0xAB, 0xC4, 0x2A,
0xE0, 0x47, 0x72, 0x2A, 0xC2, 0xD8, 0xC6, 0xFD,
0x91, 0x30, 0xD2, 0x45, 0xA4, 0x7F, 0x0F, 0x39,
0x80, 0xBC, 0xA9, 0xBD, 0xEC, 0xA5, 0x03, 0x6F,
0x01, 0xF6, 0x19, 0xD5, 0x2B, 0xD9, 0x40, 0xCD,
0x7F, 0xEF, 0x0F, 0x9D, 0x93, 0x02, 0xCD, 0x89,
0xB8, 0x2C, 0xC7, 0xD6, 0xFD, 0xAA, 0x12, 0x6E,
0x4C, 0x06, 0x35, 0x08, 0x61, 0x79, 0x27, 0xE1,
0xEA, 0x46, 0x75, 0x08, 0x5B, 0x51, 0xA1, 0x80,
0x78, 0x02, 0xEA, 0x3E, 0xEC, 0x29, 0xD2, 0x8B,
0xC5, 0x9E, 0x7D, 0xA4, 0x85, 0x8D, 0xAD, 0x73,
0x39, 0x17, 0x64, 0x82, 0x46, 0x4A, 0xA4, 0x34,
0xF0, 0xCC, 0x2F, 0x9F, 0x55, 0xA4, 0xEA, 0xEC,
0xC9, 0xA7, 0xAB, 0xBA, 0xA8, 0x84, 0x14, 0x62,
0x6B, 0x9B, 0x97, 0x2D, 0x8C, 0xB2, 0x1C, 0x16,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA256.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
VerifyHashSignature(hashSignature, dataHash, "SHA256", TestData.RSA2048Params);
}
private static void ExpectSignature(
byte[] expectedSignature,
byte[] data,
string hashAlgorithmName,
RSAParameters rsaParameters)
{
// RSA signatures use PKCS 1.5 EMSA encoding (encoding method, signature algorithm).
// EMSA specifies a fixed filler type of { 0x01, 0xFF, 0xFF ... 0xFF, 0x00 } whose length
// is as long as it needs to be to match the block size. Since the filler is deterministic,
// the signature is deterministic, so we can safely verify it here.
byte[] signature;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(rsaParameters);
signature = rsa.SignData(data, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
}
Assert.Equal(expectedSignature, signature);
}
private static void ExpectHashSignature(
byte[] expectedSignature,
byte[] dataHash,
string hashAlgorithmName,
RSAParameters rsaParameters)
{
// RSA signatures use PKCS 1.5 EMSA encoding (encoding method, signature algorithm).
// EMSA specifies a fixed filler type of { 0x01, 0xFF, 0xFF ... 0xFF, 0x00 } whose length
// is as long as it needs to be to match the block size. Since the filler is deterministic,
// the signature is deterministic, so we can safely verify it here.
byte[] signature;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(rsaParameters);
signature = rsa.SignHash(dataHash, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
}
Assert.Equal(expectedSignature, signature);
}
private static void VerifySignature(
byte[] signature,
byte[] data,
string hashAlgorithmName,
RSAParameters rsaParameters)
{
RSAParameters publicOnly = new RSAParameters
{
Modulus = rsaParameters.Modulus,
Exponent = rsaParameters.Exponent,
};
bool signatureMatched;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(publicOnly);
signatureMatched = rsa.VerifyData(data, signature, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
}
Assert.True(signatureMatched);
}
private static void VerifyHashSignature(
byte[] signature,
byte[] dataHash,
string hashAlgorithmName,
RSAParameters rsaParameters)
{
RSAParameters publicOnly = new RSAParameters
{
Modulus = rsaParameters.Modulus,
Exponent = rsaParameters.Exponent,
};
bool signatureMatched;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(publicOnly);
signatureMatched = rsa.VerifyHash(dataHash, signature, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
}
Assert.True(signatureMatched);
}
private static void SignAndVerify(byte[] data, string hashAlgorithmName, RSAParameters rsaParameters)
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(rsaParameters);
byte[] signature = rsa.SignData(data, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
bool signatureMatched = rsa.VerifyData(data, signature, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
Assert.True(signatureMatched);
}
}
}
}
| |
//
// MethodReference.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// 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.Text;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public class MethodReference : MemberReference, IMethodSignature, IGenericParameterProvider, IGenericContext {
internal ParameterDefinitionCollection parameters;
MethodReturnType return_type;
bool has_this;
bool explicit_this;
MethodCallingConvention calling_convention;
internal Collection<GenericParameter> generic_parameters;
public virtual bool HasThis {
get { return has_this; }
set { has_this = value; }
}
public virtual bool ExplicitThis {
get { return explicit_this; }
set { explicit_this = value; }
}
public virtual MethodCallingConvention CallingConvention {
get { return calling_convention; }
set { calling_convention = value; }
}
public virtual bool HasParameters {
get { return !parameters.IsNullOrEmpty (); }
}
public virtual Collection<ParameterDefinition> Parameters {
get {
if (parameters == null)
parameters = new ParameterDefinitionCollection (this);
return parameters;
}
}
IGenericParameterProvider IGenericContext.Type {
get {
var declaring_type = this.DeclaringType;
var instance = declaring_type as GenericInstanceType;
if (instance != null)
return instance.ElementType;
return declaring_type;
}
}
IGenericParameterProvider IGenericContext.Method {
get { return this; }
}
GenericParameterType IGenericParameterProvider.GenericParameterType {
get { return GenericParameterType.Method; }
}
public virtual bool HasGenericParameters {
get { return !generic_parameters.IsNullOrEmpty (); }
}
public virtual Collection<GenericParameter> GenericParameters {
get {
if (generic_parameters != null)
return generic_parameters;
return generic_parameters = new Collection<GenericParameter> ();
}
}
public TypeReference ReturnType {
get {
var return_type = MethodReturnType;
return return_type != null ? return_type.ReturnType : null;
}
set {
var return_type = MethodReturnType;
if (return_type != null)
return_type.ReturnType = value;
}
}
public virtual MethodReturnType MethodReturnType {
get { return return_type; }
set { return_type = value; }
}
public override string FullName {
get {
var builder = new StringBuilder ();
builder.Append (ReturnType.FullName)
.Append (" ")
.Append (MemberFullName ());
this.MethodSignatureFullName (builder);
return builder.ToString ();
}
}
public virtual bool IsGenericInstance {
get { return false; }
}
internal override bool ContainsGenericParameter {
get {
if (this.ReturnType.ContainsGenericParameter || base.ContainsGenericParameter)
return true;
var parameters = this.Parameters;
for (int i = 0; i < parameters.Count; i++)
if (parameters [i].ParameterType.ContainsGenericParameter)
return true;
return false;
}
}
internal MethodReference ()
{
this.return_type = new MethodReturnType (this);
this.token = new MetadataToken (TokenType.MemberRef);
}
public MethodReference (string name, TypeReference returnType)
: base (name)
{
if (returnType == null)
throw new ArgumentNullException ("returnType");
this.return_type = new MethodReturnType (this);
this.return_type.ReturnType = returnType;
this.token = new MetadataToken (TokenType.MemberRef);
}
public MethodReference (string name, TypeReference returnType, TypeReference declaringType)
: this (name, returnType)
{
if (declaringType == null)
throw new ArgumentNullException ("declaringType");
this.DeclaringType = declaringType;
}
public virtual MethodReference GetElementMethod ()
{
return this;
}
public virtual MethodDefinition Resolve ()
{
var module = this.Module;
if (module == null)
throw new NotSupportedException ();
return module.Resolve (this);
}
}
static partial class Mixin {
public static bool IsVarArg (this IMethodSignature self)
{
return (self.CallingConvention & MethodCallingConvention.VarArg) != 0;
}
public static int GetSentinelPosition (this IMethodSignature self)
{
if (!self.HasParameters)
return -1;
var parameters = self.Parameters;
for (int i = 0; i < parameters.Count; i++)
if (parameters [i].ParameterType.IsSentinel)
return i;
return -1;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Data.Tables.Models;
using Azure.Data.Tables.Sas;
namespace Azure.Data.Tables
{
/// <summary>
/// The <see cref="TableServiceClient"/> provides synchronous and asynchronous methods to perform table level operations with Azure Tables hosted in either Azure storage accounts or Azure Cosmos DB table API.
/// </summary>
public class TableServiceClient
{
private readonly ClientDiagnostics _diagnostics;
private readonly TableRestClient _tableOperations;
private readonly ServiceRestClient _serviceOperations;
private readonly ServiceRestClient _secondaryServiceOperations;
private readonly OdataMetadataFormat _format = OdataMetadataFormat.ApplicationJsonOdataMinimalmetadata;
private readonly string _version;
internal readonly bool _isCosmosEndpoint;
private readonly QueryOptions _defaultQueryOptions = new QueryOptions() { Format = OdataMetadataFormat.ApplicationJsonOdataMinimalmetadata };
private string _accountName;
private readonly Uri _endpoint;
/// <summary>
/// The name of the table account with which this client instance will interact.
/// </summary>
public virtual string AccountName
{
get
{
if (_accountName == null)
{
var builder = new TableUriBuilder(_endpoint);
_accountName = builder.AccountName;
}
return _accountName;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified <see cref="Uri" /> containing a shared access signature (SAS)
/// token credential. See <see cref="TableClient.GetSasBuilder(TableSasPermissions, DateTimeOffset)" /> for creating a SAS token.
/// </summary>
/// <param name="endpoint">
/// A <see cref="Uri"/> referencing the table service account.
/// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/".
/// </param>
/// <param name="credential">The shared access signature credential used to sign requests.</param>
public TableServiceClient(Uri endpoint, AzureSasCredential credential)
: this(endpoint, credential, options: null)
{
Argument.AssertNotNull(credential, nameof(credential));
}
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified connection string.
/// </summary>
/// <param name="connectionString">
/// A connection string includes the authentication information
/// required for your application to access data in an Azure Storage
/// account at runtime.
///
/// For more information,
/// <see href="https://docs.microsoft.com/azure/storage/common/storage-configure-connection-string">
/// Configure Azure Storage connection strings</see>.
/// </param>
public TableServiceClient(string connectionString)
: this(connectionString, options: null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified <see cref="Uri" /> containing a shared access signature (SAS)
/// token credential. See <see cref="TableClient.GetSasBuilder(TableSasPermissions, DateTimeOffset)" /> for creating a SAS token.
/// </summary>
/// <param name="endpoint">
/// A <see cref="Uri"/> referencing the table service account.
/// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/".
/// </param>
/// <param name="credential">The shared access signature credential used to sign requests.</param>
/// <param name="options">
/// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request.
/// </param>
public TableServiceClient(Uri endpoint, AzureSasCredential credential, TableClientOptions options = null)
: this(endpoint, default, credential, options)
{
if (endpoint.Scheme != "https")
{
throw new ArgumentException("Cannot use TokenCredential without HTTPS.", nameof(endpoint));
}
Argument.AssertNotNull(credential, nameof(credential));
}
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified table service <see cref="Uri" /> and <see cref="TableSharedKeyCredential" />.
/// </summary>
/// <param name="endpoint">
/// A <see cref="Uri"/> referencing the table service account.
/// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/".
/// </param>
/// <param name="credential">The shared key credential used to sign requests.</param>
public TableServiceClient(Uri endpoint, TableSharedKeyCredential credential)
: this(endpoint, new TableSharedKeyPipelinePolicy(credential), default, null)
{
Argument.AssertNotNull(credential, nameof(credential));
}
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified table service <see cref="Uri" /> and <see cref="TableSharedKeyCredential" />.
/// </summary>
/// <param name="endpoint">
/// A <see cref="Uri"/> referencing the table service account.
/// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/".
/// </param>
/// <param name="credential">The shared key credential used to sign requests.</param>
/// <param name="options">
/// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request.
/// </param>
public TableServiceClient(Uri endpoint, TableSharedKeyCredential credential, TableClientOptions options = null)
: this(endpoint, new TableSharedKeyPipelinePolicy(credential), default, options)
{
Argument.AssertNotNull(credential, nameof(credential));
}
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified connection string.
/// </summary>
/// <param name="connectionString">
/// A connection string includes the authentication information
/// required for your application to access data in an Azure Storage
/// account at runtime.
///
/// For more information,
/// <see href="https://docs.microsoft.com/azure/storage/common/storage-configure-connection-string">
/// Configure Azure Storage connection strings</see>.
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request.
/// </param>
public TableServiceClient(string connectionString, TableClientOptions options = null)
{
Argument.AssertNotNull(connectionString, nameof(connectionString));
TableConnectionString connString = TableConnectionString.Parse(connectionString);
_accountName = connString._accountName;
options ??= new TableClientOptions();
var endpointString = connString.TableStorageUri.PrimaryUri.AbsoluteUri;
var secondaryEndpoint = connString.TableStorageUri.SecondaryUri?.AbsoluteUri;
_isCosmosEndpoint = TableServiceClient.IsPremiumEndpoint(connString.TableStorageUri.PrimaryUri);
var perCallPolicies = _isCosmosEndpoint ? new[] { new CosmosPatchTransformPolicy() } : Array.Empty<HttpPipelinePolicy>();
TableSharedKeyPipelinePolicy policy = connString.Credentials switch
{
TableSharedKeyCredential credential => new TableSharedKeyPipelinePolicy(credential),
_ => default
};
HttpPipeline pipeline = HttpPipelineBuilder.Build(options, perCallPolicies: perCallPolicies, perRetryPolicies: new[] { policy }, new ResponseClassifier());
_version = options.VersionString;
_diagnostics = new TablesClientDiagnostics(options);
_tableOperations = new TableRestClient(_diagnostics, pipeline, endpointString, _version);
_serviceOperations = new ServiceRestClient(_diagnostics, pipeline, endpointString, _version);
_secondaryServiceOperations = new ServiceRestClient(_diagnostics, pipeline, secondaryEndpoint, _version);
}
internal TableServiceClient(Uri endpoint, TableSharedKeyPipelinePolicy policy, AzureSasCredential sasCredential, TableClientOptions options)
{
Argument.AssertNotNull(endpoint, nameof(endpoint));
_endpoint = endpoint;
options ??= new TableClientOptions();
_isCosmosEndpoint = IsPremiumEndpoint(endpoint);
var perCallPolicies = _isCosmosEndpoint ? new[] { new CosmosPatchTransformPolicy() } : Array.Empty<HttpPipelinePolicy>();
var endpointString = endpoint.AbsoluteUri;
string secondaryEndpoint = TableConnectionString.GetSecondaryUriFromPrimary(endpoint)?.AbsoluteUri;
HttpPipeline pipeline = sasCredential switch
{
null => HttpPipelineBuilder.Build(options, perCallPolicies: perCallPolicies, perRetryPolicies: new[] { policy }, new ResponseClassifier()),
_ => HttpPipelineBuilder.Build(options, perCallPolicies: perCallPolicies, perRetryPolicies: new HttpPipelinePolicy[] { policy, new AzureSasCredentialSynchronousPolicy(sasCredential) }, new ResponseClassifier())
};
_version = options.VersionString;
_diagnostics = new TablesClientDiagnostics(options);
_tableOperations = new TableRestClient(_diagnostics, pipeline, endpointString, _version);
_serviceOperations = new ServiceRestClient(_diagnostics, pipeline, endpointString, _version);
_secondaryServiceOperations = new ServiceRestClient(_diagnostics, pipeline, secondaryEndpoint, _version);
}
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/>
/// class for mocking.
/// </summary>
internal TableServiceClient(TableRestClient internalClient)
{
_tableOperations = internalClient;
}
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/>
/// class for mocking.
/// </summary>
protected TableServiceClient()
{ }
/// <summary>
/// Gets a <see cref="TableSasBuilder"/> instance scoped to the current account.
/// </summary>
/// <param name="permissions"><see cref="TableAccountSasPermissions"/> containing the allowed permissions.</param>
/// <param name="resourceTypes"><see cref="TableAccountSasResourceTypes"/> containing the accessible resource types.</param>
/// <param name="expiresOn">The time at which the shared access signature becomes invalid.</param>
/// <returns>An instance of <see cref="TableAccountSasBuilder"/>.</returns>
public virtual TableAccountSasBuilder GetSasBuilder(TableAccountSasPermissions permissions, TableAccountSasResourceTypes resourceTypes, DateTimeOffset expiresOn)
{
return new TableAccountSasBuilder(permissions, resourceTypes, expiresOn) { Version = _version };
}
/// <summary>
/// Gets a <see cref="TableAccountSasBuilder"/> instance scoped to the current table.
/// </summary>
/// <param name="rawPermissions">The permissions associated with the shared access signature. This string should contain one or more of the following permission characters in this order: "racwdl".</param>
/// <param name="resourceTypes"><see cref="TableAccountSasResourceTypes"/> containing the accessible resource types.</param>
/// <param name="expiresOn">The time at which the shared access signature becomes invalid.</param>
/// <returns>An instance of <see cref="TableAccountSasBuilder"/>.</returns>
public virtual TableAccountSasBuilder GetSasBuilder(string rawPermissions, TableAccountSasResourceTypes resourceTypes, DateTimeOffset expiresOn)
{
return new TableAccountSasBuilder(rawPermissions, resourceTypes, expiresOn) { Version = _version };
}
/// <summary>
/// Gets an instance of a <see cref="TableClient"/> configured with the current <see cref="TableServiceClient"/> options, affinitized to the specified <paramref name="tableName"/>.
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
public virtual TableClient GetTableClient(string tableName)
{
Argument.AssertNotNull(tableName, nameof(tableName));
return new TableClient(tableName, _tableOperations, _version, _diagnostics, _isCosmosEndpoint, _endpoint);
}
/// <summary>
/// Gets a list of tables from the storage account.
/// </summary>
/// <param name="filter">Returns only tables that satisfy the specified filter.</param>
/// <param name="maxPerPage">
/// The maximum number of tables that will be returned per page.
/// Note: This value does not limit the total number of results if the result is fully enumerated.
/// </param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="AsyncPageable{T}"/> containing a collection of <see cref="TableItem"/>s.</returns>
public virtual AsyncPageable<TableItem> GetTablesAsync(string filter = null, int? maxPerPage = null, CancellationToken cancellationToken = default)
{
return PageableHelpers.CreateAsyncEnumerable(
async pageSizeHint =>
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetTables)}");
scope.Start();
try
{
var response = await _tableOperations.QueryAsync(
null,
new QueryOptions() { Filter = filter, Select = null, Top = pageSizeHint, Format = _format },
cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Headers.XMsContinuationNextTableName, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
},
async (nextLink, pageSizeHint) =>
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetTables)}");
scope.Start();
try
{
var response = await _tableOperations.QueryAsync(
nextTableName: nextLink,
new QueryOptions() { Filter = filter, Select = null, Top = pageSizeHint, Format = _format },
cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Headers.XMsContinuationNextTableName, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
},
maxPerPage);
}
/// <summary>
/// Gets a list of tables from the storage account.
/// </summary>
/// <param name="filter">Returns only tables that satisfy the specified filter.</param>
/// <param name="maxPerPage">
/// The maximum number tables that will be returned per page.
/// Note: This value does not limit the total number of results if the result is fully enumerated.
/// </param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="Pageable{T}"/> containing a collection of <see cref="TableItem"/>.</returns>
public virtual Pageable<TableItem> GetTables(string filter = null, int? maxPerPage = null, CancellationToken cancellationToken = default)
{
return PageableHelpers.CreateEnumerable(
pageSizeHint =>
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetTables)}");
scope.Start();
try
{
var response = _tableOperations.Query(
null,
new QueryOptions() { Filter = filter, Select = null, Top = pageSizeHint, Format = _format },
cancellationToken);
return Page.FromValues(response.Value.Value, response.Headers.XMsContinuationNextTableName, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
},
(nextLink, pageSizeHint) =>
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetTables)}");
scope.Start();
try
{
var response = _tableOperations.Query(
nextTableName: nextLink,
new QueryOptions() { Filter = filter, Select = null, Top = pageSizeHint, Format = _format },
cancellationToken);
return Page.FromValues(response.Value.Value, response.Headers.XMsContinuationNextTableName, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
},
maxPerPage);
}
/// <summary>
/// Gets a list of tables from the storage account.
/// </summary>
/// <param name="filter">
/// Returns only tables that satisfy the specified filter expression.
/// For example, the following expression would filter tables with a TableName of 'foo': <c>e => e.TableName == "foo"</c>.
/// </param>
/// <param name="maxPerPage">
/// The maximum number of entities that will be returned per page.
/// Note: This value does not limit the total number of results if the result is fully enumerated.
/// </param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="AsyncPageable{T}"/> containing a collection of <see cref="TableItem"/>s.</returns>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
public virtual AsyncPageable<TableItem> GetTablesAsync(Expression<Func<TableItem, bool>> filter, int? maxPerPage = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(GetTables)}");
scope.Start();
try
{
return GetTablesAsync(TableClient.Bind(filter), maxPerPage, cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets a list of tables from the storage account.
/// </summary>
/// <param name="filter">
/// Returns only tables that satisfy the specified filter expression.
/// For example, the following expression would filter tables with a TableName of 'foo': <c>e => e.TableName == "foo"</c>.
/// </param>
/// <param name="maxPerPage">
/// The maximum number of entities that will be returned per page.
/// Note: This value does not limit the total number of results if the result is fully enumerated.
/// </param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="Pageable{T}"/> containing a collection of <see cref="TableItem"/>.</returns>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
public virtual Pageable<TableItem> GetTables(Expression<Func<TableItem, bool>> filter, int? maxPerPage = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(GetTables)}");
scope.Start();
try
{
return GetTables(TableClient.Bind(filter), maxPerPage, cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates a table on the service.
/// </summary>
/// <param name="tableName">The name of table to create.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>A <see cref="Response{TableItem}"/> containing properties of the table.</returns>
public virtual Response<TableItem> CreateTable(string tableName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tableName, nameof(tableName));
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(CreateTable)}");
scope.Start();
try
{
var response = _tableOperations.Create(new TableProperties() { TableName = tableName }, null, queryOptions: _defaultQueryOptions, cancellationToken: cancellationToken);
return Response.FromValue(response.Value as TableItem, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates a table on the service.
/// </summary>
/// <param name="tableName">The name of table to create.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>A <see cref="Response{TableItem}"/> containing properties of the table.</returns>
public virtual async Task<Response<TableItem>> CreateTableAsync(string tableName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tableName, nameof(tableName));
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(CreateTable)}");
scope.Start();
try
{
var response = await _tableOperations.CreateAsync(new TableProperties() { TableName = tableName }, null, queryOptions: _defaultQueryOptions, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value as TableItem, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates a table on the service.
/// </summary>
/// <param name="tableName">The name of the table to create.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>If the table does not already exist, a <see cref="Response{TableItem}"/>. If the table already exists, <c>null</c>.</returns>
public virtual Response<TableItem> CreateTableIfNotExists(string tableName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tableName, nameof(tableName));
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(CreateTableIfNotExists)}");
scope.Start();
try
{
var response = _tableOperations.Create(new TableProperties() { TableName = tableName }, null, queryOptions: _defaultQueryOptions, cancellationToken: cancellationToken);
return Response.FromValue(response.Value as TableItem, response.GetRawResponse());
}
catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict)
{
return default;
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates a table on the service.
/// </summary>
/// <param name="tableName">The name of the table to create.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>If the table does not already exist, a <see cref="Response{TableItem}"/>. If the table already exists, <c>null</c>.</returns>
public virtual async Task<Response<TableItem>> CreateTableIfNotExistsAsync(string tableName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tableName, nameof(tableName));
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(CreateTableIfNotExists)}");
scope.Start();
try
{
var response = await _tableOperations.CreateAsync(new TableProperties() { TableName = tableName }, null, queryOptions: _defaultQueryOptions, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value as TableItem, response.GetRawResponse());
}
catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict)
{
return default;
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes a table on the service.
/// </summary>
/// <param name="tableName">The name of the table to create.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="Response"/> indicating the result of the operation.</returns>
public virtual Response DeleteTable(string tableName, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(DeleteTable)}");
scope.Start();
try
{
return _tableOperations.Delete(tableName, cancellationToken: cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes a table on the service.
/// </summary>
/// <param name="tableName">The name of the table to create.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="Response"/> indicating the result of the operation.</returns>
public virtual async Task<Response> DeleteTableAsync(string tableName, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(DeleteTable)}");
scope.Start();
try
{
return await _tableOperations.DeleteAsync(tableName, cancellationToken: cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Sets properties for an account's Table service endpoint, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary>
/// <param name="properties"> The Table Service properties. </param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="Response"/> indicating the result of the operation.</returns>
public virtual Response SetProperties(TableServiceProperties properties, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(SetProperties)}");
scope.Start();
try
{
return _serviceOperations.SetProperties(properties, cancellationToken: cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Sets properties for an account's Table service endpoint, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary>
/// <param name="properties"> The Table Service properties. </param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="Response"/> indicating the result of the operation.</returns>
public virtual async Task<Response> SetPropertiesAsync(TableServiceProperties properties, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(SetProperties)}");
scope.Start();
try
{
return await _serviceOperations.SetPropertiesAsync(properties, cancellationToken: cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Gets the properties of an account's Table service, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="Response{TableServiceProperties}"/> indicating the result of the operation.</returns>
public virtual Response<TableServiceProperties> GetProperties(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetProperties)}");
scope.Start();
try
{
var response = _serviceOperations.GetProperties(cancellationToken: cancellationToken);
return Response.FromValue(response.Value, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Gets the properties of an account's Table service, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="Response{TableServiceProperties}"/> indicating the result of the operation.</returns>
public virtual async Task<Response<TableServiceProperties>> GetPropertiesAsync(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetProperties)}");
scope.Start();
try
{
var response = await _serviceOperations.GetPropertiesAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Retrieves statistics related to replication for the Table service. It is only available on the secondary location endpoint when read-access geo-redundant replication is enabled for the account. </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
public virtual async Task<Response<TableServiceStatistics>> GetStatisticsAsync(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetStatistics)}");
scope.Start();
try
{
var response = await _secondaryServiceOperations.GetStatisticsAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Retrieves statistics related to replication for the Table service. It is only available on the secondary location endpoint when read-access geo-redundant replication is enabled for the account. </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
public virtual Response<TableServiceStatistics> GetStatistics(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetStatistics)}");
scope.Start();
try
{
var response = _secondaryServiceOperations.GetStatistics(cancellationToken: cancellationToken);
return Response.FromValue(response.Value, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
internal static bool IsPremiumEndpoint(Uri endpoint)
{
return (endpoint.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase) && endpoint.Port != 10002) ||
endpoint.Host.IndexOf(TableConstants.CosmosTableDomain, StringComparison.OrdinalIgnoreCase) >= 0 ||
endpoint.Host.IndexOf(TableConstants.LegacyCosmosTableDomain, StringComparison.OrdinalIgnoreCase) >= 0;
}
/// <summary>
/// Creates an OData filter query string from the provided expression.
/// </summary>
/// <param name="filter">A filter expression.</param>
/// <returns>The string representation of the filter expression.</returns>
public static string CreateQueryFilter(Expression<Func<TableItem, bool>> filter) => TableClient.Bind(filter);
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.DataStructures;
namespace Microsoft.Research.CodeAnalysis
{
using Temp = System.Int32; // Stack locations
using Dest = System.Int32; // Stack location
using Source = System.Int32; // Stack location
using SubroutineContext = FList<Tuple<CFGBlock, CFGBlock, string>>;
using SubroutineEdge = Tuple<CFGBlock, CFGBlock, string>;
/// <summary>
/// The Z3 Heap analysis is structured as follows:
/// - First, an egraph based approximation of aliasing is computed for the sole purpose of estiimating reachability at call
/// sites and estimating resulting modifies at these sites.
/// - Then, we compute a Z3 model by breaking back-edges and inserting havocs in loop heads. We compute the loop modifies at the
/// same time, again approximately using finitization of what can be modified.
/// - In order to present a symbolic model to abstract interpretation that has stable variables, we need to compute best/equivalent
/// terms along straight lines of code for lookups.
/// </summary>
public class Z3HeapAnalysis<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>
where Type:IEquatable<Type>
{
Data data;
class Data
{
}
class Modifies
{
#region Constructor representation for edges in EGraph
class WrapTable
{
Dictionary<Local, Constructor.Wrapper<Local>> locals;
Dictionary<Parameter, Constructor.Wrapper<Parameter>> parameters;
Dictionary<Field, Constructor.Wrapper<Field>> fields;
Dictionary<Method, Constructor.Wrapper<Method>> pseudoFields;
Dictionary<Temp, Constructor.Wrapper<Temp>> temps;
Dictionary<string, Constructor.Wrapper<string>> strings;
Dictionary<object, Constructor.Wrapper<object>> programConstants;
Dictionary<Method, Constructor.Wrapper<Method>> methodPointers;
Dictionary<BinaryOperator, Constructor.Wrapper<BinaryOperator>> binaryOps;
Dictionary<UnaryOperator, Constructor.Wrapper<UnaryOperator>> unaryOps;
int idgen;
private Constructor.Wrapper<T> For<T>(T value, Dictionary<T, Constructor.Wrapper<T>> cache)
{
Constructor.Wrapper<T>/*?*/ result;
if (!cache.TryGetValue(value, out result))
{
result = Constructor.For(value, ref idgen, this.mdDecoder);
cache.Add(value, result);
}
return result;
}
public Constructor For(Local v) { return For(v, locals); }
public Constructor For(Parameter v) { return For(v, parameters); }
public Constructor For(Field v)
{
v = this.mdDecoder.Unspecialized(v);
return For(v, fields);
}
public Constructor For(Method v) { return For(v, pseudoFields); }
public Constructor For(Temp v) { return For(v, temps); }
public Constructor For(string v) { return For(v, strings); }
public Constructor For(BinaryOperator v) { return For(v, binaryOps); }
public Constructor For(UnaryOperator v) { return For(v, unaryOps); }
public Constructor ForConstant(object constant, Type type)
{
Constructor.Wrapper<object> c = For(constant, programConstants);
c.Type = type;
return c;
}
/// <summary>
/// Used by LdFtn
/// </summary>
/// <param name="method">the method</param>
/// <param name="type">UIntPtr</param>
public Constructor ForMethod(Method method, Type type)
{
Constructor.Wrapper<Method> c = For(method, methodPointers);
c.Type = type;
return c;
}
/// <summary>
/// Returns true if the symbolic constant represents a program constant
/// </summary>
public bool IsConstantOrMethod(Constructor c)
{
Constructor.Wrapper<object> cwrapper = c as Constructor.Wrapper<object>;
if (cwrapper != null)
{
if (this.programConstants.ContainsKey(cwrapper.Value))
{
return true;
}
}
Constructor.Wrapper<Method> mwrapper = c as Constructor.Wrapper<Method>;
if (mwrapper != null)
{
if (this.methodPointers.ContainsKey(mwrapper.Value))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns true if the symbolic constant represents a program constant
/// </summary>
public bool IsConstant(Constructor c, out Type type, out object value)
{
Constructor.Wrapper<object> cwrapper = c as Constructor.Wrapper<object>;
if (cwrapper != null)
{
if (this.programConstants.ContainsKey(cwrapper.Value))
{
type = cwrapper.Type;
value = cwrapper.Value;
System.Diagnostics.Debug.Assert(!this.mdDecoder.Equal(type, this.mdDecoder.System_Int32) || value is Int32);
return true;
}
}
type = default(Type);
value = null;
return false;
}
/// <summary>
/// Used to indirect from address to value
/// </summary>
public readonly Constructor ValueOf;
/// <summary>
/// Used to retain old value across havocs
/// </summary>
public readonly Constructor OldValueOf;
/// <summary>
/// Special model field for structs used to have a symbolic identity
/// </summary>
public readonly Constructor StructId;
/// <summary>
/// Special model field for objects used to indicate a version (updated on mutation)
/// </summary>
public readonly Constructor ObjectVersion;
public readonly Constructor NullValue;
/// <summary>
/// Used as a pure function for array element addresses ElementAddr(array,index)
/// </summary>
public readonly Constructor ElementAddress;
/// <summary>
/// Model field for array length
/// </summary>
public readonly Constructor Length;
/// <summary>
/// Model field for writable extent of pointers
/// </summary>
public readonly Constructor WritableBytes;
/// <summary>
/// dummy struct address for all void values
/// </summary>
public readonly Constructor VoidAddr;
public readonly Constructor ZeroValue;
public readonly Constructor UnaryNot;
public readonly Constructor NeZero;
/// <summary>
/// Special way to cache box operations on same values
/// </summary>
public readonly Constructor BoxOperator;
/// <summary>
/// Special field in delegates to hold method pointer
/// </summary>
public readonly Constructor FunctionPointer;
/// <summary>
/// Special field in delegates to hold target object
/// </summary>
public readonly Constructor ClosureObject;
/// <summary>
/// Breadcrumb to tag values resulting from calls. (target doesn't matter)
/// </summary>
public readonly Constructor ResultOfCall;
/// <summary>
/// Breadcrumb to tag values resulting from ldelem. (target doesn't matter)
/// </summary>
public readonly Constructor ResultOfLdelem;
#if false
/// <summary>
/// Used to approximate hash consing across join points of ElementAddr(a,i)
/// </summary>
public readonly Constructor LastArrayIndex;
public readonly Constructor LastArrayElemAddress;
#endif
readonly IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder;
public WrapTable(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
this.mdDecoder = mdDecoder;
this.locals = new Dictionary<Local, Constructor.Wrapper<Local>>();
this.parameters = new Dictionary<Parameter, Constructor.Wrapper<Parameter>>();
this.fields = new Dictionary<Field, Constructor.Wrapper<Field>>();
this.pseudoFields = new Dictionary<Method, Constructor.Wrapper<Method>>();
this.temps = new Dictionary<int, Constructor.Wrapper<Temp>>();
this.strings = new Dictionary<string, Constructor.Wrapper<string>>();
this.programConstants = new Dictionary<object, Constructor.Wrapper<object>>();
this.methodPointers = new Dictionary<Method, Constructor.Wrapper<Method>>();
this.binaryOps = new Dictionary<BinaryOperator, Constructor.Wrapper<BinaryOperator>>();
this.unaryOps = new Dictionary<UnaryOperator, Constructor.Wrapper<UnaryOperator>>();
ValueOf = For("$Value");
OldValueOf = For("$OldValue");
StructId = For("$StructId");
ObjectVersion = For("$ObjectVersion");
NullValue = For("$Null");
ElementAddress = For("$Element");
Length = For("$Length");
WritableBytes = For("$WritableBytes");
VoidAddr = For("$VoidAddr");
UnaryNot = For("$UnaryNot");
NeZero = For("$NeZero");
BoxOperator = For("$Box");
FunctionPointer = For("$FnPtr");
ClosureObject = For("$Closure");
// Breadcrumbs: we use these to tag values (target doesn't matter)
ResultOfCall = For("$ResultOfCall");
ResultOfLdelem = For("$ResultOfLdElem");
ZeroValue = ForConstant((int)0, this.mdDecoder.System_Int32);
}
}
internal abstract class Constructor : IEquatable<Constructor>, IConstantInfo, IVisibilityCheck<Method>
{
readonly int id;
protected readonly IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder;
public int GetId() { return id; }
protected Constructor(ref int idgen, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
this.id = idgen++;
this.mdDecoder = mdDecoder;
}
public abstract bool ActsAsField { get; }
public abstract bool IsVirtualMethod { get; }
public abstract bool KeepAsBottomField { get; }
public abstract bool ManifestField { get; }
public abstract Type FieldAddressType(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder);
public abstract bool HasExtraDeref { get; }
public abstract bool IsAsVisibleAs(Method method);
public abstract bool IsVisibleFrom(Method method);
public abstract bool IfRootIsParameter { get; }
/// <summary>
/// For fields and properties, this return whether they are static. Otherwise false.
/// </summary>
public abstract bool IsStatic { get; }
public class Wrapper<T> : Constructor
{
public readonly T Value;
private Type type;
public Type Type { get { return this.type; } set { this.type = value; } }
public Wrapper(T value, ref int idgen, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
: base(ref idgen, mdDecoder)
{
this.Value = value;
}
public override bool ActsAsField
{
get
{
return (this.Value is Field);
}
}
public override bool KeepAsBottomField
{
get
{
string s = this.Value as string;
if (s == null) return true;
return (s != "$UnaryNot" && s != "$NeZero");
}
}
public override bool ManifestField
{
get
{
// manifest $Value and fields and pseudo fields
string s = this.Value as string;
if (s != null) { return s == "$Value" || s == "$Length"; }
return (this.Value is Field || this.Value is Method);
}
}
public override Type FieldAddressType(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
if (this.Value is Field)
{
return mdDecoder.ManagedPointer(mdDecoder.FieldType((Field)(object)this.Value));
}
throw new NotImplementedException();
}
public override bool IsStatic
{
get
{
if (this.Value is Field)
{
return this.mdDecoder.IsStatic((Field)(object)this.Value);
}
if (this.Value is Method)
{
return this.mdDecoder.IsStatic((Method)(object)this.Value);
}
return false;
}
}
public override bool IsVirtualMethod
{
get
{
if (this.Value is Method)
{
return this.mdDecoder.IsVirtual((Method)(object)this.Value);
}
return false;
}
}
//^ [Confined]
public override string ToString()
{
if (typeof(T).Equals(typeof(Temp)))
{
return String.Format("s{0}", Value);
}
if (typeof(T).Equals(typeof(Field)))
{
Field f = (Field)(object)Value;
if (mdDecoder.IsStatic(f))
{
//return String.Format("{0}.{1}", mdDecoder.FullName(mdDecoder.DeclaringType(f)), mdDecoder.Name(f));
return String.Format("{0}.{1}", OutputPrettyCS.TypeHelper.TypeFullName(mdDecoder, mdDecoder.DeclaringType(f)), mdDecoder.Name(f));
}
return mdDecoder.Name(f);
}
if (typeof(T).Equals(typeof(Method)))
{
Method m = (Method)(object)Value;
string name = this.mdDecoder.Name(m);
Property prop;
if (mdDecoder.IsPropertyGetter(m, out prop) || mdDecoder.IsPropertySetter(m, out prop))
{
name = mdDecoder.Name(prop);
}
else
{
name = this.mdDecoder.Name(m);
}
if (mdDecoder.IsStatic(m))
{
//name = String.Format("{0}.{1}", mdDecoder.FullName(mdDecoder.DeclaringType(m)), name);
name = String.Format("{0}.{1}", OutputPrettyCS.TypeHelper.TypeFullName(mdDecoder, mdDecoder.DeclaringType(m)), name);
}
return name;
}
return Value.ToString();
}
public override bool IsAsVisibleAs(Method method)
{
if (this.Value is Field)
{
Field f = (Field)(object)this.Value;
return mdDecoder.IsAsVisibleAs(f, method);
}
if (this.Value is Method)
{
Method m = (Method)(object)this.Value;
return mdDecoder.IsAsVisibleAs(m, method);
}
if (mdDecoder.IsConstructor(method) && this.Value is Parameter)
{
var name = mdDecoder.Name((Parameter)(object)this.Value);
if (name == "this") return false;
}
return true;
}
public override bool IfRootIsParameter
{
get
{
if (this.Value is Field)
{
Field f = (Field)(object)this.Value;
return !mdDecoder.IsStatic(f);
}
if (this.Value is Method)
{
Method m = (Method)(object)this.Value;
return !mdDecoder.IsStatic(m);
}
if (this.Value is Parameter)
{
return true;
}
if (this.Value is Local)
{
return false;
}
if (this.Value is string)
{
// Special case, $Length, $Value or $WritteableByte, always visible
return true;
}
return true;
}
}
/// <summary>
/// Tests only the last access, traverse the path if you want to be sure
/// that the actual full element is visible
/// </summary>
public override bool IsVisibleFrom(Method method)
{
var declaringType = mdDecoder.DeclaringType(method);
if (this.Value is Field)
{
Field f = (Field)(object)this.Value;
return !mdDecoder.IsCompilerGenerated(f) && mdDecoder.IsVisibleFrom(f, declaringType);
}
if (this.Value is Method)
{
Method m = (Method)(object)this.Value;
return mdDecoder.IsVisibleFrom(m, declaringType);
}
if (this.Value is Parameter)
{
Parameter p = (Parameter)(object)this.Value;
return mdDecoder.Equal(mdDecoder.DeclaringMethod(p), method);
}
if (this.Value is Local)
{
Local l = (Local)(object)this.Value;
var locs = mdDecoder.Locals(method);
for (int i = 0; i < locs.Count; ++i)
{
if (locs[i].Equals(l))
return true;
}
return false;
}
if (this.Value is string)
{
// Special case, $Length, $Value or $WritteableByte, always visible
return true;
}
return true;
}
public override bool HasExtraDeref
{
get { return this.Value is Local || this.Value is Field; }
}
}
public class PureMethodConstructor : Constructor.Wrapper<Method>
{
public PureMethodConstructor(Method method, ref int idgen, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
: base(method, ref idgen, mdDecoder)
{
}
public override bool ActsAsField
{
get
{
return true;
}
}
public override Type FieldAddressType(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
return mdDecoder.ManagedPointer(mdDecoder.ReturnType(this.Value));
}
private bool IsBooleanTyped
{
get
{
return this.mdDecoder.Equal(this.mdDecoder.ReturnType(this.Value), this.mdDecoder.System_Boolean);
}
}
private bool IsGetter
{
get
{
Property prop;
return this.mdDecoder.IsPropertyGetter(this.Value, out prop);
}
}
}
public class ParameterConstructor : Constructor.Wrapper<Parameter>
{
Parameter p { get { return this.Value; } }
int argumentIndex;
public ParameterConstructor(Parameter p, ref int idgen, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
: base(p, ref idgen, mdDecoder)
{
this.argumentIndex = mdDecoder.ArgumentIndex(p);
}
public override bool ActsAsField
{
get { return false; }
}
public override Type FieldAddressType(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
throw new NotImplementedException();
}
public override bool Equals(object obj)
{
ParameterConstructor pc = obj as ParameterConstructor;
if (pc == null) return false;
return pc.argumentIndex == this.argumentIndex;
}
public override int GetHashCode()
{
return this.argumentIndex;
}
public override string ToString()
{
return mdDecoder.Name(p);
}
public override bool HasExtraDeref
{
get { return /*true*/ false; } // Mic: parameter have an extra deref only if they are out or ref, but it's covered by the IsAddressOf field
}
}
internal static Constructor.Wrapper<T> For<T>(T value, ref int idgen, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
if (value is Parameter)
{
return (Constructor.Wrapper<T>)(object)new ParameterConstructor((Parameter)(object)value, ref idgen, mdDecoder);
}
if (typeof(T).Equals(typeof(Method)) && value is Method)
{
return (Constructor.Wrapper<T>)(object)new PureMethodConstructor((Method)(object)value, ref idgen, mdDecoder);
}
return new Constructor.Wrapper<T>(value, ref idgen, mdDecoder);
}
#region IEquatable<Constructor> Members
public bool Equals(Constructor other)
{
return this == other;
}
#endregion
}
#endregion
class AbstractType : IEquatable<AbstractType>, IAbstractValueForEGraph<AbstractType>
{
#region IEquatable<AbstractType> Members
public bool Equals(AbstractType other)
{
throw new NotImplementedException();
}
#endregion
#region IAbstractValueForEGraph<AbstractType> Members
public bool HasAllBottomFields
{
get { throw new NotImplementedException(); }
}
public AbstractType ForManifestedField()
{
throw new NotImplementedException();
}
#endregion
#region IAbstractValue<AbstractType> Members
public AbstractType Top
{
get { throw new NotImplementedException(); }
}
public AbstractType Bottom
{
get { throw new NotImplementedException(); }
}
public bool IsTop
{
get { throw new NotImplementedException(); }
}
public bool IsBottom
{
get { throw new NotImplementedException(); }
}
public AbstractType ImmutableVersion()
{
throw new NotImplementedException();
}
public AbstractType Clone()
{
throw new NotImplementedException();
}
public AbstractType Join(AbstractType newState, out bool weaker, bool widen)
{
throw new NotImplementedException();
}
public AbstractType Meet(AbstractType that)
{
throw new NotImplementedException();
}
public bool LessEqual(AbstractType that)
{
throw new NotImplementedException();
}
public void Dump(System.IO.TextWriter tw)
{
throw new NotImplementedException();
}
#endregion
}
public class Domain : IAbstractValue<Domain>
{
#region State shared among all instances
static Domain top;
static Domain bot;
#endregion
#region State private to this region
/// <summary>
/// The egraph is used to keep track of must aliasing. It also associates a Type with each symbolic value
/// to do some type recovery that is useful in later phases.
/// </summary>
readonly EGraph<Constructor, AbstractType> egraph;
#endregion
#region Constructors
private Domain() { }
private Domain(
Domain from,
EGraph<Constructor, AbstractType> egraph
)
{
this.egraph = egraph;
}
#endregion
#region IAbstractValue<Domain> Members
public Domain Top
{
get
{
if (top == null)
{
top = new Domain();
}
return top;
}
}
public Domain Bottom
{
get
{
if (bot == null)
{
bot = new Domain();
}
return bot;
}
}
public bool IsTop
{
get
{
return this == top;
}
}
public bool IsBottom
{
get
{
return this == bot;
}
}
public Domain ImmutableVersion()
{
if (this.egraph != null)
{
this.egraph.ImmutableVersion(); // mark immutable
}
return this;
}
public Domain Clone()
{
return new Domain(this,
this.egraph.Clone()
);
}
public Domain Join(Domain newState, out bool weaker, bool widen)
{
throw new NotImplementedException();
}
public Domain Meet(Domain that)
{
throw new NotImplementedException();
}
public bool LessEqual(Domain that)
{
throw new NotImplementedException();
}
public void Dump(System.IO.TextWriter tw)
{
throw new NotImplementedException();
}
#endregion
}
public class Analysis :
IAnalysisDriver<APC, Domain, IVisitMSIL<APC, Local, Parameter, Method, Field, Type, Temp, Temp, Domain, Domain>, IStackContext<APC, Field, Method>>,
IVisitMSIL<APC, Local, Parameter, Method, Field, Type, Source, Source, Domain, Domain>
{
#region State
const bool EagerCaching = true;
IStackContext<APC, Field, Method> context;
IFixpointInfo<APC, Domain> fixpointInfo;
#endregion
#region IAnalysisDriver<APC,Domain,IVisitMSIL<APC,Local,Parameter,Method,Field,Type,int,int,Domain,Domain>,IStackContext<APC,Field,Method>> Members
public Domain EdgeConversion(APC from, APC next, bool joinPoint, Domain newState)
{
throw new NotImplementedException();
}
public Joiner<APC, Domain> Joiner()
{
throw new NotImplementedException();
}
public Converter<Domain, Domain> MutableVersion()
{
throw new NotImplementedException();
}
public Converter<Domain, Domain> ImmutableVersion()
{
throw new NotImplementedException();
}
public Action<Pair<Domain, System.IO.TextWriter>> Dumper()
{
throw new NotImplementedException();
}
public Func<APC, Domain, bool> IsBottom()
{
return (apc, domain) => domain.IsBottom;
}
public IVisitMSIL<APC, Local, Parameter, Method, Field, Type, Source, Source, Domain, Domain> Visitor(IStackContext<APC, Field, Method> context)
{
this.context = context;
return this;
}
public Predicate<APC> CacheStates(IFixpointInfo<APC, Domain> fixpointInfo)
{
this.fixpointInfo = fixpointInfo;
return delegate(APC pc) { return EagerCaching; };
}
#endregion
#region Per instruction semantics for heap abstraction analysis
#region IVisitMSIL<APC,Local,Parameter,Method,Field,Type,int,int,Domain,Domain> Members
public Domain Arglist(APC pc, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain BranchCond(APC pc, APC target, BranchOperator bop, Source value1, Source value2, Domain data)
{
throw new NotImplementedException();
}
public Domain BranchTrue(APC pc, APC target, Source cond, Domain data)
{
throw new NotImplementedException();
}
public Domain BranchFalse(APC pc, APC target, Source cond, Domain data)
{
throw new NotImplementedException();
}
public Domain Branch(APC pc, APC target, bool leave, Domain data)
{
throw new NotImplementedException();
}
public Domain Break(APC pc, Domain data)
{
throw new NotImplementedException();
}
public Domain Call<TypeList, ArgList>(APC pc, Method method, bool tail, bool virt, TypeList extraVarargs, Source dest, ArgList args, Domain data)
where TypeList : IIndexable<Type>
where ArgList : IIndexable<Source>
{
throw new NotImplementedException();
}
public Domain Calli<TypeList, ArgList>(APC pc, Type returnType, TypeList argTypes, bool tail, Source dest, Source fp, ArgList args, Domain data)
where TypeList : IIndexable<Type>
where ArgList : IIndexable<Source>
{
throw new NotImplementedException();
}
public Domain Ckfinite(APC pc, Source dest, Source source, Domain data)
{
throw new NotImplementedException();
}
public Domain Cpblk(APC pc, bool @volatile, Source destaddr, Source srcaddr, Source len, Domain data)
{
throw new NotImplementedException();
}
public Domain Endfilter(APC pc, Source decision, Domain data)
{
throw new NotImplementedException();
}
public Domain Endfinally(APC pc, Domain data)
{
throw new NotImplementedException();
}
public Domain Initblk(APC pc, bool @volatile, Source destaddr, Source value, Source len, Domain data)
{
throw new NotImplementedException();
}
public Domain Jmp(APC pc, Method method, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldarg(APC pc, Parameter argument, bool isOld, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldarga(APC pc, Parameter argument, bool isOld, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldftn(APC pc, Method method, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldind(APC pc, Type type, bool @volatile, Source dest, Source ptr, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldloc(APC pc, Local local, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldloca(APC pc, Local local, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Localloc(APC pc, Source dest, Source size, Domain data)
{
throw new NotImplementedException();
}
public Domain Nop(APC pc, Domain data)
{
throw new NotImplementedException();
}
public Domain Pop(APC pc, Source source, Domain data)
{
throw new NotImplementedException();
}
public Domain Return(APC pc, Source source, Domain data)
{
throw new NotImplementedException();
}
public Domain Starg(APC pc, Parameter argument, Source source, Domain data)
{
throw new NotImplementedException();
}
public Domain Stind(APC pc, Type type, bool @volatile, Source ptr, Source value, Domain data)
{
throw new NotImplementedException();
}
public Domain Stloc(APC pc, Local local, Source source, Domain data)
{
throw new NotImplementedException();
}
public Domain Switch(APC pc, Type type, IEnumerable<Pair<object, APC>> cases, Source value, Domain data)
{
throw new NotImplementedException();
}
public Domain Box(APC pc, Type type, Source dest, Source source, Domain data)
{
throw new NotImplementedException();
}
public Domain ConstrainedCallvirt<TypeList, ArgList>(APC pc, Method method, bool tail, Type constraint, TypeList extraVarargs, Source dest, ArgList args, Domain data)
where TypeList : IIndexable<Type>
where ArgList : IIndexable<Source>
{
throw new NotImplementedException();
}
public Domain Castclass(APC pc, Type type, Source dest, Source obj, Domain data)
{
throw new NotImplementedException();
}
public Domain Cpobj(APC pc, Type type, Source destptr, Source srcptr, Domain data)
{
throw new NotImplementedException();
}
public Domain Initobj(APC pc, Type type, Source ptr, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldelem(APC pc, Type type, Source dest, Source array, Source index, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldelema(APC pc, Type type, bool @readonly, Source dest, Source array, Source index, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldfld(APC pc, Field field, bool @volatile, Source dest, Source obj, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldflda(APC pc, Field field, Source dest, Source obj, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldlen(APC pc, Source dest, Source array, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldsfld(APC pc, Field field, bool @volatile, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldsflda(APC pc, Field field, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldtypetoken(APC pc, Type type, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldfieldtoken(APC pc, Field field, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldmethodtoken(APC pc, Method method, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldvirtftn(APC pc, Method method, Source dest, Source obj, Domain data)
{
throw new NotImplementedException();
}
public Domain Mkrefany(APC pc, Type type, Source dest, Source obj, Domain data)
{
throw new NotImplementedException();
}
public Domain Newarray<ArgList>(APC pc, Type type, Source dest, ArgList len, Domain data) where ArgList : IIndexable<Source>
{
throw new NotImplementedException();
}
public Domain Newobj<ArgList>(APC pc, Method ctor, Source dest, ArgList args, Domain data) where ArgList : IIndexable<Source>
{
throw new NotImplementedException();
}
public Domain Refanytype(APC pc, Source dest, Source source, Domain data)
{
throw new NotImplementedException();
}
public Domain Refanyval(APC pc, Type type, Source dest, Source source, Domain data)
{
throw new NotImplementedException();
}
public Domain Rethrow(APC pc, Domain data)
{
throw new NotImplementedException();
}
public Domain Stelem(APC pc, Type type, Source array, Source index, Source value, Domain data)
{
throw new NotImplementedException();
}
public Domain Stfld(APC pc, Field field, bool @volatile, Source obj, Source value, Domain data)
{
throw new NotImplementedException();
}
public Domain Stsfld(APC pc, Field field, bool @volatile, Source value, Domain data)
{
throw new NotImplementedException();
}
public Domain Throw(APC pc, Source exn, Domain data)
{
throw new NotImplementedException();
}
public Domain Unbox(APC pc, Type type, Source dest, Source obj, Domain data)
{
throw new NotImplementedException();
}
public Domain Unboxany(APC pc, Type type, Source dest, Source obj, Domain data)
{
throw new NotImplementedException();
}
#endregion
#region IVisitSynthIL<APC,Method,Type,int,int,Domain,Domain> Members
public Domain Entry(APC pc, Method method, Domain data)
{
throw new NotImplementedException();
}
public Domain Assume(APC pc, string tag, Source condition, Domain data)
{
throw new NotImplementedException();
}
public Domain Assert(APC pc, string tag, Source condition, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldstack(APC pc, Source offset, Source dest, Source source, bool isOld, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldstacka(APC pc, Source offset, Source dest, Source source, Type origParamType, bool isOld, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldresult(APC pc, Source dest, Source source, Domain data)
{
throw new NotImplementedException();
}
public Domain BeginOld(APC pc, APC matchingEnd, Domain data)
{
throw new NotImplementedException();
}
public Domain EndOld(APC pc, APC matchingBegin, Type type, Source dest, Source source, Domain data)
{
throw new NotImplementedException();
}
#endregion
#region IVisitExprIL<APC,Type,int,int,Domain,Domain> Members
public Domain Binary(APC pc, BinaryOperator op, Source dest, Source s1, Source s2, Domain data)
{
throw new NotImplementedException();
}
public Domain Isinst(APC pc, Type type, Source dest, Source obj, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldconst(APC pc, object constant, Type type, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Ldnull(APC pc, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Sizeof(APC pc, Type type, Source dest, Domain data)
{
throw new NotImplementedException();
}
public Domain Unary(APC pc, UnaryOperator op, bool overflow, bool unsigned, Source dest, Source source, Domain data)
{
throw new NotImplementedException();
}
#endregion
#endregion
}
}
}
}
| |
// Copyright 2021 Esri.
//
// 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 ArcGISRuntime.Helpers;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace ArcGISRuntime.WPF.Samples.AuthorMap
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Create and save map",
category: "Map",
description: "Create and save a map as an ArcGIS `PortalItem` (i.e. web map).",
instructions: "1. Select the basemap and layers you'd like to add to your map.",
tags: new[] { "ArcGIS Online", "OAuth", "portal", "publish", "share", "web map" })]
[ArcGISRuntime.Samples.Shared.Attributes.ClassFile("Helpers\\ArcGISLoginPrompt.cs")]
public partial class AuthorMap
{
// String array to store names of the available basemaps
private readonly string[] _basemapNames =
{
"Light Gray",
"Topographic",
"Streets",
"Imagery",
"Ocean"
};
// Dictionary of operational layer names and URLs
private Dictionary<string, string> _operationalLayerUrls = new Dictionary<string, string>
{
{"World Elevations", "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Elevation/WorldElevations/MapServer"},
{"World Cities", "https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer/" },
{"US Census Data", "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer"}
};
public AuthorMap()
{
this.Loaded += (s, e) => { _ = Initialize(); };
InitializeComponent();
}
private async Task Initialize()
{
ArcGISLoginPrompt.SetChallengeHandler();
bool loggedIn = await ArcGISLoginPrompt.EnsureAGOLCredentialAsync();
// Show a plain gray map in the map view.
if (loggedIn)
{
MyMapView.Map = new Map(BasemapStyle.ArcGISLightGray);
}
else MyMapView.Map = new Map();
// Fill the basemap combo box with basemap names
BasemapListBox.ItemsSource = _basemapNames;
// Add a listener for changes in the selected basemap.
BasemapListBox.SelectionChanged += BasemapSelectionChanged;
// Fill the operational layers list box with layer names
OperationalLayerListBox.ItemsSource = _operationalLayerUrls;
// Update the extent labels whenever the view point (extent) changes
MyMapView.ViewpointChanged += (s, evt) => UpdateViewExtentLabels();
}
#region UI event handlers
private void BasemapSelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Call a function to set the basemap to the one selected
ApplyBasemap(e.AddedItems[0].ToString());
}
private void OperationalLayerSelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Call a function to add the chosen layers to the map
AddOperationalLayers();
}
private void NewMapClicked(object sender, RoutedEventArgs e)
{
// Create a new map (will not have an associated PortalItem)
MyMapView.Map = new Map(BasemapStyle.ArcGISLightGray);
MyMapView.Map.Basemap.LoadAsync();
// Reset UI to be consistent with map
BasemapListBox.SelectedIndex = 0;
OperationalLayerListBox.SelectedIndex = -1;
}
private async void SaveMapClicked(object sender, RoutedEventArgs e)
{
try
{
// Show the progress bar so the user knows work is happening
SaveProgressBar.Visibility = Visibility.Visible;
// Get the current map
Map myMap = MyMapView.Map;
// Load the current map before saving to portal.
await myMap.LoadAsync();
// Apply the current extent as the map's initial extent
myMap.InitialViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
// Get the current map view for the item thumbnail
RuntimeImage thumbnailImg = await MyMapView.ExportImageAsync();
// See if the map has already been saved (has an associated portal item)
if (myMap.Item == null)
{
// Get information for the new portal item
string title = TitleTextBox.Text;
string description = DescriptionTextBox.Text;
string[] tags = TagsTextBox.Text.Split(',');
// Make sure all required info was entered
if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(description) || tags.Length == 0)
{
throw new Exception("Please enter a title, description, and some tags to describe the map.");
}
// Call a function to save the map as a new portal item
await SaveNewMapAsync(MyMapView.Map, title, description, tags, thumbnailImg);
// Report a successful save
MessageBox.Show("Saved '" + title + "' to ArcGIS Online!", "Map Saved");
}
else
{
// This is not the initial save, call SaveAsync to save changes to the existing portal item
await myMap.SaveAsync();
// Get the file stream from the new thumbnail image
Stream imageStream = await thumbnailImg.GetEncodedBufferAsync();
// Update the item thumbnail
((PortalItem)myMap.Item).SetThumbnail(imageStream);
await myMap.SaveAsync();
// Report update was successful
MessageBox.Show("Saved changes to '" + myMap.Item.Title + "'", "Updates Saved");
}
}
catch (Exception ex)
{
// Report error message
MessageBox.Show("Error saving map to ArcGIS Online: " + ex.Message);
}
finally
{
// Hide the progress bar
SaveProgressBar.Visibility = Visibility.Hidden;
}
}
#endregion UI event handlers
private void ApplyBasemap(string basemapName)
{
// Set the basemap for the map according to the user's choice in the list box.
switch (basemapName)
{
case "Light Gray":
MyMapView.Map.Basemap = new Basemap(BasemapStyle.ArcGISLightGray);
break;
case "Topographic":
MyMapView.Map.Basemap = new Basemap(BasemapStyle.ArcGISTopographic);
break;
case "Streets":
MyMapView.Map.Basemap = new Basemap(BasemapStyle.ArcGISStreets);
break;
case "Imagery":
MyMapView.Map.Basemap = new Basemap(BasemapStyle.ArcGISImagery);
break;
case "Ocean":
MyMapView.Map.Basemap = new Basemap(BasemapStyle.ArcGISOceans);
break;
}
MyMapView.Map.Basemap.LoadAsync();
}
private void AddOperationalLayers()
{
// Clear all operational layers from the map
Map myMap = MyMapView.Map;
myMap.OperationalLayers.Clear();
// Loop through the selected items in the operational layers list box
foreach (KeyValuePair<string, string> item in OperationalLayerListBox.SelectedItems)
{
// Get the service uri for each selected item
KeyValuePair<string, string> layerInfo = item;
Uri layerUri = new Uri(layerInfo.Value);
// Create a new map image layer, set it 50% opaque, and add it to the map
ArcGISMapImageLayer layer = new ArcGISMapImageLayer(layerUri)
{
Opacity = 0.5
};
myMap.OperationalLayers.Add(layer);
}
}
private async Task SaveNewMapAsync(Map myMap, string title, string description, string[] tags, RuntimeImage thumb)
{
await ArcGISLoginPrompt.EnsureAGOLCredentialAsync();
// Get the ArcGIS Online portal (will use credential from login above)
ArcGISPortal agsOnline = await ArcGISPortal.CreateAsync();
// Save the current state of the map as a portal item in the user's default folder
await myMap.SaveAsAsync(agsOnline, null, title, description, tags, thumb);
}
private void UpdateViewExtentLabels()
{
// Get the current view point for the map view
Viewpoint currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
if (currentViewpoint == null) { return; }
// Get the current map extent (envelope) from the view point
Envelope currentExtent = currentViewpoint.TargetGeometry as Envelope;
// Project the current extent to geographic coordinates (longitude / latitude)
Envelope currentGeoExtent = (Envelope)GeometryEngine.Project(currentExtent, SpatialReferences.Wgs84);
// Fill the app text boxes with min / max longitude (x) and latitude (y) to four decimal places
XMinTextBox.Text = currentGeoExtent.XMin.ToString("0.####");
YMinTextBox.Text = currentGeoExtent.YMin.ToString("0.####");
XMaxTextBox.Text = currentGeoExtent.XMax.ToString("0.####");
YMaxTextBox.Text = currentGeoExtent.YMax.ToString("0.####");
}
}
}
| |
/*
* 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.Tests
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Apache.Ignite.Core.Discovery;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Static;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Tests.Process;
using NUnit.Framework;
/// <summary>
/// Test utility methods.
/// </summary>
public static class TestUtils
{
/** Indicates long running and/or memory/cpu intensive test. */
public const string CategoryIntensive = "LONG_TEST";
/** */
public const int DfltBusywaitSleepInterval = 200;
/** */
private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess
? new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms1g",
"-Xmx4g",
"-ea"
}
: new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms512m",
"-Xmx512m",
"-ea",
"-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000"
};
/** */
private static readonly IList<string> JvmDebugOpts =
new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005" };
/** */
public static bool JvmDebug = true;
/** */
[ThreadStatic]
private static Random _random;
/** */
private static int _seed = Environment.TickCount;
/// <summary>
/// Kill Ignite processes.
/// </summary>
public static void KillProcesses()
{
IgniteProcess.KillAll();
}
/// <summary>
///
/// </summary>
public static Random Random
{
get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IList<string> TestJavaOptions()
{
IList<string> ops = new List<string>(TestJvmOpts);
if (JvmDebug)
{
foreach (string opt in JvmDebugOpts)
ops.Add(opt);
}
return ops;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static string CreateTestClasspath()
{
return Classpath.CreateClasspath(forceTestClasspath: true);
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
public static void RunMultiThreaded(Action action, int threadNum)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
action();
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
/// <param name="duration">Duration of test execution in seconds</param>
public static void RunMultiThreaded(Action action, int threadNum, int duration)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
bool stop = false;
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
while (true)
{
Thread.MemoryBarrier();
// ReSharper disable once AccessToModifiedClosure
if (stop)
break;
action();
}
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
Thread.Sleep(duration * 1000);
stop = true;
Thread.MemoryBarrier();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
/// Wait for particular topology size.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="size">Size.</param>
/// <param name="timeout">Timeout.</param>
/// <returns>
/// <c>True</c> if topology took required size.
/// </returns>
public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000)
{
int left = timeout;
while (true)
{
if (grid.GetCluster().GetNodes().Count != size)
{
if (left > 0)
{
Thread.Sleep(100);
left -= 100;
}
else
break;
}
else
return true;
}
return false;
}
/// <summary>
/// Asserts that the handle registry is empty.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, 0, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, expectedCount, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="grid">The grid to check.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout)
{
var handleRegistry = ((Ignite)grid).HandleRegistry;
if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout))
return;
var items = handleRegistry.GetItems();
if (items.Any())
Assert.Fail("HandleRegistry is not empty in grid '{0}':\n '{1}'", grid.Name,
items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y));
}
/// <summary>
/// Waits for condition, polling in busy wait loop.
/// </summary>
/// <param name="cond">Condition.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <returns>True if condition predicate returned true within interval; false otherwise.</returns>
public static bool WaitForCondition(Func<bool> cond, int timeout)
{
if (timeout <= 0)
return cond();
var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval);
while (DateTime.Now < maxTime)
{
if (cond())
return true;
Thread.Sleep(DfltBusywaitSleepInterval);
}
return false;
}
/// <summary>
/// Gets the static discovery.
/// </summary>
public static IDiscoverySpi GetStaticDiscovery()
{
return new TcpDiscoverySpi
{
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] { "127.0.0.1:47500", "127.0.0.1:47501" }
}
};
}
/// <summary>
/// Gets the default code-based test configuration.
/// </summary>
public static IgniteConfiguration GetTestConfiguration()
{
return new IgniteConfiguration
{
DiscoverySpi = GetStaticDiscovery(),
Localhost = "127.0.0.1",
JvmOptions = TestJavaOptions(),
JvmClasspath = CreateTestClasspath()
};
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Runtime.Serialization;
namespace DDay.iCal
{
/// <summary>
/// A class that represents an RFC 2445 VALARM component.
/// FIXME: move GetOccurrences() logic into an AlarmEvaluator.
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
public class Alarm :
CalendarComponent,
IAlarm
{
#region Private Fields
private List<AlarmOccurrence> m_Occurrences;
#endregion
#region Public Properties
virtual public AlarmAction Action
{
get { return Properties.Get<AlarmAction>("ACTION"); }
set { Properties.Set("ACTION", value); }
}
virtual public IAttachment Attachment
{
get { return Properties.Get<IAttachment>("ATTACH"); }
set { Properties.Set("ATTACH", value); }
}
virtual public IList<IAttendee> Attendees
{
get { return Properties.GetMany<IAttendee>("ATTENDEE"); }
set { Properties.Set("ATTENDEE", value); }
}
virtual public string Description
{
get { return Properties.Get<string>("DESCRIPTION"); }
set { Properties.Set("DESCRIPTION", value); }
}
virtual public TimeSpan Duration
{
get { return Properties.Get<TimeSpan>("DURATION"); }
set { Properties.Set("DURATION", value); }
}
virtual public int Repeat
{
get { return Properties.Get<int>("REPEAT"); }
set { Properties.Set("REPEAT", value); }
}
virtual public string Summary
{
get { return Properties.Get<string>("SUMMARY"); }
set { Properties.Set("SUMMARY", value); }
}
virtual public ITrigger Trigger
{
get { return Properties.Get<ITrigger>("TRIGGER"); }
set { Properties.Set("TRIGGER", value); }
}
#endregion
#region Protected Properties
virtual protected List<AlarmOccurrence> Occurrences
{
get { return m_Occurrences; }
set { m_Occurrences = value; }
}
#endregion
#region Constructors
public Alarm()
{
Initialize();
}
void Initialize()
{
Name = Components.ALARM;
Occurrences = new List<AlarmOccurrence>();
}
#endregion
#region Public Methods
/// <summary>
/// Gets a list of alarm occurrences for the given recurring component, <paramref name="rc"/>
/// that occur between <paramref name="FromDate"/> and <paramref name="ToDate"/>.
/// </summary>
virtual public IList<AlarmOccurrence> GetOccurrences(IRecurringComponent rc, IDateTime FromDate, IDateTime ToDate)
{
Occurrences.Clear();
if (Trigger != null)
{
// If the trigger is relative, it can recur right along with
// the recurring items, otherwise, it happens once and
// only once (at a precise time).
if (Trigger.IsRelative)
{
// Ensure that "FromDate" has already been set
if (FromDate == null)
FromDate = rc.Start.Copy<IDateTime>();
TimeSpan d = default(TimeSpan);
foreach (Occurrence o in rc.GetOccurrences(FromDate, ToDate))
{
IDateTime dt = o.Period.StartTime;
if (Trigger.Related == TriggerRelation.End)
{
if (o.Period.EndTime != null)
{
dt = o.Period.EndTime;
if (d == default(TimeSpan))
d = o.Period.Duration;
}
// Use the "last-found" duration as a reference point
else if (d != default(TimeSpan))
dt = o.Period.StartTime.Add(d);
else throw new ArgumentException("Alarm trigger is relative to the END of the occurrence; however, the occurence has no discernible end.");
}
Occurrences.Add(new AlarmOccurrence(this, dt.Add(Trigger.Duration.Value), rc));
}
}
else
{
IDateTime dt = Trigger.DateTime.Copy<IDateTime>();
dt.AssociatedObject = this;
Occurrences.Add(new AlarmOccurrence(this, dt, rc));
}
// If a REPEAT and DURATION value were specified,
// then handle those repetitions here.
AddRepeatedItems();
}
return Occurrences;
}
/// <summary>
/// Polls the <see cref="Alarm"/> component for alarms that have been triggered
/// since the provided <paramref name="Start"/> date/time. If <paramref name="Start"/>
/// is null, all triggered alarms will be returned.
/// </summary>
/// <param name="Start">The earliest date/time to poll trigerred alarms for.</param>
/// <returns>A list of <see cref="AlarmOccurrence"/> objects, each containing a triggered alarm.</returns>
virtual public IList<AlarmOccurrence> Poll(IDateTime Start, IDateTime End)
{
List<AlarmOccurrence> Results = new List<AlarmOccurrence>();
// Evaluate the alarms to determine the recurrences
RecurringComponent rc = Parent as RecurringComponent;
if (rc != null)
{
Results.AddRange(GetOccurrences(rc, Start, End));
Results.Sort();
}
return Results;
}
#endregion
#region Protected Methods
/// <summary>
/// Handles the repetitions that occur from the <c>REPEAT</c> and
/// <c>DURATION</c> properties. Each recurrence of the alarm will
/// have its own set of generated repetitions.
/// </summary>
virtual protected void AddRepeatedItems()
{
#pragma warning disable 0472
if (Repeat != null)
{
int len = Occurrences.Count;
for (int i = 0; i < len; i++)
{
AlarmOccurrence ao = Occurrences[i];
IDateTime alarmTime = ao.DateTime.Copy<IDateTime>();
for (int j = 0; j < Repeat; j++)
{
alarmTime = alarmTime.Add(Duration);
Occurrences.Add(new AlarmOccurrence(this, alarmTime.Copy<IDateTime>(), ao.Component));
}
}
}
#pragma warning restore 0472
}
#endregion
#region Overrides
protected override void OnDeserializing(StreamingContext context)
{
base.OnDeserializing(context);
Initialize();
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.Common;
using System.Transactions;
using System.Timers;
using Fs.Native.Windows;
using System.Threading;
namespace Fs.Data
{
public abstract class Db
{
public delegate void TableEnumerationHandler(DataRow row, string tableNameCol);
public delegate void ColumnEnumerationHandler(DataRow row, string colNameCol);
public DbConnection Connection
{
get
{
if (_connection != null)
{
return _connection;
}
else
{
return GetConnection();
}
}
set
{
_connection = value;
}
}protected DbConnection _connection;
public string ConnStr
{
get
{
if (string.IsNullOrEmpty(_connstr))
{
throw new Exception("Error: Connection string missing");
}
return _connstr;
}
set
{
_connstr = value;
}
}protected string _connstr;
public Db()
{
ConnStr = "";
}
public Db(string ConnectionString)
{
ConnStr = ConnectionString;
}
public DataSet GetDataSet(DataAdapter adapter)
{
int RowCount = 0;
DataSet ds = new DataSet();
try
{
RowCount = adapter.Fill(ds);
}
catch (Exception e)
{
Exceptions.LogOnly(e);
RowCount = 0;
ds.ExtendedProperties["error"] = e;
}
return ds;
}
public abstract DataTable PagedQuery(string primaryField, string curtPage, string pageSize, string fieldClause, string tableClause, string whereClause, string orderClause, string groupClause);
public DataTable GetDataTable(string Sql)
{
DataSet ds = GetDataSet(GetAdapter(Sql));
return GetDataTable(ds);
}
public DataTable GetDataTable(DataSet dataset)
{
if (dataset.Tables != null && dataset.Tables.Count > 0)
{
return dataset.Tables[0];
}
return null;
}
public ExecuteResult Execute(string Sql, DbConnection Connection, Transaction Tst)
{
int RowCount;
if (Connection == null)
{
Connection = GetConnection();
}
try
{
if (Connection.State == ConnectionState.Closed)
{
Connection.Open();
}
if (Tst != null)
{
Connection.EnlistTransaction(Tst);
}
DbCommand cm = GetCommand(Sql, Connection);
RowCount = cm.ExecuteNonQuery();
return new ExecuteResult(RowCount, null);
}
catch (TransactionException err)
{
if (Tst != null)
{
Tst.Rollback(err);
}
Exceptions.LogOnly(err);
return new ExecuteResult(null, err);
}
catch (Exception err)
{
if (Tst != null)
{
Tst.Rollback(err);
}
Exceptions.LogOnly(err);
return new ExecuteResult(null, err);
}
finally
{
Connection.Close();
}
}
public int Execute(string Sql)
{
return Execute(Sql, null, null).IntRlt;
}
public ExecuteResult ExecuteReader(string Sql, DbConnection Connection, Transaction Tst)
{
IDataReader rlt;
if (Connection == null)
{
Connection = GetConnection();
}
try
{
if (Connection.State == ConnectionState.Closed)
{
Connection.Open();
}
if (Tst != null)
{
Connection.EnlistTransaction(Tst);
}
DbCommand cm = GetCommand(Sql, Connection);
rlt = cm.ExecuteReader(CommandBehavior.CloseConnection);
return new ExecuteResult(rlt, null);
}
catch (TransactionException err)
{
if (Tst != null)
{
Tst.Rollback(err);
}
Exceptions.LogOnly(err);
return new ExecuteResult(null, err);
}
catch (Exception err)
{
if (Tst != null)
{
Tst.Rollback(err);
}
Exceptions.LogOnly(err);
return new ExecuteResult(null, err);
}
finally
{
Connection.Close();
}
}
public IDataReader ExecuteReader(string Sql)
{
return ExecuteReader(Sql, null, null).ReaderRlt;
}
public ExecuteResult ExecScalar(string Sql, DbConnection Connection, Transaction Tst)
{
object rlt;
if (Connection == null)
{
Connection = GetConnection();
}
try
{
if (Connection.State == ConnectionState.Closed)
{
Connection.Open();
}
if (Tst != null)
{
Connection.EnlistTransaction(Tst);
}
DbCommand cm = GetCommand(Sql, Connection);
rlt = cm.ExecuteScalar();
return new ExecuteResult(rlt, null);
}
catch (TransactionException err)
{
if (Tst != null)
{
Tst.Rollback(err);
}
Exceptions.LogOnly(err);
return new ExecuteResult(null, err);
}
catch (Exception err)
{
if (Tst != null)
{
Tst.Rollback(err);
}
Exceptions.LogOnly(err);
return new ExecuteResult(null, err);
}
finally
{
Connection.Close();
}
}
public object ExecScalar(string Sql)
{
return ExecScalar(Sql, null, null).IntRlt as object;
}
public void EnumTables(TableEnumerationHandler callback)
{
DataTable dt = GetSchema("tables");
foreach (DataRow row in dt.Rows)
{
callback(row, "TABLE_NAME");
}
}
//public void EnumColumns(string tableName, ColumnEnumerationHandler callback)
//{
//}
public DataTable GetSchema()
{
return GetSchema(null);
}
public DataTable GetSchema(string collectionName)
{
DataTable dt;
DbConnection cn = GetConnection();
cn.Open();
if (string.IsNullOrEmpty(collectionName))
{
dt = cn.GetSchema();
}
else
{
dt = cn.GetSchema(collectionName);
}
cn.Close();
return dt;
}
public abstract DataAdapter GetAdapter(string Sql);
public virtual DbCommand GetCommand(string sql)
{
return GetCommand(sql, GetConnection());
}
public abstract DbCommand GetCommand(string Sql, DbConnection Connection);
public abstract DbCommand GetCommand(string Sql, DbConnection Connection, DbTransaction Transaction);
public abstract DbConnection GetConnectionSingleTry();
public virtual DbConnection GetConnection()
{
return GetConnection(5, 1000);
}
public virtual DbConnection GetConnection(int retryTimes, int waitInterval)
{
for (int i = 0; i < retryTimes; i++)
{
DbConnection rlt = GetConnectionSingleTry();
if (rlt != null)
{
return rlt;
}
else
{
Thread.Sleep(waitInterval);
}
}
return null;
}
public abstract DataColumnCollection GetColumnsInfo(string tableName);
}
}
| |
/*
Gaigen 2.5 Test Suite
*/
/*
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
using System;
namespace c3ga_ns {
/// <summary>This class can hold a general multivector.
///
/// The coordinates are stored in type double.
///
/// There are 4 coordinate groups:
/// group 0:1 (grade 0).
/// group 1:e1, e2, e3 (grade 1).
/// group 2:e1^e2, e1^e3, e2^e3 (grade 2).
/// group 3:e1^e2^e3 (grade 3).
///
/// 8 doubles are allocated inside the struct.
///
/// </summary>
public class mv : mv_if
{
/// <summary>
/// the coordinates
/// </summary>
protected internal double[][] m_c = new double[4][];
/// <summary>
/// Constructs a new mv with value 0.
/// </summary>
public mv() {Set();}
/// <summary>
/// Copy constructor.
/// </summary>
public mv(mv A) {Set(A);}
/// <summary>
/// Constructs a new mv with scalar value 'scalar'.
/// </summary>
public mv(double scalar) {Set(scalar);}
/// <summary>
/// Constructs a new mv from compressed 'coordinates'.
/// <param name="gu">bitwise OR of the GRADEs or GROUPs that are non-zero.</param>
/// <param name="coordinates"> compressed coordinates.</param>
/// </summary>
public mv(GroupBitmap gu, double[] coordinates) {Set(gu, coordinates);}
/// <summary>
/// Constructs a new mv from 'coordinates'.
/// <param name="coordinates">The coordinates (one array for each group, entries may be null). The arrays are kept.</param>
/// </summary>
public mv(double[][] coordinates) {Set(coordinates);}
/// <summary>
/// Converts a e1_t to a mv.
/// </summary>
public mv(e1_t A) {Set(A);}
/// <summary>
/// Converts a e2_t to a mv.
/// </summary>
public mv(e2_t A) {Set(A);}
/// <summary>
/// Converts a e3_t to a mv.
/// </summary>
public mv(e3_t A) {Set(A);}
/// <summary>
/// Converts a I3_t to a mv.
/// </summary>
public mv(I3_t A) {Set(A);}
/// <summary>
/// Converts a vector to a mv.
/// </summary>
public mv(vector A) {Set(A);}
/// <summary>
/// Converts a bivector to a mv.
/// </summary>
public mv(bivector A) {Set(A);}
/// <summary>
/// Converts a trivector to a mv.
/// </summary>
public mv(trivector A) {Set(A);}
/// <summary>
/// Converts a rotor to a mv.
/// </summary>
public mv(rotor A) {Set(A);}
/// <summary>
/// Converts a oddVersor to a mv.
/// </summary>
public mv(oddVersor A) {Set(A);}
/// <summary>
/// returns group usage bitmap
/// </summary>
public GroupBitmap gu() {
return
((m_c[0] == null) ? 0 : GroupBitmap.GROUP_0) |
((m_c[1] == null) ? 0 : GroupBitmap.GROUP_1) |
((m_c[2] == null) ? 0 : GroupBitmap.GROUP_2) |
((m_c[3] == null) ? 0 : GroupBitmap.GROUP_3) |
0;
}
/// <summary>
/// Returns array of array of coordinates.
/// Each entry contain the coordinates for one group/grade.
/// </summary>
public double[][] c() { return m_c; }
/// <summary>sets this to 0.
/// </summary>
public void Set() {
m_c[0] = null;
m_c[1] = null;
m_c[2] = null;
m_c[3] = null;
}
/// <summary>sets this to scalar value.
/// </summary>
public void Set(double val) {
AllocateGroups(GroupBitmap.GROUP_0);
m_c[0][0] = val;
}
/// <summary>sets this coordinates in 'arr'.
/// </summary>
/// <param name="gu">bitwise or of the GROUPs and GRADEs which are present in 'arr'.
/// </param>
/// <param name="arr">compressed coordinates.
/// </param>
public void Set(GroupBitmap gu, double[] arr) {
AllocateGroups(gu);
int idx = 0;
if ((gu & GroupBitmap.GROUP_0) != 0) {
for (int i = 0; i < 1; i++)
m_c[0][i] = arr[idx + i];
idx += 1;
}
if ((gu & GroupBitmap.GROUP_1) != 0) {
for (int i = 0; i < 3; i++)
m_c[1][i] = arr[idx + i];
idx += 3;
}
if ((gu & GroupBitmap.GROUP_2) != 0) {
for (int i = 0; i < 3; i++)
m_c[2][i] = arr[idx + i];
idx += 3;
}
if ((gu & GroupBitmap.GROUP_3) != 0) {
for (int i = 0; i < 1; i++)
m_c[3][i] = arr[idx + i];
idx += 1;
}
}
/// <summary>sets this coordinates in 'arr'.
/// 'arr' is kept, so changes to 'arr' will be reflected in the value of this multivector. Make sure 'arr' has length 4 and each subarray has the length of the respective group/grade
/// </summary>
/// <param name="arr">coordinates.
/// </param>
public void Set(double[][] arr) {
m_c = arr;
}
/// <summary>sets this to multivector value.
/// </summary>
public void Set(mv src) {
AllocateGroups(src.gu());
if (m_c[0] != null) {
c3ga.Copy_1(m_c[0], src.m_c[0]);
}
if (m_c[1] != null) {
c3ga.Copy_3(m_c[1], src.m_c[1]);
}
if (m_c[2] != null) {
c3ga.Copy_3(m_c[2], src.m_c[2]);
}
if (m_c[3] != null) {
c3ga.Copy_1(m_c[3], src.m_c[3]);
}
}
/// <summary>sets this to e1_t value.
/// </summary>
public void Set(e1_t src) {
AllocateGroups(GroupBitmap.GROUP_1);
double[] ptr;
ptr = m_c[1];
ptr[0] = 1.0;
ptr[1] = ptr[2] = 0.0;
}
/// <summary>sets this to e2_t value.
/// </summary>
public void Set(e2_t src) {
AllocateGroups(GroupBitmap.GROUP_1);
double[] ptr;
ptr = m_c[1];
ptr[0] = ptr[2] = 0.0;
ptr[1] = 1.0;
}
/// <summary>sets this to e3_t value.
/// </summary>
public void Set(e3_t src) {
AllocateGroups(GroupBitmap.GROUP_1);
double[] ptr;
ptr = m_c[1];
ptr[0] = ptr[1] = 0.0;
ptr[2] = 1.0;
}
/// <summary>sets this to I3_t value.
/// </summary>
public void Set(I3_t src) {
AllocateGroups(GroupBitmap.GROUP_3);
double[] ptr;
ptr = m_c[3];
ptr[0] = 1.0;
}
/// <summary>sets this to vector value.
/// </summary>
public void Set(vector src) {
AllocateGroups(GroupBitmap.GROUP_1);
double[] ptr;
ptr = m_c[1];
ptr[0] = src.m_e1;
ptr[1] = src.m_e2;
ptr[2] = src.m_e3;
}
/// <summary>sets this to bivector value.
/// </summary>
public void Set(bivector src) {
AllocateGroups(GroupBitmap.GROUP_2);
double[] ptr;
ptr = m_c[2];
ptr[0] = src.m_e1_e2;
ptr[1] = -src.m_e3_e1;
ptr[2] = src.m_e2_e3;
}
/// <summary>sets this to trivector value.
/// </summary>
public void Set(trivector src) {
AllocateGroups(GroupBitmap.GROUP_3);
double[] ptr;
ptr = m_c[3];
ptr[0] = src.m_e1_e2_e3;
}
/// <summary>sets this to rotor value.
/// </summary>
public void Set(rotor src) {
AllocateGroups(GroupBitmap.GROUP_0|GroupBitmap.GROUP_2);
double[] ptr;
ptr = m_c[0];
ptr[0] = src.m_scalar;
ptr = m_c[2];
ptr[0] = src.m_e1_e2;
ptr[1] = -src.m_e3_e1;
ptr[2] = src.m_e2_e3;
}
/// <summary>sets this to oddVersor value.
/// </summary>
public void Set(oddVersor src) {
AllocateGroups(GroupBitmap.GROUP_1|GroupBitmap.GROUP_3);
double[] ptr;
ptr = m_c[1];
ptr[0] = src.m_e1;
ptr[1] = src.m_e2;
ptr[2] = src.m_e3;
ptr = m_c[3];
ptr[0] = src.m_e1_e2_e3;
}
/// <summary>Returns the scalar coordinate of this mv
/// </summary>
public double get_scalar() {
return (m_c[0] == null) ? 0.0: m_c[0][0];
}
/// <summary>Returns the e1 coordinate of this mv
/// </summary>
public double get_e1() {
return (m_c[1] == null) ? 0.0: m_c[1][0];
}
/// <summary>Returns the e2 coordinate of this mv
/// </summary>
public double get_e2() {
return (m_c[1] == null) ? 0.0: m_c[1][1];
}
/// <summary>Returns the e3 coordinate of this mv
/// </summary>
public double get_e3() {
return (m_c[1] == null) ? 0.0: m_c[1][2];
}
/// <summary>Returns the e1_e2 coordinate of this mv
/// </summary>
public double get_e1_e2() {
return (m_c[2] == null) ? 0.0: m_c[2][0];
}
/// <summary>Returns the e1_e3 coordinate of this mv
/// </summary>
public double get_e1_e3() {
return (m_c[2] == null) ? 0.0: m_c[2][1];
}
/// <summary>Returns the e2_e3 coordinate of this mv
/// </summary>
public double get_e2_e3() {
return (m_c[2] == null) ? 0.0: m_c[2][2];
}
/// <summary>Returns the e1_e2_e3 coordinate of this mv
/// </summary>
public double get_e1_e2_e3() {
return (m_c[3] == null) ? 0.0: m_c[3][0];
}
/// <summary>
/// Reserves memory for the groups specified by 'gu'.
/// Keeps old memory (and values) when possible.
/// </summary>
private void AllocateGroups(GroupBitmap gu) {
for (int i = 0; (1 << i) <= (int)gu; i++) {
if (((1 << i) & (int)gu) != 0) {
if (m_c[i] == null)
m_c[i] = new double[c3ga.MvSize[1 << i]];
}
else m_c[i] = null;
}
}
/// <summary>
/// Reserves memory for coordinate GROUP_0.
/// If the group is already present, nothing changes.
/// If the group is not present, memory is allocated for the new group,
/// and the coordinates for the group are set to zero.
/// </summary>
private void ReserveGroup_0() {
if (m_c[0] == null) {
m_c[0] = new double[1];
}
}
/// <summary>
/// Reserves memory for coordinate GROUP_1.
/// If the group is already present, nothing changes.
/// If the group is not present, memory is allocated for the new group,
/// and the coordinates for the group are set to zero.
/// </summary>
private void ReserveGroup_1() {
if (m_c[1] == null) {
m_c[1] = new double[3];
}
}
/// <summary>
/// Reserves memory for coordinate GROUP_2.
/// If the group is already present, nothing changes.
/// If the group is not present, memory is allocated for the new group,
/// and the coordinates for the group are set to zero.
/// </summary>
private void ReserveGroup_2() {
if (m_c[2] == null) {
m_c[2] = new double[3];
}
}
/// <summary>
/// Reserves memory for coordinate GROUP_3.
/// If the group is already present, nothing changes.
/// If the group is not present, memory is allocated for the new group,
/// and the coordinates for the group are set to zero.
/// </summary>
private void ReserveGroup_3() {
if (m_c[3] == null) {
m_c[3] = new double[1];
}
}
/// Sets the scalar coordinate of this mv.
public void set_scalar(double val) {
ReserveGroup_0();
m_c[0][0] = val;
}
/// Sets the e1 coordinate of this mv.
public void set_e1(double val) {
ReserveGroup_1();
m_c[1][0] = val;
}
/// Sets the e2 coordinate of this mv.
public void set_e2(double val) {
ReserveGroup_1();
m_c[1][1] = val;
}
/// Sets the e3 coordinate of this mv.
public void set_e3(double val) {
ReserveGroup_1();
m_c[1][2] = val;
}
/// Sets the e1_e2 coordinate of this mv.
public void set_e1_e2(double val) {
ReserveGroup_2();
m_c[2][0] = val;
}
/// Sets the e1_e3 coordinate of this mv.
public void set_e1_e3(double val) {
ReserveGroup_2();
m_c[2][1] = val;
}
/// Sets the e2_e3 coordinate of this mv.
public void set_e2_e3(double val) {
ReserveGroup_2();
m_c[2][2] = val;
}
/// Sets the e1_e2_e3 coordinate of this mv.
public void set_e1_e2_e3(double val) {
ReserveGroup_3();
m_c[3][0] = val;
}
/// <summary>returns the absolute largest coordinate.</summary>
public double LargestCoordinate() {
double maxValue = 0.0, C;
for (int g = 0; g < m_c.Length; g++) {
if (m_c[g] != null) {
double[] Cg = m_c[g];
for (int b = 0; b < Cg.Length; b++) {
C = Math.Abs(Cg[b]);
if (C > maxValue) {
maxValue = C;
}
}
}
}
return maxValue;
}
/// <summary>returns the absolute largest coordinate and the corresponding basis blade bitmap (in 'bm') .</summary>
public double LargestBasisBlade(ref int bm) {
double maxC = -1.0, C;
int idx = 0; // global index into coordinates (run from 0 to 8).
bm = 0;
for (int g = 0; g < m_c.Length; g++) {
if (m_c[g] != null) {
double[] Cg = m_c[g];
for (int b = 0; b < m_c[g].Length; b++) {
C = Math.Abs(Cg[b]);
if (C > maxC) {
maxC = C;
bm = c3ga.BasisElementBitmapByIndex[idx];
}
idx++;
}
}
else idx += c3ga.GroupSize[g];
}
return maxC;
} // end of LargestBasisBlade()
/// <summary>Releases memory for (near-)zero groups/grades.
/// This also speeds up subsequent operations, because those do not have to process the released groups/grades anymore.
/// </summary>
/// <param name="eps">A positive threshold value.
/// Coordinates which are smaller than epsilon are considered to be zero.
/// </param>
public void Compress(double eps) {
if ((m_c[0] != null) && c3ga.zeroGroup_0(m_c[0], eps))
m_c[0] = null;
if ((m_c[1] != null) && c3ga.zeroGroup_1(m_c[1], eps))
m_c[1] = null;
if ((m_c[2] != null) && c3ga.zeroGroup_2(m_c[2], eps))
m_c[2] = null;
if ((m_c[3] != null) && c3ga.zeroGroup_3(m_c[3], eps))
m_c[3] = null;
}
/// <summary>
/// Returns this multivector, converted to a string.
/// The floating point formatter is controlled via c3ga.setStringFormat().
/// </summary>
public override string ToString() {
return c3ga.String(this);
}
/// <summary>
/// Returns this multivector, converted to a string.
/// The floating point formatter is "F".
/// </summary>
public string ToString_f() {
return ToString("F");
}
/// <summary>
/// Returns this multivector, converted to a string.
/// The floating point formatter is "E".
/// </summary>
public string ToString_e() {
return ToString("E");
}
/// <summary>
/// Returns this multivector, converted to a string.
/// The floating point formatter is "E20".
/// </summary>
public string ToString_e20() {
return ToString("E20");
}
/// <summary>
/// Returns this multivector, converted to a string.
/// <param name="fp">floating point format. Use 'null' for the default format (see setStringFormat()).</param>
/// </summary>
public string ToString(string fp) {
return c3ga.String(this, fp);
}
/// <summary>
/// Converts this multivector to a 'mv' (implementation of interface 'mv_interface')
/// </summary>
public mv to_mv()
{
return this;
}
} // end of class mv
} // end of namespace c3ga_ns
| |
// 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.IO;
using System.Xml;
using System.Collections;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class has static methods to determine line numbers and column numbers for given
/// XML nodes.
/// </summary>
/// <owner>RGoel</owner>
internal static class XmlSearcher
{
/// <summary>
/// Given an XmlNode belonging to a document that lives on disk, this method determines
/// the line/column number of that node in the document. It does this by re-reading the
/// document from disk and searching for the given node.
/// </summary>
/// <param name="xmlNodeToFind">Any XmlElement or XmlAttribute node (preferably in a document that still exists on disk).</param>
/// <param name="foundLineNumber">(out) The line number where the specified node begins.</param>
/// <param name="foundColumnNumber">(out) The column number where the specified node begins.</param>
/// <returns>true if found, false otherwise. Should not throw any exceptions.</returns>
/// <owner>RGoel</owner>
internal static bool GetLineColumnByNode
(
XmlNode xmlNodeToFind,
out int foundLineNumber,
out int foundColumnNumber
)
{
// Initialize the output parameters.
foundLineNumber = 0;
foundColumnNumber = 0;
if (xmlNodeToFind == null)
{
return false;
}
// Get the filename where this XML node came from. Make sure it still
// exists on disk. If not, there's nothing we can do. Sorry.
string fileName = XmlUtilities.GetXmlNodeFile(xmlNodeToFind, String.Empty);
if ((fileName.Length == 0) || (!File.Exists(fileName)))
{
return false;
}
// Next, we need to compute the "element number" and "attribute number" of
// the given XmlNode in its original container document. Element number is
// simply a 1-based number identifying a particular XML element starting from
// the beginning of the document, ignoring depth. As you're walking the tree,
// visiting each node in order, and recursing deeper whenever possible, the Nth
// element you visit has element number N. Attribute number is simply the
// 1-based index of the attribute within the given Xml element. An attribute
// number of zero indicates that we're not searching for a particular attribute,
// and all we care about is the element as a whole.
int elementNumber;
int attributeNumber;
if (!GetElementAndAttributeNumber(xmlNodeToFind, out elementNumber, out attributeNumber))
{
return false;
}
// Now that we know what element/attribute number we're searching for, find
// it in the Xml document on disk, and grab the line/column number.
return GetLineColumnByNodeNumber(fileName, elementNumber, attributeNumber,
out foundLineNumber, out foundColumnNumber);
}
/// <summary>
/// Determines the element number and attribute number of a given XmlAttribute node,
/// or just the element number for a given XmlElement node.
/// </summary>
/// <param name="xmlNodeToFind">Any XmlElement or XmlAttribute within an XmlDocument.</param>
/// <param name="elementNumber">(out) The element number of the given node.</param>
/// <param name="attributeNumber">(out) If the given node was an XmlAttribute node, then the attribute number of that node, otherwise zero.</param>
/// <returns>true if found, false otherwise. Should not throw any exceptions.</returns>
/// <owner>RGoel</owner>
internal static bool GetElementAndAttributeNumber
(
XmlNode xmlNodeToFind,
out int elementNumber,
out int attributeNumber
)
{
ErrorUtilities.VerifyThrow(xmlNodeToFind != null, "No Xml node!");
// Initialize output parameters.
elementNumber = 0;
attributeNumber = 0;
XmlNode elementToFind;
// First determine the XmlNode in the main hierarchy to search for. If the passed-in
// node is already an XmlElement or Text node, then we already have the node
// that we're searching for. But if the passed-in node is an XmlAttribute, then
// we want to search for the XmlElement that contains that attribute.
// If the node is any other type, try the parent node. It's a better line number than no line number.
if ((xmlNodeToFind.NodeType != XmlNodeType.Element) &&
(xmlNodeToFind.NodeType != XmlNodeType.Text) &&
(xmlNodeToFind.NodeType != XmlNodeType.Attribute))
{
if (xmlNodeToFind.ParentNode != null)
{
xmlNodeToFind = xmlNodeToFind.ParentNode;
}
}
if ((xmlNodeToFind.NodeType == XmlNodeType.Element) || (xmlNodeToFind.NodeType == XmlNodeType.Text))
{
elementToFind = xmlNodeToFind;
}
else if (xmlNodeToFind.NodeType == XmlNodeType.Attribute)
{
elementToFind = ((XmlAttribute) xmlNodeToFind).OwnerElement;
ErrorUtilities.VerifyThrow(elementToFind != null, "How can an xml attribute not have a parent?");
}
else
{
// We don't support searching for anything other than XmlAttribute, XmlElement, or text node.
return false;
}
// Figure out the element number for this particular XML element, by iteratively
// visiting every single node in the XmlDocument in sequence. Start with the
// root node which is the XmlDocument node.
XmlNode xmlNode = xmlNodeToFind.OwnerDocument;
while (true)
{
// If the current node is an XmlElement or text node, bump up our variable which tracks the
// number of XmlElements visited so far.
if ((xmlNode.NodeType == XmlNodeType.Element) || (xmlNode.NodeType == XmlNodeType.Text))
{
elementNumber++;
// If the current XmlElement node is actually the one the caller wanted
// us to search for, then we've found the element number. Yippee.
if (xmlNode == elementToFind)
{
break;
}
}
// The rest of this is all about moving to the next node in the tree.
if (xmlNode.HasChildNodes)
{
// If the current node has any children, then the next node to visit
// is the first child.
xmlNode = xmlNode.FirstChild;
}
else
{
// Current node has no children. So we basically want its next
// sibling. Unless of course it has no more siblings, in which
// case we want its parent's next sibling. Unless of course its
// parent doesn't have any more siblings, in which case we want
// its parent's parent's sibling. Etc, etc.
while ((xmlNode != null) && (xmlNode.NextSibling == null))
{
xmlNode = xmlNode.ParentNode;
}
if (xmlNode == null)
{
// Oops, we reached the end of the document, so bail.
break;
}
else
{
xmlNode = xmlNode.NextSibling;
}
}
}
if (xmlNode == null)
{
// We visited every XmlElement in the document without finding the
// specific XmlElement we were supposed to. Oh well, too bad.
elementNumber = 0;
return false;
}
// If we were originally asked to actually find an XmlAttribute within
// an XmlElement, now comes Part 2. We've already found the correct
// element, so now we just need to iterate through the attributes within
// the element in order until we find the desired one.
if (xmlNodeToFind.NodeType == XmlNodeType.Attribute)
{
bool foundAttribute = false;
XmlAttribute xmlAttributeToFind = xmlNodeToFind as XmlAttribute;
foreach (XmlAttribute xmlAttribute in ((XmlElement)elementToFind).Attributes)
{
attributeNumber++;
if (xmlAttribute == xmlAttributeToFind)
{
foundAttribute = true;
break;
}
}
if (!foundAttribute)
{
return false;
}
}
return true;
}
/// <summary>
/// Read through the entire XML of a given project file, searching for the element/attribute
/// specified by element number and attribute number. Return the line number and column
/// number where it was found.
/// </summary>
/// <param name="projectFile">Path to project file on disk.</param>
/// <param name="xmlElementNumberToSearchFor">Which Xml element to search for.</param>
/// <param name="xmlAttributeNumberToSearchFor">
/// Which Xml attribute within the above Xml element to search for. Pass in zero
/// if you are searching for the Element as a whole and not a particular attribute.
/// </param>
/// <param name="foundLineNumber">(out) The line number where the given element/attribute begins.</param>
/// <param name="foundColumnNumber">The column number where the given element/attribute begins.</param>
/// <returns>true if found, false otherwise. Should not throw any exceptions.</returns>
/// <owner>RGoel</owner>
internal static bool GetLineColumnByNodeNumber
(
string projectFile,
int xmlElementNumberToSearchFor,
int xmlAttributeNumberToSearchFor,
out int foundLineNumber,
out int foundColumnNumber
)
{
ErrorUtilities.VerifyThrow(xmlElementNumberToSearchFor != 0, "No element to search for!");
ErrorUtilities.VerifyThrow((projectFile != null) && (projectFile.Length != 0), "No project file!");
// Initialize output parameters.
foundLineNumber = 0;
foundColumnNumber = 0;
try
{
// We're going to need to re-read the file from disk in order to find
// the line/column number of the specified node.
using (XmlTextReader reader = new XmlTextReader(projectFile))
{
reader.DtdProcessing = DtdProcessing.Ignore;
int currentXmlElementNumber = 0;
// While we haven't reached the end of the file, and we haven't found the
// specified node ...
while (reader.Read() && (foundColumnNumber == 0) && (foundLineNumber == 0))
{
// Read to the next node. If it is an XML element or Xml text node, then ...
if ((reader.NodeType == XmlNodeType.Element) || (reader.NodeType == XmlNodeType.Text))
{
// Bump up our current XML element count.
currentXmlElementNumber++;
// Check to see if this XML element is the one we've been searching for,
// based on if the numbers match.
if (currentXmlElementNumber == xmlElementNumberToSearchFor)
{
// We've found the desired XML element. If the caller didn't care
// for a particular attribute, then we're done. Return the current
// position of the XmlTextReader.
if (0 == xmlAttributeNumberToSearchFor)
{
foundLineNumber = reader.LineNumber;
foundColumnNumber = reader.LinePosition;
if (reader.NodeType == XmlNodeType.Element)
{
// Do a minus-one here, because the XmlTextReader points us at the first
// letter of the tag name, whereas we would prefer to point at the opening
// left-angle-bracket. (Whitespace between the left-angle-bracket and
// the tag name is not allowed in XML, so this is safe.)
foundColumnNumber = foundColumnNumber - 1;
}
}
else if (reader.MoveToFirstAttribute())
{
// Caller wants a particular attribute within the element,
// and the element does have 1 or more attributes. So let's
// try to find the right one.
int currentXmlAttributeNumber = 0;
// Loop through all the XML attributes on the current element.
do
{
// Bump the current attribute number and check to see if this
// is the one.
currentXmlAttributeNumber++;
if (currentXmlAttributeNumber == xmlAttributeNumberToSearchFor)
{
// We found the desired attribute. Return the current
// position of the XmlTextReader.
foundLineNumber = reader.LineNumber;
foundColumnNumber = reader.LinePosition;
}
} while (reader.MoveToNextAttribute() && (foundColumnNumber == 0) && (foundLineNumber == 0));
}
}
}
}
}
}
catch (XmlException)
{
// Eat the exception. If anything fails, we simply don't surface the line/column number.
}
catch (IOException)
{
// Eat the exception. If anything fails, we simply don't surface the line/column number.
}
catch (UnauthorizedAccessException)
{
// Eat the exception. If anything fails, we simply don't surface the line/column number.
}
return ((foundColumnNumber != 0) && (foundLineNumber != 0));
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim 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 OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System.Diagnostics;
using System.Timers;
using log4net;
using System.Reflection;
namespace OpenSim.Region.CoreModules.Agent.Xfer
{
public class XferModule : IRegionModule, IXfer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
private Dictionary<string, FileData> NewFiles = new Dictionary<string, FileData>();
private Dictionary<ulong, XferDownLoad> Transfers = new Dictionary<ulong, XferDownLoad>();
private class FileData
{
public byte[] Data;
public int Count;
}
private const int TIMEOUT_CHECK_INTERVAL = 1000;
private Timer _timeoutTimer;
#region IRegionModule Members
public void Initialize(Scene scene, IConfigSource config)
{
m_scene = scene;
m_scene.EventManager.OnNewClient += NewClient;
m_scene.RegisterModuleInterface<IXfer>(this);
_timeoutTimer = new Timer(TIMEOUT_CHECK_INTERVAL);
_timeoutTimer.Elapsed += new ElapsedEventHandler(_timeoutTimer_Elapsed);
_timeoutTimer.Start();
}
public void PostInitialize()
{
}
public void Close()
{
_timeoutTimer.Stop();
}
public string Name
{
get { return "XferModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
#region IXfer Members
public bool AddNewFile(string fileName, byte[] data)
{
lock (NewFiles)
{
if (NewFiles.ContainsKey(fileName))
{
NewFiles[fileName].Count++;
NewFiles[fileName].Data = data;
// m_log.WarnFormat("[Xfer]: Add({0}) {1}", NewFiles[fileName].Count, fileName);
}
else
{
FileData fd = new FileData();
fd.Count = 1;
fd.Data = data;
NewFiles.Add(fileName, fd);
// m_log.WarnFormat("[Xfer]: Added {0}", fileName);
}
}
return true;
}
#endregion
private void _timeoutTimer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
//disable the timer so that we don't get reentry
_timeoutTimer.Enabled = false;
lock (NewFiles)
{
List<ulong> deadXferIds = new List<ulong>();
foreach (XferModule.XferDownLoad download in Transfers.Values)
{
if (download.WindowTimeout)
{
if (download.XferTimeout || download.RetriesExceeded)
{
//the whole transfer is is taking too long and must be stopped
m_log.ErrorFormat("[Xfer] Canceling transfer {0} for {1} due to timeout", download.FileName, download.Client.Name);
//download.Client.SendAlertMessage("Transfer has failed to complete, please try again");
const int ERR_TIMEOUT = -23016;
download.Client.SendAbortXfer(download.XferID, ERR_TIMEOUT);
deadXferIds.Add(download.XferID);
}
else
{
//we need to resend the current window
download.ResendCurrentWindow();
}
}
}
foreach (ulong deadXferId in deadXferIds)
{
Transfers.Remove(deadXferId);
}
// m_log.WarnFormat("[Xfer]: Removed ID {0}", deadXferId);
}
}
finally
{
//reenable the timer
_timeoutTimer.Enabled = true;
}
}
public void NewClient(IClientAPI client)
{
client.OnRequestXfer += RequestXfer;
client.OnConfirmXfer += AckPacket;
client.OnAbortXfer += AbortXfer;
}
/// <summary>
///
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="xferID"></param>
/// <param name="fileName"></param>
public void RequestXfer(IClientAPI remoteClient, ulong xferID, string fileName)
{
lock (NewFiles)
{
if (NewFiles.ContainsKey(fileName))
{
if (!Transfers.ContainsKey(xferID))
{
byte[] fileData = NewFiles[fileName].Data;
XferDownLoad transaction = new XferDownLoad(fileName, fileData, xferID, remoteClient);
// m_log.WarnFormat("[Xfer]: Requested ID {0} {1}", xferID, fileName);
Transfers.Add(xferID, transaction);
transaction.StartSend();
// The transaction for this file is either complete or on its way
RemoveOrDecrement(fileName);
}
}
else
{
m_log.WarnFormat("[Xfer]: {0} not found", fileName);
}
}
}
public void AbortXfer(IClientAPI remoteClient, ulong xferID)
{
// m_log.WarnFormat("[Xfer]: Abort ID {0}", xferID);
lock (NewFiles)
{
if (Transfers.ContainsKey(xferID))
RemoveOrDecrement(Transfers[xferID].FileName);
Transfers.Remove(xferID);
}
}
public void AckPacket(IClientAPI remoteClient, ulong xferID, uint packet)
{
lock (NewFiles)
{
if (Transfers.ContainsKey(xferID))
{
if (Transfers[xferID].AckPacket(packet))
{
Transfers.Remove(xferID);
}
}
}
}
private void RemoveOrDecrement(string fileName)
{
// NewFiles must be locked
if (NewFiles.ContainsKey(fileName))
{
// m_log.WarnFormat("[Xfer]: Remove({0}) {1}", NewFiles[fileName].Count, fileName);
if (NewFiles[fileName].Count == 1)
NewFiles.Remove(fileName);
else
NewFiles[fileName].Count--;
}
}
public class XferDownLoad : IComparable<XferDownLoad>
{
public const int WINDOW_SIZE = 8;
public const int CHUNK_SIZE = 1000;
public const int WINDOW_ACK_TIMEOUT = 3 * 1000;
public const int MAX_WINDOW_RETRIES = 5;
public const int MIN_TRANSFER_RATE_BYTES_SEC = 750;
public const int MIN_XFER_TIMEOUT = 15000;
private enum AckState : byte
{
UNACKED_UNSENT,
UNACKED_SENT,
ACKED
}
public IClientAPI Client;
public byte[] Data = new byte[0];
public string FileName = String.Empty;
public uint Serial = 1;
public ulong XferID = 0;
private bool _sendComplete;
private ulong _transferQueuedOn = Util.GetLongTickCount();
private ulong _lastWindowTransmission = Util.GetLongTickCount();
private ulong _xferTimeoutTime;
private uint _windowLeftEdge = 0;
private AckState[] _windowAcks = new AckState[WINDOW_SIZE];
private int _windowRetryCount = 0;
private uint _currentWindowSize = WINDOW_SIZE;
private uint _desiredWindowSize = WINDOW_SIZE;
public XferDownLoad(string fileName, byte[] data, ulong xferID, IClientAPI client)
{
// m_log.DebugFormat("[Xfer]: XferDownload ID {0} {1}", xferID, fileName);
FileName = fileName;
Data = data;
XferID = xferID;
Client = client;
ulong calculatedXferTimeout = (ulong)((data.Length / MIN_TRANSFER_RATE_BYTES_SEC) * 1000);
_xferTimeoutTime = Util.GetLongTickCount() + Math.Max(calculatedXferTimeout, MIN_XFER_TIMEOUT);
}
public XferDownLoad()
{
}
public bool WindowTimeout
{
get
{
return _lastWindowTransmission + WINDOW_ACK_TIMEOUT < Util.GetLongTickCount();
}
}
public bool XferTimeout
{
get
{
return _xferTimeoutTime < Util.GetLongTickCount();
}
}
public bool RetriesExceeded
{
get
{
return _windowRetryCount > MAX_WINDOW_RETRIES;
}
}
/// <summary>
/// Start a transfer
/// </summary>
/// <returns>True if the transfer is complete, false if not</returns>
public void StartSend()
{
SendToWindowEdge(_currentWindowSize);
}
private uint DataPointerFromPacketNum(uint packetNum)
{
return packetNum * CHUNK_SIZE;
}
private void SendToWindowEdge(uint edgeRoom)
{
for (uint i = _currentWindowSize - edgeRoom; i < _currentWindowSize; i++)
{
//for each unacked window slot, send the corresponding packet
bool finalPacket = SendChunk(i);
_windowAcks[i] = AckState.UNACKED_SENT;
if (finalPacket)
{
_sendComplete = true;
break;
}
}
_lastWindowTransmission = Util.GetLongTickCount();
}
private bool SendChunk(uint i)
{
uint packetNum = _windowLeftEdge + i;
uint dataPointer = DataPointerFromPacketNum(packetNum);
//determine the size of the chunk to be sent and if this is the final packet
uint dataSize;
bool finalPacket;
if ((Data.Length - dataPointer) > CHUNK_SIZE)
{
dataSize = CHUNK_SIZE;
finalPacket = false;
}
else
{
//if the remaining size is less than or equal to the max chunk size, this
//is the final packet
dataSize = (uint)Data.Length - dataPointer;
finalPacket = true;
}
//use to simulate random packet drops
/*if (rnd1.Next(10) == 0)
{
return finalPacket;
}*/
//------------------------------------
uint totalSize = dataSize;
bool doEncodeSize = packetNum == 0;
if (doEncodeSize)
{
totalSize += 4;
}
byte[] transferData = new byte[totalSize];
if (doEncodeSize) Array.Copy(Utils.IntToBytes(Data.Length), 0, transferData, 0, 4);
Array.Copy(Data, dataPointer, transferData, doEncodeSize ? 4 : 0, dataSize);
if (finalPacket) packetNum |= (uint)0x80000000;
Client.SendXferPacket(XferID, packetNum, transferData);
return finalPacket;
}
//use to simulate random packet drops
//private Random rnd1 = new Random();
/// <summary>
/// Respond to an ack packet from the client
/// </summary>
/// <param name="packet"></param>
/// <returns>True if the transfer is complete, false otherwise</returns>
public bool AckPacket(uint packet)
{
//use to simulate random packet drops
/*if (rnd1.Next(10) == 0)
{
return false;
}*/
//------------------------------------
//make sure the ack is inside the window
if (packet >= _windowLeftEdge
&& packet < _windowLeftEdge + _currentWindowSize)
{
//slide the window forward to the last ack
//and send more data
_windowAcks[packet - _windowLeftEdge] = AckState.ACKED;
if (! _sendComplete)
{
uint amt = SlideWindowForward(packet - _windowLeftEdge + 1);
if (amt > 0) SendToWindowEdge(amt);
}
if (_sendComplete && this.WindowFullyAcked())
{
// m_log.DebugFormat("[Xfer]: XferDownload ID {0} {1} completed", this.XferID, this.FileName);
return true;
}
}
return false;
}
private bool WindowFullyAcked()
{
if (Data.Length == 0)
{
return true;
}
uint numPackets = (uint)Math.Ceiling(Data.Length / (float)CHUNK_SIZE);
uint windowLastSlot = numPackets - _windowLeftEdge - 1;
if (_windowAcks[windowLastSlot] == AckState.ACKED)
{
return true;
}
return false;
}
private uint SlideWindowForward(uint slideAmount)
{
_windowLeftEdge += slideAmount;
for (uint i = 0; i < _currentWindowSize; i++)
{
if (i + slideAmount < _currentWindowSize)
{
_windowAcks[i] = _windowAcks[i+slideAmount];
}
else
{
_windowAcks[i] = AckState.UNACKED_UNSENT;
}
}
_windowRetryCount = 0;
if (_currentWindowSize > _desiredWindowSize)
{
//adjust the current window by either the difference in the current window and this
//window, or by the slide amount, whichever is lesser (shrinks the window from the left)
uint windowAdjustment = Math.Min(slideAmount, _currentWindowSize - _desiredWindowSize);
_currentWindowSize -= windowAdjustment;
//if the slide is greater than the window difference, we can send the new open right
//of the window
return slideAmount - windowAdjustment;
}
else
{
return slideAmount;
}
}
/// <summary>
/// for use in a priority queue
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int CompareTo(XferDownLoad other)
{
if (_lastWindowTransmission < other._lastWindowTransmission)
{
return -1;
}
if (_lastWindowTransmission > other._lastWindowTransmission)
{
return 1;
}
return 0;
}
internal void ResendCurrentWindow()
{
_windowRetryCount++;
// m_log.DebugFormat("[XFER]: Resending window (retry #{0}) for {1} after timeout. Window size: {2}", _windowRetryCount, this.Client.Name, _currentWindowSize);
if (_currentWindowSize > 1)
{
_desiredWindowSize = _currentWindowSize / 2;
}
for (int i = 0; i < _currentWindowSize; i++)
{
_windowAcks[i] = AckState.UNACKED_UNSENT;
}
_sendComplete = false;
SendToWindowEdge(_currentWindowSize);
}
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using Agens.Stickers;
namespace Agens.StickersEditor
{
[CustomEditor(typeof(Sticker))]
public class StickerEditor : Editor
{
private SerializedProperty Frames;
private SerializedProperty Sequence;
private SerializedProperty Name;
private SerializedProperty Fps;
private SerializedProperty Repetitions;
private static GUIContent[] s_PlayIcons = new GUIContent[2];
private List<Editor> textureEditors;
private MethodInfo RepaintMethod;
private object GUIView;
private Editor currentTextureEditor
{
get
{
if (textureEditors == null)
{
CreateTextureEditor();
}
if (!playing)
{
return textureEditors[0];
}
var index = AnimatedIndex(Frames, Fps);
if (index < textureEditors.Count)
{
return textureEditors[index];
}
return null;
}
}
public static int AnimatedIndex(SerializedProperty frames, SerializedProperty fps)
{
var length = frames.arraySize / (float)fps.intValue;
var time = (float)Wrap(EditorApplication.timeSinceStartup, 0, length);
var normalized = Mathf.InverseLerp(0, length, time);
var frameIndex = Mathf.FloorToInt(normalized * frames.arraySize);
return frameIndex;
}
private static double Wrap(double number, double min, double max)
{
return ((number - min) % (max - min)) + min;
}
private void OnEnable()
{
Frames = serializedObject.FindProperty("Frames");
Sequence = serializedObject.FindProperty("Sequence");
Name = serializedObject.FindProperty("Name");
Fps = serializedObject.FindProperty("Fps");
Repetitions = serializedObject.FindProperty("Repetitions");
s_PlayIcons[0] = EditorGUIUtility.IconContent("preAudioPlayOff", "Play");
s_PlayIcons[1] = EditorGUIUtility.IconContent("preAudioPlayOn", "Stop");
}
public static void AddStickerSequence(SerializedProperty sequence, SerializedProperty name, SerializedProperty fps, SerializedProperty frames)
{
var path = EditorUtility.OpenFilePanelWithFilters("Select Sticker Sequence", string.Empty, new string[] { "Image", "png,gif,jpg,jpeg" });
var folder = Path.GetDirectoryName(path);
//var folder = EditorUtility.OpenFolderPanel("Select Sticker Sequence", string.Empty, string.Empty);
Debug.Log("path: " + path + " folder: " + folder);
var files = Directory.GetFiles(folder, "*.*", SearchOption.TopDirectoryOnly)
.Where(StickerEditorUtility.HasValidFileExtension).ToList();
files.Sort();
sequence.boolValue = true;
var dir = new DirectoryInfo(folder);
name.stringValue = dir.Name;
fps.intValue = 15;
frames.arraySize = files.Count;
for (int index = 0; index < files.Count; index++)
{
var file = files[index];
var projectPath = Application.dataPath;
var filePath = file.Replace(projectPath, "Assets");
Debug.Log("loaded texture at " + filePath);
var asset = AssetDatabase.LoadAssetAtPath<Texture2D>(filePath);
var prop = frames.GetArrayElementAtIndex(index);
prop.objectReferenceValue = asset;
}
}
private static bool playing;
public override void OnPreviewSettings()
{
playing = CycleButton(!playing ? 0 : 1, s_PlayIcons, "preButton") != 0;
if (textureEditors == null)
{
CreateTextureEditor();
}
if (currentTextureEditor != null)
{
currentTextureEditor.OnPreviewSettings();
}
}
static int CycleButton(int selected, GUIContent[] options, GUIStyle style)
{
if (GUILayout.Button(options[selected], style))
{
++selected;
if (selected >= options.Length)
selected = 0;
}
return selected;
}
public override bool HasPreviewGUI()
{
var sticker = serializedObject;
var frames = sticker.FindProperty("Frames");
return frames.arraySize > 0;
}
public override void OnInteractivePreviewGUI(Rect r, GUIStyle background)
{
if (textureEditors == null || textureEditors.Count == 0)
{
CreateTextureEditor();
}
if (currentTextureEditor != null)
{
currentTextureEditor.OnInteractivePreviewGUI(r, background);
}
if (playing && Sequence.boolValue && Frames.arraySize > 1)
{
if (RepaintMethod == null)
{
var type = typeof(Editor).Assembly.GetType("UnityEditor.GUIView");
var prop = type.GetProperty("current", BindingFlags.Static | BindingFlags.Public);
GUIView = prop.GetValue(null, null);
RepaintMethod = GUIView.GetType().GetMethod("Repaint", BindingFlags.Public | BindingFlags.Instance);
}
RepaintMethod.Invoke(GUIView, null);
}
}
public override string GetInfoString()
{
if (textureEditors == null || textureEditors.Count == 0)
{
CreateTextureEditor();
}
if (currentTextureEditor != null)
{
return currentTextureEditor.GetInfoString();
}
return string.Empty;
}
private void CreateTextureEditor()
{
var sticker = serializedObject;
var frames = sticker.FindProperty("Frames");
textureEditors = new List<Editor>(frames.arraySize);
for (int i = 0; i < frames.arraySize; i++)
{
var firstFrame = frames.GetArrayElementAtIndex(i);
var texture = firstFrame.objectReferenceValue as Texture2D;
if (texture != null)
{
textureEditors.Add(CreateEditor(texture));
}
else
{
textureEditors.Add(null);
}
}
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.PropertyField(Name);
EditorGUI.EndDisabledGroup();
var rect = GUILayoutUtility.GetRect(new GUIContent(Sequence.displayName, Sequence.tooltip), GUIStyle.none, GUILayout.Height(20));
var sequenceRect = new Rect(rect);
sequenceRect.width = EditorGUIUtility.labelWidth + 20f;
EditorGUI.PropertyField(sequenceRect, Sequence);
#if UNITY_5_4_OR_NEWER
using (new EditorGUI.DisabledScope(playing))
#else
EditorGUI.BeginDisabledGroup(playing);
#endif
{
rect.xMin = sequenceRect.xMax;
if (GUI.Button(rect, "Load from Folder"))
{
AddStickerSequence(Sequence, Name, Fps, Frames);
}
EditorGUILayout.PropertyField(Fps);
EditorGUILayout.PropertyField(Repetitions);
}
#if !UNITY_5_4_OR_NEWER
EditorGUI.EndDisabledGroup();
#endif
if (Frames.arraySize == 0)
{
Frames.InsertArrayElementAtIndex(0);
}
if (!Sequence.boolValue && Frames.arraySize > 1)
{
Frames.arraySize = 1;
}
EditorGUI.BeginChangeCheck();
DrawFrame();
if (EditorGUI.EndChangeCheck())
{
CreateTextureEditor();
}
serializedObject.ApplyModifiedProperties();
}
private void DrawFrame()
{
if (Sequence.boolValue)
{
EditorGUILayout.PropertyField(Frames, true);
}
else
{
EditorGUILayout.PropertyField(Frames.GetArrayElementAtIndex(0), new GUIContent("Frame"));
}
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Interception
{
using System.Data.Common;
using System.Data.Entity.Core;
using System.Data.Entity.Core.Common;
using System.Data.Entity.Core.EntityClient;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Infrastructure.Interception;
using System.Data.Entity.SqlServer;
using System.Data.Entity.TestHelpers;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Xunit;
public class CommitFailureTests : FunctionalTestBase
{
[Fact]
public void CommitFailureHandler_ClearTransactionHistory_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory());
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
[Fact]
public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_commit_fail()
{
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory());
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 1,
useTransactionHandler: false,
useExecutionStrategy: false,
rollbackOnFail: true);
}
[Fact]
public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 2,
useTransactionHandler: false,
useExecutionStrategy: false,
rollbackOnFail: false);
}
[Fact]
[UseDefaultExecutionStrategy]
public void TransactionHandler_and_no_ExecutionStrategy_rethrows_original_exception_on_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<TimeoutException>(() => c()),
c =>
{
var exception = Assert.Throws<EntityException>(() => c());
Assert.IsType<TimeoutException>(exception.InnerException);
},
expectedBlogs: 1,
useTransactionHandler: true,
useExecutionStrategy: false,
rollbackOnFail: true);
}
[Fact]
public void TransactionHandler_and_no_ExecutionStrategy_does_not_throw_on_false_commit_fail()
{
Execute_commit_failure_test(
c => c(),
c => c(),
expectedBlogs: 2,
useTransactionHandler: true,
useExecutionStrategy: false,
rollbackOnFail: false);
}
[Fact]
public void No_TransactionHandler_and_ExecutionStrategy_throws_CommitFailedException_on_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 1,
useTransactionHandler: false,
useExecutionStrategy: true,
rollbackOnFail: true);
}
[Fact]
public void No_TransactionHandler_and_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 2,
useTransactionHandler: false,
useExecutionStrategy: true,
rollbackOnFail: false);
}
[Fact]
public void TransactionHandler_and_ExecutionStrategy_retries_on_commit_fail()
{
Execute_commit_failure_test(
c => c(),
c => c(),
expectedBlogs: 2,
useTransactionHandler: true,
useExecutionStrategy: true,
rollbackOnFail: true);
}
private void Execute_commit_failure_test(
Action<Action> verifyInitialization, Action<Action> verifySaveChanges, int expectedBlogs, bool useTransactionHandler,
bool useExecutionStrategy, bool rollbackOnFail)
{
var failingTransactionInterceptorMock = new Mock<FailingTransactionInterceptor> { CallBase = true };
var failingTransactionInterceptor = failingTransactionInterceptorMock.Object;
DbInterception.Add(failingTransactionInterceptor);
if (useTransactionHandler)
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
}
if (useExecutionStrategy)
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key =>
(Func<IDbExecutionStrategy>)
(() => new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1))));
}
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = rollbackOnFail;
verifyInitialization(() => context.Blogs.Count());
failingTransactionInterceptor.ShouldFailTimes = 0;
Assert.Equal(1, context.Blogs.Count());
failingTransactionInterceptor.ShouldFailTimes = 1;
context.Blogs.Add(new BlogContext.Blog());
verifySaveChanges(() => context.SaveChanges());
failingTransactionInterceptorMock.Verify(
m => m.Committing(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext>()),
Times.Exactly(
useTransactionHandler
? useExecutionStrategy
? 6
: rollbackOnFail
? 4
: 3
: 4));
}
using (var context = new BlogContextCommit())
{
Assert.Equal(expectedBlogs, context.Blogs.Count());
using (var transactionContext = new TransactionContext(context.Database.Connection))
{
using (var infoContext = GetInfoContext(transactionContext))
{
Assert.True(
!infoContext.TableExists("__Transactions")
|| !transactionContext.Transactions.Any());
}
}
}
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
context => context.SaveChanges());
}
#if !NET40
[Fact]
public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_async()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
context => context.SaveChangesAsync().Wait());
}
#endif
[Fact]
public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_with_custom_TransactionContext()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(c => new MyTransactionContext(c)), null, null));
TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
context =>
{
context.SaveChanges();
using (var infoContext = GetInfoContext(context))
{
Assert.True(infoContext.TableExists("MyTransactions"));
var column = infoContext.Columns.Single(c => c.Name == "Time");
Assert.Equal("datetime2", column.Type);
}
});
}
public class MyTransactionContext : TransactionContext
{
public MyTransactionContext(DbConnection connection)
: base(connection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TransactionRow>()
.ToTable("MyTransactions")
.HasKey(e => e.Id)
.Property(e => e.CreationTime).HasColumnName("Time").HasColumnType("datetime2");
}
}
private void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
Action<BlogContextCommit> runAndVerify)
{
var failingTransactionInterceptorMock = new Mock<FailingTransactionInterceptor> { CallBase = true };
var failingTransactionInterceptor = failingTransactionInterceptorMock.Object;
DbInterception.Add(failingTransactionInterceptor);
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key =>
(Func<IDbExecutionStrategy>)
(() => new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1))));
try
{
using (var context = new BlogContextCommit())
{
failingTransactionInterceptor.ShouldFailTimes = 0;
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
failingTransactionInterceptor.ShouldFailTimes = 2;
failingTransactionInterceptor.ShouldRollBack = false;
context.Blogs.Add(new BlogContext.Blog());
runAndVerify(context);
failingTransactionInterceptorMock.Verify(
m => m.Committing(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext>()), Times.Exactly(3));
}
using (var context = new BlogContextCommit())
{
Assert.Equal(2, context.Blogs.Count());
using (var transactionContext = new TransactionContext(context.Database.Connection))
{
using (var infoContext = GetInfoContext(transactionContext))
{
Assert.True(
!infoContext.TableExists("__Transactions")
|| !transactionContext.Transactions.Any());
}
}
}
}
finally
{
DbInterception.Remove(failingTransactionInterceptorMock.Object);
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void CommitFailureHandler_Dispose_does_not_use_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
c.TransactionHandler.Dispose();
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(3));
});
}
[Fact]
public void CommitFailureHandler_Dispose_catches_exceptions()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
using (var transactionContext = new TransactionContext(((EntityConnection)c.Connection).StoreConnection))
{
foreach (var tran in transactionContext.Set<TransactionRow>().ToList())
{
transactionContext.Transactions.Remove(tran);
}
transactionContext.SaveChanges();
}
c.TransactionHandler.Dispose();
});
}
[Fact]
public void CommitFailureHandler_prunes_transactions_after_set_amount()
{
CommitFailureHandler_prunes_transactions_after_set_amount_implementation(false);
}
[Fact]
public void CommitFailureHandler_prunes_transactions_after_set_amount_and_handles_false_failure()
{
CommitFailureHandler_prunes_transactions_after_set_amount_implementation(true);
}
private void CommitFailureHandler_prunes_transactions_after_set_amount_implementation(bool shouldThrow)
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
var transactionHandler = (MyCommitFailureHandler)objectContext.TransactionHandler;
for (var i = 0; i < transactionHandler.PruningLimit; i++)
{
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
}
AssertTransactionHistoryCount(context, transactionHandler.PruningLimit);
if (shouldThrow)
{
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = false;
}
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
AssertTransactionHistoryCount(context, 1);
Assert.Equal(1, transactionHandler.TransactionContext.ChangeTracker.Entries<TransactionRow>().Count());
}
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void CommitFailureHandler_ClearTransactionHistory_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory();
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(4));
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistory_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory();
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(4));
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistory_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory());
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
#if !NET40
[Fact]
public void CommitFailureHandler_ClearTransactionHistoryAsync_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait();
executionStrategyMock.Verify(
e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Once());
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_ClearTransactionHistoryAsync_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ExceptionHelpers.UnwrapAggregateExceptions(
() => ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait()));
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistoryAsync_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait();
executionStrategyMock.Verify(
e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Once());
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistoryAsync_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ExceptionHelpers.UnwrapAggregateExceptions(
() => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait()));
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
#endif
private void CommitFailureHandler_with_ExecutionStrategy_test(
Action<ObjectContext, Mock<SimpleExecutionStrategy>> pruneAndVerify)
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null));
var executionStrategyMock = new Mock<SimpleExecutionStrategy> { CallBase = true };
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => executionStrategyMock.Object));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
AssertTransactionHistoryCount(context, 1);
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(3));
executionStrategyMock.Verify(
e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Never());
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
pruneAndVerify(objectContext, executionStrategyMock);
using (var transactionContext = new TransactionContext(context.Database.Connection))
{
Assert.Equal(0, transactionContext.Transactions.Count());
}
}
}
finally
{
MutableResolver.ClearResolvers();
}
}
private void AssertTransactionHistoryCount(DbContext context, int count)
{
AssertTransactionHistoryCount(((IObjectContextAdapter)context).ObjectContext, count);
}
private void AssertTransactionHistoryCount(ObjectContext context, int count)
{
using (var transactionContext = new TransactionContext(((EntityConnection)context.Connection).StoreConnection))
{
Assert.Equal(count, transactionContext.Transactions.Count());
}
}
public class SimpleExecutionStrategy : IDbExecutionStrategy
{
public bool RetriesOnFailure
{
get { return false; }
}
public virtual void Execute(Action operation)
{
operation();
}
public virtual TResult Execute<TResult>(Func<TResult> operation)
{
return operation();
}
public virtual Task ExecuteAsync(Func<Task> operation, CancellationToken cancellationToken)
{
return operation();
}
public virtual Task<TResult> ExecuteAsync<TResult>(Func<Task<TResult>> operation, CancellationToken cancellationToken)
{
return operation();
}
}
public class MyCommitFailureHandler : CommitFailureHandler
{
public MyCommitFailureHandler(Func<DbConnection, TransactionContext> transactionContextFactory)
: base(transactionContextFactory)
{
}
public new void MarkTransactionForPruning(TransactionRow transaction)
{
base.MarkTransactionForPruning(transaction);
}
public new TransactionContext TransactionContext
{
get { return base.TransactionContext; }
}
public new virtual int PruningLimit
{
get { return base.PruningLimit; }
}
}
[Fact]
[UseDefaultExecutionStrategy]
public void CommitFailureHandler_supports_nested_transactions()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
context.Blogs.Add(new BlogContext.Blog());
using (var transaction = context.Database.BeginTransaction())
{
using (var innerContext = new BlogContextCommit())
{
using (var innerTransaction = innerContext.Database.BeginTransaction())
{
Assert.Equal(1, innerContext.Blogs.Count());
innerContext.Blogs.Add(new BlogContext.Blog());
innerContext.SaveChanges();
innerTransaction.Commit();
}
}
context.SaveChanges();
transaction.Commit();
}
}
using (var context = new BlogContextCommit())
{
Assert.Equal(3, context.Blogs.Count());
}
}
finally
{
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SqlAzureExecutionStrategy()));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
}
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(c => new TransactionContextNoInit(c)), null, null));
using (var context = new BlogContextCommit())
{
context.Blogs.Add(new BlogContext.Blog());
Assert.Throws<EntityException>(() => context.SaveChanges());
context.Database.ExecuteSqlCommand(
TransactionalBehavior.DoNotEnsureTransaction,
((IObjectContextAdapter)context).ObjectContext.TransactionHandler.BuildDatabaseInitializationScript());
context.SaveChanges();
}
using (var context = new BlogContextCommit())
{
Assert.Equal(2, context.Blogs.Count());
}
}
finally
{
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database_if_no_migration_generator()
{
var mockDbProviderServiceResolver = new Mock<IDbDependencyResolver>();
mockDbProviderServiceResolver
.Setup(r => r.GetService(It.IsAny<Type>(), It.IsAny<string>()))
.Returns(SqlProviderServices.Instance);
MutableResolver.AddResolver<DbProviderServices>(mockDbProviderServiceResolver.Object);
var mockDbProviderFactoryResolver = new Mock<IDbDependencyResolver>();
mockDbProviderFactoryResolver
.Setup(r => r.GetService(It.IsAny<Type>(), It.IsAny<string>()))
.Returns(SqlClientFactory.Instance);
MutableResolver.AddResolver<DbProviderFactory>(mockDbProviderFactoryResolver.Object);
BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database();
}
[Fact]
public void FromContext_returns_the_current_handler()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
var commitFailureHandler = CommitFailureHandler.FromContext(((IObjectContextAdapter)context).ObjectContext);
Assert.IsType<CommitFailureHandler>(commitFailureHandler);
Assert.Same(commitFailureHandler, CommitFailureHandler.FromContext(context));
}
}
finally
{
MutableResolver.ClearResolvers();
}
}
[Fact]
public void TransactionHandler_is_disposed_even_if_the_context_is_not()
{
var context = new BlogContextCommit();
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
var weakDbContext = new WeakReference(context);
var weakObjectContext = new WeakReference(((IObjectContextAdapter)context).ObjectContext);
var weakTransactionHandler = new WeakReference(((IObjectContextAdapter)context).ObjectContext.TransactionHandler);
context = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weakDbContext.IsAlive);
Assert.False(weakObjectContext.IsAlive);
DbDispatchersHelpers.AssertNoInterceptors();
// Need a second pass as the TransactionHandler is removed from the interceptors in the ObjectContext finalizer
GC.Collect();
Assert.False(weakTransactionHandler.IsAlive);
}
public class TransactionContextNoInit : TransactionContext
{
static TransactionContextNoInit()
{
Database.SetInitializer<TransactionContextNoInit>(null);
}
public TransactionContextNoInit(DbConnection connection)
: base(connection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TransactionRow>()
.ToTable("TransactionContextNoInit");
}
}
public class FailingTransactionInterceptor : IDbTransactionInterceptor
{
private int _timesToFail;
private int _shouldFailTimes;
public int ShouldFailTimes
{
get { return _shouldFailTimes; }
set
{
_shouldFailTimes = value;
_timesToFail = value;
}
}
public bool ShouldRollBack;
public FailingTransactionInterceptor()
{
_timesToFail = ShouldFailTimes;
}
public void ConnectionGetting(DbTransaction transaction, DbTransactionInterceptionContext<DbConnection> interceptionContext)
{
}
public void ConnectionGot(DbTransaction transaction, DbTransactionInterceptionContext<DbConnection> interceptionContext)
{
}
public void IsolationLevelGetting(
DbTransaction transaction, DbTransactionInterceptionContext<IsolationLevel> interceptionContext)
{
}
public void IsolationLevelGot(DbTransaction transaction, DbTransactionInterceptionContext<IsolationLevel> interceptionContext)
{
}
public virtual void Committing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
if (_timesToFail-- > 0)
{
if (ShouldRollBack)
{
transaction.Rollback();
}
else
{
transaction.Commit();
}
interceptionContext.Exception = new TimeoutException();
}
else
{
_timesToFail = ShouldFailTimes;
}
}
public void Committed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void Disposing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void Disposed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void RollingBack(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void RolledBack(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
}
public class BlogContextCommit : BlogContext
{
static BlogContextCommit()
{
Database.SetInitializer<BlogContextCommit>(new BlogInitializer());
}
}
}
}
| |
// 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.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// An Azure Batch job.
/// </summary>
public partial class CloudJob : ITransportObjectProvider<Models.JobAddParameter>, IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<bool?> AllowTaskPreemptionProperty;
public readonly PropertyAccessor<IList<EnvironmentSetting>> CommonEnvironmentSettingsProperty;
public readonly PropertyAccessor<JobConstraints> ConstraintsProperty;
public readonly PropertyAccessor<DateTime?> CreationTimeProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<string> ETagProperty;
public readonly PropertyAccessor<JobExecutionInformation> ExecutionInformationProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<JobManagerTask> JobManagerTaskProperty;
public readonly PropertyAccessor<JobPreparationTask> JobPreparationTaskProperty;
public readonly PropertyAccessor<JobReleaseTask> JobReleaseTaskProperty;
public readonly PropertyAccessor<DateTime?> LastModifiedProperty;
public readonly PropertyAccessor<int?> MaxParallelTasksProperty;
public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty;
public readonly PropertyAccessor<JobNetworkConfiguration> NetworkConfigurationProperty;
public readonly PropertyAccessor<Common.OnAllTasksComplete?> OnAllTasksCompleteProperty;
public readonly PropertyAccessor<Common.OnTaskFailure?> OnTaskFailureProperty;
public readonly PropertyAccessor<PoolInformation> PoolInformationProperty;
public readonly PropertyAccessor<Common.JobState?> PreviousStateProperty;
public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty;
public readonly PropertyAccessor<int?> PriorityProperty;
public readonly PropertyAccessor<Common.JobState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<JobStatistics> StatisticsProperty;
public readonly PropertyAccessor<string> UrlProperty;
public readonly PropertyAccessor<bool?> UsesTaskDependenciesProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AllowTaskPreemptionProperty = this.CreatePropertyAccessor<bool?>(nameof(AllowTaskPreemption), BindingAccess.Read | BindingAccess.Write);
this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>(nameof(CommonEnvironmentSettings), BindingAccess.Read | BindingAccess.Write);
this.ConstraintsProperty = this.CreatePropertyAccessor<JobConstraints>(nameof(Constraints), BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(CreationTime), BindingAccess.None);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write);
this.ETagProperty = this.CreatePropertyAccessor<string>(nameof(ETag), BindingAccess.None);
this.ExecutionInformationProperty = this.CreatePropertyAccessor<JobExecutionInformation>(nameof(ExecutionInformation), BindingAccess.None);
this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write);
this.JobManagerTaskProperty = this.CreatePropertyAccessor<JobManagerTask>(nameof(JobManagerTask), BindingAccess.Read | BindingAccess.Write);
this.JobPreparationTaskProperty = this.CreatePropertyAccessor<JobPreparationTask>(nameof(JobPreparationTask), BindingAccess.Read | BindingAccess.Write);
this.JobReleaseTaskProperty = this.CreatePropertyAccessor<JobReleaseTask>(nameof(JobReleaseTask), BindingAccess.Read | BindingAccess.Write);
this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>(nameof(LastModified), BindingAccess.None);
this.MaxParallelTasksProperty = this.CreatePropertyAccessor<int?>(nameof(MaxParallelTasks), BindingAccess.Read | BindingAccess.Write);
this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor<JobNetworkConfiguration>(nameof(NetworkConfiguration), BindingAccess.Read | BindingAccess.Write);
this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor<Common.OnAllTasksComplete?>(nameof(OnAllTasksComplete), BindingAccess.Read | BindingAccess.Write);
this.OnTaskFailureProperty = this.CreatePropertyAccessor<Common.OnTaskFailure?>(nameof(OnTaskFailure), BindingAccess.Read | BindingAccess.Write);
this.PoolInformationProperty = this.CreatePropertyAccessor<PoolInformation>(nameof(PoolInformation), BindingAccess.Read | BindingAccess.Write);
this.PreviousStateProperty = this.CreatePropertyAccessor<Common.JobState?>(nameof(PreviousState), BindingAccess.None);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(PreviousStateTransitionTime), BindingAccess.None);
this.PriorityProperty = this.CreatePropertyAccessor<int?>(nameof(Priority), BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor<Common.JobState?>(nameof(State), BindingAccess.None);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None);
this.StatisticsProperty = this.CreatePropertyAccessor<JobStatistics>(nameof(Statistics), BindingAccess.None);
this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None);
this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor<bool?>(nameof(UsesTaskDependencies), BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.CloudJob protocolObject) : base(BindingState.Bound)
{
this.AllowTaskPreemptionProperty = this.CreatePropertyAccessor(
protocolObject.AllowTaskPreemption,
nameof(AllowTaskPreemption),
BindingAccess.Read | BindingAccess.Write);
this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollectionAndFreeze(protocolObject.CommonEnvironmentSettings),
nameof(CommonEnvironmentSettings),
BindingAccess.Read);
this.ConstraintsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new JobConstraints(o)),
nameof(Constraints),
BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor(
protocolObject.CreationTime,
nameof(CreationTime),
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
nameof(DisplayName),
BindingAccess.Read);
this.ETagProperty = this.CreatePropertyAccessor(
protocolObject.ETag,
nameof(ETag),
BindingAccess.Read);
this.ExecutionInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new JobExecutionInformation(o).Freeze()),
nameof(ExecutionInformation),
BindingAccess.Read);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
nameof(Id),
BindingAccess.Read);
this.JobManagerTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobManagerTask, o => new JobManagerTask(o).Freeze()),
nameof(JobManagerTask),
BindingAccess.Read);
this.JobPreparationTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobPreparationTask, o => new JobPreparationTask(o).Freeze()),
nameof(JobPreparationTask),
BindingAccess.Read);
this.JobReleaseTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobReleaseTask, o => new JobReleaseTask(o).Freeze()),
nameof(JobReleaseTask),
BindingAccess.Read);
this.LastModifiedProperty = this.CreatePropertyAccessor(
protocolObject.LastModified,
nameof(LastModified),
BindingAccess.Read);
this.MaxParallelTasksProperty = this.CreatePropertyAccessor(
protocolObject.MaxParallelTasks,
nameof(MaxParallelTasks),
BindingAccess.Read | BindingAccess.Write);
this.MetadataProperty = this.CreatePropertyAccessor(
MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata),
nameof(Metadata),
BindingAccess.Read | BindingAccess.Write);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new JobNetworkConfiguration(o).Freeze()),
nameof(NetworkConfiguration),
BindingAccess.Read);
this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.OnAllTasksComplete, Common.OnAllTasksComplete>(protocolObject.OnAllTasksComplete),
nameof(OnAllTasksComplete),
BindingAccess.Read | BindingAccess.Write);
this.OnTaskFailureProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.OnTaskFailure, Common.OnTaskFailure>(protocolObject.OnTaskFailure),
nameof(OnTaskFailure),
BindingAccess.Read);
this.PoolInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.PoolInfo, o => new PoolInformation(o)),
nameof(PoolInformation),
BindingAccess.Read | BindingAccess.Write);
this.PreviousStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.JobState, Common.JobState>(protocolObject.PreviousState),
nameof(PreviousState),
BindingAccess.Read);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.PreviousStateTransitionTime,
nameof(PreviousStateTransitionTime),
BindingAccess.Read);
this.PriorityProperty = this.CreatePropertyAccessor(
protocolObject.Priority,
nameof(Priority),
BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.JobState, Common.JobState>(protocolObject.State),
nameof(State),
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
nameof(StateTransitionTime),
BindingAccess.Read);
this.StatisticsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new JobStatistics(o).Freeze()),
nameof(Statistics),
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
nameof(Url),
BindingAccess.Read);
this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor(
protocolObject.UsesTaskDependencies,
nameof(UsesTaskDependencies),
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CloudJob"/> class.
/// </summary>
/// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param>
/// <param name='baseBehaviors'>The base behaviors to use.</param>
internal CloudJob(
BatchClient parentBatchClient,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.propertyContainer = new PropertyContainer();
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
}
/// <summary>
/// Default constructor to support mocking the <see cref="CloudJob"/> class.
/// </summary>
protected CloudJob()
{
this.propertyContainer = new PropertyContainer();
}
internal CloudJob(
BatchClient parentBatchClient,
Models.CloudJob protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="CloudJob"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region CloudJob
/// <summary>
/// Gets or sets whether Tasks in this job can be preempted by other high priority jobs.
/// </summary>
/// <remarks>
/// If the value is set to True, other high priority jobs submitted to the system will take precedence and will be
/// able requeue tasks from this job. You can update a job's allowTaskPreemption after it has been created using
/// the update job API.
/// </remarks>
public bool? AllowTaskPreemption
{
get { return this.propertyContainer.AllowTaskPreemptionProperty.Value; }
set { this.propertyContainer.AllowTaskPreemptionProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of common environment variable settings. These environment variables are set for all tasks
/// in this <see cref="CloudJob"/> (including the Job Manager, Job Preparation and Job Release tasks).
/// </summary>
public IList<EnvironmentSetting> CommonEnvironmentSettings
{
get { return this.propertyContainer.CommonEnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.CommonEnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the execution constraints for the job.
/// </summary>
public JobConstraints Constraints
{
get { return this.propertyContainer.ConstraintsProperty.Value; }
set { this.propertyContainer.ConstraintsProperty.Value = value; }
}
/// <summary>
/// Gets the creation time of the job.
/// </summary>
public DateTime? CreationTime
{
get { return this.propertyContainer.CreationTimeProperty.Value; }
}
/// <summary>
/// Gets or sets the display name of the job.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets the ETag for the job.
/// </summary>
public string ETag
{
get { return this.propertyContainer.ETagProperty.Value; }
}
/// <summary>
/// Gets the execution information for the job.
/// </summary>
public JobExecutionInformation ExecutionInformation
{
get { return this.propertyContainer.ExecutionInformationProperty.Value; }
}
/// <summary>
/// Gets or sets the id of the job.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets or sets the Job Manager task. The Job Manager task is launched when the <see cref="CloudJob"/> is started.
/// </summary>
public JobManagerTask JobManagerTask
{
get { return this.propertyContainer.JobManagerTaskProperty.Value; }
set { this.propertyContainer.JobManagerTaskProperty.Value = value; }
}
/// <summary>
/// Gets or sets the Job Preparation task. The Batch service will run the Job Preparation task on a compute node
/// before starting any tasks of that job on that compute node.
/// </summary>
public JobPreparationTask JobPreparationTask
{
get { return this.propertyContainer.JobPreparationTaskProperty.Value; }
set { this.propertyContainer.JobPreparationTaskProperty.Value = value; }
}
/// <summary>
/// Gets or sets the Job Release Task runs when the Job ends, because of one of the following: The user calls the
/// Terminate Job API, or the Delete Job API while the Job is still active, the Job's maximum wall clock time constraint
/// is reached, and the Job is still active, or the Job's Job Manager Task completed, and the Job is configured to
/// terminate when the Job Manager completes. The Job Release Task runs on each Node where Tasks of the Job have
/// run and the Job Preparation Task ran and completed. If you reimage a Node after it has run the Job Preparation
/// Task, and the Job ends without any further Tasks of the Job running on that Node (and hence the Job Preparation
/// Task does not re-run), then the Job Release Task does not run on that Compute Node. If a Node reboots while the
/// Job Release Task is still running, the Job Release Task runs again when the Compute Node starts up. The Job is
/// not marked as complete until all Job Release Tasks have completed. The Job Release Task runs in the background.
/// It does not occupy a scheduling slot; that is, it does not count towards the taskSlotsPerNode limit specified
/// on the Pool.
/// </summary>
public JobReleaseTask JobReleaseTask
{
get { return this.propertyContainer.JobReleaseTaskProperty.Value; }
set { this.propertyContainer.JobReleaseTaskProperty.Value = value; }
}
/// <summary>
/// Gets the last modified time of the job.
/// </summary>
public DateTime? LastModified
{
get { return this.propertyContainer.LastModifiedProperty.Value; }
}
/// <summary>
/// Gets or sets the maximum number of tasks that can be executed in parallel for the job.
/// </summary>
/// <remarks>
/// The value of maxParallelTasks must be -1 or greater than 0 if specified. If not specified, the default value
/// is -1, which means there's no limit to the number of tasks that can be run at once. You can update a job's maxParallelTasks
/// after it has been created using the update job API.
/// </remarks>
public int? MaxParallelTasks
{
get { return this.propertyContainer.MaxParallelTasksProperty.Value; }
set { this.propertyContainer.MaxParallelTasksProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of name-value pairs associated with the job as metadata.
/// </summary>
public IList<MetadataItem> Metadata
{
get { return this.propertyContainer.MetadataProperty.Value; }
set
{
this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the network configuration for the job.
/// </summary>
public JobNetworkConfiguration NetworkConfiguration
{
get { return this.propertyContainer.NetworkConfigurationProperty.Value; }
set { this.propertyContainer.NetworkConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets or sets the action the Batch service should take when all tasks in the job are in the <see cref="Common.JobState.Completed"/>
/// state.
/// </summary>
public Common.OnAllTasksComplete? OnAllTasksComplete
{
get { return this.propertyContainer.OnAllTasksCompleteProperty.Value; }
set { this.propertyContainer.OnAllTasksCompleteProperty.Value = value; }
}
/// <summary>
/// Gets or sets the action the Batch service should take when any task in the job fails.
/// </summary>
/// <remarks>
/// A task is considered to have failed if it completes with a non-zero exit code and has exhausted its retry count,
/// or if it had a scheduling error.
/// </remarks>
public Common.OnTaskFailure? OnTaskFailure
{
get { return this.propertyContainer.OnTaskFailureProperty.Value; }
set { this.propertyContainer.OnTaskFailureProperty.Value = value; }
}
/// <summary>
/// Gets or sets the pool on which the Batch service runs the job's tasks.
/// </summary>
public PoolInformation PoolInformation
{
get { return this.propertyContainer.PoolInformationProperty.Value; }
set { this.propertyContainer.PoolInformationProperty.Value = value; }
}
/// <summary>
/// Gets the previous state of the job.
/// </summary>
/// <remarks>
/// If the job is in its initial <see cref="Common.JobState.Active"/> state, the PreviousState property is not defined.
/// </remarks>
public Common.JobState? PreviousState
{
get { return this.propertyContainer.PreviousStateProperty.Value; }
}
/// <summary>
/// Gets the time at which the job entered its previous state.
/// </summary>
/// <remarks>
/// If the job is in its initial <see cref="Common.JobState.Active"/> state, the PreviousStateTransitionTime property
/// is not defined.
/// </remarks>
public DateTime? PreviousStateTransitionTime
{
get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets or sets the priority of the job. Priority values can range from -1000 to 1000, with -1000 being the lowest
/// priority and 1000 being the highest priority.
/// </summary>
/// <remarks>
/// The default value is 0.
/// </remarks>
public int? Priority
{
get { return this.propertyContainer.PriorityProperty.Value; }
set { this.propertyContainer.PriorityProperty.Value = value; }
}
/// <summary>
/// Gets the current state of the job.
/// </summary>
public Common.JobState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the job entered its current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets resource usage statistics for the entire lifetime of the job.
/// </summary>
/// <remarks>
/// This property is populated only if the <see cref="CloudJob"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/>
/// including the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The Batch
/// service performs periodic roll-up of statistics. The typical delay is about 30 minutes.
/// </remarks>
public JobStatistics Statistics
{
get { return this.propertyContainer.StatisticsProperty.Value; }
}
/// <summary>
/// Gets the URL of the job.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
/// <summary>
/// Gets or sets whether tasks in the job can define dependencies on each other.
/// </summary>
/// <remarks>
/// The default value is false.
/// </remarks>
public bool? UsesTaskDependencies
{
get { return this.propertyContainer.UsesTaskDependenciesProperty.Value; }
set { this.propertyContainer.UsesTaskDependenciesProperty.Value = value; }
}
#endregion // CloudJob
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.JobAddParameter ITransportObjectProvider<Models.JobAddParameter>.GetTransportObject()
{
Models.JobAddParameter result = new Models.JobAddParameter()
{
AllowTaskPreemption = this.AllowTaskPreemption,
CommonEnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.CommonEnvironmentSettings),
Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
Id = this.Id,
JobManagerTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobManagerTask, (o) => o.GetTransportObject()),
JobPreparationTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobPreparationTask, (o) => o.GetTransportObject()),
JobReleaseTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobReleaseTask, (o) => o.GetTransportObject()),
MaxParallelTasks = this.MaxParallelTasks,
Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata),
NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()),
OnAllTasksComplete = UtilitiesInternal.MapNullableEnum<Common.OnAllTasksComplete, Models.OnAllTasksComplete>(this.OnAllTasksComplete),
OnTaskFailure = UtilitiesInternal.MapNullableEnum<Common.OnTaskFailure, Models.OnTaskFailure>(this.OnTaskFailure),
PoolInfo = UtilitiesInternal.CreateObjectWithNullCheck(this.PoolInformation, (o) => o.GetTransportObject()),
Priority = this.Priority,
UsesTaskDependencies = this.UsesTaskDependencies,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
using System;
using System.Collections;
using System.Windows.Forms;
using PluginCore;
using WeifenLuo.WinFormsUI;
using ProjectManager.Projects.AS3;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace ConfigToggle
{
public class PluginUI : UserControl
{
private CheckedListBox config_constants;
private RichTextBox richTextBox;
private SplitContainer split;
private TreeView values;
private ContextMenuStrip right_click_context;
private System.ComponentModel.IContainer components;
private ToolStripTextBox toolStripTextBox1;
private PluginMain pluginMain;
public PluginUI(PluginMain pluginMain)
{
this.InitializeComponent();
this.pluginMain = pluginMain;
}
public RichTextBox Output
{
get { return this.richTextBox; }
}
#region Windows Forms Designer Generated Code
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor. The Forms designer might
/// not be able to load this method if it was changed manually.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.config_constants = new System.Windows.Forms.CheckedListBox();
this.richTextBox = new System.Windows.Forms.RichTextBox();
this.split = new System.Windows.Forms.SplitContainer();
this.values = new System.Windows.Forms.TreeView();
this.right_click_context = new System.Windows.Forms.ContextMenuStrip(this.components);
this.toolStripTextBox1 = new System.Windows.Forms.ToolStripTextBox();
this.split.Panel1.SuspendLayout();
this.split.Panel2.SuspendLayout();
this.split.SuspendLayout();
this.right_click_context.SuspendLayout();
this.SuspendLayout();
//
// config_constants
//
this.config_constants.AccessibleRole = System.Windows.Forms.AccessibleRole.Pane;
this.config_constants.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.config_constants.CheckOnClick = true;
this.config_constants.ColumnWidth = 90;
this.config_constants.Dock = System.Windows.Forms.DockStyle.Fill;
this.config_constants.FormattingEnabled = true;
this.config_constants.Location = new System.Drawing.Point(0, 0);
this.config_constants.MultiColumn = true;
this.config_constants.Name = "config_constants";
this.config_constants.Size = new System.Drawing.Size(143, 291);
this.config_constants.TabIndex = 1;
this.config_constants.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.config_constants_ItemCheck);
//
// richTextBox
//
this.richTextBox.Location = new System.Drawing.Point(3, 154);
this.richTextBox.Name = "richTextBox";
this.richTextBox.Size = new System.Drawing.Size(170, 109);
this.richTextBox.TabIndex = 2;
this.richTextBox.Text = "";
this.richTextBox.Visible = false;
//
// split
//
this.split.Dock = System.Windows.Forms.DockStyle.Fill;
this.split.Location = new System.Drawing.Point(0, 0);
this.split.Name = "split";
//
// split.Panel1
//
this.split.Panel1.Controls.Add(this.config_constants);
//
// split.Panel2
//
this.split.Panel2.Controls.Add(this.richTextBox);
this.split.Panel2.Controls.Add(this.values);
this.split.Size = new System.Drawing.Size(280, 291);
this.split.SplitterDistance = 143;
this.split.TabIndex = 5;
//
// values
//
this.values.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.values.Dock = System.Windows.Forms.DockStyle.Fill;
this.values.Indent = 19;
this.values.LabelEdit = true;
this.values.Location = new System.Drawing.Point(0, 0);
this.values.Name = "values";
this.values.Size = new System.Drawing.Size(133, 291);
this.values.TabIndex = 6;
this.values.AfterLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(this.values_AfterLabelEdit);
this.values.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.values_NodeMouseClick);
this.values.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.values_KeyPress);
//
// right_click_context
//
this.right_click_context.Enabled = false;
this.right_click_context.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripTextBox1});
this.right_click_context.Name = "contextMenuStrip1";
this.right_click_context.Size = new System.Drawing.Size(161, 51);
this.right_click_context.Text = "Add below";
//
// toolStripTextBox1
//
this.toolStripTextBox1.AcceptsReturn = true;
this.toolStripTextBox1.Enabled = false;
this.toolStripTextBox1.HideSelection = false;
this.toolStripTextBox1.Name = "toolStripTextBox1";
this.toolStripTextBox1.Size = new System.Drawing.Size(100, 23);
this.toolStripTextBox1.Text = "Add new config below";
this.toolStripTextBox1.ToolTipText = "Type new config below and press enter";
this.toolStripTextBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.right_click_textbox_handler);
//
// PluginUI
//
this.AutoScroll = true;
this.ContextMenuStrip = this.right_click_context;
this.Controls.Add(this.split);
this.Name = "PluginUI";
this.Size = new System.Drawing.Size(280, 291);
this.split.Panel1.ResumeLayout(false);
this.split.Panel2.ResumeLayout(false);
this.split.ResumeLayout(false);
this.right_click_context.ResumeLayout(false);
this.right_click_context.PerformLayout();
this.ResumeLayout(false);
}
#endregion
public string[] GetCompilerConstants()
{
IProject project = PluginBase.CurrentProject;
if (project == null)
{
//Output.Text += "No project loaded";
return null;
}
AS3Project as3_project = project as AS3Project;
return as3_project.CompilerOptions.CompilerConstants;
}
public bool IsConstantCONFIG( string constant )
{
return constant.EndsWith("true") || constant.EndsWith("false");
}
public bool IsConstantVALUE(string constant) // CONFIG::dupa, 123 but it also can be a string value! in both cases input will do
{
return constant.IndexOf(',') != -1;
//return constant.EndsWith("true") || constant.EndsWith("false");
}
public void RefreshUI()
{
string[] constants = GetCompilerConstants();
string all = "";
config_constants.Items.Clear();
config_constants.ItemCheck -= config_constants_ItemCheck;
values.Nodes.Clear();
foreach (string constant in constants)
{
if (IsConstantCONFIG(constant))
{
string key;
string value;
string conf_namespace;
ExtractCONFIGKeyValue(constant, out key, out value, out conf_namespace);
//all += "config: >" + key + "< ]" + value + "[\n";
config_constants.Items.Add(key, value == "true");
}
else
if (IsConstantVALUE(constant))
{
string key;
string value;
ExtractVALUEKeyValue(constant, out key, out value);
TreeNode parent = values.Nodes.Add(key);
parent.Nodes.Add(value);
}
else
{
all += " unrecog: " + constant + "\n";
}
}
//Output.Text += "Compiler constants:\n" + all;
values.ExpandAll();
config_constants.ItemCheck += config_constants_ItemCheck;
}
// %snamespace::key%s,%svalue
public Regex config_regex = new Regex(@"\s*(?<namespace>[a-zA-z1-9]*)::(?<key>[a-zA-z1-9]*)\s*,\s*(?<value>[a-zA-z1-9]*)");
public Regex value_regex = new Regex(@"\s*(?<key>[a-zA-z1-9:]*)\s*,\s*(?<value>[a-zA-z1-9"" -]*)");
private void ExtractCONFIGKeyValue(string constant, out string key, out string value, out string conf_namespace)
{
Match match = config_regex.Match(constant);
key = match.Groups["key"].Value;
value = match.Groups["value"].Value;
conf_namespace = match.Groups["namespace"].Value;
/*Output.Text += " namespace: " + conf_namespace;
Output.Text += " key: " + key;
Output.Text += " value: " + value;*/
}
private void ExtractVALUEKeyValue(string constant, out string key, out string value)
{
Match match = value_regex.Match(constant);
key = match.Groups["key"].Value;
value = match.Groups["value"].Value;
}
private void config_constants_ItemCheck(object sender, ItemCheckEventArgs e)
{
//Output.Text += "Clicked " + obj.Text; // +" newvalue " + e.NewValue + "\n";
IProject project = PluginBase.CurrentProject;
if (project == null)
{
//Output.Text += "No project loaded";
return;
}
AS3Project as3_project = project as AS3Project;
string[] constants = GetCompilerConstants();
System.Windows.Forms.CheckedListBox obj = sender as CheckedListBox;
for (int i = 0; i < constants.GetLength(0); i++)
{
//Output.Text += " " + constants[i];
if (IsConstantCONFIG(constants[i]))
{
string key;
string value;
string conf_namespace;
ExtractCONFIGKeyValue(constants[i], out key, out value, out conf_namespace);
if (key == obj.Text) // is this the clicked one
{
constants[i] = conf_namespace + "::" + key + "," + (e.NewValue == CheckState.Checked ? "true" : "false");
//Output.Text += "toggled " + constants[i] + "\n";
as3_project.Save();
return;
}
}
}
}
private void values_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
e.Node.BeginEdit();
}
private void values_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
if (values.SelectedNode != null && !values.SelectedNode.IsEditing)
values.SelectedNode.BeginEdit();
}
}
private void values_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
if (e.CancelEdit)
return;
/*if (e.Node.Parent == null)
Output.Text += "Parent is null / " + e.Node.Text + "\n";
else
Output.Text += e.Node.Parent.Text + " / " + e.Node.Text + "\n";
return;*/
IProject project = PluginBase.CurrentProject;
if (project == null)
{
//Output.Text += "No project loaded";
return;
}
AS3Project as3_project = project as AS3Project;
string[] constants = GetCompilerConstants();
string old_key = "";
string new_key = "";
string new_value = null;
if (e.Node.Parent == null) // edited the CONFIG::name part, so change the key
{
old_key = e.Node.Text;
new_key = e.Label;
//new_value shall be taken from
if (old_key == new_key)
return;
}
else // edited the value
{
old_key = e.Node.Parent.Text;
new_key = old_key;
new_value = e.Label;
//Output.Text += e.Node.Parent.Text + " / " + e.Node.Text;
}
for (int i = 0; i < constants.GetLength(0); i++)
{
//Output.Text += " " + constants[i];
if (!IsConstantCONFIG(constants[i]) && IsConstantVALUE(constants[i]))
{
string key;
string value;
ExtractVALUEKeyValue(constants[i], out key, out value);
if (key == new_key) // is this the clicked one
{
if (new_value == null)
new_value = value;
constants[i] = new_key + "," + new_value;
Output.Text += "edited to " + constants[i] + "\n";
as3_project.Save();
return;
}
}
}
}
private void right_click_textbox_handler(object sender, KeyPressEventArgs e)
{
//Output.Text += "key down" + e.KeyChar + "\n";
/*
if (e.KeyChar == 13)
{
IProject project = PluginBase.CurrentProject;
if (project == null || !(project is AS3Project))
{
return;
}
AS3Project as3_project = project as AS3Project;
as3_project.CompilerOptions.CompilerConstants. how to add new?
//contextMenuStrip1.Hide();
as3_project.Save();
}
*/
}
//this.toolStripTextBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.right_click_textbox_handler);
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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.
*/
//#define Debug
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Reflection;
using System.Threading;
using Aurora.Framework;
using Mischel.Collections;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
namespace Aurora.ScriptEngine.AuroraDotNetEngine
{
public class MaintenanceThread
{
#region Declares
private const int EMPTY_WORK_KILL_THREAD_TIME = 250;
private readonly EventManager EventManager;
/// <summary>
/// Queue that handles the loading and unloading of scripts
/// </summary>
private readonly StartPerformanceQueue LUQueue = new StartPerformanceQueue();
private readonly ConcurrentQueue<QueueItemStruct> ScriptEvents = new ConcurrentQueue<QueueItemStruct>();
private readonly PriorityQueue<QueueItemStruct, Int64> SleepingScriptEvents =
new PriorityQueue<QueueItemStruct, Int64>(10, DateTimeComparer);
private readonly ScriptEngine m_ScriptEngine;
public Int64 CmdHandlerQueueIsRunning;
private float EventPerformance = 0.1f;
public bool EventProcessorIsRunning;
private bool FiredStartupEvent;
public int MaxScriptThreads = 1;
private DateTime NextSleepersTest = DateTime.Now;
public bool RunInMainProcessingThread;
public bool ScriptChangeIsRunning;
private int SleepingScriptEventCount;
public AuroraThreadPool cmdThreadpool;
private int m_CheckingEvents;
private int m_CheckingSleepers;
public bool m_Started;
public AuroraThreadPool scriptChangeThreadpool;
public AuroraThreadPool scriptThreadpool;
public bool Started
{
get { return m_Started; }
set
{
m_Started = true;
scriptChangeThreadpool.QueueEvent(ScriptChangeQueue, 2);
//Start the queue because it can't start itself
cmdThreadpool.ClearEvents();
cmdThreadpool.QueueEvent(CmdHandlerQueue, 2);
}
}
private static int DateTimeComparer(Int64 a, Int64 b)
{
return b.CompareTo(a);
}
#endregion
#region Constructor
public MaintenanceThread(ScriptEngine Engine)
{
m_ScriptEngine = Engine;
EventManager = Engine.EventManager;
RunInMainProcessingThread = Engine.Config.GetBoolean("RunInMainProcessingThread", false);
RunInMainProcessingThread = false; // temporary false until code is fix to work with true
//There IS a reason we start this, even if RunInMain is enabled
// If this isn't enabled, we run into issues with the CmdHandlerQueue,
// as it always must be async, so we must run the pool anyway
AuroraThreadPoolStartInfo info = new AuroraThreadPoolStartInfo
{
priority = ThreadPriority.Normal,
Threads = 1,
MaxSleepTime = Engine.Config.GetInt("SleepTime", 100),
SleepIncrementTime = Engine.Config.GetInt("SleepIncrementTime", 1),
Name = "Script Cmd Thread Pools"
};
cmdThreadpool = new AuroraThreadPool(info);
info.Name = "Script Loading Thread Pools";
scriptChangeThreadpool = new AuroraThreadPool(info);
MaxScriptThreads = Engine.Config.GetInt("Threads", 100); // leave control threads out of user option
AuroraThreadPoolStartInfo sinfo = new AuroraThreadPoolStartInfo
{
priority = ThreadPriority.Normal,
Threads = MaxScriptThreads,
MaxSleepTime = Engine.Config.GetInt("SleepTime", 100),
SleepIncrementTime = Engine.Config.GetInt("SleepIncrementTime", 1),
KillThreadAfterQueueClear = true,
Name = "Script Event Thread Pools"
};
scriptThreadpool = new AuroraThreadPool(sinfo);
AppDomain.CurrentDomain.AssemblyResolve += m_ScriptEngine.AssemblyResolver.OnAssemblyResolve;
}
#endregion
#region Loops
/// <summary>
/// This loop deals with starting and stoping scripts
/// </summary>
/// <returns></returns>
public void ScriptChangeQueue()
{
if (m_ScriptEngine.Worlds.Count == 0)
return;
IMonitorModule module = m_ScriptEngine.Worlds[0].RequestModuleInterface<IMonitorModule>();
int StartTime = Util.EnvironmentTickCount();
if (!Started) //Break early
return;
if (m_ScriptEngine.ConsoleDisabled || m_ScriptEngine.Disabled)
return;
ScriptChangeIsRunning = true;
object oitems;
bool broken = false;
for (int i = 0; i < 5; i++)
{
if (LUQueue.GetNext(out oitems))
StartScripts(oitems as LUStruct[]);
else
{
//None left, stop looping
broken = true;
break;
}
}
if (!broken)
{
scriptChangeThreadpool.QueueEvent(ScriptChangeQueue, 2); //Requeue us, still more to do
return;
}
if (!FiredStartupEvent)
{
//If we are empty, we are all done with script startup and can tell the region that we are all done
if (LUQueue.Count() == 0)
{
FiredStartupEvent = true;
foreach (IScene scene in m_ScriptEngine.Worlds)
{
scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptEngine.ScriptFailCount,
m_ScriptEngine.ScriptErrorMessages);
scene.EventManager.TriggerModuleFinishedStartup("ScriptEngine", new List<string>
{
m_ScriptEngine.
ScriptFailCount.
ToString(),
m_ScriptEngine.
ScriptErrorMessages
}); //Tell that we are done
}
}
}
ScriptChangeIsRunning = false;
Thread.Sleep(20);
if (module != null)
{
#if (!ISWIN)
foreach (IScene scene in m_ScriptEngine.Worlds)
{
ITimeMonitor scriptMonitor = (ITimeMonitor)module.GetMonitor(scene.RegionInfo.RegionID.ToString(), MonitorModuleHelper.ScriptFrameTime);
if (scriptMonitor != null)
{
scriptMonitor.AddTime(Util.EnvironmentTickCountSubtract(StartTime));
}
}
#else
foreach (ITimeMonitor scriptMonitor in m_ScriptEngine.Worlds.Select(scene => (ITimeMonitor)
module.GetMonitor(scene.RegionInfo.RegionID.ToString(), MonitorModuleHelper.ScriptFrameTime)).Where(scriptMonitor => scriptMonitor != null))
{
scriptMonitor.AddTime(Util.EnvironmentTickCountSubtract(StartTime));
}
#endif
}
}
public void StartScripts(LUStruct[] items)
{
List<LUStruct> NeedsFired = new List<LUStruct>();
foreach (LUStruct item in items)
{
if (item.Action == LUType.Unload)
{
//Close
item.ID.CloseAndDispose(true);
}
else if (item.Action == LUType.Load ||
item.Action == LUType.Reupload)
{
try
{
//Start
if (item.ID.Start(item))
NeedsFired.Add(item);
}
catch (Exception ex)
{
MainConsole.Instance.Error("[" + m_ScriptEngine.ScriptEngineName + "]: LEAKED COMPILE ERROR: " + ex);
}
}
}
foreach (LUStruct item in NeedsFired)
{
//Fire the events afterward so that they all start at the same time
item.ID.FireEvents();
}
}
public void CmdHandlerQueue()
{
if (m_ScriptEngine.Worlds.Count == 0)
{
Interlocked.Exchange(ref CmdHandlerQueueIsRunning, 0);
return;
}
Interlocked.Exchange(ref CmdHandlerQueueIsRunning, 1);
IMonitorModule module = m_ScriptEngine.Worlds[0].RequestModuleInterface<IMonitorModule>();
int StartTime = Util.EnvironmentTickCount();
if (!Started) //Break early
return;
if (m_ScriptEngine.ConsoleDisabled || m_ScriptEngine.Disabled)
return;
//Check timers, etc
bool didAnything = false;
try
{
didAnything = m_ScriptEngine.DoOneScriptPluginPass();
}
catch (Exception ex)
{
MainConsole.Instance.WarnFormat("[{0}]: Error in CmdHandlerPass, {1}", m_ScriptEngine.ScriptEngineName, ex);
}
if (module != null)
{
#if (!ISWIN)
foreach (IScene scene in m_ScriptEngine.Worlds)
{
ITimeMonitor scriptMonitor = (ITimeMonitor)module.GetMonitor(scene.RegionInfo.RegionID.ToString(), MonitorModuleHelper.ScriptFrameTime);
if (scriptMonitor != null)
{
scriptMonitor.AddTime(Util.EnvironmentTickCountSubtract(StartTime));
}
}
#else
foreach (ITimeMonitor scriptMonitor in m_ScriptEngine.Worlds.Select(scene => (ITimeMonitor)
module.GetMonitor(scene.RegionInfo.RegionID.ToString(), MonitorModuleHelper.ScriptFrameTime)).Where(scriptMonitor => scriptMonitor != null))
{
scriptMonitor.AddTime(Util.EnvironmentTickCountSubtract(StartTime));
}
#endif
}
if (didAnything) //If we did something, run us again soon
cmdThreadpool.QueueEvent(CmdHandlerQueue, 2);
else
Interlocked.Exchange(ref CmdHandlerQueueIsRunning, 0);
}
#endregion
#region Add
public void AddScriptChange(LUStruct[] items, LoadPriority priority)
{
if (RunInMainProcessingThread)
StartScripts(items);
else
{
LUQueue.Add(items, priority);
if (!ScriptChangeIsRunning)
StartThread("Change");
}
}
#endregion
#region Remove
public void RemoveState(ScriptData ID)
{
m_ScriptEngine.StateSave.DeleteFrom(ID);
}
#endregion
#region Start thread
public void Stop()
{
scriptThreadpool.Restart();
scriptChangeThreadpool.Restart();
cmdThreadpool.Restart();
}
public void Stats()
{
#pragma warning disable 618
foreach (Thread t in scriptThreadpool.GetThreads())
{
if (t != null)
{
t.Suspend();
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(t, true);
t.Resume();
MainConsole.Instance.Debug("Thread " + t.Name);
MainConsole.Instance.Debug(trace.GetFrames());
}
}
foreach (Thread t in scriptChangeThreadpool.GetThreads())
{
if (t != null)
{
t.Suspend();
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(t, true);
t.Resume();
MainConsole.Instance.Debug("Thread " + t.Name);
MainConsole.Instance.Debug(trace.GetFrames());
}
}
foreach (Thread t in cmdThreadpool.GetThreads())
{
if (t != null)
{
t.Suspend();
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(t, true);
t.Resume();
MainConsole.Instance.Debug("Thread " + t.Name);
MainConsole.Instance.Debug(trace.GetFrames());
}
}
#pragma warning restore 618
}
/// <summary>
/// Queue the event loop given by thread
/// </summary>
/// <param name = "thread"></param>
private void StartThread(string thread)
{
if (thread == "Change")
{
scriptChangeThreadpool.QueueEvent(ScriptChangeQueue, 2);
}
else if (thread == "CmdHandlerQueue" && Interlocked.Read(ref CmdHandlerQueueIsRunning) == 0)
{
cmdThreadpool.ClearEvents();
cmdThreadpool.QueueEvent(CmdHandlerQueue, 2);
}
}
/// <summary>
/// Makes sure that all the threads that need to be running are running and starts them if they need to be running
/// </summary>
public void PokeThreads(UUID itemID)
{
if (itemID != UUID.Zero)
{
ScriptData script = ScriptEngine.ScriptProtection.GetScript(itemID);
if (script != null && script.Script != null)
script.Script.NeedsStateSaved = true;
}
if (LUQueue.Count() > 0 && !ScriptChangeIsRunning)
StartThread("Change");
if (Interlocked.Read(ref CmdHandlerQueueIsRunning) == 0)
StartThread("CmdHandlerQueue");
}
public void DisableThreads()
{
Interlocked.Exchange(ref CmdHandlerQueueIsRunning, 0);
EventProcessorIsRunning = false;
ScriptChangeIsRunning = false;
cmdThreadpool.ClearEvents();
scriptChangeThreadpool.ClearEvents();
scriptThreadpool.ClearEvents();
}
#endregion
#region Scripts events scheduler control
public void RemoveFromEventSchQueue(ScriptData ID, bool abortcur)
{
if (ID == null)
return;
//Ignore any events to be added after this
ID.IgnoreNew = true;
//Clear out the old events
Interlocked.Increment(ref ID.VersionID);
}
public void SetEventSchSetIgnoreNew(ScriptData ID, bool yes)
{
if (ID == null)
return;
ID.IgnoreNew = yes;
}
public void AddEventSchQueue(ScriptData ID, string FunctionName, DetectParams[] qParams, EventPriority priority,
params object[] param)
{
QueueItemStruct QIS;
if (ID == null || ID.Script == null || ID.IgnoreNew)
return;
if (!ID.SetEventParams(FunctionName, qParams)) // check events delay rules
return;
QIS = new QueueItemStruct
{
EventsProcData = new ScriptEventsProcData(),
ID = ID,
functionName = FunctionName,
llDetectParams = qParams,
param = param,
VersionID = Interlocked.Read(ref ID.VersionID),
State = ID.State,
CurrentlyAt = null
};
ScriptEvents.Enqueue(QIS);
long threadCount = Interlocked.Read(ref scriptThreadpool.nthreads);
if (threadCount == 0 || threadCount < (ScriptEvents.Count + (SleepingScriptEventCount / 2)) * EventPerformance)
{
scriptThreadpool.QueueEvent(eventLoop, 2);
}
}
public bool AddEventSchQIS(QueueItemStruct QIS, EventPriority priority)
{
if (QIS.ID == null || QIS.ID.Script == null || QIS.ID.IgnoreNew)
{
EventManager.EventComplete(QIS);
return false;
}
if (!QIS.ID.SetEventParams(QIS.functionName, QIS.llDetectParams)) // check events delay rules
{
EventManager.EventComplete(QIS);
return false;
}
QIS.CurrentlyAt = null;
if (priority == EventPriority.Suspended || priority == EventPriority.Continued)
{
lock (SleepingScriptEvents)
{
long time = priority == EventPriority.Suspended ? DateTime.Now.AddMilliseconds(10).Ticks : DateTime.Now.Ticks;
//Let it sleep for 10ms so that other scripts can process before it, any repeating plugins ought to use this
SleepingScriptEvents.Enqueue(QIS, time);
SleepingScriptEventCount++;
#if Debug
MainConsole.Instance.Warn (ScriptEventCount + ", " + QIS.functionName);
#endif
}
}
else
ScriptEvents.Enqueue(QIS);
long threadCount = Interlocked.Read(ref scriptThreadpool.nthreads);
if (threadCount == 0 || threadCount < (ScriptEvents.Count + (SleepingScriptEventCount / 2)) * EventPerformance)
{
scriptThreadpool.QueueEvent(eventLoop, 2);
}
return true;
}
public void eventLoop()
{
int numberOfEmptyWork = 0;
while (!m_ScriptEngine.ConsoleDisabled && !m_ScriptEngine.Disabled)
{
//int numScriptsProcessed = 0;
int numSleepScriptsProcessed = 0;
//const int minNumScriptsToProcess = 1;
//processMoreScripts:
QueueItemStruct QIS = null;
//Check whether it is time, and then do the thread safety piece
if (Interlocked.CompareExchange(ref m_CheckingSleepers, 1, 0) == 0)
{
lock (SleepingScriptEvents)
{
if (SleepingScriptEvents.Count > 0)
{
QIS = SleepingScriptEvents.Dequeue().Value;
restart:
if (QIS.RunningNumber > 2 && SleepingScriptEventCount > 0 &&
numSleepScriptsProcessed < SleepingScriptEventCount)
{
QIS.RunningNumber = 1;
SleepingScriptEvents.Enqueue(QIS, QIS.EventsProcData.TimeCheck.Ticks);
QIS = SleepingScriptEvents.Dequeue().Value;
numSleepScriptsProcessed++;
goto restart;
}
}
}
if (QIS != null)
{
if (QIS.EventsProcData.TimeCheck.Ticks < DateTime.Now.Ticks)
{
DateTime NextTime = DateTime.MaxValue;
lock (SleepingScriptEvents)
{
if (SleepingScriptEvents.Count > 0)
NextTime = SleepingScriptEvents.Peek().Value.EventsProcData.TimeCheck;
//Now add in the next sleep time
NextSleepersTest = NextTime;
//All done
Interlocked.Exchange(ref m_CheckingSleepers, 0);
}
//Execute the event
EventSchExec(QIS);
lock (SleepingScriptEvents)
SleepingScriptEventCount--;
//numScriptsProcessed++;
}
else
{
lock (SleepingScriptEvents)
{
NextSleepersTest = QIS.EventsProcData.TimeCheck;
SleepingScriptEvents.Enqueue(QIS, QIS.EventsProcData.TimeCheck.Ticks);
//All done
Interlocked.Exchange(ref m_CheckingSleepers, 0);
}
}
}
else //No more left, don't check again
{
lock (SleepingScriptEvents)
{
NextSleepersTest = DateTime.MaxValue;
//All done
Interlocked.Exchange(ref m_CheckingSleepers, 0);
}
}
}
QIS = null;
int timeToSleep = 5;
//If we can, get the next event
if (Interlocked.CompareExchange(ref m_CheckingEvents, 1, 0) == 0)
{
if (ScriptEvents.TryDequeue(out QIS))
{
Interlocked.Exchange(ref m_CheckingEvents, 0);
#if Debug
MainConsole.Instance.Warn(QIS.functionName + "," + ScriptEvents.Count);
#endif
EventSchExec(QIS);
//numScriptsProcessed++;
}
else
Interlocked.Exchange(ref m_CheckingEvents, 0);
}
//Process a bunch each time
//if (ScriptEventCount > 0 && numScriptsProcessed < minNumScriptsToProcess)
// goto processMoreScripts;
if (ScriptEvents.Count == 0 && NextSleepersTest.Ticks != DateTime.MaxValue.Ticks)
timeToSleep = (int)(NextSleepersTest - DateTime.Now).TotalMilliseconds;
if (timeToSleep < 5)
timeToSleep = 5;
if (timeToSleep > 50)
timeToSleep = 50;
if (SleepingScriptEventCount == 0 && ScriptEvents.Count == 0)
{
numberOfEmptyWork++;
if (numberOfEmptyWork > EMPTY_WORK_KILL_THREAD_TIME)
//Don't break immediately, otherwise we have to wait to spawn more threads
{
break; //No more events, end
}
else if (numberOfEmptyWork > EMPTY_WORK_KILL_THREAD_TIME / 20)
timeToSleep += 10;
}
else if (Interlocked.Read(ref scriptThreadpool.nthreads) >
(ScriptEvents.Count + (int)((SleepingScriptEventCount / 2f + 0.5f))) ||
Interlocked.Read(ref scriptThreadpool.nthreads) > MaxScriptThreads)
{
numberOfEmptyWork++;
if (numberOfEmptyWork > (EMPTY_WORK_KILL_THREAD_TIME / 2)) //Don't break immediately
{
break; //Too many threads, kill some off
}
else if (numberOfEmptyWork > EMPTY_WORK_KILL_THREAD_TIME / 20)
timeToSleep += 5;
}
else
numberOfEmptyWork /= 2; //Cut it down, but don't zero it out, as this may just be one event
#if Debug
MainConsole.Instance.Warn ("Sleep: " + timeToSleep);
#endif
Interlocked.Increment(ref scriptThreadpool.nSleepingthreads);
Thread.Sleep(timeToSleep);
Interlocked.Decrement(ref scriptThreadpool.nSleepingthreads);
}
}
public void EventSchExec(QueueItemStruct QIS)
{
if (QIS.ID == null || QIS.ID.Script == null)
return;
if (!QIS.ID.Running)
{
//do only state_entry and on_rez
if (QIS.functionName != "state_entry"
|| QIS.functionName != "on_rez")
{
return;
}
}
//Check the versionID so that we can kill events
if (QIS.functionName != "link_message" &&
QIS.VersionID != Interlocked.Read(ref QIS.ID.VersionID))
{
MainConsole.Instance.WarnFormat("FOUND BAD VERSION ID, OLD {0}, NEW {1}, FUNCTION NAME {2}", QIS.VersionID,
Interlocked.Read(ref QIS.ID.VersionID), QIS.functionName);
//return;
}
MainConsole.Instance.Trace("[ADNE]: Running Event " + QIS.functionName + " in object " + QIS.ID.Part.ToString() + " in region " + QIS.ID.Part.ParentEntity.Scene.RegionInfo.RegionName);
if (!EventSchProcessQIS(ref QIS)) //Execute the event
{
//All done
QIS.EventsProcData.State = ScriptEventsState.Idle;
}
else
{
if (QIS.CurrentlyAt.SleepTo.Ticks != 0)
{
QIS.EventsProcData.TimeCheck = QIS.CurrentlyAt.SleepTo;
QIS.EventsProcData.State = ScriptEventsState.Sleep;
//If it is greater, we need to check sooner for this one
if (NextSleepersTest.Ticks > QIS.CurrentlyAt.SleepTo.Ticks)
NextSleepersTest = QIS.CurrentlyAt.SleepTo;
lock (SleepingScriptEvents)
{
SleepingScriptEvents.Enqueue(QIS, QIS.CurrentlyAt.SleepTo.Ticks);
SleepingScriptEventCount++;
}
}
else
{
QIS.EventsProcData.State = ScriptEventsState.Running;
this.ScriptEvents.Enqueue(QIS);
}
}
}
public bool EventSchProcessQIS(ref QueueItemStruct QIS)
{
try
{
Exception ex = null;
EnumeratorInfo Running = QIS.ID.Script.ExecuteEvent(QIS.State,
QIS.functionName,
QIS.param, QIS.CurrentlyAt, out ex);
if (ex != null)
{
//Check exceptions, some are ours to deal with, and others are to be logged
if (ex.Message.Contains("SelfDeleteException"))
{
if (QIS.ID.Part != null && QIS.ID.Part.ParentEntity != null)
{
IBackupModule backup =
QIS.ID.Part.ParentEntity.Scene.RequestModuleInterface<IBackupModule>();
if (backup != null)
backup.DeleteSceneObjects(
new ISceneEntity[1] { QIS.ID.Part.ParentEntity }, true, true);
}
}
else if (ex.Message.Contains("ScriptDeleteException"))
{
if (QIS.ID.Part != null && QIS.ID.Part.ParentEntity != null)
QIS.ID.Part.Inventory.RemoveInventoryItem(QIS.ID.ItemID);
}
//Log it for the user
else if (!(ex.Message.Contains("EventAbortException")) &&
!(ex.Message.Contains("MinEventDelayException")))
QIS.ID.DisplayUserNotification(ex.ToString(), "executing", false, true);
return false;
}
else if (Running != null)
{
//Did not finish so requeue it
QIS.CurrentlyAt = Running;
QIS.RunningNumber++;
return true; //Do the return... otherwise we open the queue for this event back up
}
}
catch (Exception ex)
{
//Error, tell the user
QIS.ID.DisplayUserNotification(ex.ToString(), "executing", false, true);
}
//Tell the event manager about it so that the events will be removed from the queue
EventManager.EventComplete(QIS);
return false;
}
#endregion
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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.IO;
using NUnit.Framework;
namespace DiscUtils
{
[TestFixture]
public class DiscFileSystemFileTest
{
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void CreateFile(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
using (Stream s = fs.GetFileInfo("foo.txt").Open(FileMode.Create, FileAccess.ReadWrite))
{
s.WriteByte(1);
}
DiscFileInfo fi = fs.GetFileInfo("foo.txt");
Assert.IsTrue(fi.Exists);
Assert.AreEqual(FileAttributes.Archive, fi.Attributes);
Assert.AreEqual(1, fi.Length);
using (Stream s = fs.OpenFile("Foo.txt", FileMode.Open, FileAccess.Read))
{
Assert.AreEqual(1, s.ReadByte());
}
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
[ExpectedException(typeof(IOException))]
[Category("ThrowsException")]
public void CreateFileInvalid_Long(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
using (Stream s = fs.GetFileInfo(new string('X', 256)).Open(FileMode.Create, FileAccess.ReadWrite))
{
s.WriteByte(1);
}
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
[ExpectedException(typeof(IOException))]
[Category("ThrowsException")]
public void CreateFileInvalid_Characters(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
using (Stream s = fs.GetFileInfo("A\0File").Open(FileMode.Create, FileAccess.ReadWrite))
{
s.WriteByte(1);
}
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void DeleteFile(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
using (Stream s = fs.GetFileInfo("foo.txt").Open(FileMode.Create, FileAccess.ReadWrite)) { }
Assert.AreEqual(1, fs.Root.GetFiles().Length);
DiscFileInfo fi = fs.GetFileInfo("foo.txt");
fi.Delete();
Assert.AreEqual(0, fs.Root.GetFiles().Length);
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void Length(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
using (Stream s = fs.GetFileInfo("foo.txt").Open(FileMode.Create, FileAccess.ReadWrite))
{
s.SetLength(3128);
}
Assert.AreEqual(3128, fs.GetFileInfo("foo.txt").Length);
using (Stream s = fs.OpenFile("foo.txt", FileMode.Open, FileAccess.ReadWrite))
{
s.SetLength(3);
Assert.AreEqual(3, s.Length);
}
Assert.AreEqual(3, fs.GetFileInfo("foo.txt").Length);
using (Stream s = fs.OpenFile("foo.txt", FileMode.Open, FileAccess.ReadWrite))
{
s.SetLength(3333);
byte[] buffer = new byte[512];
for(int i = 0; i < buffer.Length; ++i)
{
buffer[i] = (byte)i;
}
s.Write(buffer, 0, buffer.Length);
s.Write(buffer, 0, buffer.Length);
Assert.AreEqual(1024, s.Position);
Assert.AreEqual(3333, s.Length);
s.SetLength(512);
Assert.AreEqual(512, s.Length);
}
using (Stream s = fs.OpenFile("foo.txt", FileMode.Open, FileAccess.ReadWrite))
{
byte[] buffer = new byte[512];
int numRead = s.Read(buffer, 0, buffer.Length);
int totalRead = 0;
while (numRead != 0)
{
totalRead += numRead;
numRead = s.Read(buffer, totalRead, buffer.Length - totalRead);
}
for (int i = 0; i < buffer.Length; ++i)
{
Assert.AreEqual((byte)i, buffer[i]);
}
}
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
[ExpectedException(typeof(FileNotFoundException))]
[Category("ThrowsException")]
public void Open_FileNotFound(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
DiscFileInfo di = fs.GetFileInfo("foo.txt");
using (Stream s = di.Open(FileMode.Open)) { }
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
[ExpectedException(typeof(IOException))]
[Category("ThrowsException")]
public void Open_FileExists(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
DiscFileInfo di = fs.GetFileInfo("foo.txt");
using (Stream s = di.Open(FileMode.Create)) { s.WriteByte(1); }
using (Stream s = di.Open(FileMode.CreateNew)) { }
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
[ExpectedException(typeof(IOException))]
[Category("ThrowsException")]
public void Open_DirExists(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
fs.CreateDirectory("FOO.TXT");
DiscFileInfo di = fs.GetFileInfo("foo.txt");
using (Stream s = di.Open(FileMode.Create)) { s.WriteByte(1); }
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void Open_Read(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
DiscFileInfo di = fs.GetFileInfo("foo.txt");
using (Stream s = di.Open(FileMode.Create))
{
s.WriteByte(1);
}
using (Stream s = di.Open(FileMode.Open, FileAccess.Read))
{
Assert.IsFalse(s.CanWrite);
Assert.IsTrue(s.CanRead);
Assert.AreEqual(1, s.ReadByte());
}
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
[ExpectedException(typeof(IOException))]
[Category("ThrowsException")]
public void Open_Read_Fail(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
DiscFileInfo di = fs.GetFileInfo("foo.txt");
using (Stream s = di.Open(FileMode.Create, FileAccess.Read))
{
s.WriteByte(1);
}
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void Open_Write(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
DiscFileInfo di = fs.GetFileInfo("foo.txt");
using (Stream s = di.Open(FileMode.Create, FileAccess.Write))
{
Assert.IsTrue(s.CanWrite);
Assert.IsFalse(s.CanRead);
s.WriteByte(1);
}
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
[ExpectedException(typeof(IOException))]
[Category("ThrowsException")]
public void Open_Write_Fail(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
DiscFileInfo di = fs.GetFileInfo("foo.txt");
using (Stream s = di.Open(FileMode.Create, FileAccess.ReadWrite))
{
s.WriteByte(1);
}
using (Stream s = di.Open(FileMode.Open, FileAccess.Write))
{
Assert.IsTrue(s.CanWrite);
Assert.IsFalse(s.CanRead);
s.ReadByte();
}
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void Name(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
Assert.AreEqual("foo.txt", fs.GetFileInfo("foo.txt").Name);
Assert.AreEqual("foo.txt", fs.GetFileInfo(@"path\foo.txt").Name);
Assert.AreEqual("foo.txt", fs.GetFileInfo(@"\foo.txt").Name);
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void Attributes(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
DiscFileInfo fi = fs.GetFileInfo("foo.txt");
using (Stream s = fi.Open(FileMode.Create)) { }
// Check default attributes
Assert.AreEqual(FileAttributes.Archive, fi.Attributes);
// Check round-trip
FileAttributes newAttrs = FileAttributes.Hidden | FileAttributes.ReadOnly | FileAttributes.System;
fi.Attributes = newAttrs;
Assert.AreEqual(newAttrs, fi.Attributes);
// And check persistence to disk
Assert.AreEqual(newAttrs, fs.GetFileInfo("foo.txt").Attributes);
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
[ExpectedException(typeof(ArgumentException))]
[Category("ThrowsException")]
public void Attributes_ChangeType(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
DiscFileInfo fi = fs.GetFileInfo("foo.txt");
using (Stream s = fi.Open(FileMode.Create)) { }
fi.Attributes = fi.Attributes | FileAttributes.Directory;
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void Exists(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
DiscFileInfo fi = fs.GetFileInfo("foo.txt");
Assert.IsFalse(fi.Exists);
using (Stream s = fi.Open(FileMode.Create)) { }
Assert.IsTrue(fi.Exists);
fs.CreateDirectory("dir.txt");
Assert.IsFalse(fs.GetFileInfo("dir.txt").Exists);
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void CreationTimeUtc(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
using (Stream s = fs.OpenFile("foo.txt", FileMode.Create)) { }
Assert.GreaterOrEqual(DateTime.UtcNow, fs.GetFileInfo("foo.txt").CreationTimeUtc);
Assert.LessOrEqual(DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(10)), fs.GetFileInfo("foo.txt").CreationTimeUtc);
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void CreationTime(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
using (Stream s = fs.OpenFile("foo.txt", FileMode.Create)) { }
Assert.GreaterOrEqual(DateTime.Now, fs.GetFileInfo("foo.txt").CreationTime);
Assert.LessOrEqual(DateTime.Now.Subtract(TimeSpan.FromSeconds(10)), fs.GetFileInfo("foo.txt").CreationTime);
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void LastAccessTime(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
using (Stream s = fs.OpenFile("foo.txt", FileMode.Create)) { }
DiscFileInfo fi = fs.GetFileInfo("foo.txt");
DateTime baseTime = DateTime.Now - TimeSpan.FromDays(2);
fi.LastAccessTime = baseTime;
using (Stream s = fs.OpenFile("foo.txt", FileMode.Open, FileAccess.Read)) { }
Assert.Less(baseTime, fi.LastAccessTime);
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void LastWriteTime(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
using (Stream s = fs.OpenFile("foo.txt", FileMode.Create)) { }
DiscFileInfo fi = fs.GetFileInfo("foo.txt");
DateTime baseTime = DateTime.Now - TimeSpan.FromMinutes(10);
fi.LastWriteTime = baseTime;
using (Stream s = fs.OpenFile("foo.txt", FileMode.Open)) { s.WriteByte(1); }
Assert.Less(baseTime, fi.LastWriteTime);
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void Delete(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
using (Stream s = fs.OpenFile("foo.txt", FileMode.Create)) { }
fs.GetFileInfo("foo.txt").Delete();
Assert.IsFalse(fs.FileExists("foo.txt"));
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
[ExpectedException(typeof(FileNotFoundException))]
[Category("ThrowsException")]
public void Delete_Dir(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
fs.CreateDirectory("foo.txt");
fs.GetFileInfo("foo.txt").Delete();
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
[ExpectedException(typeof(FileNotFoundException))]
[Category("ThrowsException")]
public void Delete_NoFile(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
fs.GetFileInfo("foo.txt").Delete();
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void CopyFile(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
DiscFileInfo fi = fs.GetFileInfo("foo.txt");
using (Stream s = fi.Create())
{
for (int i = 0; i < 10; ++i)
{
s.Write(new byte[111], 0, 111);
}
}
fi.Attributes = FileAttributes.Hidden | FileAttributes.System;
fi.CopyTo("foo2.txt");
fi = fs.GetFileInfo("foo2.txt");
Assert.IsTrue(fi.Exists);
Assert.AreEqual(1110, fi.Length);
Assert.AreEqual(FileAttributes.Hidden | FileAttributes.System, fi.Attributes);
fi = fs.GetFileInfo("foo.txt");
Assert.IsTrue(fi.Exists);
fi = fs.GetFileInfo("foo2.txt");
Assert.IsTrue(fi.Exists);
Assert.AreEqual(1110, fi.Length);
Assert.AreEqual(FileAttributes.Hidden | FileAttributes.System, fi.Attributes);
fi = fs.GetFileInfo("foo.txt");
Assert.IsTrue(fi.Exists);
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void MoveFile(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
DiscFileInfo fi = fs.GetFileInfo("foo.txt");
using (Stream s = fi.Create())
{
for (int i = 0; i < 10; ++i)
{
s.Write(new byte[111], 0, 111);
}
}
fi.Attributes = FileAttributes.Hidden | FileAttributes.System;
fi.MoveTo("foo2.txt");
fi = fs.GetFileInfo("foo2.txt");
Assert.IsTrue(fi.Exists);
Assert.AreEqual(1110, fi.Length);
Assert.AreEqual(FileAttributes.Hidden | FileAttributes.System, fi.Attributes);
fi = fs.GetFileInfo("foo.txt");
Assert.IsFalse(fi.Exists);
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void MoveFile_Overwrite(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
DiscFileInfo fi = fs.GetFileInfo("foo.txt");
using (Stream s = fi.Create())
{
s.WriteByte(1);
}
DiscFileInfo fi2 = fs.GetFileInfo("foo2.txt");
using (Stream s = fi2.Create())
{
}
fs.MoveFile("foo.txt", "foo2.txt", true);
Assert.IsFalse(fi.Exists);
Assert.IsTrue(fi2.Exists);
Assert.AreEqual(1, fi2.Length);
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void Equals(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
Assert.AreEqual(fs.GetFileInfo("foo.txt"), fs.GetFileInfo("foo.txt"));
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void Parent(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
fs.CreateDirectory(@"SOMEDIR\ADIR");
using (Stream s = fs.OpenFile(@"SOMEDIR\ADIR\FILE.TXT", FileMode.Create)) { }
DiscFileInfo fi = fs.GetFileInfo(@"SOMEDIR\ADIR\FILE.TXT");
Assert.AreEqual(fs.GetDirectoryInfo(@"SOMEDIR\ADIR"), fi.Parent);
Assert.AreEqual(fs.GetDirectoryInfo(@"SOMEDIR\ADIR"), fi.Directory);
}
[TestCaseSource(typeof(FileSystemSource), "ReadWriteFileSystems")]
public void VolumeLabel(NewFileSystemDelegate fsFactory)
{
DiscFileSystem fs = fsFactory();
string volLabel = fs.VolumeLabel;
Assert.NotNull(volLabel);
}
}
}
| |
using Android;
using Android.Content;
using Android.Content.Res;
using Android.Graphics;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.Lang;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace CustomBalloon
{
public class MyBalloonView : View
{
private readonly Regex re = new Regex(@"\:(\w+)\:", RegexOptions.Compiled);
private readonly Dictionary<string, int> _emojis =
new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
{
{ "grin", 0x1F601 },
{ "joy", 0x1F602 },
{ "smile", 0x1F603 },
{ "smiling", 0x1F604 },
{ "sweat_smile", 0x1F605 },
{ "laugh", 0x1F606 }
};
private readonly List<string> monkeyPhrases =
new List<string>() {
"Xamarin Evolve rocks my rainbow socks!",
"Have you visited the Darwin Lounge?",
"Is Woz in the house?",
"What's in your swag bag?",
"I learned a lot this week!",
"Did you get a selfie with James?",
"How much coffee did you drink today?",
"I'm ready to create awesome apps!",
"A banana split would be good right now"
};
private string _defaultGreeting = "Hello";
private Paint _textPaint;
private Paint _backgroundPaint;
private bool _showEmojis;
private string _text;
private float _textSize;
private int _triangleHeight;
private Color _balloonColor;
private Color _textColor;
private Color _accentColor;
private bool _useAccentColor;
//at a minimum you must provide a constructor that takes a Context and an AttributeSet object as parameters
public MyBalloonView(Context context, IAttributeSet attrs) : base(context, attrs)
{
InitializePaint();
TypedArray typeArray = context.Theme.ObtainStyledAttributes(attrs, Resource.Styleable.MyBalloonView, 0, 0);
ShowEmojis = typeArray.GetBoolean(Resource.Styleable.MyBalloonView_showEmoji, true);
BalloonColor = typeArray.GetColor(Resource.Styleable.MyBalloonView_balloonColor, Color.Black);
TriangleHeight = typeArray.GetInt(Resource.Styleable.MyBalloonView_triangleHeight, 40);
Text = typeArray.GetString(Resource.Styleable.MyBalloonView_text);
TextSize = typeArray.GetDimension(Resource.Styleable.MyBalloonView_textSize, 36f);
TextColor = typeArray.GetColor(Resource.Styleable.MyBalloonView_textColor, Color.White);
typeArray.Recycle();
}
public MyBalloonView(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
{
InitializePaint();
}
public MyBalloonView(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes)
: base(context, attrs, defStyleAttr, defStyleRes)
{
InitializePaint();
}
public string Text
{
get { return _text; }
set
{
_text = FormatText(value);
InvalidateAndRedraw();
}
}
public float TextSize
{
get { return _textSize; }
set
{
_textSize = value;
_textPaint.TextSize = _textSize;
InvalidateAndRedraw();
}
}
public bool ShowEmojis
{
get { return _showEmojis; }
set
{
_showEmojis = value;
InvalidateAndRedraw();
}
}
public Color AccentColor
{
get { return _accentColor; }
set
{
_accentColor = value;
InvalidateAndRedraw();
}
}
public Color BalloonColor
{
get { return _balloonColor; }
set
{
_balloonColor = value;
InvalidateAndRedraw();
}
}
public Color TextColor
{
get { return _textColor; }
set
{
_textColor = value;
_textPaint.Color = _textColor;
InvalidateAndRedraw();
}
}
public int TriangleHeight
{
get { return _triangleHeight; }
set
{
_triangleHeight = value;
InvalidateAndRedraw();
}
}
public override bool OnTouchEvent(MotionEvent e)
{
_useAccentColor = (e.Action == MotionEventActions.Down);
if (e.Action == MotionEventActions.Up)
{
this.Text = GetRandomPhrase();
}
InvalidateAndRedraw();
return true;
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
float textMeasurement = _textPaint.MeasureText(this.Text);
SetMeasuredDimension((int)textMeasurement + 50, MeasuredHeight);
}
protected override void OnDraw(Canvas canvas)
{
_backgroundPaint.Color = (_useAccentColor) ? AccentColor : BalloonColor;
float textMeasurement = _textPaint.MeasureText(this.Text);
float balloonCenterX = MeasuredWidth / 2;
int triangleStart = 80;
RectF r = new RectF(0, 0, MeasuredWidth, MeasuredHeight - TriangleHeight);
canvas.DrawRoundRect(r, 30f, 30f, _backgroundPaint);
Point startingPoint = new Point(triangleStart, (int)r.Bottom);
Point firstLine = new Point(triangleStart, MeasuredHeight);
Point secondLine = new Point(triangleStart - (TriangleHeight / 2), MeasuredHeight - TriangleHeight);
Path path = new Path();
path.MoveTo(startingPoint.X, startingPoint.Y);
path.LineTo(firstLine.X, firstLine.Y);
path.LineTo(secondLine.X, secondLine.Y);
float textX = balloonCenterX - textMeasurement / 2;
float textY = MeasuredHeight / 2;
canvas.DrawPath(path, _backgroundPaint);
canvas.DrawText(this.Text, textX, textY, _textPaint);
}
private void InvalidateAndRedraw()
{
Invalidate();
RequestLayout();
}
private string FormatText(string text)
{
string formattedText = string.IsNullOrEmpty(text) ? _defaultGreeting : text;
if (ShowEmojis && !string.IsNullOrEmpty(text))
{
formattedText = re.Replace(text,
match => GetEmoji(match.Groups[1].Value, match.Value));
}
return formattedText;
}
private string GetEmoji(string key, string originalText)
{
string emojified = _emojis.ContainsKey(key)
? new string(Character.ToChars(_emojis[key]))
: originalText;
return emojified;
}
private string GetRandomPhrase()
{
int maxValue = monkeyPhrases.Count - 1;
int maxEmojiValue = _emojis.Count - 1;
Random randomPhrase = new Random();
int randomIndex = randomPhrase.Next(0, maxValue);
string phrase = monkeyPhrases.ElementAt(randomIndex);
Random randomEmoji = new Random();
int randomEmojiIndex = randomEmoji.Next(0, maxEmojiValue);
string emoji = _emojis.Keys.ElementAt(randomEmojiIndex);
return $"{phrase} :{emoji}:";
}
private void InitializePaint()
{
_textPaint = new Paint();
_backgroundPaint = new Paint();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using ICSharpCode.SharpZipLib.Zip;
using MarkdownSharp;
using NuGet;
using Splat;
using ICSharpCode.SharpZipLib.Core;
namespace Squirrel
{
internal static class FrameworkTargetVersion
{
public static FrameworkName Net40 = new FrameworkName(".NETFramework,Version=v4.0");
public static FrameworkName Net45 = new FrameworkName(".NETFramework,Version=v4.5");
}
public interface IReleasePackage
{
string InputPackageFile { get; }
string ReleasePackageFile { get; }
string SuggestedReleaseFileName { get; }
string CreateReleasePackage(string outputFile, string packagesRootDir = null, Func<string, string> releaseNotesProcessor = null, Action<string> contentsPostProcessHook = null);
}
public static class VersionComparer
{
public static bool Matches(IVersionSpec versionSpec, SemanticVersion version)
{
if (versionSpec == null)
return true; // I CAN'T DEAL WITH THIS
bool minVersion;
if (versionSpec.MinVersion == null) {
minVersion = true; // no preconditon? LET'S DO IT
} else if (versionSpec.IsMinInclusive) {
minVersion = version >= versionSpec.MinVersion;
} else {
minVersion = version > versionSpec.MinVersion;
}
bool maxVersion;
if (versionSpec.MaxVersion == null) {
maxVersion = true; // no preconditon? LET'S DO IT
} else if (versionSpec.IsMaxInclusive) {
maxVersion = version <= versionSpec.MaxVersion;
} else {
maxVersion = version < versionSpec.MaxVersion;
}
return maxVersion && minVersion;
}
}
public class ReleasePackage : IEnableLogger, IReleasePackage
{
IEnumerable<IPackage> localPackageCache;
public ReleasePackage(string inputPackageFile, bool isReleasePackage = false)
{
InputPackageFile = inputPackageFile;
if (isReleasePackage) {
ReleasePackageFile = inputPackageFile;
}
}
public string InputPackageFile { get; protected set; }
public string ReleasePackageFile { get; protected set; }
public string SuggestedReleaseFileName {
get {
var zp = new ZipPackage(InputPackageFile);
return String.Format("{0}-{1}-full.nupkg", zp.Id, zp.Version);
}
}
public Version Version { get { return InputPackageFile.ToVersion(); } }
public string CreateReleasePackage(string outputFile, string packagesRootDir = null, Func<string, string> releaseNotesProcessor = null, Action<string> contentsPostProcessHook = null)
{
Contract.Requires(!String.IsNullOrEmpty(outputFile));
releaseNotesProcessor = releaseNotesProcessor ?? (x => (new Markdown()).Transform(x));
if (ReleasePackageFile != null) {
return ReleasePackageFile;
}
var package = new ZipPackage(InputPackageFile);
// we can tell from here what platform(s) the package targets
// but given this is a simple package we only
// ever expect one entry here (crash hard otherwise)
var frameworks = package.GetSupportedFrameworks();
if (frameworks.Count() > 1) {
var platforms = frameworks
.Aggregate(new StringBuilder(), (sb, f) => sb.Append(f.ToString() + "; "));
throw new InvalidOperationException(String.Format(
"The input package file {0} targets multiple platforms - {1} - and cannot be transformed into a release package.", InputPackageFile, platforms));
} else if (!frameworks.Any()) {
throw new InvalidOperationException(String.Format(
"The input package file {0} targets no platform and cannot be transformed into a release package.", InputPackageFile));
}
var targetFramework = frameworks.Single();
// Recursively walk the dependency tree and extract all of the
// dependent packages into the a temporary directory
this.Log().Info("Creating release package: {0} => {1}", InputPackageFile, outputFile);
var dependencies = findAllDependentPackages(
package,
new LocalPackageRepository(packagesRootDir),
frameworkName: targetFramework);
string tempPath = null;
using (Utility.WithTempDirectory(out tempPath, null)) {
var tempDir = new DirectoryInfo(tempPath);
extractZipDecoded(InputPackageFile, tempPath);
this.Log().Info("Extracting dependent packages: [{0}]", String.Join(",", dependencies.Select(x => x.Id)));
extractDependentPackages(dependencies, tempDir, targetFramework);
var specPath = tempDir.GetFiles("*.nuspec").First().FullName;
this.Log().Info("Removing unnecessary data");
removeDependenciesFromPackageSpec(specPath);
removeDeveloperDocumentation(tempDir);
if (releaseNotesProcessor != null) {
renderReleaseNotesMarkdown(specPath, releaseNotesProcessor);
}
addDeltaFilesToContentTypes(tempDir.FullName);
if (contentsPostProcessHook != null) {
contentsPostProcessHook(tempPath);
}
createZipEncoded(outputFile, tempPath);
ReleasePackageFile = outputFile;
return ReleasePackageFile;
}
}
// nupkg file %-encodes zip entry names. This method decodes entry names before writing to disk.
// We must do this, or PathTooLongException may be thrown for some unicode entry names.
void extractZipDecoded(string zipFilePath, string outFolder)
{
var zf = new ZipFile(zipFilePath);
foreach (ZipEntry zipEntry in zf) {
if (!zipEntry.IsFile) continue;
var entryFileName = Uri.UnescapeDataString(zipEntry.Name);
var buffer = new byte[4096];
var zipStream = zf.GetInputStream(zipEntry);
var fullZipToPath = Path.Combine(outFolder, entryFileName);
var directoryName = Path.GetDirectoryName(fullZipToPath);
if (directoryName.Length > 0) {
Directory.CreateDirectory(directoryName);
}
using (FileStream streamWriter = File.Create(fullZipToPath)) {
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
}
zf.Close();
}
// Create zip file with entry names %-encoded, as nupkg file does.
void createZipEncoded(string zipFilePath, string folder)
{
folder = Path.GetFullPath(folder);
var offset = folder.Length + (folder.EndsWith("\\", StringComparison.OrdinalIgnoreCase) ? 1 : 0);
var fsOut = File.Create(zipFilePath);
var zipStream = new ZipOutputStream(fsOut);
zipStream.SetLevel(5);
compressFolderEncoded(folder, zipStream, offset);
zipStream.IsStreamOwner = true;
zipStream.Close();
}
void compressFolderEncoded(string path, ZipOutputStream zipStream, int folderOffset)
{
string[] files = Directory.GetFiles(path);
foreach (string filename in files) {
FileInfo fi = new FileInfo(filename);
string entryName = filename.Substring(folderOffset);
entryName = ZipEntry.CleanName(entryName);
entryName = Uri.EscapeUriString(entryName);
var newEntry = new ZipEntry(entryName);
newEntry.DateTime = fi.LastWriteTime;
newEntry.Size = fi.Length;
zipStream.PutNextEntry(newEntry);
var buffer = new byte[4096];
using (FileStream streamReader = File.OpenRead(filename)) {
StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();
}
string[] folders = Directory.GetDirectories(path);
foreach (string folder in folders) {
compressFolderEncoded(folder, zipStream, folderOffset);
}
}
void extractDependentPackages(IEnumerable<IPackage> dependencies, DirectoryInfo tempPath, FrameworkName framework)
{
dependencies.ForEach(pkg => {
this.Log().Info("Scanning {0}", pkg.Id);
pkg.GetLibFiles().ForEach(file => {
var outPath = new FileInfo(Path.Combine(tempPath.FullName, file.Path));
if (!VersionUtility.IsCompatible(framework , new[] { file.TargetFramework }))
{
this.Log().Info("Ignoring {0} as the target framework is not compatible", outPath);
return;
}
Directory.CreateDirectory(outPath.Directory.FullName);
using (var of = File.Create(outPath.FullName)) {
this.Log().Info("Writing {0} to {1}", file.Path, outPath);
file.GetStream().CopyTo(of);
}
});
});
}
void removeDeveloperDocumentation(DirectoryInfo expandedRepoPath)
{
expandedRepoPath.GetAllFilesRecursively()
.Where(x => x.Name.EndsWith(".dll", true, CultureInfo.InvariantCulture))
.Select(x => new FileInfo(x.FullName.ToLowerInvariant().Replace(".dll", ".xml")))
.Where(x => x.Exists)
.ForEach(x => x.Delete());
}
void renderReleaseNotesMarkdown(string specPath, Func<string, string> releaseNotesProcessor)
{
var doc = new XmlDocument();
doc.Load(specPath);
// XXX: This code looks full tart
var metadata = doc.DocumentElement.ChildNodes
.OfType<XmlElement>()
.First(x => x.Name.ToLowerInvariant() == "metadata");
var releaseNotes = metadata.ChildNodes
.OfType<XmlElement>()
.FirstOrDefault(x => x.Name.ToLowerInvariant() == "releasenotes");
if (releaseNotes == null) {
this.Log().Info("No release notes found in {0}", specPath);
return;
}
releaseNotes.InnerText = String.Format("<![CDATA[\n" + "{0}\n" + "]]>",
releaseNotesProcessor(releaseNotes.InnerText));
doc.Save(specPath);
}
void removeDependenciesFromPackageSpec(string specPath)
{
var xdoc = new XmlDocument();
xdoc.Load(specPath);
var metadata = xdoc.DocumentElement.FirstChild;
var dependenciesNode = metadata.ChildNodes.OfType<XmlElement>().FirstOrDefault(x => x.Name.ToLowerInvariant() == "dependencies");
if (dependenciesNode != null) {
metadata.RemoveChild(dependenciesNode);
}
xdoc.Save(specPath);
}
internal IEnumerable<IPackage> findAllDependentPackages(
IPackage package = null,
IPackageRepository packageRepository = null,
HashSet<string> packageCache = null,
FrameworkName frameworkName = null)
{
package = package ?? new ZipPackage(InputPackageFile);
packageCache = packageCache ?? new HashSet<string>();
var deps = package.DependencySets
.Where(x => x.TargetFramework == null
|| x.TargetFramework == frameworkName)
.SelectMany(x => x.Dependencies);
return deps.SelectMany(dependency => {
var ret = matchPackage(packageRepository, dependency.Id, dependency.VersionSpec);
if (ret == null) {
var message = String.Format("Couldn't find file for package in {1}: {0}", dependency.Id, packageRepository.Source);
this.Log().Error(message);
throw new Exception(message);
}
if (packageCache.Contains(ret.GetFullName())) {
return Enumerable.Empty<IPackage>();
}
packageCache.Add(ret.GetFullName());
return findAllDependentPackages(ret, packageRepository, packageCache, frameworkName).StartWith(ret).Distinct(y => y.GetFullName());
}).ToArray();
}
IPackage matchPackage(IPackageRepository packageRepository, string id, IVersionSpec version)
{
return packageRepository.FindPackagesById(id).FirstOrDefault(x => VersionComparer.Matches(version, x.Version));
}
static internal void addDeltaFilesToContentTypes(string rootDirectory)
{
var doc = new XmlDocument();
var path = Path.Combine(rootDirectory, "[Content_Types].xml");
doc.Load(path);
ContentType.Merge(doc);
using (var sw = new StreamWriter(path, false, Encoding.UTF8)) {
doc.Save(sw);
}
}
}
public class ChecksumFailedException : Exception
{
public string Filename { get; set; }
}
}
| |
// 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.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Graphics.Textures;
using osu.Framework.IO.Stores;
using osu.Framework.Testing;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Formats;
using osu.Game.IO;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Objects;
using osu.Game.Screens.Ranking;
using osu.Game.Skinning;
using osu.Game.Storyboards;
using osu.Game.Tests.Visual;
using osu.Game.Users;
namespace osu.Game.Tests.Beatmaps
{
[HeadlessTest]
public abstract class HitObjectSampleTest : PlayerTestScene, IStorageResourceProvider
{
protected abstract IResourceStore<byte[]> RulesetResources { get; }
protected LegacySkin Skin { get; private set; }
[Resolved]
private RulesetStore rulesetStore { get; set; }
private readonly SkinInfo userSkinInfo = new SkinInfo();
private readonly BeatmapInfo beatmapInfo = new BeatmapInfo
{
BeatmapSet = new BeatmapSetInfo(),
Metadata = new BeatmapMetadata
{
Author = User.SYSTEM_USER
}
};
private readonly TestResourceStore userSkinResourceStore = new TestResourceStore();
private readonly TestResourceStore beatmapSkinResourceStore = new TestResourceStore();
private SkinSourceDependencyContainer dependencies;
private IBeatmap currentTestBeatmap;
protected sealed override bool HasCustomSteps => true;
protected override bool Autoplay => true;
protected sealed override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
=> new DependencyContainer(dependencies = new SkinSourceDependencyContainer(base.CreateChildDependencies(parent)));
protected sealed override IBeatmap CreateBeatmap(RulesetInfo ruleset) => currentTestBeatmap;
protected sealed override WorkingBeatmap CreateWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null)
=> new TestWorkingBeatmap(beatmapInfo, beatmapSkinResourceStore, beatmap, storyboard, Clock, this);
protected override TestPlayer CreatePlayer(Ruleset ruleset) => new TestPlayer(false);
protected void CreateTestWithBeatmap(string filename)
{
CreateTest(() =>
{
AddStep("clear performed lookups", () =>
{
userSkinResourceStore.PerformedLookups.Clear();
beatmapSkinResourceStore.PerformedLookups.Clear();
});
AddStep($"load {filename}", () =>
{
using (var reader = new LineBufferedReader(RulesetResources.GetStream($"Resources/SampleLookups/{filename}")))
currentTestBeatmap = Decoder.GetDecoder<Beatmap>(reader).Decode(reader);
// populate ruleset for beatmap converters that require it to be present.
currentTestBeatmap.BeatmapInfo.Ruleset = rulesetStore.GetRuleset(currentTestBeatmap.BeatmapInfo.RulesetID);
});
});
AddStep("seek to completion", () => Player.GameplayClockContainer.Seek(Player.DrawableRuleset.Objects.Last().GetEndTime()));
AddUntilStep("results displayed", () => Stack.CurrentScreen is ResultsScreen);
}
protected void SetupSkins(string beatmapFile, string userFile)
{
AddStep("setup skins", () =>
{
userSkinInfo.Files = new List<SkinFileInfo>
{
new SkinFileInfo
{
Filename = userFile,
FileInfo = new IO.FileInfo { Hash = userFile }
}
};
beatmapInfo.BeatmapSet.Files = new List<BeatmapSetFileInfo>
{
new BeatmapSetFileInfo
{
Filename = beatmapFile,
FileInfo = new IO.FileInfo { Hash = beatmapFile }
}
};
// Need to refresh the cached skin source to refresh the skin resource store.
dependencies.SkinSource = new SkinProvidingContainer(Skin = new LegacySkin(userSkinInfo, this));
});
}
protected void AssertBeatmapLookup(string name) => AddAssert($"\"{name}\" looked up from beatmap skin",
() => !userSkinResourceStore.PerformedLookups.Contains(name) && beatmapSkinResourceStore.PerformedLookups.Contains(name));
protected void AssertUserLookup(string name) => AddAssert($"\"{name}\" looked up from user skin",
() => !beatmapSkinResourceStore.PerformedLookups.Contains(name) && userSkinResourceStore.PerformedLookups.Contains(name));
protected void AssertNoLookup(string name) => AddAssert($"\"{name}\" not looked up",
() => !beatmapSkinResourceStore.PerformedLookups.Contains(name) && !userSkinResourceStore.PerformedLookups.Contains(name));
#region IResourceStorageProvider
public AudioManager AudioManager => Audio;
public IResourceStore<byte[]> Files => userSkinResourceStore;
public new IResourceStore<byte[]> Resources => base.Resources;
public IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => null;
#endregion
private class SkinSourceDependencyContainer : IReadOnlyDependencyContainer
{
public ISkinSource SkinSource;
private readonly IReadOnlyDependencyContainer fallback;
public SkinSourceDependencyContainer(IReadOnlyDependencyContainer fallback)
{
this.fallback = fallback;
}
public object Get(Type type)
{
if (type == typeof(ISkinSource))
return SkinSource;
return fallback.Get(type);
}
public object Get(Type type, CacheInfo info)
{
if (type == typeof(ISkinSource))
return SkinSource;
return fallback.Get(type, info);
}
public void Inject<T>(T instance) where T : class
{
// Never used directly
}
}
private class TestResourceStore : IResourceStore<byte[]>
{
public readonly List<string> PerformedLookups = new List<string>();
public byte[] Get(string name)
{
markLookup(name);
return Array.Empty<byte>();
}
public Task<byte[]> GetAsync(string name)
{
markLookup(name);
return Task.FromResult(Array.Empty<byte>());
}
public Stream GetStream(string name)
{
markLookup(name);
return new MemoryStream();
}
private void markLookup(string name) => PerformedLookups.Add(name.Substring(name.LastIndexOf(Path.DirectorySeparatorChar) + 1));
public IEnumerable<string> GetAvailableResources() => Enumerable.Empty<string>();
public void Dispose()
{
}
}
private class TestWorkingBeatmap : ClockBackedTestWorkingBeatmap
{
private readonly BeatmapInfo skinBeatmapInfo;
private readonly IResourceStore<byte[]> resourceStore;
private readonly IStorageResourceProvider resources;
public TestWorkingBeatmap(BeatmapInfo skinBeatmapInfo, IResourceStore<byte[]> resourceStore, IBeatmap beatmap, Storyboard storyboard, IFrameBasedClock referenceClock, IStorageResourceProvider resources)
: base(beatmap, storyboard, referenceClock, resources.AudioManager)
{
this.skinBeatmapInfo = skinBeatmapInfo;
this.resourceStore = resourceStore;
this.resources = resources;
}
protected override ISkin GetSkin() => new LegacyBeatmapSkin(skinBeatmapInfo, resourceStore, resources);
}
}
}
| |
// 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.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableSortedDictionaryBuilderTest : ImmutableDictionaryBuilderTestBase
{
[Fact]
public void CreateBuilder()
{
var builder = ImmutableSortedDictionary.CreateBuilder<string, string>();
Assert.NotNull(builder);
builder = ImmutableSortedDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
Assert.Same(StringComparer.Ordinal, builder.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, builder.ValueComparer);
builder = ImmutableSortedDictionary.CreateBuilder<string, string>(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.Ordinal, builder.KeyComparer);
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.ValueComparer);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableSortedDictionary<int, string>.Empty.ToBuilder();
builder.Add(3, "3");
builder.Add(5, "5");
Assert.Equal(2, builder.Count);
Assert.True(builder.ContainsKey(3));
Assert.True(builder.ContainsKey(5));
Assert.False(builder.ContainsKey(7));
var set = builder.ToImmutable();
Assert.Equal(builder.Count, set.Count);
builder.Add(8, "8");
Assert.Equal(3, builder.Count);
Assert.Equal(2, set.Count);
Assert.True(builder.ContainsKey(8));
Assert.False(set.ContainsKey(8));
}
[Fact]
public void BuilderFromMap()
{
var set = ImmutableSortedDictionary<int, string>.Empty.Add(1, "1");
var builder = set.ToBuilder();
Assert.True(builder.ContainsKey(1));
builder.Add(3, "3");
builder.Add(5, "5");
Assert.Equal(3, builder.Count);
Assert.True(builder.ContainsKey(3));
Assert.True(builder.ContainsKey(5));
Assert.False(builder.ContainsKey(7));
var set2 = builder.ToImmutable();
Assert.Equal(builder.Count, set2.Count);
Assert.True(set2.ContainsKey(1));
builder.Add(8, "8");
Assert.Equal(4, builder.Count);
Assert.Equal(3, set2.Count);
Assert.True(builder.ContainsKey(8));
Assert.False(set.ContainsKey(8));
Assert.False(set2.ContainsKey(8));
}
[Fact]
public void SeveralChanges()
{
var mutable = ImmutableSortedDictionary<int, string>.Empty.ToBuilder();
var immutable1 = mutable.ToImmutable();
Assert.Same(immutable1, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences.");
mutable.Add(1, "a");
var immutable2 = mutable.ToImmutable();
Assert.NotSame(immutable1, immutable2); //, "Mutating the collection did not reset the Immutable property.");
Assert.Same(immutable2, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences.");
Assert.Equal(1, immutable2.Count);
}
[Fact]
public void AddRange()
{
var builder = ImmutableSortedDictionary.Create<string, int>().ToBuilder();
builder.AddRange(new Dictionary<string, int> { { "a", 1 }, { "b", 2 } });
Assert.Equal(2, builder.Count);
Assert.Equal(1, builder["a"]);
Assert.Equal(2, builder["b"]);
}
[Fact]
public void RemoveRange()
{
var builder =
ImmutableSortedDictionary.Create<string, int>()
.AddRange(new Dictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 } })
.ToBuilder();
Assert.Equal(3, builder.Count);
builder.RemoveRange(new[] { "a", "b" });
Assert.Equal(1, builder.Count);
Assert.Equal(3, builder["c"]);
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableSortedDictionary<int, string>.Empty
.AddRange(Enumerable.Range(1, 10).Select(n => new KeyValuePair<int, string>(n, null)))
.ToBuilder();
Assert.Equal(
Enumerable.Range(1, 10).Select(n => new KeyValuePair<int, string>(n, null)),
builder);
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11, null);
// Verify that a new enumerator will succeed.
Assert.Equal(
Enumerable.Range(1, 11).Select(n => new KeyValuePair<int, string>(n, null)),
builder);
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
Assert.Equal(
Enumerable.Range(1, 11).Select(n => new KeyValuePair<int, string>(n, null)),
builder);
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableSortedDictionary<int, string>.Empty.Add(1, null);
var builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // no changes at all.
builder.Add(2, null);
var newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void ContainsValue()
{
var map = ImmutableSortedDictionary.Create<string, int>().Add("five", 5);
var builder = map.ToBuilder();
Assert.True(builder.ContainsValue(5));
Assert.False(builder.ContainsValue(4));
}
[Fact]
public void Clear()
{
var builder = ImmutableSortedDictionary.Create<string, int>().ToBuilder();
builder.Add("five", 5);
Assert.Equal(1, builder.Count);
builder.Clear();
Assert.Equal(0, builder.Count);
}
[Fact]
public void KeyComparer()
{
var builder = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("B", "1").ToBuilder();
Assert.Same(Comparer<string>.Default, builder.KeyComparer);
Assert.True(builder.ContainsKey("a"));
Assert.False(builder.ContainsKey("A"));
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
Assert.Equal(2, builder.Count);
Assert.True(builder.ContainsKey("a"));
Assert.True(builder.ContainsKey("A"));
Assert.True(builder.ContainsKey("b"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
Assert.True(set.ContainsKey("a"));
Assert.True(set.ContainsKey("A"));
Assert.True(set.ContainsKey("b"));
}
[Fact]
public void KeyComparerCollisions()
{
// First check where collisions have matching values.
var builder = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "1").ToBuilder();
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Equal(1, builder.Count);
Assert.True(builder.ContainsKey("a"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
Assert.Equal(1, set.Count);
Assert.True(set.ContainsKey("a"));
// Now check where collisions have conflicting values.
builder = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "2").Add("b", "3").ToBuilder();
Assert.Throws<ArgumentException>(() => builder.KeyComparer = StringComparer.OrdinalIgnoreCase);
// Force all values to be considered equal.
builder.ValueComparer = EverythingEqual<string>.Default;
Assert.Same(EverythingEqual<string>.Default, builder.ValueComparer);
builder.KeyComparer = StringComparer.OrdinalIgnoreCase; // should not throw because values will be seen as equal.
Assert.Equal(2, builder.Count);
Assert.True(builder.ContainsKey("a"));
Assert.True(builder.ContainsKey("b"));
}
[Fact]
public void KeyComparerEmptyCollection()
{
var builder = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("B", "1").ToBuilder();
Assert.Same(Comparer<string>.Default, builder.KeyComparer);
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void GetValueOrDefaultOfConcreteType()
{
var empty = ImmutableSortedDictionary.Create<string, int>().ToBuilder();
var populated = ImmutableSortedDictionary.Create<string, int>().Add("a", 5).ToBuilder();
Assert.Equal(0, empty.GetValueOrDefault("a"));
Assert.Equal(1, empty.GetValueOrDefault("a", 1));
Assert.Equal(5, populated.GetValueOrDefault("a"));
Assert.Equal(5, populated.GetValueOrDefault("a", 1));
}
protected override IImmutableDictionary<TKey, TValue> GetEmptyImmutableDictionary<TKey, TValue>()
{
return ImmutableSortedDictionary.Create<TKey, TValue>();
}
protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer)
{
return ImmutableSortedDictionary.Create<string, TValue>(comparer);
}
protected override bool TryGetKeyHelper<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey equalKey, out TKey actualKey)
{
return ((ImmutableSortedDictionary<TKey, TValue>.Builder)dictionary).TryGetKey(equalKey, out actualKey);
}
protected override IDictionary<TKey, TValue> GetBuilder<TKey, TValue>(IImmutableDictionary<TKey, TValue> basis)
{
return ((ImmutableSortedDictionary<TKey, TValue>)(basis ?? GetEmptyImmutableDictionary<TKey, TValue>())).ToBuilder();
}
}
}
| |
using HyperSlackers.Bootstrap.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using HyperSlackers.Bootstrap.Extensions;
namespace HyperSlackers.Bootstrap.Builders
{
public class TableBuilder<TModel> : DisposableHtmlElement<TModel, Table>
{
private bool disposed = false;
internal TableBuilder(HtmlHelper<TModel> html, Table table)
: base(html, table)
{
Contract.Requires<ArgumentNullException>(html != null, "html");
Contract.Requires<ArgumentNullException>(table != null, "table");
textWriter.Write(element.StartTag);
if (!element.caption.IsNullOrWhiteSpace())
{
textWriter.Write(string.Format("<caption>{0}</caption>", element.caption));
}
}
public TableHeaderBuilder<TModel> BeginHeader()
{
Contract.Ensures(Contract.Result<TableHeaderBuilder<TModel>>() != null);
element.wasHeaderTagRendered = true;
return new TableHeaderBuilder<TModel>(html, new TableHeader());
}
public TableHeaderBuilder<TModel> BeginHeader(TableHeader header)
{
Contract.Requires<ArgumentNullException>(header != null, "header");
Contract.Ensures(Contract.Result<TableHeaderBuilder<TModel>>() != null);
element.wasHeaderTagRendered = true;
return new TableHeaderBuilder<TModel>(html, header);
}
public IHtmlString Header(params string[] columnHeaders)
{
Contract.Requires<ArgumentNullException>(columnHeaders != null, "columnHeaders");
return Header(TableColor.Default, columnHeaders);
}
public IHtmlString Header(TableColor style, params string[] columnHeaders)
{
Contract.Requires<ArgumentNullException>(columnHeaders != null, "columnHeaders");
EnsureHeader();
StringBuilder header = new StringBuilder();
TableHeaderRow row = new TableHeaderRow();
TableHeaderCell cell = new TableHeaderCell();
row.Style(style);
header.Append(row.StartTag);
foreach (var item in columnHeaders)
{
header.Append(cell.StartTag);
header.Append(item);
header.Append(cell.EndTag);
}
header.Append(row.EndTag);
return MvcHtmlString.Create(header.ToString());
}
public IHtmlString Header(params IHtmlString[] columnHeaders)
{
Contract.Requires<ArgumentNullException>(columnHeaders != null, "columnHeaders");
return Header(TableColor.Default, columnHeaders);
}
public IHtmlString Header(TableColor style, params IHtmlString[] columnHeaders)
{
Contract.Requires<ArgumentNullException>(columnHeaders != null, "columnHeaders");
EnsureHeader();
StringBuilder header = new StringBuilder();
TableHeaderRow row = new TableHeaderRow();
TableHeaderCell cell = new TableHeaderCell();
row.Style(style);
header.Append(row.StartTag);
foreach (var item in columnHeaders)
{
header.Append(cell.StartTag);
header.Append(item);
header.Append(cell.EndTag);
}
header.Append(row.EndTag);
return MvcHtmlString.Create(header.ToString());
}
public TableBodyBuilder<TModel> BeginBody()
{
Contract.Ensures(Contract.Result<TableBodyBuilder<TModel>>() != null);
element.wasBodyTagRendered = true;
return new TableBodyBuilder<TModel>(html, new TableBody());
}
public TableBodyBuilder<TModel> BeginBody(TableBody body)
{
Contract.Requires<ArgumentNullException>(body != null, "body");
Contract.Ensures(Contract.Result<TableBodyBuilder<TModel>>() != null);
element.wasBodyTagRendered = true;
return new TableBodyBuilder<TModel>(html, body);
}
public TableRowBuilder<TModel> BeginRow()
{
Contract.Ensures(Contract.Result<TableRowBuilder<TModel>>() != null);
EnsureBody();
return new TableRowBuilder<TModel>(html, new TableRow());
}
public TableRowBuilder<TModel> BeginRow(TableRow row)
{
Contract.Requires<ArgumentNullException>(row != null, "row");
Contract.Ensures(Contract.Result<TableRowBuilder<TModel>>() != null);
EnsureBody();
return new TableRowBuilder<TModel>(html, row);
}
public TableRowBuilder<TModel> BeginRow(TableColor style)
{
Contract.Ensures(Contract.Result<TableRowBuilder<TModel>>() != null);
EnsureBody();
TableRow tableRow = (new TableRow()).Style(style);
return new TableRowBuilder<TModel>(html, tableRow);
}
public TableRowBuilder<TModel> BeginRow(object htmlAttributes)
{
Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes");
Contract.Ensures(Contract.Result<TableRowBuilder<TModel>>() != null);
EnsureBody();
TableRow tableRow = (new TableRow()).HtmlAttributes(htmlAttributes);
return new TableRowBuilder<TModel>(html, tableRow);
}
public TableRowBuilder<TModel> BeginRow(TableColor style, object htmlAttributes)
{
Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes");
Contract.Ensures(Contract.Result<TableRowBuilder<TModel>>() != null);
EnsureBody();
TableRow tableRow = (new TableRow()).Style(style).HtmlAttributes(htmlAttributes);
return new TableRowBuilder<TModel>(html, tableRow);
}
public IHtmlString Row(params string[] cellContents)
{
Contract.Requires<ArgumentNullException>(cellContents != null, "cellContents");
return Row(TableColor.Default, cellContents);
}
public IHtmlString Row(TableColor style, params string[] cellContents)
{
Contract.Requires<ArgumentNullException>(cellContents != null, "cellContents");
EnsureBody();
StringBuilder tableRow = new StringBuilder();
TableRow row = new TableRow();
TableCell cell = new TableCell();
row.Style(style);
tableRow.Append(row.StartTag);
foreach (var item in cellContents)
{
tableRow.Append(cell.StartTag);
tableRow.Append(item);
tableRow.Append(cell.EndTag);
}
tableRow.Append(row.EndTag);
return MvcHtmlString.Create(tableRow.ToString());
}
public IHtmlString Row(params IHtmlString[] cellContents)
{
Contract.Requires<ArgumentNullException>(cellContents != null, "cellContents");
return Row(TableColor.Default, cellContents);
}
public IHtmlString Row(TableColor style, params IHtmlString[] cellContents)
{
Contract.Requires<ArgumentNullException>(cellContents != null, "cellContents");
EnsureBody();
StringBuilder tableRow = new StringBuilder();
TableRow row = new TableRow();
TableCell cell = new TableCell();
row.Style(style);
tableRow.Append(row.StartTag);
foreach (var item in cellContents)
{
tableRow.Append(cell.StartTag);
tableRow.Append(item);
tableRow.Append(cell.EndTag);
}
tableRow.Append(row.EndTag);
return MvcHtmlString.Create(tableRow.ToString());
}
public TableFooterBuilder<TModel> BeginFooter()
{
Contract.Ensures(Contract.Result<TableFooterBuilder<TModel>>() != null);
return new TableFooterBuilder<TModel>(html, new TableFooter());
}
public TableFooterBuilder<TModel> BeginFooter(TableFooter footer)
{
Contract.Requires<ArgumentNullException>(footer != null, "footer");
Contract.Ensures(Contract.Result<TableFooterBuilder<TModel>>() != null);
return new TableFooterBuilder<TModel>(html, footer);
}
public IHtmlString Footer(params string[] columnFooters)
{
Contract.Requires<ArgumentNullException>(columnFooters != null, "columnFooters");
EnsureFooter();
StringBuilder footer = new StringBuilder();
TableFooterRow row = new TableFooterRow();
TableFooterCell cell = new TableFooterCell();
footer.Append(row.StartTag);
foreach (var item in columnFooters)
{
footer.Append(cell.StartTag);
footer.Append(item);
footer.Append(cell.EndTag);
}
footer.Append(row.EndTag);
return MvcHtmlString.Create(footer.ToString());
}
public IHtmlString Footer(params IHtmlString[] columnFooters)
{
Contract.Requires<ArgumentNullException>(columnFooters != null, "columnFooters");
EnsureFooter();
StringBuilder footer = new StringBuilder();
TableFooterRow row = new TableFooterRow();
TableFooterCell cell = new TableFooterCell();
footer.Append(row.StartTag);
foreach (var item in columnFooters)
{
footer.Append(cell.StartTag);
footer.Append(item);
footer.Append(cell.EndTag);
}
footer.Append(row.EndTag);
return MvcHtmlString.Create(footer.ToString());
}
private void EnsureHeader()
{
if (!element.wasHeaderTagRendered && !element.isHeaderTagOpen)
{
element.isHeaderTagOpen = true;
textWriter.Write("<thead>");
}
}
private void EnsureHeaderClosed()
{
if (element.isHeaderTagOpen)
{
element.isHeaderTagOpen = false;
element.wasHeaderTagRendered = true;
textWriter.Write("</thead>");
}
}
private void EnsureBody()
{
EnsureHeaderClosed();
if (!element.wasBodyTagRendered && !element.isBodyTagOpen)
{
element.isBodyTagOpen = true;
textWriter.Write("<tbody>");
}
}
private void EnsureBodyClosed()
{
if (element.isBodyTagOpen)
{
element.isBodyTagOpen = false;
element.wasBodyTagRendered = true;
textWriter.Write("</tbody>");
}
}
private void EnsureFooter()
{
EnsureHeaderClosed();
EnsureBodyClosed();
if (!element.wasFooterTagRendered && !element.isFooterTagOpen)
{
element.isFooterTagOpen = true;
textWriter.Write("<tfoot>");
}
}
private void EnsureFooterClosed()
{
if (element.isFooterTagOpen)
{
element.isFooterTagOpen = false;
element.wasFooterTagRendered = true;
textWriter.Write("</tfoot>");
}
}
protected override void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
EnsureHeaderClosed();
EnsureBodyClosed();
EnsureFooterClosed();
disposed = true;
}
}
base.Dispose(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 Xunit;
using System;
using System.Xml;
using System.Xml.XPath;
using XPathTests.Common;
namespace XPathTests.FunctionalTests.Expressions
{
/// <summary>
/// Expressions - Numbers
/// </summary>
public static partial class NumbersTests
{
/// <summary>
/// Verify result.
/// 1 + 1 = 2
/// </summary>
[Fact]
public static void NumbersTest211()
{
var xml = "dummy.xml";
var testExpression = @"1 + 1";
var expected = 2d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Verify result.
/// 0.5 + 0.5 = 1.0
/// </summary>
[Fact]
public static void NumbersTest212()
{
var xml = "dummy.xml";
var testExpression = @"0.5 + 0.5";
var expected = 1.0d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Verify result.
/// 1 + child::para[1]
/// </summary>
[Fact]
public static void NumbersTest213()
{
var xml = "xp004.xml";
var startingNodePath = "/Doc/Test2";
var testExpression = @"1 + child::Para[1]";
var expected = 11d;
Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath);
}
/// <summary>
/// Verify result.
/// child::para[1] + 1
/// </summary>
[Fact]
public static void NumbersTest214()
{
var xml = "xp004.xml";
var startingNodePath = "/Doc/Test2";
var testExpression = @"child::Para[1] + 1";
var expected = 11d;
Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath);
}
/// <summary>
/// Verify result.
/// 2 - 1 = 1
/// </summary>
[Fact]
public static void NumbersTest215()
{
var xml = "dummy.xml";
var testExpression = @"2 - 1";
var expected = 1d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Verify result.
/// 1.5 - 0.5 = 1.0
/// </summary>
[Fact]
public static void NumbersTest216()
{
var xml = "dummy.xml";
var testExpression = @"1.5 - 0.5";
var expected = 1.0d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Verify result.
/// 5 mod 2 = 1
/// </summary>
[Fact]
public static void NumbersTest217()
{
var xml = "dummy.xml";
var testExpression = @"5 mod 2";
var expected = 1d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Verify result.
/// 5 mod -2 = 1
/// </summary>
[Fact]
public static void NumbersTest218()
{
var xml = "dummy.xml";
var testExpression = @"5 mod -2";
var expected = 1d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Verify result.
/// -5 mod 2 = -1
/// </summary>
[Fact]
public static void NumbersTest219()
{
var xml = "dummy.xml";
var testExpression = @"-5 mod 2";
var expected = -1d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Verify result.
/// -5 mod -2 = -1
/// </summary>
[Fact]
public static void NumbersTest2110()
{
var xml = "dummy.xml";
var testExpression = @"-5 mod -2";
var expected = -1d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Verify result.
/// 50 div 10 = 5
/// </summary>
[Fact]
public static void NumbersTest2111()
{
var xml = "dummy.xml";
var testExpression = @"50 div 10";
var expected = 5d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Verify result.
/// 2.5 div 0.5 = 5.0
/// </summary>
[Fact]
public static void NumbersTest2112()
{
var xml = "dummy.xml";
var testExpression = @"2.5 div 0.5";
var expected = 5.0d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Verify result.
/// 50 div child::para[1]
/// </summary>
[Fact]
public static void NumbersTest2113()
{
var xml = "xp004.xml";
var startingNodePath = "/Doc/Test2";
var testExpression = @"50 div child::Para[1]";
var expected = 5d;
Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath);
}
/// <summary>
/// Verify result.
/// child::para[1] div 2
/// </summary>
[Fact]
public static void NumbersTest2114()
{
var xml = "xp004.xml";
var startingNodePath = "/Doc/Test2";
var testExpression = @"child::Para[1] div 2";
var expected = 5d;
Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath);
}
/// <summary>
/// Verify result.
/// 2 * 1 = 2
/// </summary>
[Fact]
public static void NumbersTest2115()
{
var xml = "dummy.xml";
var testExpression = @"2 * 1";
var expected = 2d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Verify result.
/// 2.5 * 0.5 = 1.25
/// </summary>
[Fact]
public static void NumbersTest2116()
{
var xml = "dummy.xml";
var testExpression = @"2.5 * 0.5";
var expected = 1.25d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// if any of the operands is NaN result should be NaN
/// NaN mod 1
/// </summary>
[Fact]
public static void NumbersTest2117()
{
var xml = "dummy.xml";
var testExpression = @"number(0 div 0) mod 1";
var expected = Double.NaN;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Expected NaN
/// 1 mod NaN
/// </summary>
[Fact]
public static void NumbersTest2118()
{
var xml = "dummy.xml";
var testExpression = @"1 mod number(0 div 0)";
var expected = Double.NaN;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// NaN expected
/// Infinity mod 1
/// </summary>
[Fact]
public static void NumbersTest2119()
{
var xml = "dummy.xml";
var testExpression = @"number(1 div 0) mod 1";
var expected = Double.NaN;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// NaN expected
/// Infinity mod 0
/// </summary>
[Fact]
public static void NumbersTest2120()
{
var xml = "dummy.xml";
var testExpression = @"number(1 div 0) mod 0";
var expected = Double.NaN;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// NaN expected
/// 1 mod 0
/// </summary>
[Fact]
public static void NumbersTest2121()
{
var xml = "dummy.xml";
var testExpression = @"1 mod 0";
var expected = Double.NaN;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// 1 mod Infinity = 1
/// </summary>
[Fact]
public static void NumbersTest2122()
{
var xml = "dummy.xml";
var testExpression = @"1 mod number(1 div 0)";
var expected = 1d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// -1 mod Infinity = -1
/// </summary>
[Fact]
public static void NumbersTest2123()
{
var xml = "dummy.xml";
var testExpression = @"-1 mod number(1 div 0)";
var expected = -1d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// 1 mod -Infinity =1
/// </summary>
[Fact]
public static void NumbersTest2124()
{
var xml = "dummy.xml";
var testExpression = @"1 mod number(-1 div 0)";
var expected = 1d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// 0 mod 5 = 0
/// </summary>
[Fact]
public static void NumbersTest2125()
{
var xml = "dummy.xml";
var testExpression = @"0 mod 5";
var expected = 0d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// 5.2345 mod 3.0 = 2.2344999999999997
/// </summary>
[Fact]
public static void NumbersTest2126()
{
var xml = "dummy.xml";
var testExpression = @"5.2345 mod 3.0";
var expected = 2.2344999999999997d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Test for the scanner. It has different code path for digits of the form .xxx and x.xxx
/// .5 + .5 = 1.0
/// </summary>
[Fact]
public static void NumbersTest2127()
{
var xml = "dummy.xml";
var testExpression = @".5 + .5";
var expected = 1.0d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Test for the scanner. It has different code path for digits of the form .xxx and x.xxx
/// .0 + .0 = 0.0
/// </summary>
[Fact]
public static void NumbersTest2128()
{
var xml = "dummy.xml";
var testExpression = @".0 + .0";
var expected = 0.0d;
Utils.XPathNumberTest(xml, testExpression, expected);
}
/// <summary>
/// Test for the scanner. It has different code path for digits of the form .xxx and x.xxx
/// .0 + .0 = 0.0
/// </summary>
[Fact]
public static void NumbersTest2129()
{
var xml = "dummy.xml";
var testExpression = @".0 + .0=.0";
var expected = true;
Utils.XPathBooleanTest(xml, testExpression, expected);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using NUnit.Framework;
using System.Linq;
using Newtonsoft.Json;
namespace QuantConnect.Tests
{
[TestFixture, Category("TravisExclude")]
public class RegressionTests
{
[Test, TestCaseSource(nameof(GetRegressionTestParameters))]
public void AlgorithmStatisticsRegression(AlgorithmStatisticsTestParameters parameters)
{
QuantConnect.Configuration.Config.Set("quandl-auth-token", "WyAazVXnq7ATy_fefTqm");
QuantConnect.Configuration.Config.Set("forward-console-messages", "false");
if (parameters.Algorithm == "OptionChainConsistencyRegressionAlgorithm")
{
// special arrangement for consistency test - we check if limits work fine
QuantConnect.Configuration.Config.Set("symbol-minute-limit", "100");
QuantConnect.Configuration.Config.Set("symbol-second-limit", "100");
QuantConnect.Configuration.Config.Set("symbol-tick-limit", "100");
}
if (parameters.Algorithm == "BasicTemplateIntrinioEconomicData")
{
var intrinioCredentials = new Dictionary<string, string>
{
{"intrinio-username", "121078c02c20a09aa5d9c541087e7fa4"},
{"intrinio-password", "65be35238b14de4cd0afc0edf364efc3" }
};
QuantConnect.Configuration.Config.Set("parameters", JsonConvert.SerializeObject(intrinioCredentials));
}
AlgorithmRunner.RunLocalBacktest(parameters.Algorithm, parameters.Statistics, parameters.AlphaStatistics, parameters.Language);
}
private static TestCaseData[] GetRegressionTestParameters()
{
var emptyStatistics = new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"}
};
var basicTemplateStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "264.956%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.669%"},
{"Sharpe Ratio", "4.411"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.007"},
{"Beta", "76.375"},
{"Annual Standard Deviation", "0.193"},
{"Annual Variance", "0.037"},
{"Information Ratio", "4.355"},
{"Tracking Error", "0.193"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$3.09"}
};
var basicTemplateFrameworkStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "264.956%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.669%"},
{"Sharpe Ratio", "4.411"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.007"},
{"Beta", "76.375"},
{"Annual Standard Deviation", "0.193"},
{"Annual Variance", "0.037"},
{"Information Ratio", "4.355"},
{"Tracking Error", "0.193"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$3.09"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
{"Total Insights Analysis Completed", "86"},
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$151474.9016"},
{"Total Accumulated Estimated Alpha Value", "$24404.2897"},
{"Mean Population Estimated Insight Value", "$246.508"},
{"Mean Population Direction", "48.8372%"},
{"Mean Population Magnitude", "48.8372%"},
{"Rolling Averaged Population Direction", "68.2411%"},
{"Rolling Averaged Population Magnitude", "68.2411%"}
};
var basicTemplateOptionsStatistics = new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.28%"},
{"Compounding Annual Return", "-78.105%"},
{"Drawdown", "0.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.280%"},
{"Sharpe Ratio", "0"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.50"},
};
var limitFillRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "34"},
{"Average Win", "0.02%"},
{"Average Loss", "-0.02%"},
{"Compounding Annual Return", "9.733%"},
{"Drawdown", "0.400%"},
{"Expectancy", "0.513"},
{"Net Profit", "0.119%"},
{"Sharpe Ratio", "1.954"},
{"Loss Rate", "25%"},
{"Win Rate", "75%"},
{"Profit-Loss Ratio", "1.02"},
{"Alpha", "-0.107"},
{"Beta", "15.186"},
{"Annual Standard Deviation", "0.031"},
{"Annual Variance", "0.001"},
{"Information Ratio", "1.6"},
{"Tracking Error", "0.031"},
{"Treynor Ratio", "0.004"},
{"Total Fees", "$34.00"},
};
var updateOrderRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "21"},
{"Average Win", "0%"},
{"Average Loss", "-1.71%"},
{"Compounding Annual Return", "-8.289%"},
{"Drawdown", "16.700%"},
{"Expectancy", "-1"},
{"Net Profit", "-15.892%"},
{"Sharpe Ratio", "-1.358"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.065"},
{"Beta", "-0.998"},
{"Annual Standard Deviation", "0.062"},
{"Annual Variance", "0.004"},
{"Information Ratio", "-1.679"},
{"Tracking Error", "0.062"},
{"Treynor Ratio", "0.085"},
{"Total Fees", "$21.00"},
};
var regressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "5433"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-3.886%"},
{"Drawdown", "0.100%"},
{"Expectancy", "-0.991"},
{"Net Profit", "-0.054%"},
{"Sharpe Ratio", "-30.336"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "2.40"},
{"Alpha", "-0.019"},
{"Beta", "-0.339"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-38.93"},
{"Tracking Error", "0.001"},
{"Treynor Ratio", "0.067"},
{"Total Fees", "$5433.00"}
};
var universeSelectionRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Average Win", "0.70%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-73.872%"},
{"Drawdown", "6.600%"},
{"Expectancy", "0"},
{"Net Profit", "-6.060%"},
{"Sharpe Ratio", "-3.973"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.68"},
{"Beta", "-29.799"},
{"Annual Standard Deviation", "0.318"},
{"Annual Variance", "0.101"},
{"Information Ratio", "-4.034"},
{"Tracking Error", "0.318"},
{"Treynor Ratio", "0.042"},
{"Total Fees", "$5.00"},
};
var customDataRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "155.365%"},
{"Drawdown", "84.800%"},
{"Expectancy", "0"},
{"Net Profit", "5123.170%"},
{"Sharpe Ratio", "1.2"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.008"},
{"Beta", "73.725"},
{"Annual Standard Deviation", "0.84"},
{"Annual Variance", "0.706"},
{"Information Ratio", "1.183"},
{"Tracking Error", "0.84"},
{"Treynor Ratio", "0.014"},
{"Total Fees", "$0.00"}
};
var addRemoveSecurityRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Average Win", "0.49%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "307.853%"},
{"Drawdown", "1.400%"},
{"Expectancy", "0"},
{"Net Profit", "1.814%"},
{"Sharpe Ratio", "6.474"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.004"},
{"Beta", "82.594"},
{"Annual Standard Deviation", "0.141"},
{"Annual Variance", "0.02"},
{"Information Ratio", "6.4"},
{"Tracking Error", "0.141"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$25.20"}
};
var dropboxBaseDataUniverseSelectionStatistics = new Dictionary<string, string>
{
{"Total Trades", "90"},
{"Average Win", "0.78%"},
{"Average Loss", "-0.40%"},
{"Compounding Annual Return", "18.626%"},
{"Drawdown", "4.700%"},
{"Expectancy", "1.071"},
{"Net Profit", "18.626%"},
{"Sharpe Ratio", "1.997"},
{"Loss Rate", "30%"},
{"Win Rate", "70%"},
{"Profit-Loss Ratio", "1.97"},
{"Alpha", "0.112"},
{"Beta", "2.998"},
{"Annual Standard Deviation", "0.086"},
{"Annual Variance", "0.007"},
{"Information Ratio", "1.768"},
{"Tracking Error", "0.086"},
{"Treynor Ratio", "0.057"},
{"Total Fees", "$240.17"},
};
var dropboxUniverseSelectionStatistics = new Dictionary<string, string>
{
{"Total Trades", "66"},
{"Average Win", "1.06%"},
{"Average Loss", "-0.50%"},
{"Compounding Annual Return", "18.581%"},
{"Drawdown", "7.100%"},
{"Expectancy", "0.815"},
{"Net Profit", "18.581%"},
{"Sharpe Ratio", "1.44"},
{"Loss Rate", "42%"},
{"Win Rate", "58%"},
{"Profit-Loss Ratio", "2.13"},
{"Alpha", "0.309"},
{"Beta", "-10.101"},
{"Annual Standard Deviation", "0.1"},
{"Annual Variance", "0.01"},
{"Information Ratio", "1.277"},
{"Tracking Error", "0.1"},
{"Treynor Ratio", "-0.014"},
{"Total Fees", "$185.37"},
};
var parameterizedStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "278.616%"},
{"Drawdown", "0.300%"},
{"Expectancy", "0"},
{"Net Profit", "1.717%"},
{"Sharpe Ratio", "11.017"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "78.067"},
{"Annual Standard Deviation", "0.078"},
{"Annual Variance", "0.006"},
{"Information Ratio", "10.897"},
{"Tracking Error", "0.078"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$3.09"},
};
var historyAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "372.677%"},
{"Drawdown", "1.100%"},
{"Expectancy", "0"},
{"Net Profit", "1.717%"},
{"Sharpe Ratio", "4.521"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "79.192"},
{"Annual Standard Deviation", "0.193"},
{"Annual Variance", "0.037"},
{"Information Ratio", "4.466"},
{"Tracking Error", "0.193"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$3.09"},
};
var coarseFundamentalTop5AlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "10"},
{"Average Win", "1.15%"},
{"Average Loss", "-0.47%"},
{"Compounding Annual Return", "-0.746%"},
{"Drawdown", "3.000%"},
{"Expectancy", "-0.313"},
{"Net Profit", "-0.746%"},
{"Sharpe Ratio", "-0.267"},
{"Loss Rate", "80%"},
{"Win Rate", "20%"},
{"Profit-Loss Ratio", "2.44"},
{"Alpha", "-0.008"},
{"Beta", "0.032"},
{"Annual Standard Deviation", "0.027"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-1.014"},
{"Tracking Error", "0.027"},
{"Treynor Ratio", "-0.222"},
{"Total Fees", "$10.61"},
};
var coarseFineFundamentalRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "6"},
{"Average Win", "0%"},
{"Average Loss", "-0.84%"},
{"Compounding Annual Return", "-57.345%"},
{"Drawdown", "9.100%"},
{"Expectancy", "-1"},
{"Net Profit", "-6.763%"},
{"Sharpe Ratio", "-3.288"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.105"},
{"Beta", "-46.73"},
{"Annual Standard Deviation", "0.235"},
{"Annual Variance", "0.055"},
{"Information Ratio", "-3.366"},
{"Tracking Error", "0.236"},
{"Treynor Ratio", "0.017"},
{"Total Fees", "$13.92"},
};
var macdTrendAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "84"},
{"Average Win", "4.79%"},
{"Average Loss", "-4.17%"},
{"Compounding Annual Return", "2.967%"},
{"Drawdown", "34.800%"},
{"Expectancy", "0.228"},
{"Net Profit", "37.970%"},
{"Sharpe Ratio", "0.299"},
{"Loss Rate", "43%"},
{"Win Rate", "57%"},
{"Profit-Loss Ratio", "1.15"},
{"Alpha", "0.111"},
{"Beta", "-3.721"},
{"Annual Standard Deviation", "0.124"},
{"Annual Variance", "0.015"},
{"Information Ratio", "0.137"},
{"Tracking Error", "0.124"},
{"Treynor Ratio", "-0.01"},
{"Total Fees", "$420.57"},
};
var optionSplitRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades","2"},
{"Average Win","0%"},
{"Average Loss","-0.02%"},
{"Compounding Annual Return","-1.242%"},
{"Drawdown","0.000%"},
{"Expectancy","-1"},
{"Net Profit","-0.017%"},
{"Sharpe Ratio","-7.099"},
{"Loss Rate","100%"},
{"Win Rate","0%"},
{"Profit-Loss Ratio","0"},
{"Alpha","-0.01"},
{"Beta","0"},
{"Annual Standard Deviation","0.001"},
{"Annual Variance","0"},
{"Information Ratio","7.126"},
{"Tracking Error","6.064"},
{"Treynor Ratio","174.306"},
{"Total Fees","$0.50"},
};
var optionRenameRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0%"},
{"Average Loss", "-0.02%"},
{"Compounding Annual Return", "-0.472%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.006%"},
{"Sharpe Ratio", "-3.403"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.016"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "10.014"},
{"Tracking Error", "0.877"},
{"Treynor Ratio", "4.203"},
{"Total Fees", "$2.50"},
};
var optionOpenInterestRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-2.042%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.010%"},
{"Sharpe Ratio", "-11.225"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "-0.036"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-11.225"},
{"Tracking Error", "0.033"},
{"Treynor Ratio", "0.355"},
{"Total Fees", "$0.50"},
};
var optionChainConsistencyRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-3.86%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "3.900%"},
{"Expectancy", "-1"},
{"Net Profit", "-3.855%"},
{"Sharpe Ratio", "0"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.50"},
};
var weeklyUniverseSelectionRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "8"},
{"Average Win", "0.28%"},
{"Average Loss", "-0.33%"},
{"Compounding Annual Return", "-1.247%"},
{"Drawdown", "1.300%"},
{"Expectancy", "-0.078"},
{"Net Profit", "-0.105%"},
{"Sharpe Ratio", "-0.27"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.84"},
{"Alpha", "-0.239"},
{"Beta", "12.675"},
{"Annual Standard Deviation", "0.04"},
{"Annual Variance", "0.002"},
{"Information Ratio", "-0.723"},
{"Tracking Error", "0.04"},
{"Treynor Ratio", "-0.001"},
{"Total Fees", "$23.23"},
};
var optionExerciseAssignRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0.30%"},
{"Average Loss", "-0.33%"},
{"Compounding Annual Return", "-85.023%"},
{"Drawdown", "0.400%"},
{"Expectancy", "-0.358"},
{"Net Profit", "-0.350%"},
{"Sharpe Ratio", "0"},
{"Loss Rate", "67%"},
{"Win Rate", "33%"},
{"Profit-Loss Ratio", "0.93"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.50"},
};
var basicTemplateDailyStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "244.780%"},
{"Drawdown", "1.100%"},
{"Expectancy", "0"},
{"Net Profit", "4.153%"},
{"Sharpe Ratio", "6.461"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.706"},
{"Beta", "15.77"},
{"Annual Standard Deviation", "0.146"},
{"Annual Variance", "0.021"},
{"Information Ratio", "6.359"},
{"Tracking Error", "0.146"},
{"Treynor Ratio", "0.06"},
{"Total Fees", "$3.09"},
};
var hourSplitStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-0.096%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Net Profit", "-0.001%"},
{"Sharpe Ratio", "-11.225"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$1.00"}
};
var hourReverseSplitStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-1.444%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Net Profit", "-0.007%"},
{"Sharpe Ratio", "-11.225"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$1.00"}
};
var fractionalQuantityRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "6"},
{"Average Win", "0.95%"},
{"Average Loss", "-2.02%"},
{"Compounding Annual Return", "254.082%"},
{"Drawdown", "6.600%"},
{"Expectancy", "-0.018"},
{"Net Profit", "1.395%"},
{"Sharpe Ratio", "1.176"},
{"Loss Rate", "33%"},
{"Win Rate", "67%"},
{"Profit-Loss Ratio", "0.47"},
{"Alpha", "-1.18"},
{"Beta", "1.249"},
{"Annual Standard Deviation", "0.813"},
{"Annual Variance", "0.66"},
{"Information Ratio", "-4.244"},
{"Tracking Error", "0.178"},
{"Treynor Ratio", "0.765"},
{"Total Fees", "$2045.20"}
};
var basicTemplateCryptoAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "10"},
{"Average Win", "0%"},
{"Average Loss", "-0.17%"},
{"Compounding Annual Return", "-99.993%"},
{"Drawdown", "3.800%"},
{"Expectancy", "-1"},
{"Net Profit", "-2.577%"},
{"Sharpe Ratio", "-15.89"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-5.559"},
{"Beta", "333.506"},
{"Annual Standard Deviation", "0.205"},
{"Annual Variance", "0.042"},
{"Information Ratio", "-15.972"},
{"Tracking Error", "0.204"},
{"Treynor Ratio", "-0.01"},
{"Total Fees", "$96.51"}
};
var indicatorSuiteAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "19.097%"},
{"Drawdown", "7.300%"},
{"Expectancy", "0"},
{"Net Profit", "41.840%"},
{"Sharpe Ratio", "1.639"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.29"},
{"Beta", "-5.494"},
{"Annual Standard Deviation", "0.11"},
{"Annual Variance", "0.012"},
{"Information Ratio", "1.457"},
{"Tracking Error", "0.11"},
{"Treynor Ratio", "-0.033"},
{"Total Fees", "$1.00"}
};
var basicTemplateIntrinioEconomicData = new Dictionary<string, string>
{
{"Total Trades", "89"},
{"Average Win", "0.09%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "5.704%"},
{"Drawdown", "4.800%"},
{"Expectancy", "1.469"},
{"Net Profit", "24.865%"},
{"Sharpe Ratio", "1.143"},
{"Loss Rate", "70%"},
{"Win Rate", "30%"},
{"Profit-Loss Ratio", "7.23"},
{"Alpha", "0.065"},
{"Beta", "-0.522"},
{"Annual Standard Deviation", "0.048"},
{"Annual Variance", "0.002"},
{"Information Ratio", "0.74"},
{"Tracking Error", "0.048"},
{"Treynor Ratio", "-0.105"},
{"Total Fees", "$100.58"}
};
var volumeWeightedAveragePriceExecutionModelRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "61"},
{"Average Win", "0.10%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "585.503%"},
{"Drawdown", "0.600%"},
{"Expectancy", "0"},
{"Net Profit", "2.492%"},
{"Sharpe Ratio", "9.136"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "113.313"},
{"Annual Standard Deviation", "0.137"},
{"Annual Variance", "0.019"},
{"Information Ratio", "9.063"},
{"Tracking Error", "0.137"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$96.79"},
{"Total Insights Generated", "5"},
{"Total Insights Closed", "3"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "3"},
{"Short Insight Count", "2"},
{"Long/Short Ratio", "150.0%"},
{"Estimated Monthly Alpha Value", "$54250.3481"},
{"Total Accumulated Estimated Alpha Value", "$8740.3339"},
{"Mean Population Estimated Insight Value", "$2913.4446"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
};
var standardDeviationExecutionModelRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "63"},
{"Average Win", "0.06%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "793.499%"},
{"Drawdown", "0.400%"},
{"Expectancy", "0"},
{"Net Profit", "2.840%"},
{"Sharpe Ratio", "10.781"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "128.815"},
{"Annual Standard Deviation", "0.132"},
{"Annual Variance", "0.017"},
{"Information Ratio", "10.71"},
{"Tracking Error", "0.132"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$76.61"},
{"Total Insights Generated", "5"},
{"Total Insights Closed", "3"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "3"},
{"Short Insight Count", "2"},
{"Long/Short Ratio", "150.0%"},
{"Estimated Monthly Alpha Value", "$54250.3481"},
{"Total Accumulated Estimated Alpha Value", "$8740.3339"},
{"Mean Population Estimated Insight Value", "$2913.4446"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
};
var cancelOpenOrdersRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "5.800%"},
{"Expectancy", "0"},
{"Net Profit", "-3.339%"},
{"Sharpe Ratio", "-11.206"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-8.422"},
{"Beta", "610.348"},
{"Annual Standard Deviation", "0.375"},
{"Annual Variance", "0.141"},
{"Information Ratio", "-11.243"},
{"Tracking Error", "0.375"},
{"Treynor Ratio", "-0.007"},
{"Total Fees", "$0.00"}
};
var scheduledUniverseSelectionModelRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "17"},
{"Average Win", "0.26%"},
{"Average Loss", "-0.11%"},
{"Compounding Annual Return", "26.961%"},
{"Drawdown", "0.700%"},
{"Expectancy", "1.895"},
{"Net Profit", "2.115%"},
{"Sharpe Ratio", "4.218"},
{"Loss Rate", "12%"},
{"Win Rate", "88%"},
{"Profit-Loss Ratio", "2.31"},
{"Alpha", "0.327"},
{"Beta", "-9.439"},
{"Annual Standard Deviation", "0.043"},
{"Annual Variance", "0.002"},
{"Information Ratio", "3.864"},
{"Tracking Error", "0.043"},
{"Treynor Ratio", "-0.019"},
{"Total Fees", "$0.00"},
{"Total Insights Generated", "54"},
{"Total Insights Closed", "52"},
{"Total Insights Analysis Completed", "46"},
{"Long Insight Count", "54"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "43.4783%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "65.5952%"},
{"Rolling Averaged Population Magnitude", "0%"},
};
return new List<AlgorithmStatisticsTestParameters>
{
// CSharp
new AlgorithmStatisticsTestParameters("AddRemoveSecurityRegressionAlgorithm", addRemoveSecurityRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("BasicTemplateAlgorithm", basicTemplateStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("BasicTemplateFrameworkAlgorithm", basicTemplateFrameworkStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("BasicTemplateOptionsAlgorithm", basicTemplateOptionsStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("CustomDataRegressionAlgorithm", customDataRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("DropboxBaseDataUniverseSelectionAlgorithm", dropboxBaseDataUniverseSelectionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("DropboxUniverseSelectionAlgorithm", dropboxUniverseSelectionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("LimitFillRegressionAlgorithm", limitFillRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("ParameterizedAlgorithm", parameterizedStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("RegressionAlgorithm", regressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("UniverseSelectionRegressionAlgorithm", universeSelectionRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("UpdateOrderRegressionAlgorithm", updateOrderRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("HistoryAlgorithm", historyAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("CoarseFundamentalTop5Algorithm", coarseFundamentalTop5AlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("CoarseFineFundamentalRegressionAlgorithm", coarseFineFundamentalRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("MACDTrendAlgorithm", macdTrendAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("OptionSplitRegressionAlgorithm", optionSplitRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("OptionRenameRegressionAlgorithm", optionRenameRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("OptionOpenInterestRegressionAlgorithm", optionOpenInterestRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("OptionChainConsistencyRegressionAlgorithm", optionChainConsistencyRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("WeeklyUniverseSelectionRegressionAlgorithm", weeklyUniverseSelectionRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("OptionExerciseAssignRegressionAlgorithm",optionExerciseAssignRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("BasicTemplateDailyAlgorithm", basicTemplateDailyStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("HourSplitRegressionAlgorithm", hourSplitStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("HourReverseSplitRegressionAlgorithm", hourReverseSplitStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("FractionalQuantityRegressionAlgorithm", fractionalQuantityRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("BasicTemplateCryptoAlgorithm", basicTemplateCryptoAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("BasicTemplateFrameworkCryptoAlgorithm", basicTemplateCryptoAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("IndicatorSuiteAlgorithm", indicatorSuiteAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("ForexInternalFeedOnDataSameResolutionRegressionAlgorithm", emptyStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("ForexInternalFeedOnDataHigherResolutionRegressionAlgorithm", emptyStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("BasicTemplateIntrinioEconomicData", basicTemplateIntrinioEconomicData, Language.CSharp),
new AlgorithmStatisticsTestParameters("DuplicateSecurityWithBenchmarkRegressionAlgorithm", emptyStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm", volumeWeightedAveragePriceExecutionModelRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("StandardDeviationExecutionModelRegressionAlgorithm", standardDeviationExecutionModelRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("CancelOpenOrdersRegressionAlgorithm", cancelOpenOrdersRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("ScheduledUniverseSelectionModelRegressionAlgorithm", scheduledUniverseSelectionModelRegressionAlgorithmStatistics, Language.CSharp),
// Python
new AlgorithmStatisticsTestParameters("AddRemoveSecurityRegressionAlgorithm", addRemoveSecurityRegressionStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("BasicTemplateAlgorithm", basicTemplateStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("BasicTemplateFrameworkAlgorithm", basicTemplateFrameworkStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("BasicTemplateOptionsAlgorithm", basicTemplateOptionsStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("CustomDataRegressionAlgorithm", customDataRegressionStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("DropboxBaseDataUniverseSelectionAlgorithm", dropboxBaseDataUniverseSelectionStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("DropboxUniverseSelectionAlgorithm", dropboxUniverseSelectionStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("LimitFillRegressionAlgorithm", limitFillRegressionStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("ParameterizedAlgorithm", parameterizedStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("RegressionAlgorithm", regressionStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("UniverseSelectionRegressionAlgorithm", universeSelectionRegressionStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("UpdateOrderRegressionAlgorithm", updateOrderRegressionStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("HistoryAlgorithm", historyAlgorithmStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("CoarseFundamentalTop5Algorithm", coarseFundamentalTop5AlgorithmStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("CoarseFineFundamentalRegressionAlgorithm", coarseFineFundamentalRegressionAlgorithmStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("MACDTrendAlgorithm", macdTrendAlgorithmStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("OptionSplitRegressionAlgorithm", optionSplitRegressionAlgorithmStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("OptionRenameRegressionAlgorithm", optionRenameRegressionAlgorithmStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("OptionOpenInterestRegressionAlgorithm", optionOpenInterestRegressionAlgorithmStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("OptionChainConsistencyRegressionAlgorithm", optionChainConsistencyRegressionAlgorithmStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("WeeklyUniverseSelectionRegressionAlgorithm", weeklyUniverseSelectionRegressionAlgorithmStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("OptionExerciseAssignRegressionAlgorithm",optionExerciseAssignRegressionAlgorithmStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("BasicTemplateDailyAlgorithm", basicTemplateDailyStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("HourSplitRegressionAlgorithm", hourSplitStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("HourReverseSplitRegressionAlgorithm", hourReverseSplitStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("FractionalQuantityRegressionAlgorithm", fractionalQuantityRegressionStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("CustomIndicatorAlgorithm", basicTemplateStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("BasicTemplateCryptoAlgorithm", basicTemplateCryptoAlgorithmStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("IndicatorSuiteAlgorithm", indicatorSuiteAlgorithmStatistics, Language.Python),
new AlgorithmStatisticsTestParameters("ScheduledUniverseSelectionModelRegressionAlgorithm", scheduledUniverseSelectionModelRegressionAlgorithmStatistics, Language.Python),
// FSharp
// new AlgorithmStatisticsTestParameters("BasicTemplateAlgorithm", basicTemplateStatistics, Language.FSharp),
// VisualBasic
// new AlgorithmStatisticsTestParameters("BasicTemplateAlgorithm", basicTemplateStatistics, Language.VisualBasic),
}.Select(x => new TestCaseData(x).SetName(x.Language + "/" + x.Algorithm)).ToArray();
}
public class AlgorithmStatisticsTestParameters
{
public readonly string Algorithm;
public readonly Dictionary<string, string> Statistics;
public readonly AlphaRuntimeStatistics AlphaStatistics;
public readonly Language Language;
public AlgorithmStatisticsTestParameters(string algorithm, Dictionary<string, string> statistics, Language language)
{
Algorithm = algorithm;
Statistics = statistics;
Language = language;
}
}
}
}
| |
// 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.AcceptanceTestsAzureCompositeModelClient
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// InheritanceOperations operations.
/// </summary>
internal partial class InheritanceOperations : Microsoft.Rest.IServiceOperations<AzureCompositeModel>, IInheritanceOperations
{
/// <summary>
/// Initializes a new instance of the InheritanceOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal InheritanceOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that extend others
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Siamese>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
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;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Siamese>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Siamese>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that extend others
/// </summary>
/// <param name='complexBody'>
/// Please put a siamese with id=2, name="Siameee", color=green,
/// breed=persion, which hates 2 dogs, the 1st one named "Potato" with id=1
/// and food="tomato", and the 2nd one named "Tomato" with id=-1 and
/// food="french fries".
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidWithHttpMessagesAsync(Siamese complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (complexBody == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "complexBody");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
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;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
//
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is DotSpatial.dll for the DotSpatial project
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in August, 2007.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Data;
using GeoAPI.Geometries;
namespace DotSpatial.Data
{
/// <summary>
/// A layer contains a list of features of a specific type that matches the geometry type.
/// While this supports IRenderable, this merely forwards the drawing instructions to
/// each of its members, but does not allow the control of any default layer properties here.
/// Calling FeatureDataSource.Open will create a number of layers of the appropriate
/// specific type and also create a specific layer type that is derived from this class
/// that does expose default "layer" properties, as well as the symbology elements.
/// </summary>
public interface IFeatureSet : IDataSet, IAttributeSource
{
#region Events
/// <summary>
/// Occurs when the vertices are invalidated, encouraging a re-draw
/// </summary>
event EventHandler VerticesInvalidated;
/// <summary>
/// Occurs when a new feature is added to the list
/// </summary>
event EventHandler<FeatureEventArgs> FeatureAdded;
/// <summary>
/// Occurs when a feature is removed from the list.
/// </summary>
event EventHandler<FeatureEventArgs> FeatureRemoved;
#endregion
#region Methods
/// <summary>
/// For attributes that are small enough to be loaded into a data table, this
/// will join attributes from a foreign table. This method
/// won't create new rows in this table, so only matching members are brought in,
/// but no rows are removed either, so not all rows will receive data.
/// </summary>
/// <param name="table">Foreign data table.</param>
/// <param name="localJoinField">The field name to join on in this table.</param>
/// <param name="dataTableJoinField">The field in the foreign table.</param>
/// <returns>
/// A modified featureset with the changes.
/// </returns>
IFeatureSet Join(DataTable table, string localJoinField, string dataTableJoinField);
/// <summary>
/// For attributes that are small enough to be loaded into a data table, this
/// will join attributes from a foreign table (from an excel file). This method
/// won't create new rows in this table, so only matching members are brought in,
/// but no rows are removed either, so not all rows will receive data.
/// </summary>
/// <param name="xlsFilePath">The complete path of the file to join</param>
/// <param name="localJoinField">The field name to join on in this table</param>
/// <param name="xlsJoinField">The field in the foreign table.</param>
/// <returns>
/// A modified featureset with the changes.
/// </returns>
IFeatureSet Join(string xlsFilePath, string localJoinField,
string xlsJoinField);
/// <summary>
/// If this featureset is in index mode, this will append the vertices and shapeindex of the shape.
/// Otherwise, this will add a new feature based on this shape. If the attributes of the shape are not null,
/// this will attempt to append a new datarow It is up to the developer
/// to ensure that the object array of attributes matches the this featureset. If the Attributes of this feature are loaded,
/// this will add the attributes in ram only. Otherwise, this will attempt to insert the attributes as a
/// new record using the "AddRow" method. The schema of the object array should match this featureset's column schema.
/// </summary>
/// <param name="shape">The shape to add to this featureset.</param>
void AddShape(Shape shape);
/// <summary>
/// Adds any type of list or array of shapes. If this featureset is not in index moded,
/// it will add the features to the featurelist and suspend events for faster copying.
/// </summary>
/// <param name="shapes">An enumerable collection of shapes.</param>
void AddShapes(IEnumerable<Shape> shapes);
/// <summary>
/// Gets the specified feature by constructing it from the vertices, rather
/// than requiring that all the features be created. (which takes up a lot of memory).
/// </summary>
/// <param name="index">The integer index</param>
IFeature GetFeature(int index);
/// <summary>
/// Gets a shape at the specified shape index. If the featureset is in
/// indexmode, this returns a copy of the shape. If not, it will create
/// a new shape based on the specified feature.
/// </summary>
/// <param name="index">The zero based integer index of the shape.</param>
/// <param name="getAttributes">If getAttributes is true, then this also try to get attributes for that shape.
/// If attributes are loaded, then it will use the existing datarow. Otherwise, it will read the attributes
/// from the file. (This second option is not recommended for large repeats. In such a case, the attributes
/// can be set manually from a larger bulk query of the data source.)</param>
/// <returns>The Shape object</returns>
Shape GetShape(int index, bool getAttributes);
/// <summary>
/// Given a datarow, this will return the associated feature. This FeatureSet
/// uses an internal dictionary, so that even if the items are re-ordered
/// or have new members inserted, this lookup will still work.
/// </summary>
/// <param name="row">The DataRow for which to obtaind the feature</param>
/// <returns>The feature to obtain that is associated with the specified data row.</returns>
IFeature FeatureFromRow(DataRow row);
/// <summary>
/// Generates a new feature, adds it to the features and returns the value.
/// </summary>
/// <returns>The feature that was added to this featureset</returns>
IFeature AddFeature(IGeometry geometry);
/// <summary>
/// Adds the FID values as a field called FID, but only if the FID field
/// does not already exist
/// </summary>
void AddFid();
/// <summary>
/// Copies all the features from the specified featureset.
/// </summary>
/// <param name="source">The source IFeatureSet to copy features from.</param>
/// <param name="copyAttributes">Boolean, true if the attributes should be copied as well. If this is true,
/// and the attributes are not loaded, a FillAttributes call will be made.</param>
void CopyFeatures(IFeatureSet source, bool copyAttributes);
/// <summary>
/// Retrieves a subset using exclusively the features matching the specified values.
/// </summary>
/// <param name="indices">An integer list of indices to copy into the new FeatureSet</param>
/// <returns>A FeatureSet with the new items.</returns>
IFeatureSet CopySubset(List<int> indices);
/// <summary>
/// Copies the subset of specified features to create a new featureset that is restricted to
/// just the members specified.
/// </summary>
/// <param name="filterExpression">The string expression to test.</param>
/// <returns>A FeatureSet that has members that only match the specified members.</returns>
IFeatureSet CopySubset(string filterExpression);
/// <summary>
/// Copies only the names and types of the attribute fields, without copying any of the attributes or features.
/// </summary>
/// <param name="source">The source featureSet to obtain the schema from.</param>
void CopyTableSchema(IFeatureSet source);
/// <summary>
/// Copies the Table schema (column names/data types)
/// from a DatatTable, but doesn't copy any values.
/// </summary>
/// <param name="sourceTable">The Table to obtain schema from.</param>
void CopyTableSchema(DataTable sourceTable);
/// <summary>
/// Instructs the shapefile to read all the attributes from the file.
/// This may also be a cue to read values from a database.
/// </summary>
void FillAttributes();
/// <summary>
/// Instructs the shapefile to read all the attributes from the file.
/// This may also be a cue to read values from a database.
/// </summary>
void FillAttributes(IProgressHandler progressHandler);
/// <summary>
/// This forces the vertex initialization so that Vertices, ShapeIndices, and the
/// ShapeIndex property on each feature will no longer be null.
/// </summary>
void InitializeVertices();
/// <summary>
/// Switches a boolean so that the next time that the vertices are requested,
/// they must be re-calculated from the feature coordinates.
/// </summary>
/// <remarks>This only affects reading values from the Vertices cache</remarks>
void InvalidateVertices();
/// <summary>
/// Attempts to remove the specified shape.
/// </summary>
/// <param name="index">
/// The integer index of the shape to remove.
/// </param>
/// <returns>
/// Boolean, true if the remove was successful.
/// </returns>
bool RemoveShapeAt(int index);
/// <summary>
/// Attempts to remove a range of shapes by index. This is optimized to
/// work better for large numbers. For one or two, using RemoveShapeAt might
/// be faster.
/// </summary>
/// <param name="indices">
/// The enumerable set of indices to remove.
/// </param>
void RemoveShapesAt(IEnumerable<int> indices);
#endregion
#region Properties
/// <summary>
/// Gets whether or not the attributes have all been loaded into the data table.
/// </summary>
bool AttributesPopulated
{
get;
set;
}
/// <summary>
/// Gets or sets the coordinate type across the entire featureset.
/// </summary>
CoordinateType CoordinateType
{
get;
set;
}
/// <summary>
/// Gets the DataTable associated with this specific feature.
/// </summary>
DataTable DataTable
{
get;
set;
}
/// <summary>
/// Gets the list of all the features that are included in this layer.
/// </summary>
IFeatureList Features
{
get;
set;
}
/// <summary>
/// This is an optional GeometryFactory that can be set to control how the geometries on features are
/// created. if this is not specified, the default from DotSptaial.Topology is used.
/// </summary>
IGeometryFactory FeatureGeometryFactory
{
get;
set;
}
/// <summary>
/// Gets the feature lookup Table itself.
/// </summary>
Dictionary<DataRow, IFeature> FeatureLookup
{
get;
}
/// <summary>
/// Gets an enumeration indicating the type of feature represented in this dataset, if any.
/// </summary>
FeatureType FeatureType
{
get;
set;
}
/// <summary>
/// Gets the string fileName for this feature layer, if any
/// </summary>
string Filename
{
get;
set;
}
/// <summary>
/// These specifically allow the user to make sense of the Vertices array. These are
/// fast acting sealed classes and are not meant to be overridden or support clever
/// new implementations.
/// </summary>
List<ShapeRange> ShapeIndices
{
get;
set;
}
/// <summary>
/// If this is true, then the ShapeIndices and Vertex values are used,
/// and features are created on demand. Otherwise the list of Features
/// is used directly.
/// </summary>
bool IndexMode
{
get;
set;
}
/// <summary>
/// Gets an array of Vertex structures with X and Y coordinates
/// </summary>
double[] Vertex
{
get;
set;
}
/// <summary>
/// Z coordinates
/// </summary>
double[] Z
{
get;
set;
}
/// <summary>
/// M coordinates
/// </summary>
double[] M
{
get;
set;
}
/// <summary>
/// Gets a boolean that indicates whether or not the InvalidateVertices has been called
/// more recently than the cached vertex array has been built.
/// </summary>
bool VerticesAreValid
{
get;
}
/// <summary>
/// Skips the features themselves and uses the shapeindicies instead.
/// </summary>
/// <param name="region">The region to select members from</param>
/// <returns>A list of integer valued shape indices that are selected.</returns>
List<int> SelectIndices(Extent region);
#endregion
/// <summary>
/// Saves the information in the Layers provided by this datasource onto its existing file location
/// </summary>
void Save();
/// <summary>
/// Saves a datasource to the file.
/// </summary>
/// <param name="fileName">The string fileName location to save to</param>
/// <param name="overwrite">Boolean, if this is true then it will overwrite a file of the existing name.</param>
void SaveAs(string fileName, bool overwrite);
/// <summary>
/// returns only the features that have envelopes that
/// intersect with the specified envelope.
/// </summary>
/// <param name="region">The specified region to test for intersect with</param>
/// <returns>A List of the IFeature elements that are contained in this region</returns>
List<IFeature> Select(Extent region);
/// <summary>
/// returns only the features that have envelopes that
/// intersect with the specified envelope.
/// </summary>
/// <param name="region">The specified region to test for intersect with</param>
/// <param name="selectedRegion">This returns the geographic extents for the entire selected area.</param>
/// <returns>A List of the IFeature elements that are contained in this region</returns>
List<IFeature> Select(Extent region, out Extent selectedRegion);
/// <summary>
/// The string filter expression to use in order to return the desired features.
/// </summary>
/// <param name="filterExpression">The features to return.</param>
/// <returns>The list of desired features.</returns>
List<IFeature> SelectByAttribute(string filterExpression);
/// <summary>
/// This version is more tightly integrated to the DataTable and returns the row indices, rather
/// than attempting to link the results to features themselves, which may not even exist.
/// </summary>
/// <param name="filterExpression">The filter expression</param>
/// <returns>The list of indices</returns>
List<int> SelectIndexByAttribute(string filterExpression);
/// <summary>
/// After changing coordinates, this will force the re-calculation of envelopes on a feature
/// level as well as on the featureset level.
/// </summary>
void UpdateExtent();
}
}
| |
namespace Macabresoft.Macabre2D.Framework;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
/// <summary>
/// A quad tree used in detecting collisions. I read the tutorial found at the following link to
/// construct this class:
/// https://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374
/// </summary>
public sealed class QuadTree<T> where T : IBoundable {
private readonly Vector2 _bottomLeftBounds;
private readonly List<T> _boundables = new();
private readonly int _depth;
private readonly QuadTree<T>[] _nodes = new QuadTree<T>[4];
private readonly Vector2 _topRightBounds;
/// <summary>
/// Initializes a new instance of the <see cref="QuadTree{T}" /> class.
/// </summary>
/// <param name="depth">The depth.</param>
/// <param name="x">The left most position of the tree's bounds.</param>
/// <param name="y">The bottom most position of the tree's bounds.</param>
/// <param name="width">The width of the tree's bounds.</param>
/// <param name="height">The height of the tree's bounds.</param>
public QuadTree(int depth, float x, float y, float width, float height) {
this._depth = depth;
this._bottomLeftBounds = new Vector2(x, y);
this._topRightBounds = this._bottomLeftBounds + new Vector2(width, height);
}
/// <summary>
/// Gets or sets the maximum levels.
/// </summary>
/// <value>The maximum levels.</value>
public int MaxLevels { get; set; } = 5;
/// <summary>
/// Gets or sets the maximum objects.
/// </summary>
/// <value>The maximum objects.</value>
public int MaxObjects { get; set; } = 10;
/// <summary>
/// Clears this instance.
/// </summary>
public void Clear() {
this._boundables.Clear();
if (this._nodes[0] != null) {
foreach (var node in this._nodes) {
node.Clear();
}
}
}
/// <summary>
/// Inserts the item into its proper position in the quad tree.
/// </summary>
/// <param name="item">The item to insert.</param>
public void Insert(T item) {
// We only have to null check the first node, because we always add every node at once.
var hasNodes = this._nodes[0] != null;
if (hasNodes) {
var boundingArea = item.BoundingArea;
var quadrant = this.GetQuadrant(boundingArea);
if (quadrant != Quadrant.None) {
this._nodes[(int)quadrant].Insert(item);
return;
}
}
this._boundables.Add(item);
if (this._boundables.Count >= this.MaxObjects && this._depth < this.MaxLevels) {
if (!hasNodes) {
this.Split();
}
for (var i = this._boundables.Count - 1; i >= 0; i--) {
var collider = this._boundables[i];
var boundingArea = collider.BoundingArea;
var quadrant = this.GetQuadrant(boundingArea);
if (quadrant != Quadrant.None) {
this._nodes[(int)quadrant].Insert(collider);
this._boundables.Remove(collider);
}
}
}
}
/// <summary>
/// Inserts all provided items into their proper position in the quad tree.
/// </summary>
/// <param name="items">The items.</param>
public void InsertMany(IEnumerable<T> items) {
foreach (var item in items) {
this.Insert(item);
}
}
/// <summary>
/// Retrieves all colliders which could potentially be colliding with the specified collider.
/// </summary>
/// <param name="boundable">The boundable.</param>
/// <returns>All potential collision colliders.</returns>
public List<T> RetrievePotentialCollisions(T boundable) {
return this.RetrievePotentialCollisions(boundable.BoundingArea);
}
/// <summary>
/// Retrieves all colliders which could potentially be in the specified bounding area.
/// </summary>
/// <param name="boundingArea">The bounding area.</param>
/// <returns>All potential collision colliders.</returns>
public List<T> RetrievePotentialCollisions(BoundingArea boundingArea) {
var potentialCollisions = new List<T>(this._boundables);
var quadrant = this.GetQuadrant(boundingArea);
if (quadrant != Quadrant.None) {
potentialCollisions.AddRange(this._nodes[(int)quadrant].RetrievePotentialCollisions(boundingArea));
}
return potentialCollisions;
}
private Quadrant GetQuadrant(BoundingArea boundingArea) {
var x = boundingArea.Minimum.X;
var y = boundingArea.Minimum.Y;
var width = boundingArea.Maximum.X - x;
var height = boundingArea.Maximum.Y - y;
var quadrant = Quadrant.None;
var verticalMidpoint = x + height * 0.5f;
var horizontalMidPoint = x + width * 0.5f;
var isBottomQuadrant = y < verticalMidpoint && y + height < verticalMidpoint;
var isTopQuadrant = y > verticalMidpoint;
if (x < horizontalMidPoint && x + width < horizontalMidPoint) {
if (isBottomQuadrant) {
quadrant = Quadrant.BottomLeft;
}
else if (isTopQuadrant) {
quadrant = Quadrant.TopLeft;
}
}
else if (x > horizontalMidPoint) {
if (isBottomQuadrant) {
quadrant = Quadrant.BottomRight;
}
else if (isTopQuadrant) {
quadrant = Quadrant.TopRight;
}
}
return quadrant;
}
private void Split() {
var newWidth = (this._topRightBounds.X - this._bottomLeftBounds.X) * 0.5f;
var newHeight = (this._topRightBounds.Y - this._bottomLeftBounds.Y) * 0.5f;
this._nodes[(int)Quadrant.BottomRight] = new QuadTree<T>(
this._depth + 1,
this._bottomLeftBounds.X + newWidth,
this._bottomLeftBounds.Y,
newWidth,
newHeight);
this._nodes[(int)Quadrant.BottomLeft] = new QuadTree<T>(
this._depth + 1,
this._bottomLeftBounds.X,
this._bottomLeftBounds.Y,
newWidth,
newHeight);
this._nodes[(int)Quadrant.TopLeft] = new QuadTree<T>(
this._depth + 1,
this._bottomLeftBounds.X,
this._bottomLeftBounds.Y + newHeight,
newWidth,
newHeight);
this._nodes[(int)Quadrant.TopRight] = new QuadTree<T>(
this._depth + 1,
this._bottomLeftBounds.X + newWidth,
this._bottomLeftBounds.Y + newHeight,
newWidth,
newHeight);
}
/// <summary>
/// Potential quadrants for children.
/// </summary>
private enum Quadrant {
None = -1,
BottomLeft = 0,
BottomRight = 1,
TopLeft = 2,
TopRight = 3
}
}
| |
/*
* 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.
*/
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace Apache.Ignite.Core.Tests.Compute
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests for compute.
/// </summary>
public partial class ComputeApiTest
{
/** Java binary class name. */
private const string JavaBinaryCls = "PlatformComputeJavaBinarizable";
/** */
public const string DefaultCacheName = "default";
/** First node. */
private IIgnite _grid1;
/** Second node. */
private IIgnite _grid2;
/** Third node. */
private IIgnite _grid3;
/** Thin client. */
private IIgniteClient _igniteClient;
/// <summary>
/// Initialization routine.
/// </summary>
[TestFixtureSetUp]
public void InitClient()
{
var configs = GetConfigs();
_grid1 = Ignition.Start(Configuration(configs.Item1));
_grid2 = Ignition.Start(Configuration(configs.Item2));
AffinityTopologyVersion waitingTop = new AffinityTopologyVersion(2, 1);
Assert.True(_grid1.WaitTopology(waitingTop), "Failed to wait topology " + waitingTop);
_grid3 = Ignition.Start(Configuration(configs.Item3));
// Start thin client.
_igniteClient = Ignition.StartClient(GetThinClientConfiguration());
}
/// <summary>
/// Gets the configs.
/// </summary>
protected virtual Tuple<string, string, string> GetConfigs()
{
var path = Path.Combine("Config", "Compute", "compute-grid");
return Tuple.Create(path + "1.xml", path + "2.xml", path + "3.xml");
}
/// <summary>
/// Gets the thin client configuration.
/// </summary>
private static IgniteClientConfiguration GetThinClientConfiguration()
{
return new IgniteClientConfiguration
{
Endpoints = new List<string> { IPAddress.Loopback.ToString() },
SocketTimeout = TimeSpan.FromSeconds(15)
};
}
/// <summary>
/// Gets the expected compact footers setting.
/// </summary>
protected virtual bool CompactFooter
{
get { return true; }
}
[TestFixtureTearDown]
public void StopClient()
{
Ignition.StopAll(true);
}
[TearDown]
public void AfterTest()
{
TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3);
}
/// <summary>
/// Test that it is possible to get projection from grid.
/// </summary>
[Test]
public void TestProjection()
{
IClusterGroup prj = _grid1.GetCluster();
Assert.NotNull(prj);
Assert.AreEqual(prj, prj.Ignite);
// Check that default Compute projection excludes client nodes.
CollectionAssert.AreEquivalent(prj.ForServers().GetNodes(), prj.GetCompute().ClusterGroup.GetNodes());
}
/// <summary>
/// Test non-existent cache.
/// </summary>
[Test]
public void TestNonExistentCache()
{
Assert.Catch(typeof(ArgumentException), () =>
{
_grid1.GetCache<int, int>("bad_name");
});
}
/// <summary>
/// Test node content.
/// </summary>
[Test]
public void TestNodeContent()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
foreach (IClusterNode node in nodes)
{
Assert.NotNull(node.Addresses);
Assert.IsTrue(node.Addresses.Count > 0);
Assert.Throws<NotSupportedException>(() => node.Addresses.Add("addr"));
Assert.NotNull(node.Attributes);
Assert.IsTrue(node.Attributes.Count > 0);
Assert.Throws<NotSupportedException>(() => node.Attributes.Add("key", "val"));
#pragma warning disable 618
Assert.AreSame(node.Attributes, node.GetAttributes());
#pragma warning restore 618
Assert.NotNull(node.HostNames);
Assert.Throws<NotSupportedException>(() => node.HostNames.Add("h"));
Assert.IsTrue(node.Id != Guid.Empty);
Assert.IsTrue(node.Order > 0);
Assert.NotNull(node.GetMetrics());
}
}
/// <summary>
/// Test cluster metrics.
/// </summary>
[Test]
public void TestClusterMetrics()
{
var cluster = _grid1.GetCluster();
var metrics = cluster.GetMetrics();
Assert.IsNotNull(metrics);
Assert.AreEqual(cluster.GetNodes().Count, metrics.TotalNodes);
TestUtils.WaitForTrueCondition(() => cluster.GetMetrics().LastUpdateTime > metrics.LastUpdateTime, 2000);
var newMetrics = cluster.GetMetrics();
Assert.IsFalse(metrics == newMetrics);
Assert.IsTrue(metrics.LastUpdateTime < newMetrics.LastUpdateTime);
}
/// <summary>
/// Test cluster metrics.
/// </summary>
[Test]
public void TestNodeMetrics()
{
var node = _grid1.GetCluster().GetNode();
IClusterMetrics metrics = node.GetMetrics();
Assert.IsNotNull(metrics);
Assert.IsTrue(metrics == node.GetMetrics());
Thread.Sleep(2000);
IClusterMetrics newMetrics = node.GetMetrics();
Assert.IsFalse(metrics == newMetrics);
Assert.IsTrue(metrics.LastUpdateTime < newMetrics.LastUpdateTime);
}
/// <summary>
/// Test cluster metrics.
/// </summary>
[Test]
public void TestResetMetrics()
{
var cluster = _grid1.GetCluster();
Thread.Sleep(2000);
var metrics1 = cluster.GetMetrics();
cluster.ResetMetrics();
var metrics2 = cluster.GetMetrics();
Assert.IsNotNull(metrics1);
Assert.IsNotNull(metrics2);
}
/// <summary>
/// Test node ping.
/// </summary>
[Test]
public void TestPingNode()
{
var cluster = _grid1.GetCluster();
Assert.IsTrue(cluster.GetNodes().Select(node => node.Id).All(cluster.PingNode));
Assert.IsFalse(cluster.PingNode(Guid.NewGuid()));
}
/// <summary>
/// Tests the topology version.
/// </summary>
[Test]
public void TestTopologyVersion()
{
var cluster = _grid1.GetCluster();
var topVer = cluster.TopologyVersion;
Ignition.Stop(_grid3.Name, true);
Assert.AreEqual(topVer + 1, _grid1.GetCluster().TopologyVersion);
_grid3 = Ignition.Start(Configuration(GetConfigs().Item3));
Assert.AreEqual(topVer + 2, _grid1.GetCluster().TopologyVersion);
}
/// <summary>
/// Tests the topology by version.
/// </summary>
[Test]
public void TestTopology()
{
var cluster = _grid1.GetCluster();
Assert.AreEqual(1, cluster.GetTopology(1).Count);
Assert.AreEqual(null, cluster.GetTopology(int.MaxValue));
// Check that Nodes and Topology return the same for current version
var topVer = cluster.TopologyVersion;
var top = cluster.GetTopology(topVer);
var nodes = cluster.GetNodes();
Assert.AreEqual(top.Count, nodes.Count);
Assert.IsTrue(top.All(nodes.Contains));
// Stop/start node to advance version and check that history is still correct
Assert.IsTrue(Ignition.Stop(_grid2.Name, true));
try
{
top = cluster.GetTopology(topVer);
Assert.AreEqual(top.Count, nodes.Count);
Assert.IsTrue(top.All(nodes.Contains));
}
finally
{
_grid2 = Ignition.Start(Configuration(GetConfigs().Item2));
}
}
/// <summary>
/// Test nodes in full topology.
/// </summary>
[Test]
public void TestNodes()
{
Assert.IsNotNull(_grid1.GetCluster().GetNode());
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 3);
// Check subsequent call on the same topology.
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 3);
Assert.IsTrue(Ignition.Stop(_grid2.Name, true));
// Check subsequent calls on updating topologies.
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 2);
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 2);
_grid2 = Ignition.Start(Configuration(GetConfigs().Item2));
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 3);
}
/// <summary>
/// Test "ForNodes" and "ForNodeIds".
/// </summary>
[Test]
public void TestForNodes()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterNode first = nodes.ElementAt(0);
IClusterNode second = nodes.ElementAt(1);
IClusterGroup singleNodePrj = _grid1.GetCluster().ForNodeIds(first.Id);
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
singleNodePrj = _grid1.GetCluster().ForNodeIds(new List<Guid> { first.Id });
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
singleNodePrj = _grid1.GetCluster().ForNodes(first);
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
singleNodePrj = _grid1.GetCluster().ForNodes(new List<IClusterNode> { first });
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
IClusterGroup multiNodePrj = _grid1.GetCluster().ForNodeIds(first.Id, second.Id);
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
multiNodePrj = _grid1.GetCluster().ForNodeIds(new[] {first, second}.Select(x => x.Id));
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
multiNodePrj = _grid1.GetCluster().ForNodes(first, second);
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
multiNodePrj = _grid1.GetCluster().ForNodes(new List<IClusterNode> { first, second });
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
}
/// <summary>
/// Test "ForNodes" and "ForNodeIds". Make sure lazy enumerables are enumerated only once.
/// </summary>
[Test]
public void TestForNodesLaziness()
{
var nodes = _grid1.GetCluster().GetNodes().Take(2).ToArray();
var callCount = 0;
Func<IClusterNode, IClusterNode> nodeSelector = node =>
{
callCount++;
return node;
};
Func<IClusterNode, Guid> idSelector = node =>
{
callCount++;
return node.Id;
};
var projection = _grid1.GetCluster().ForNodes(nodes.Select(nodeSelector));
Assert.AreEqual(2, projection.GetNodes().Count);
Assert.AreEqual(2, callCount);
projection = _grid1.GetCluster().ForNodeIds(nodes.Select(idSelector));
Assert.AreEqual(2, projection.GetNodes().Count);
Assert.AreEqual(4, callCount);
}
/// <summary>
/// Test for local node projection.
/// </summary>
[Test]
public void TestForLocal()
{
IClusterGroup prj = _grid1.GetCluster().ForLocal();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.AreEqual(_grid1.GetCluster().GetLocalNode(), prj.GetNodes().First());
}
/// <summary>
/// Test for remote nodes projection.
/// </summary>
[Test]
public void TestForRemotes()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForRemotes();
Assert.AreEqual(2, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(0)));
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(1)));
}
/// <summary>
/// Test for daemon nodes projection.
/// </summary>
[Test]
public void TestForDaemons()
{
Assert.AreEqual(0, _grid1.GetCluster().ForDaemons().GetNodes().Count);
using (var ignite = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
SpringConfigUrl = GetConfigs().Item1,
IgniteInstanceName = "daemonGrid",
IsDaemon = true
})
)
{
var prj = _grid1.GetCluster().ForDaemons();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.AreEqual(ignite.GetCluster().GetLocalNode().Id, prj.GetNode().Id);
Assert.IsTrue(prj.GetNode().IsDaemon);
Assert.IsTrue(ignite.GetCluster().GetLocalNode().IsDaemon);
}
}
/// <summary>
/// Test for host nodes projection.
/// </summary>
[Test]
public void TestForHost()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForHost(nodes.First());
Assert.AreEqual(3, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(0)));
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(1)));
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(2)));
}
/// <summary>
/// Test for oldest, youngest and random projections.
/// </summary>
[Test]
public void TestForOldestYoungestRandom()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForYoungest();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
prj = _grid1.GetCluster().ForOldest();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
prj = _grid1.GetCluster().ForRandom();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
}
/// <summary>
/// Tests ForServers projection.
/// </summary>
[Test]
public void TestForServers()
{
var cluster = _grid1.GetCluster();
var servers = cluster.ForServers().GetNodes();
Assert.AreEqual(2, servers.Count);
Assert.IsTrue(servers.All(x => !x.IsClient));
var serverAndClient =
cluster.ForNodeIds(new[] { _grid2, _grid3 }.Select(x => x.GetCluster().GetLocalNode().Id));
Assert.AreEqual(1, serverAndClient.ForServers().GetNodes().Count);
var client = cluster.ForNodeIds(new[] { _grid3 }.Select(x => x.GetCluster().GetLocalNode().Id));
Assert.AreEqual(0, client.ForServers().GetNodes().Count);
}
/// <summary>
/// Tests thin client ForServers projection.
/// </summary>
[Test]
public void TestThinClientForServers()
{
var cluster = _igniteClient.GetCluster();
var servers = cluster.ForServers().GetNodes();
Assert.AreEqual(2, servers.Count);
Assert.IsTrue(servers.All(x => !x.IsClient));
}
/// <summary>
/// Test for attribute projection.
/// </summary>
[Test]
public void TestForAttribute()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForAttribute("my_attr", "value1");
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
Assert.AreEqual("value1", prj.GetNodes().First().GetAttribute<string>("my_attr"));
}
/// <summary>
/// Test thin client for attribute projection.
/// </summary>
[Test]
public void TestClientForAttribute()
{
IClientClusterGroup clientPrj = _igniteClient.GetCluster().ForAttribute("my_attr", "value1");
Assert.AreEqual(1,clientPrj.GetNodes().Count);
var nodeId = _grid1.GetCluster().ForAttribute("my_attr", "value1").GetNodes().Single().Id;
Assert.AreEqual(nodeId, clientPrj.GetNode().Id);
}
/// <summary>
/// Test for cache/data/client projections.
/// </summary>
[Test]
public void TestForCacheNodes()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
// Cache nodes.
IClusterGroup prjCache = _grid1.GetCluster().ForCacheNodes("cache1");
Assert.AreEqual(2, prjCache.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prjCache.GetNodes().ElementAt(0)));
Assert.IsTrue(nodes.Contains(prjCache.GetNodes().ElementAt(1)));
// Data nodes.
IClusterGroup prjData = _grid1.GetCluster().ForDataNodes("cache1");
Assert.AreEqual(2, prjData.GetNodes().Count);
Assert.IsTrue(prjCache.GetNodes().Contains(prjData.GetNodes().ElementAt(0)));
Assert.IsTrue(prjCache.GetNodes().Contains(prjData.GetNodes().ElementAt(1)));
// Client nodes.
IClusterGroup prjClient = _grid1.GetCluster().ForClientNodes("cache1");
Assert.AreEqual(0, prjClient.GetNodes().Count);
}
/// <summary>
/// Test for cache predicate.
/// </summary>
[Test]
public void TestForPredicate()
{
IClusterGroup prj1 = _grid1.GetCluster()
.ForPredicate(new NotAttributePredicate<IClusterNode>("value1").Apply);
Assert.AreEqual(2, prj1.GetNodes().Count);
IClusterGroup prj2 = prj1
.ForPredicate(new NotAttributePredicate<IClusterNode>("value2").Apply);
Assert.AreEqual(1, prj2.GetNodes().Count);
string val;
prj2.GetNodes().First().TryGetAttribute("my_attr", out val);
Assert.IsTrue(val == null || (!val.Equals("value1") && !val.Equals("value2")));
}
/// <summary>
/// Test thin client for cache predicate.
/// </summary>
[Test]
public void TestClientForPredicate()
{
var prj1 = _igniteClient.GetCluster()
.ForPredicate(new NotAttributePredicate<IClientClusterNode>("value1").Apply);
Assert.AreEqual(2, prj1.GetNodes().Count);
var prj2 = prj1
.ForPredicate(new NotAttributePredicate<IClientClusterNode>("value2").Apply);
Assert.AreEqual(1, prj2.GetNodes().Count);
var val = (string) prj2.GetNodes().First().Attributes.FirstOrDefault(attr => attr.Key == "my_attr").Value;
Assert.IsTrue(val == null || (!val.Equals("value1") && !val.Equals("value2")));
}
/// <summary>
/// Attribute predicate.
/// </summary>
private class NotAttributePredicate<T> where T: IBaselineNode
{
/** Required attribute value. */
private readonly string _attrVal;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="attrVal">Required attribute value.</param>
public NotAttributePredicate(string attrVal)
{
_attrVal = attrVal;
}
/** <inhreitDoc /> */
public bool Apply(T node)
{
object val;
node.Attributes.TryGetValue("my_attr", out val);
return val == null || !val.Equals(_attrVal);
}
}
/// <summary>
/// Tests the action broadcast.
/// </summary>
[Test]
public void TestBroadcastAction()
{
var id = Guid.NewGuid();
_grid1.GetCompute().Broadcast(new ComputeAction(id));
Assert.AreEqual(2, ComputeAction.InvokeCount(id));
id = Guid.NewGuid();
_grid1.GetCompute().BroadcastAsync(new ComputeAction(id)).Wait();
Assert.AreEqual(2, ComputeAction.InvokeCount(id));
}
/// <summary>
/// Tests single action run.
/// </summary>
[Test]
public void TestRunAction()
{
var id = Guid.NewGuid();
_grid1.GetCompute().Run(new ComputeAction(id));
Assert.AreEqual(1, ComputeAction.InvokeCount(id));
id = Guid.NewGuid();
_grid1.GetCompute().RunAsync(new ComputeAction(id)).Wait();
Assert.AreEqual(1, ComputeAction.InvokeCount(id));
}
/// <summary>
/// Tests single action run.
/// </summary>
[Test]
public void TestRunActionAsyncCancel()
{
using (var cts = new CancellationTokenSource())
{
// Cancel while executing
var task = _grid1.GetCompute().RunAsync(new ComputeAction(), cts.Token);
cts.Cancel();
TestUtils.WaitForTrueCondition(() => task.IsCanceled);
// Use cancelled token
var task2 = _grid1.GetCompute().RunAsync(new ComputeAction(), cts.Token);
Assert.IsTrue(task2.IsCanceled);
}
}
/// <summary>
/// Tests multiple actions run.
/// </summary>
[Test]
public void TestRunActions()
{
var id = Guid.NewGuid();
_grid1.GetCompute().Run(Enumerable.Range(0, 10).Select(x => new ComputeAction(id)));
Assert.AreEqual(10, ComputeAction.InvokeCount(id));
var id2 = Guid.NewGuid();
_grid1.GetCompute().RunAsync(Enumerable.Range(0, 10).Select(x => new ComputeAction(id2))).Wait();
Assert.AreEqual(10, ComputeAction.InvokeCount(id2));
}
/// <summary>
/// Tests affinity run.
/// </summary>
[Test]
public void TestAffinityRun()
{
const string cacheName = DefaultCacheName;
// Test keys for non-client nodes
var nodes = new[] {_grid1, _grid2}.Select(x => x.GetCluster().GetLocalNode());
var aff = _grid1.GetAffinity(cacheName);
foreach (var node in nodes)
{
var primaryKey = TestUtils.GetPrimaryKey(_grid1, cacheName, node);
var affinityKey = aff.GetAffinityKey<int, int>(primaryKey);
var computeAction = new ComputeAction
{
ReservedPartition = aff.GetPartition(primaryKey),
CacheNames = new[] {cacheName}
};
_grid1.GetCompute().AffinityRun(cacheName, affinityKey, computeAction);
Assert.AreEqual(node.Id, ComputeAction.LastNodeId);
_grid1.GetCompute().AffinityRunAsync(cacheName, affinityKey, computeAction).Wait();
Assert.AreEqual(node.Id, ComputeAction.LastNodeId);
}
}
/// <summary>
/// Tests affinity call.
/// </summary>
[Test]
public void TestAffinityCall()
{
const string cacheName = DefaultCacheName;
// Test keys for non-client nodes
var nodes = new[] { _grid1, _grid2 }.Select(x => x.GetCluster().GetLocalNode());
var aff = _grid1.GetAffinity(cacheName);
foreach (var node in nodes)
{
var primaryKey = TestUtils.GetPrimaryKey(_grid1, cacheName, node);
var affinityKey = aff.GetAffinityKey<int, int>(primaryKey);
var result = _grid1.GetCompute().AffinityCall(cacheName, affinityKey, new ComputeFunc());
Assert.AreEqual(result, ComputeFunc.InvokeCount);
Assert.AreEqual(node.Id, ComputeFunc.LastNodeId);
// Async.
ComputeFunc.InvokeCount = 0;
result = _grid1.GetCompute().AffinityCallAsync(cacheName, affinityKey, new ComputeFunc()).Result;
Assert.AreEqual(result, ComputeFunc.InvokeCount);
Assert.AreEqual(node.Id, ComputeFunc.LastNodeId);
}
}
/// <summary>
/// Tests affinity call with partition.
/// </summary>
[Test]
public void TestAffinityCallWithPartition([Values(true, false)] bool async)
{
var cacheName = DefaultCacheName;
var aff = _grid1.GetAffinity(cacheName);
var localNode = _grid1.GetCluster().GetLocalNode();
var part = aff.GetPrimaryPartitions(localNode).First();
var compute = _grid1.GetCompute();
Func<IEnumerable<string>, int> action = names => async
? compute.AffinityCallAsync(names, part, new ComputeFunc()).Result
: compute.AffinityCall(names, part, new ComputeFunc());
// One cache.
var res = action(new[] {cacheName});
Assert.AreEqual(res, ComputeFunc.InvokeCount);
Assert.AreEqual(localNode.Id, ComputeFunc.LastNodeId);
// Two caches.
var cache = _grid1.CreateCache<int, int>(TestUtils.TestName);
res = action(new[] {cacheName, cache.Name});
Assert.AreEqual(res, ComputeFunc.InvokeCount);
Assert.AreEqual(localNode.Id, ComputeFunc.LastNodeId);
// Empty caches.
var ex = Assert.Throws<ArgumentException>(() => action(new string[0]));
StringAssert.StartsWith("cacheNames can not be empty", ex.Message);
// Invalid cache name.
Assert.Throws<AggregateException>(() => action(new[] {"bad"}));
// Invalid partition.
Assert.Throws<ArgumentException>(() => compute.AffinityCall(new[] {cacheName}, -1, new ComputeFunc()));
}
/// <summary>
/// Tests affinity run with partition.
/// </summary>
[Test]
public void TestAffinityRunWithPartition([Values(true, false)] bool local,
[Values(true, false)] bool multiCache, [Values(true, false)] bool async)
{
var cacheNames = new List<string> {DefaultCacheName};
if (multiCache)
{
var cache2 = _grid1.CreateCache<int, int>(TestUtils.TestName);
cacheNames.Add(cache2.Name);
}
var node = local
? _grid1.GetCluster().GetLocalNode()
: _grid2.GetCluster().GetLocalNode();
var aff = _grid1.GetAffinity(cacheNames[0]);
// Wait for some partitions to be assigned to the node.
TestUtils.WaitForTrueCondition(() => aff.GetPrimaryPartitions(node).Any());
var part = aff.GetPrimaryPartitions(node).First();
var computeAction = new ComputeAction
{
ReservedPartition = part,
CacheNames = cacheNames
};
var action = async
? (Action) (() => _grid1.GetCompute().AffinityRunAsync(cacheNames, part, computeAction).Wait())
: () => _grid1.GetCompute().AffinityRun(cacheNames, part, computeAction);
// Good case.
action();
Assert.AreEqual(node.Id, ComputeAction.LastNodeId);
// Exception in user code.
computeAction.ShouldThrow = true;
var aex = Assert.Throws<AggregateException>(() => action());
var ex = aex.GetBaseException();
StringAssert.StartsWith("Remote job threw user exception", ex.Message);
Assert.AreEqual("Error in ComputeAction", ex.GetInnermostException().Message);
}
/// <summary>
/// Tests affinity operations with cancellation.
/// </summary>
[Test]
public void TestAffinityOpAsyncWithCancellation([Values(true, false)] bool callOrRun,
[Values(true, false)] bool keyOrPart)
{
var compute = _grid1.GetCompute();
Action<CancellationToken> action = token =>
{
if (callOrRun)
{
if (keyOrPart)
{
compute.AffinityCallAsync(DefaultCacheName, 1, new ComputeFunc(), token).Wait();
}
else
{
compute.AffinityCallAsync(new[] {DefaultCacheName}, 1, new ComputeFunc(), token).Wait();
}
}
else
{
if (keyOrPart)
{
compute.AffinityRunAsync(DefaultCacheName, 1, new ComputeAction(), token).Wait();
}
else
{
compute.AffinityRunAsync(new[] {DefaultCacheName}, 1, new ComputeAction(), token).Wait();
}
}
};
// Not cancelled.
Assert.DoesNotThrow(() => action(CancellationToken.None));
// Cancelled.
var ex = Assert.Throws<AggregateException>(() => action(new CancellationToken(true)));
Assert.IsInstanceOf<TaskCanceledException>(ex.GetInnermostException());
}
/// <summary>
/// Test simple dotNet task execution.
/// </summary>
[Test]
public void TestNetTaskSimple()
{
Assert.AreEqual(2, _grid1.GetCompute()
.Execute<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>(
typeof(NetSimpleTask), new NetSimpleJobArgument(1)).Res);
Assert.AreEqual(2, _grid1.GetCompute()
.ExecuteAsync<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>(
typeof(NetSimpleTask), new NetSimpleJobArgument(1)).Result.Res);
Assert.AreEqual(4, _grid1.GetCompute().Execute(new NetSimpleTask(), new NetSimpleJobArgument(2)).Res);
Assert.AreEqual(6, _grid1.GetCompute().ExecuteAsync(new NetSimpleTask(), new NetSimpleJobArgument(3))
.Result.Res);
}
/// <summary>
/// Tests the exceptions.
/// </summary>
[Test]
public void TestExceptions()
{
Assert.Throws<AggregateException>(() => _grid1.GetCompute().Broadcast(new InvalidComputeAction()));
Assert.Throws<AggregateException>(
() => _grid1.GetCompute().Execute<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>(
typeof (NetSimpleTask), new NetSimpleJobArgument(-1)));
// Local.
var ex = Assert.Throws<AggregateException>(() =>
_grid1.GetCluster().ForLocal().GetCompute().Broadcast(new ExceptionalComputeAction()));
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("Compute job has failed on local node, examine InnerException for details.",
ex.InnerException.Message);
Assert.IsNotNull(ex.InnerException.InnerException);
Assert.AreEqual(ExceptionalComputeAction.ErrorText, ex.InnerException.InnerException.Message);
// Remote.
ex = Assert.Throws<AggregateException>(() =>
_grid1.GetCluster().ForRemotes().GetCompute().Broadcast(new ExceptionalComputeAction()));
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("Compute job has failed on remote node, examine InnerException for details.",
ex.InnerException.Message);
Assert.IsNotNull(ex.InnerException.InnerException);
Assert.AreEqual(ExceptionalComputeAction.ErrorText, ex.InnerException.InnerException.Message);
}
/// <summary>
/// Tests the footer setting.
/// </summary>
[Test]
public void TestFooterSetting()
{
Assert.AreEqual(CompactFooter, ((Ignite) _grid1).Marshaller.CompactFooter);
foreach (var g in new[] {_grid1, _grid2, _grid3})
Assert.AreEqual(CompactFooter, g.GetConfiguration().BinaryConfiguration.CompactFooter);
}
/// <summary>
/// Create configuration.
/// </summary>
/// <param name="path">XML config path.</param>
private static IgniteConfiguration Configuration(string path)
{
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof(PlatformComputeBinarizable)),
new BinaryTypeConfiguration(typeof(PlatformComputeNetBinarizable)),
new BinaryTypeConfiguration(JavaBinaryCls),
new BinaryTypeConfiguration(typeof(PlatformComputeEnum)),
new BinaryTypeConfiguration(typeof(InteropComputeEnumFieldTest))
},
NameMapper = new BinaryBasicNameMapper { IsSimpleName = true }
},
SpringConfigUrl = path
};
}
}
class PlatformComputeBinarizable
{
public int Field
{
get;
set;
}
}
class PlatformComputeNetBinarizable : PlatformComputeBinarizable
{
}
[Serializable]
class NetSimpleTask : IComputeTask<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>
{
/** <inheritDoc /> */
public IDictionary<IComputeJob<NetSimpleJobResult>, IClusterNode> Map(IList<IClusterNode> subgrid,
NetSimpleJobArgument arg)
{
var jobs = new Dictionary<IComputeJob<NetSimpleJobResult>, IClusterNode>();
for (int i = 0; i < subgrid.Count; i++)
{
var job = arg.Arg > 0 ? new NetSimpleJob {Arg = arg} : new InvalidNetSimpleJob();
jobs[job] = subgrid[i];
}
return jobs;
}
/** <inheritDoc /> */
public ComputeJobResultPolicy OnResult(IComputeJobResult<NetSimpleJobResult> res,
IList<IComputeJobResult<NetSimpleJobResult>> rcvd)
{
return ComputeJobResultPolicy.Wait;
}
/** <inheritDoc /> */
public NetSimpleTaskResult Reduce(IList<IComputeJobResult<NetSimpleJobResult>> results)
{
return new NetSimpleTaskResult(results.Sum(res => res.Data.Res));
}
}
[Serializable]
class NetSimpleJob : IComputeJob<NetSimpleJobResult>
{
public NetSimpleJobArgument Arg;
/** <inheritDoc /> */
public NetSimpleJobResult Execute()
{
return new NetSimpleJobResult(Arg.Arg);
}
/** <inheritDoc /> */
public void Cancel()
{
// No-op.
}
}
class InvalidNetSimpleJob : NetSimpleJob, IBinarizable
{
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
[Serializable]
class NetSimpleJobArgument
{
public int Arg;
public NetSimpleJobArgument(int arg)
{
Arg = arg;
}
}
[Serializable]
class NetSimpleTaskResult
{
public int Res;
public NetSimpleTaskResult(int res)
{
Res = res;
}
}
[Serializable]
class NetSimpleJobResult
{
public int Res;
public NetSimpleJobResult(int res)
{
Res = res;
}
}
[Serializable]
class ComputeAction : IComputeAction
{
[InstanceResource]
#pragma warning disable 649
// ReSharper disable once UnassignedField.Local
private IIgnite _grid;
public static ConcurrentBag<Guid> Invokes = new ConcurrentBag<Guid>();
public static Guid LastNodeId;
public Guid Id { get; set; }
public int? ReservedPartition { get; set; }
public ICollection<string> CacheNames { get; set; }
public bool ShouldThrow { get; set; }
public ComputeAction()
{
// No-op.
}
public ComputeAction(Guid id)
{
Id = id;
}
public void Invoke()
{
Thread.Sleep(10);
Invokes.Add(Id);
LastNodeId = _grid.GetCluster().GetLocalNode().Id;
if (ReservedPartition != null)
{
Assert.IsNotNull(CacheNames);
foreach (var cacheName in CacheNames)
{
Assert.IsTrue(TestUtils.IsPartitionReserved(_grid, cacheName, ReservedPartition.Value));
}
}
if (ShouldThrow)
{
throw new Exception("Error in ComputeAction");
}
}
public static int InvokeCount(Guid id)
{
return Invokes.Count(x => x == id);
}
}
class InvalidComputeAction : ComputeAction, IBinarizable
{
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
class ExceptionalComputeAction : IComputeAction
{
public const string ErrorText = "Expected user exception";
public void Invoke()
{
throw new OverflowException(ErrorText);
}
}
interface IUserInterface<out T>
{
T Invoke();
}
interface INestedComputeFunc : IComputeFunc<int>
{
}
[Serializable]
class ComputeFunc : INestedComputeFunc, IUserInterface<int>
{
[InstanceResource]
// ReSharper disable once UnassignedField.Local
private IIgnite _grid;
public static int InvokeCount;
public static Guid LastNodeId;
int IComputeFunc<int>.Invoke()
{
Thread.Sleep(10);
InvokeCount++;
LastNodeId = _grid.GetCluster().GetLocalNode().Id;
return InvokeCount;
}
int IUserInterface<int>.Invoke()
{
// Same signature as IComputeFunc<int>, but from different interface
throw new Exception("Invalid method");
}
public int Invoke()
{
// Same signature as IComputeFunc<int>, but due to explicit interface implementation this is a wrong method
throw new Exception("Invalid method");
}
}
public enum PlatformComputeEnum : ushort
{
Foo,
Bar,
Baz
}
public class InteropComputeEnumFieldTest
{
public PlatformComputeEnum InteropEnum { get; set; }
}
}
| |
using System;
using System.Linq;
using System.Threading;
namespace AvalonAssets.Fyjelu
{
/// <summary>
/// A array implementation of <see cref="IObjectPool{T}" /> implementation with predefined pool size limit.
/// </summary>
/// <remarks>
/// <para>
/// Given a <see cref="IObjectFactory{T}" />, this class will maintain a simple pool of instances.
/// A finite number of idle instances is enforced, but when the pool is empty, new instances are created to support
/// the new load.
/// </para>
/// <para>
/// Hence this class places no limit on the number of active instances created by the pool.
/// This pool is thread-safe.
/// </para>
/// </remarks>
/// <typeparam name="T">The type of IObjectPool held in this pool</typeparam>
public class ArrayObjectPool<T> : AbstractObjectPool<T> where T : class
{
private const int DefaultPoolSize = 20;
private readonly IObjectFactory<T> _factory;
private readonly T[] _items; // Slow cache
private T _firstItem; // For quick access
/// <summary>
/// Create a new <see cref="ArrayObjectPool{T}" /> using the specified factory to create new instances.
/// </summary>
/// <remarks>
/// It limits the maximum number of idle instances to default value.
/// </remarks>
/// <param name="factory">The <see cref="IObjectFactory{T}" /> used to populate the pool.</param>
public ArrayObjectPool(IObjectFactory<T> factory) : this(factory, DefaultPoolSize)
{
}
/// <summary>
/// Create a new <see cref="ArrayObjectPool{T}" /> using the specified factory to create new instances.
/// </summary>
/// <remarks>
/// It limits the maximum number of idle instances to <paramref name="poolSize" />.
/// </remarks>
/// <param name="factory">The <see cref="IObjectFactory{T}" /> used to populate the pool.</param>
/// <param name="poolSize">Maximum size of the pool.</param>
public ArrayObjectPool(IObjectFactory<T> factory, int poolSize)
: base(PoolExceptionHandleOption.Swallow)
{
// Argument validation
if (factory == null)
throw new ArgumentNullException("factory");
if (poolSize <= 0)
throw new ArgumentOutOfRangeException("poolSize");
_factory = factory;
_items = new T[poolSize - 1];
}
/// <summary>
/// Allocate an object from the pool.
/// </summary>
/// <remarks>
/// <para>
/// If there are idle instances available in the pool, the first element is activated, and
/// return to the client.
/// If there are no idle instances available, <see cref="IObjectFactory{T}.Make" /> is invoked to create a
/// new instance.
/// </para>
/// <para>
/// All instances are <see cref="IObjectFactory{T}.Activate" /> before being returned to the client. If the
/// instances fail the activation, it will be destoryed.
/// </para>
/// <para>
/// Exceptions throws by <see cref="IObjectFactory{T}.Activate" /> or
/// <see cref="IObjectFactory{T}.Destory" /> instances are silently swallowed.
/// </para>
/// </remarks>
/// <returns>An instance from the pool.</returns>
/// <exception cref="Exception">
/// When <see cref="IObjectFactory{T}.Make" /> or
/// <see cref="IObjectFactory{T}.Make" /> throws an exception.
/// </exception>
public override T Allocate()
{
var obj = _firstItem;
// Try to get first item
if (obj == null || obj != Interlocked.CompareExchange(ref _firstItem, null, obj))
obj = SlowAllocate(); // Failed to get from first item, use slower method instead.
else
{
// Success to get from first item,
try
{
// Activate object
_factory.Activate(obj);
}
catch (Exception activateException)
{
// Failed activation
// Check the exception rethrow setting
CheckExceptionRethrow(activateException);
try
{
// Destroy object
_factory.Destory(obj);
}
catch (Exception destoryException)
{
// Failed to destroy
// Check the exception rethrow setting
CheckExceptionRethrow(destoryException);
}
// Failed to get from first item, use slower method instead.
obj = SlowAllocate();
}
}
return obj;
}
/// <summary>
/// Frees an instance to the pool, put it in the pool after successful deactivation.
/// </summary>
/// <param name="obj">A <see cref="Allocate" /> instance to be disposed.</param>
/// <remarks>
/// <para>
/// The returning instance is destroyed if deactivation throws an exception, or the stack is already full.
/// </para>
/// <para>
/// Exceptions throws by <see cref="IObjectFactory{T}.Deactivate" /> or
/// <see cref="IObjectFactory{T}.Destory" /> instances are silently swallowed.
/// </para>
/// </remarks>
/// <exception cref="Exception">
/// When <see cref="IObjectFactory{T}.Deactivate" /> or
/// <see cref="IObjectFactory{T}.Destory" /> throws an exception.
/// </exception>
public override void Free(T obj)
{
try
{
// Deactivate object
_factory.Deactivate(obj);
}
catch (Exception deactivateException)
{
// Failed deactivation
// Check the exception rethrow setting
CheckExceptionRethrow(deactivateException);
try
{
// Destroy object
_factory.Destory(obj);
}
catch (Exception destoryException)
{
// Failed to destroy
// Check the exception rethrow setting
CheckExceptionRethrow(destoryException);
return;
}
return;
}
// Intentionally not using interlocked here.
// In a worst case scenario two objects may be stored into same slot.
// It is very unlikely to happen and will only mean that one of the objects will get collected.
if (_firstItem == null)
_firstItem = obj;
else
SlowFree(obj); // Use slower method if first item is occupied.
}
/// <summary>
/// Return the number of instances currently in this pool.
/// </summary>
/// <remarks>
/// This may be considered an approximation of the number of objects that can be borrowed without creating any new
/// instances.
/// </remarks>
/// <returns>The number of instances currently in this pool.</returns>
public override int GetCacheSize()
{
return _items.Count(s => s != null) + (_firstItem == null ? 0 : 1);
}
/// <summary>
/// Clears any objects sitting idle in the pool, releasing any associated resources.
/// </summary>
/// <remarks>
/// Idle objects cleared must be <see cref="IObjectFactory{T}.Destory" />. If new objects is cached during
/// clearing, it may not be clear.
/// </remarks>
/// <exception cref="Exception">
/// When <see cref="IObjectFactory{T}.Destory" /> throws an exception.
/// </exception>
public override void Clear()
{
var items = _items;
for (var i = 0; i < items.Length; i++)
{
var obj = items[i];
if (obj == null) continue;
// Try to get i item
if (obj != Interlocked.CompareExchange(ref items[i], null, obj)) continue;
try
{
// Destroy object
_factory.Destory(obj);
}
catch (Exception destoryException)
{
// Failed to destroy
// Check the exception rethrow setting
CheckExceptionRethrow(destoryException);
}
}
}
/// <summary>
/// Allocate an object from the pool using linear search.
/// </summary>
/// <remarks>
/// <see cref="SlowFree" /> will try to store recycled objects close to the start thus statistically reducing how far
/// will typically be searched.
/// </remarks>
/// <returns>An instance from the pool.</returns>
private T SlowAllocate()
{
T obj;
var items = _items;
for (var i = 0; i < items.Length; i++)
{
obj = items[i];
if (obj == null) continue;
// Try to get i item
if (obj != Interlocked.CompareExchange(ref items[i], null, obj)) continue;
try
{
// Activate object
_factory.Activate(obj);
return obj;
}
catch (Exception activateException)
{
// Failed activation
// Check the exception rethrow setting
CheckExceptionRethrow(activateException);
try
{
// Destroy object
_factory.Destory(obj);
}
catch (Exception destoryException)
{
// Failed to destroy
// Check the exception rethrow setting
CheckExceptionRethrow(destoryException);
}
}
}
// Failed to get cached object, create a new one
obj = _factory.Make();
if (obj == null)
throw new Exception("Factory failed to create a object.");
return obj;
}
/// <summary>
/// Frees an instance to the pool, put it in the pool after successful deactivation.
/// </summary>
/// <remarks>
/// <see cref="SlowAllocate" /> will try to get recycled objects close to the start thus statistically reducing how far
/// will typically be searched.
/// </remarks>
/// <param name="obj"></param>
private void SlowFree(T obj)
{
var items = _items;
for (var i = 0; i < items.Length; i++)
{
// Intentionally not using interlocked here.
// In a worst case scenario two objects may be stored into same slot.
// It is very unlikely to happen and will only mean that one of the objects will get collected.
if (items[i] != null) continue;
items[i] = obj;
break;
}
}
}
}
| |
// 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.Collections.Generic;
/// <summary>
/// Dictionary.ValueCollection.CopyTo(Array,Int32)
/// </summary>
public class DictionaryValueCollectionCopyTo
{
private const int SIZE = 10;
public static int Main()
{
DictionaryValueCollectionCopyTo valuecollectCopyTo = new DictionaryValueCollectionCopyTo();
TestLibrary.TestFramework.BeginTestCase("DictionaryValueCollectionCopyTo");
if (valuecollectCopyTo.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method CopyTo in the ValueCollection 1");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("str1", "Test1");
dic.Add("str2", "Test2");
Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic);
string[] TVals = new string[SIZE];
values.CopyTo(TVals, 0);
string strVals = null;
for (int i = 0; i < TVals.Length; i++)
{
if (TVals[i] != null)
{
strVals += TVals[i].ToString();
}
}
if (TVals[0].ToString() != "Test1" || TVals[1].ToString() != "Test2" || strVals != "Test1Test2")
{
TestLibrary.TestFramework.LogError("001", "the ExpecResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method CopyTo in the ValueCollection 2");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("str1", "Test1");
dic.Add("str2", "Test2");
Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic);
string[] TVals = new string[SIZE];
values.CopyTo(TVals, 5);
string strVals = null;
for (int i = 0; i < TVals.Length; i++)
{
if (TVals[i] != null)
{
strVals += TVals[i].ToString();
}
}
if (TVals[5].ToString() != "Test1" || TVals[6].ToString() != "Test2" || strVals != "Test1Test2")
{
TestLibrary.TestFramework.LogError("003", "the ExpecResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3:Invoke the method CopyTo in the ValueCollection 3");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic);
string[] TVals = new string[SIZE];
values.CopyTo(TVals, 0);
for (int i = 0; i < TVals.Length; i++)
{
if (TVals[i] != null)
{
TestLibrary.TestFramework.LogError("005", "the ExpecResult is not the ActualResult");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1:The argument array is null");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic);
string[] TVals = null;
values.CopyTo(TVals, 0);
TestLibrary.TestFramework.LogError("N001", "The argument array is null but not throw exception");
retVal = false;
}
catch (ArgumentNullException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2:The argument index is less than zero");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic);
string[] TVals = new string[SIZE];
int index = -1;
values.CopyTo(TVals, index);
TestLibrary.TestFramework.LogError("N003", "The argument index is less than zero but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3:The argument index is larger than array length");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("str1", "Test1");
Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic);
string[] TVals = new string[SIZE];
int index = SIZE + 1;
values.CopyTo(TVals, index);
TestLibrary.TestFramework.LogError("N005", "The argument index is larger than array length but not throw exception");
retVal = false;
}
catch (ArgumentException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4:The number of elements in the source Dictionary.ValueCollection is greater than the available space from index to the end of the destination array");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("str1", "Test1");
dic.Add("str1", "Test1");
Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic);
string[] TVals = new string[SIZE];
int index = SIZE - 1;
values.CopyTo(TVals, index);
TestLibrary.TestFramework.LogError("N007", "The ExpectResult should throw exception but the ActualResult not throw exception");
retVal = false;
}
catch (ArgumentException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using UnityEngine;
using System.Collections.Generic;
using System;
public class MapBuilder : MonoBehaviour {
public static MapProperties mapProperties;
public static Dictionary<string, List<string>> TilesetCollisions = new Dictionary<string, List<string>>();
public static List<MapLayer> MapLayers = new List<MapLayer>();
public static List<MapView> MapViews = new List<MapView>();
public static GameObject MapContainer;
static string MapDataFolder = "Maps/Map Data/";
static string TilesetDataFolder = "Maps/Tilesheets/";
static Sprite[] AllTiles;
static string MapPath;
static string MapName;
static float X;
static float Y;
static public void BuildMap(string mapName, float x, float y){
MapPath = MapDataFolder + mapName;
MapName = mapName;
mapProperties = MapPropertiesReader.GetMapProperties(MapPath);
MapLayers = mapProperties.Layers;
MapViews = mapProperties.Views;
X = x;
Y = y;
CreateMapContainer();
BuildMapViews();
BuildMapLayers();
}
static void BuildMapViews(){
GameObject NewView;
int ViewCount = 0;
foreach (MapView View in MapViews) {
NewView = GameObject.CreatePrimitive(PrimitiveType.Cube);
NewView.name = MapName + "_View_" + ViewCount;
NewView.transform.parent = MapContainer.transform;
NewView.transform.localPosition = new Vector3(X + View.XStart + (View.XEnd/2), Y + View.YStart + (View.YEnd/2), 0);
NewView.transform.localScale = new Vector3(View.XEnd, View.YEnd, 20);
NewView.AddComponent<MapViewController>();
ViewCount++;
}
}
static void BuildMapLayers() {
GameObject ThisLayer;
foreach (MapLayer Layer in MapLayers){
Debug.Log(Layer.LayerId);
if(MapContainer.transform.Find("MapLayer_" + Layer.LayerId) != null) {
ThisLayer = MapContainer.transform.Find("MapLayer_" + Layer.LayerId).gameObject;
} else {
ThisLayer = new GameObject("MapLayer_" + Layer.LayerId);
ThisLayer.transform.parent = MapContainer.transform;
ThisLayer.transform.localPosition = new Vector3(0, 0, Layer.LayerId);
}
AllTiles = Resources.LoadAll<Sprite>(TilesetDataFolder + Layer.Tilesheet);
TilesetCollisions = MapPropertiesReader.GetCSVProperties(TilesetDataFolder + Layer.Tilesheet + "_collisions");
TossTilesheetErrors(Layer.Tilesheet);
BuildLayer(ThisLayer, Layer);
}
}
static void CreateMapContainer(){
MapContainer = GameObject.Find("MapContainer");
if(MapContainer == null){
MapContainer = new GameObject();
MapContainer.name = "MapContainer";
MapContainer.transform.position = new Vector3(0, 0, 0);
}
}
static void BuildLayer(GameObject container, MapLayer layer){
List<List<string>> TextMap;
GameObject currentTile;
TextMap = MapPropertiesReader.GetTextMap(MapPath + "_layer_" + layer.Name);
TextMap.Reverse();
int posX = 0;
int posY = 0;
foreach(List<string> mapRow in TextMap){
posX = 0;
foreach(string mapCel in mapRow){
currentTile = BuildTile(mapCel, layer);
if(currentTile != null){
currentTile.transform.parent = container.transform;
currentTile.transform.localPosition = new Vector3(X + posX, Y + posY, 0);
currentTile.GetComponent<SpriteRenderer>().sortingLayerName = "map_" + layer;
}
posX++;
}
posY++;
}
}
static GameObject BuildTile(string mapCel, MapLayer layer){
GameObject NewTile;
Sprite NewTileSprite;
int TileId;
int.TryParse(mapCel, out TileId);
if(TileId != null && TileId != 0){
NewTile = Resources.Load("RetroGameKit/Tile Prefabs/BlankTile", typeof(GameObject)) as GameObject;
NewTile = Instantiate(NewTile, new Vector3(0,0,0), Quaternion.identity) as GameObject;
NewTileSprite = AllTiles[TileId];
NewTile.GetComponent<SpriteRenderer>().sprite = NewTileSprite;
if(layer.UseColliders){
AddCollider(NewTile, mapCel);
}
} else {
NewTile = null;
}
return NewTile;
}
static GameObject GetResource(string prefabName){
return Resources.Load("RetroGameKit/Tile Prefabs/" + prefabName, typeof(GameObject)) as GameObject;
}
static void BuildCollider(string mapCel, string tileType, GameObject NewTile, GameObject Resource, Vector3 position, Quaternion rotation){
if(TileIs(mapCel, tileType)) {
GameObject Collider = Instantiate(Resource, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
Collider.transform.parent = NewTile.transform;
Collider.transform.localPosition = position;
Collider.transform.rotation = rotation;
Collider.transform.localScale = new Vector3(1,1,20);
SetColliderProperty(Collider, mapCel);
if(!EngineProperties.DebugShowColliders) {
Collider.GetComponent<MeshRenderer>().enabled = false;
}
}
}
static void SetColliderProperty(GameObject collider, string mapCel){
if(TileIs(mapCel, "solid")){
collider.layer = LayerMask.NameToLayer("Solid");
}
if(TileIs(mapCel, "solidOnTop")){
collider.layer = LayerMask.NameToLayer("SolidOnTop");
}
}
static bool TileIs(string mapCel, string property){
return TilesetCollisions.ContainsKey(property) && TilesetCollisions[property].Contains(mapCel);
}
static void AddCollider(GameObject NewTile, string mapCel){
BuildCollider(mapCel, "square", NewTile, GetResource("Collision_square"), new Vector3(0, 0, 0), Quaternion.Euler(0, 180, 0));
BuildCollider(mapCel, "elbow_bottomleft", NewTile, GetResource("Collision_elbow"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "elbow_bottomright", NewTile, GetResource("Collision_elbow"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "elbow_topleft", NewTile, GetResource("Collision_elbow"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "elbow_topright", NewTile, GetResource("Collision_elbow"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "quarter_bottomleft", NewTile, GetResource("Collision_quarter"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "quarter_bottomright", NewTile, GetResource("Collision_quarter"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "quarter_topleft", NewTile, GetResource("Collision_quarter"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "quarter_topright", NewTile, GetResource("Collision_quarter"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "half_bottom", NewTile, GetResource("Collision_half"), new Vector3(1, 0.5f, 0), Quaternion.Euler(0,0,90));
BuildCollider(mapCel, "half_top", NewTile, GetResource("Collision_half"), new Vector3(1, 1, 0), Quaternion.Euler(0,0,90));
BuildCollider(mapCel, "half_left", NewTile, GetResource("Collision_half"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "half_right", NewTile, GetResource("Collision_half"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x1_surface_ground_right", NewTile, GetResource("Collision_slope_1x1_surface"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x1_surface_ground_left", NewTile, GetResource("Collision_slope_1x1_surface"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x1_notch_ground_right", NewTile, GetResource("Collision_slope_1x1_notch"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x1_notch_ground_left", NewTile, GetResource("Collision_slope_1x1_notch"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x1_surface_ceiling_right", NewTile, GetResource("Collision_slope_1x1_surface"), new Vector3(1, 1, 0), Quaternion.Euler(0,0,90));
BuildCollider(mapCel, "slope_1x1_surface_ceiling_left", NewTile, GetResource("Collision_slope_1x1_surface"), new Vector3(0, 1, 0), Quaternion.Euler(0,180,90));
BuildCollider(mapCel, "slope_1x1_notch_ceiling_right", NewTile, GetResource("Collision_slope_1x1_notch"), new Vector3(1, 1, 0), Quaternion.Euler(0,0,90));
BuildCollider(mapCel, "slope_1x1_notch_ceiling_left", NewTile, GetResource("Collision_slope_1x1_notch"), new Vector3(0, 1, 0), Quaternion.Euler(0,180,90));
BuildCollider(mapCel, "slope_1x2_surface_ground_right_a", NewTile, GetResource("Collision_slope_1x2_surface_a"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x2_surface_ground_right_b", NewTile, GetResource("Collision_slope_1x2_surface_b"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x2_notch_ground_right", NewTile, GetResource("Collision_slope_1x2_notch"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x2_surface_ground_left_a", NewTile, GetResource("Collision_slope_1x2_surface_a"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x2_surface_ground_left_b", NewTile, GetResource("Collision_slope_1x2_surface_b"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x2_notch_ground_left", NewTile, GetResource("Collision_slope_1x2_notch"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x2_surface_ceiling_right_a", NewTile, GetResource("Collision_slope_1x2_surface_a"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x2_surface_ceiling_right_b", NewTile, GetResource("Collision_slope_1x2_surface_b"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x2_surface_ceiling_left_a", NewTile, GetResource("Collision_slope_1x2_surface_a"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "slope_1x2_surface_ceiling_left_b", NewTile, GetResource("Collision_slope_1x2_surface_b"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "slope_1x2_notch_ceiling_right", NewTile, GetResource("Collision_slope_1x2_notch"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x2_notch_ceiling_left", NewTile, GetResource("Collision_slope_1x2_notch"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "slope_1x3_surface_ground_right_c", NewTile, GetResource("Collision_slope_1x3_surface_c"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x3_surface_ground_right_b", NewTile, GetResource("Collision_slope_1x3_surface_b"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x3_surface_ground_right_a", NewTile, GetResource("Collision_slope_1x3_surface_a"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x3_surface_ground_left_c", NewTile, GetResource("Collision_slope_1x3_surface_c"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x3_surface_ground_left_b", NewTile, GetResource("Collision_slope_1x3_surface_b"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x3_surface_ground_left_a", NewTile, GetResource("Collision_slope_1x3_surface_a"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x3_notch_ground_right", NewTile, GetResource("Collision_slope_1x3_notch"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x3_notch_ground_left", NewTile, GetResource("Collision_slope_1x3_notch"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x3_surface_ceiling_right_c", NewTile, GetResource("Collision_slope_1x3_surface_c"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x3_surface_ceiling_right_b", NewTile, GetResource("Collision_slope_1x3_surface_b"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x3_surface_ceiling_right_a", NewTile, GetResource("Collision_slope_1x3_surface_a"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x3_surface_ceiling_left_c", NewTile, GetResource("Collision_slope_1x3_surface_c"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "slope_1x3_surface_ceiling_left_b", NewTile, GetResource("Collision_slope_1x3_surface_b"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "slope_1x3_surface_ceiling_left_a", NewTile, GetResource("Collision_slope_1x3_surface_a"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "slope_1x3_notch_ceiling_right", NewTile, GetResource("Collision_slope_1x3_notch"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x3_notch_ceiling_left", NewTile, GetResource("Collision_slope_1x3_notch"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "slope_1x4_surface_ground_right_d", NewTile, GetResource("Collision_slope_1x4_surface_d"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x4_surface_ground_right_c", NewTile, GetResource("Collision_slope_1x4_surface_c"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x4_surface_ground_right_b", NewTile, GetResource("Collision_slope_1x4_surface_b"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x4_surface_ground_right_a", NewTile, GetResource("Collision_slope_1x4_surface_a"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x4_surface_ground_left_d", NewTile, GetResource("Collision_slope_1x4_surface_d"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x4_surface_ground_left_c", NewTile, GetResource("Collision_slope_1x4_surface_c"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x4_surface_ground_left_b", NewTile, GetResource("Collision_slope_1x4_surface_b"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x4_surface_ground_left_a", NewTile, GetResource("Collision_slope_1x4_surface_a"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x4_notch_ground_right", NewTile, GetResource("Collision_slope_1x4_notch"), new Vector3(1, 0, 0), Quaternion.Euler(0,0,0));
BuildCollider(mapCel, "slope_1x4_notch_ground_left", NewTile, GetResource("Collision_slope_1x4_notch"), new Vector3(0, 0, 0), Quaternion.Euler(0,180,0));
BuildCollider(mapCel, "slope_1x4_surface_ceiling_right_d", NewTile, GetResource("Collision_slope_1x4_surface_d"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x4_surface_ceiling_right_c", NewTile, GetResource("Collision_slope_1x4_surface_c"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x4_surface_ceiling_right_b", NewTile, GetResource("Collision_slope_1x4_surface_b"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x4_surface_ceiling_right_a", NewTile, GetResource("Collision_slope_1x4_surface_a"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x4_surface_ceiling_left_d", NewTile, GetResource("Collision_slope_1x4_surface_d"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "slope_1x4_surface_ceiling_left_c", NewTile, GetResource("Collision_slope_1x4_surface_c"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "slope_1x4_surface_ceiling_left_b", NewTile, GetResource("Collision_slope_1x4_surface_b"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "slope_1x4_surface_ceiling_left_a", NewTile, GetResource("Collision_slope_1x4_surface_a"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
BuildCollider(mapCel, "slope_1x4_notch_ceiling_right", NewTile, GetResource("Collision_slope_1x4_notch"), new Vector3(1, 1, 0), Quaternion.Euler(0,180,180));
BuildCollider(mapCel, "slope_1x4_notch_ceiling_left", NewTile, GetResource("Collision_slope_1x4_notch"), new Vector3(0, 1, 0), Quaternion.Euler(0,0,180));
}
static void TossTilesheetErrors(string imageName){
if(AllTiles.Length == 0){
ErrorLogger.Log("Could not find image for tilesheet: " + imageName, "Ensure that an image by the correct name exists in the correct directory");
}
if(AllTiles.Length == 1){
ErrorLogger.Log("Image for tilesheet has not been sliced properly: " + imageName, "In the IDE, edit the properties of the image to set Sprite Mode to Multiple, then slice the sprite.");
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Profiling;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Manages client side native call lifecycle.
/// </summary>
internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse>
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>();
readonly CallInvocationDetails<TRequest, TResponse> details;
readonly INativeCall injectedNativeCall; // for testing
// Completion of a pending unary response if not null.
TaskCompletionSource<TResponse> unaryResponseTcs;
// Indicates that response streaming call has finished.
TaskCompletionSource<object> streamingCallFinishedTcs = new TaskCompletionSource<object>();
// Response headers set here once received.
TaskCompletionSource<Metadata> responseHeadersTcs = new TaskCompletionSource<Metadata>();
// Set after status is received. Used for both unary and streaming response calls.
ClientSideStatus? finishedStatus;
public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails)
: base(callDetails.RequestMarshaller.Serializer, callDetails.ResponseMarshaller.Deserializer, callDetails.Channel.Environment)
{
this.details = callDetails.WithOptions(callDetails.Options.Normalize());
this.initialMetadataSent = true; // we always send metadata at the very beginning of the call.
}
/// <summary>
/// This constructor should only be used for testing.
/// </summary>
public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails, INativeCall injectedNativeCall) : this(callDetails)
{
this.injectedNativeCall = injectedNativeCall;
}
// TODO: this method is not Async, so it shouldn't be in AsyncCall class, but
// it is reusing fair amount of code in this class, so we are leaving it here.
/// <summary>
/// Blocking unary request - unary response call.
/// </summary>
public TResponse UnaryCall(TRequest msg)
{
var profiler = Profilers.ForCurrentThread();
using (profiler.NewScope("AsyncCall.UnaryCall"))
using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.Create())
{
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(cq);
halfcloseRequested = true;
readingDone = true;
}
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
using (var ctx = BatchContextSafeHandle.Create())
{
call.StartUnary(ctx, payload, metadataArray, GetWriteFlagsForCall());
var ev = cq.Pluck(ctx.Handle);
bool success = (ev.success != 0);
try
{
using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch"))
{
HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessage(), ctx.GetReceivedInitialMetadata());
}
}
catch (Exception e)
{
Logger.Error(e, "Exception occured while invoking completion delegate.");
}
}
// Once the blocking call returns, the result should be available synchronously.
// Note that GetAwaiter().GetResult() doesn't wrap exceptions in AggregateException.
return unaryResponseTcs.Task.GetAwaiter().GetResult();
}
}
/// <summary>
/// Starts a unary request - unary response call.
/// </summary>
public Task<TResponse> UnaryCallAsync(TRequest msg)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(environment.CompletionQueue);
halfcloseRequested = true;
readingDone = true;
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartUnary(HandleUnaryResponse, payload, metadataArray, GetWriteFlagsForCall());
}
return unaryResponseTcs.Task;
}
}
/// <summary>
/// Starts a streamed request - unary response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public Task<TResponse> ClientStreamingCallAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(environment.CompletionQueue);
readingDone = true;
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartClientStreaming(HandleUnaryResponse, metadataArray);
}
return unaryResponseTcs.Task;
}
}
/// <summary>
/// Starts a unary request - streamed response call.
/// </summary>
public void StartServerStreamingCall(TRequest msg)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(environment.CompletionQueue);
halfcloseRequested = true;
byte[] payload = UnsafeSerialize(msg);
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartServerStreaming(HandleFinished, payload, metadataArray, GetWriteFlagsForCall());
}
call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders);
}
}
/// <summary>
/// Starts a streaming request - streaming response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public void StartDuplexStreamingCall()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(environment.CompletionQueue);
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartDuplexStreaming(HandleFinished, metadataArray);
}
call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders);
}
}
/// <summary>
/// Sends a streaming request. Only one pending send action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartSendMessage(TRequest msg, WriteFlags writeFlags, AsyncCompletionDelegate<object> completionDelegate)
{
StartSendMessageInternal(msg, writeFlags, completionDelegate);
}
/// <summary>
/// Receives a streaming response. Only one pending read action is allowed at any given time.
/// </summary>
public Task<TResponse> ReadMessageAsync()
{
return ReadMessageInternalAsync();
}
/// <summary>
/// Sends halfclose, indicating client is done with streaming requests.
/// Only one pending send action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartSendCloseFromClient(AsyncCompletionDelegate<object> completionDelegate)
{
lock (myLock)
{
GrpcPreconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
CheckSendingAllowed(allowFinished: true);
if (!disposed && !finished)
{
call.StartSendCloseFromClient(HandleSendCloseFromClientFinished);
}
else
{
// In case the call has already been finished by the serverside,
// the halfclose has already been done implicitly, so we only
// emit the notification for the completion delegate.
Task.Run(() => HandleSendCloseFromClientFinished(true));
}
halfcloseRequested = true;
sendCompletionDelegate = completionDelegate;
}
}
/// <summary>
/// Get the task that completes once if streaming call finishes with ok status and throws RpcException with given status otherwise.
/// </summary>
public Task StreamingCallFinishedTask
{
get
{
return streamingCallFinishedTcs.Task;
}
}
/// <summary>
/// Get the task that completes once response headers are received.
/// </summary>
public Task<Metadata> ResponseHeadersAsync
{
get
{
return responseHeadersTcs.Task;
}
}
/// <summary>
/// Gets the resulting status if the call has already finished.
/// Throws InvalidOperationException otherwise.
/// </summary>
public Status GetStatus()
{
lock (myLock)
{
GrpcPreconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished.");
return finishedStatus.Value.Status;
}
}
/// <summary>
/// Gets the trailing metadata if the call has already finished.
/// Throws InvalidOperationException otherwise.
/// </summary>
public Metadata GetTrailers()
{
lock (myLock)
{
GrpcPreconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished.");
return finishedStatus.Value.Trailers;
}
}
public CallInvocationDetails<TRequest, TResponse> Details
{
get
{
return this.details;
}
}
protected override void OnAfterReleaseResources()
{
details.Channel.RemoveCallReference(this);
}
protected override bool IsClient
{
get { return true; }
}
private void Initialize(CompletionQueueSafeHandle cq)
{
using (Profilers.ForCurrentThread().NewScope("AsyncCall.Initialize"))
{
var call = CreateNativeCall(cq);
details.Channel.AddCallReference(this);
InitializeInternal(call);
RegisterCancellationCallback();
}
}
private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq)
{
using (Profilers.ForCurrentThread().NewScope("AsyncCall.CreateNativeCall"))
{
if (injectedNativeCall != null)
{
return injectedNativeCall; // allows injecting a mock INativeCall in tests.
}
var parentCall = details.Options.PropagationToken != null ? details.Options.PropagationToken.ParentCall : CallSafeHandle.NullInstance;
var credentials = details.Options.Credentials;
using (var nativeCredentials = credentials != null ? credentials.ToNativeCredentials() : null)
{
var result = details.Channel.Handle.CreateCall(environment.CompletionRegistry,
parentCall, ContextPropagationToken.DefaultMask, cq,
details.Method, details.Host, Timespec.FromDateTime(details.Options.Deadline.Value), nativeCredentials);
return result;
}
}
}
// Make sure that once cancellationToken for this call is cancelled, Cancel() will be called.
private void RegisterCancellationCallback()
{
var token = details.Options.CancellationToken;
if (token.CanBeCanceled)
{
token.Register(() => this.Cancel());
}
}
/// <summary>
/// Gets WriteFlags set in callDetails.Options.WriteOptions
/// </summary>
private WriteFlags GetWriteFlagsForCall()
{
var writeOptions = details.Options.WriteOptions;
return writeOptions != null ? writeOptions.Flags : default(WriteFlags);
}
/// <summary>
/// Handles receive status completion for calls with streaming response.
/// </summary>
private void HandleReceivedResponseHeaders(bool success, Metadata responseHeaders)
{
responseHeadersTcs.SetResult(responseHeaders);
}
/// <summary>
/// Handler for unary response completion.
/// </summary>
private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders)
{
// NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT,
// success will be always set to true.
using (Profilers.ForCurrentThread().NewScope("AsyncCall.HandleUnaryResponse"))
{
TResponse msg = default(TResponse);
var deserializeException = TryDeserialize(receivedMessage, out msg);
lock (myLock)
{
finished = true;
if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK)
{
receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers);
}
finishedStatus = receivedStatus;
ReleaseResourcesIfPossible();
}
responseHeadersTcs.SetResult(responseHeaders);
var status = receivedStatus.Status;
if (status.StatusCode != StatusCode.OK)
{
unaryResponseTcs.SetException(new RpcException(status));
return;
}
unaryResponseTcs.SetResult(msg);
}
}
protected override void CheckSendingAllowed(bool allowFinished)
{
base.CheckSendingAllowed(true);
// throwing RpcException if we already received status on client
// side makes the most sense.
// Note that this throws even for StatusCode.OK.
if (!allowFinished && finishedStatus.HasValue)
{
throw new RpcException(finishedStatus.Value.Status);
}
}
/// <summary>
/// Handles receive status completion for calls with streaming response.
/// </summary>
private void HandleFinished(bool success, ClientSideStatus receivedStatus)
{
// NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT,
// success will be always set to true.
lock (myLock)
{
finished = true;
finishedStatus = receivedStatus;
ReleaseResourcesIfPossible();
}
var status = receivedStatus.Status;
if (status.StatusCode != StatusCode.OK)
{
streamingCallFinishedTcs.SetException(new RpcException(status));
return;
}
streamingCallFinishedTcs.SetResult(null);
}
}
}
| |
using System;
using System.Text;
using Sandbox.ModAPI;
using VRage.Utils;
using VRage.Game;
using VRage.Game.ModAPI;
using VRage.ModAPI;
namespace SpaceEquipmentLtd.Utils
{
public class Logging
{
private string _ModName;
private int _WorkshopId;
private string _LogFilename;
private Type _TypeOfMod;
private System.IO.TextWriter _Writer = null;
private IMyHudNotification _Notify = null;
private int _Indent = 0;
private StringBuilder _Cache = new StringBuilder();
[Flags]
public enum BlockNameOptions
{
None = 0x0000,
IncludeTypename = 0x0001
}
[Flags]
public enum Level
{
Verbose = 0x0001,
Info = 0x0002,
Event = 0x0004,
Error = 0x0008,
All = 0xFFFF
}
public static string BlockName(object block)
{
return BlockName(block, BlockNameOptions.IncludeTypename);
}
public static string BlockName(object block, BlockNameOptions options)
{
var inventory = block as IMyInventory;
if (inventory != null)
{
block = inventory.Owner;
}
var slimBlock = block as IMySlimBlock;
if (slimBlock != null)
{
if (slimBlock.FatBlock != null) block = slimBlock.FatBlock;
else
{
return string.Format("{0}.{1}", slimBlock.CubeGrid != null ? slimBlock.CubeGrid.DisplayName : "Unknown Grid", slimBlock.BlockDefinition.DisplayNameText);
}
}
var terminalBlock = block as IMyTerminalBlock;
if (terminalBlock != null)
{
if ((options & BlockNameOptions.IncludeTypename) != 0) return string.Format("{0}.{1} [{2}]", terminalBlock.CubeGrid != null ? terminalBlock.CubeGrid.DisplayName : "Unknown Grid", terminalBlock.CustomName, terminalBlock.BlockDefinition.TypeIdString);
return string.Format("{0}.{1}", terminalBlock.CubeGrid != null ? terminalBlock.CubeGrid.DisplayName : "Unknown Grid", terminalBlock.CustomName);
}
var cubeBlock = block as IMyCubeBlock;
if (cubeBlock != null)
{
return string.Format("{0} [{1}/{2}]", cubeBlock.CubeGrid != null ? cubeBlock.CubeGrid.DisplayName : "Unknown Grid", cubeBlock.BlockDefinition.TypeIdString, cubeBlock.BlockDefinition.SubtypeName);
}
var entity = block as IMyEntity;
if (entity != null)
{
return string.Format("{0} ({1})", entity.DisplayName, entity.EntityId);
}
var cubeGrid = block as IMyCubeGrid;
if (cubeGrid != null) return cubeGrid.DisplayName;
var character = block as IMyCharacter;
if (character != null) return string.Format("Character: {0}", character.DisplayName);
return block != null ? block.ToString() : "NULL";
}
public Level LogLevel { get; set; }
public bool EnableHudNotification { get; set; }
/// <summary>
///
/// </summary>
public Logging(string modName, int workshopId, string logFileName, Type typeOfMod)
{
MyLog.Default.WriteLineAndConsole(_ModName + " Create Log instance Utils=" + (MyAPIGateway.Utilities != null).ToString());
_ModName = modName;
_WorkshopId = workshopId;
_LogFilename = logFileName;
_TypeOfMod = typeOfMod;
}
/// <summary>
/// Precheckl to avoid retriveing large amout of data,
/// that might be not needed afterwards
/// </summary>
/// <param name="level"></param>
/// <returns></returns>
public bool ShouldLog(Level level)
{
return (LogLevel & level) != 0;
}
/// <summary>
///
/// </summary>
public void IncreaseIndent(Level level)
{
if ((LogLevel & level) != 0) _Indent++;
}
/// <summary>
///
/// </summary>
public void DecreaseIndent(Level level)
{
if ((LogLevel & level) != 0)
if (_Indent > 0) _Indent--;
}
/// <summary>
///
/// </summary>
public void ResetIndent(Level level)
{
if ((LogLevel & level) != 0) _Indent = 0;
}
/// <summary>
///
/// </summary>
public void Error(Exception e)
{
Error(e.ToString());
}
/// <summary>
///
/// </summary>
public void Error(string msg, params object[] args)
{
Error(string.Format(msg, args));
}
/// <summary>
///
/// </summary>
public void Error(string msg)
{
if ((LogLevel & Level.Error) == 0) return;
Write("ERROR: " + msg);
try
{
MyLog.Default.WriteLineAndConsole(_ModName + " error: " + msg);
string text = _ModName + " error - open %AppData%/SpaceEngineers/Storage/" + _LogFilename + " for details";
if (EnableHudNotification)
{
ShowOnHud(text);
}
}
catch (Exception e)
{
Write(string.Format("ERROR: Could not send notification to local client: " + e.ToString()));
}
}
/// <summary>
///
/// </summary>
public void Write(Level level, string msg, params Object[] args)
{
if ((LogLevel & level) == 0) return;
Write(string.Format(msg, args));
}
/// <summary>
///
/// </summary>
public void Write(Level level, string msg)
{
if ((LogLevel & level) == 0) return;
Write(msg);
}
/// <summary>
///
/// </summary>
private void Write(string msg)
{
try
{
lock (_Cache)
{
_Cache.Append(DateTime.Now.ToString("u") + ":");
for (int i = 0; i < _Indent; i++)
{
_Cache.Append(" ");
}
_Cache.Append(msg).AppendLine();
if (_Writer == null && MyAPIGateway.Utilities != null)
{
_Writer = MyAPIGateway.Utilities.WriteFileInLocalStorage(_LogFilename, _TypeOfMod);
}
if (_Writer != null)
{
_Writer.Write(_Cache);
_Writer.Flush();
_Cache.Clear();
}
}
}
catch (Exception e)
{
MyLog.Default.WriteLineAndConsole(_ModName + " had an error while logging message='" + msg + "'\nLogger error: " + e.Message + "\n" + e.StackTrace);
}
}
/// <summary>
///
/// </summary>
/// <param name="text"></param>
/// <param name="displayms"></param>
public void ShowOnHud(string text, int displayms = 10000)
{
if (_Notify == null)
{
_Notify = MyAPIGateway.Utilities.CreateNotification(text, displayms, MyFontEnum.Red);
}
else
{
_Notify.Text = text;
_Notify.ResetAliveTime();
}
_Notify.Show();
}
/// <summary>
///
/// </summary>
public void Close()
{
if (_Writer != null)
{
_Writer.Flush();
_Writer.Close();
_Writer.Dispose();
_Writer = null;
}
_Indent = 0;
_Cache.Clear();
}
}
}
| |
using System;
using System.Text.RegularExpressions;
using NUnit.Framework;
namespace Xsd2Db.CommandLineParser.Test
{
/// <summary>
/// Performs basic testing on the sub-expressions of the command line pattern.
/// </summary>
public abstract class PatternTest_Basic
{
/// <summary>
/// The application regex to use
/// </summary>
public readonly string ApplicationRegex;
/// <summary>
/// The parameter regex to use
/// </summary>
public readonly string ParameterRegex;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="applicationRegex">The application regex to use</param>
/// <param name="parameterRegex">The parameter regex to use</param>
public PatternTest_Basic(
string applicationRegex,
string parameterRegex)
{
this.ApplicationRegex = applicationRegex;
this.ParameterRegex = parameterRegex;
}
/// <summary>
/// Ensure that the application regular expression correctly identifies
/// a program name.
/// </summary>
[Test]
public void MatchProgramName()
{
string commandline = HelperFunction.MakeCommandLine(String.Empty);
Regex programName = new Regex(this.ApplicationRegex);
Match match = programName.Match(commandline);
HelperFunction.ValidateApplication(match);
}
/// <summary>
/// Ensures that the parameter regular expression correctly recognizes
/// a switch using the "-" prefix.
/// </summary>
[Test]
public void MatchSwitch_01()
{
string arguments = "-a";
Regex argument = new Regex(this.ParameterRegex);
Match match = argument.Match(arguments);
HelperFunction.ValidateArguments(match, 1);
HelperFunction.ValidateParameter(match, 0, "a", String.Empty);
}
/// <summary>
/// Ensures that the parameter regular expression correctly recognizes
/// a switch using the "--" prefix.
/// </summary>
[Test]
public void MatchSwitch_02()
{
string arguments = "--a";
Regex argument = new Regex(this.ParameterRegex);
Match match = argument.Match(arguments);
HelperFunction.ValidateArguments(match, 1);
HelperFunction.ValidateParameter(match, 0, "a", String.Empty);
}
/// <summary>
/// Ensures that the parameter regular expression correctly recognizes
/// a switch using the "/" prefix.
/// </summary>
[Test]
public void MatchSwitch_03()
{
string arguments = "/a";
Regex argument = new Regex(this.ParameterRegex);
Match match = argument.Match(arguments);
HelperFunction.ValidateArguments(match, 1);
HelperFunction.ValidateParameter(match, 0, "a", String.Empty);
}
/// <summary>
/// Ensures that the parameter regular expression correctly recognizes
/// a switch using the "-" prefix and a seperating space.
/// </summary>
[Test]
public void MatchParameter_01()
{
string arguments = "-a b";
Regex argument = new Regex(this.ParameterRegex);
Match match = argument.Match(arguments);
HelperFunction.ValidateArguments(match, 1);
HelperFunction.ValidateParameter(match, 0, "a", "b");
}
/// <summary>
/// Ensures that the parameter regular expression correctly recognizes
/// a switch using the "-" prefix and a seperating colon.
/// </summary>
[Test]
public void MatchParameter_02()
{
string arguments = "-a:b";
Regex argument = new Regex(this.ParameterRegex);
Match match = argument.Match(arguments);
HelperFunction.ValidateArguments(match, 1);
HelperFunction.ValidateParameter(match, 0, "a", "b");
}
/// <summary>
/// Ensures that the parameter regular expression correctly recognizes
/// a switch using the "-" prefix and a seperating equals sign.
/// </summary>
[Test]
public void MatchParameter_03()
{
string arguments = "-a=b";
Regex argument = new Regex(this.ParameterRegex);
Match match = argument.Match(arguments);
HelperFunction.ValidateArguments(match, 1);
HelperFunction.ValidateParameter(match, 0, "a", "b");
}
/// <summary>
/// Ensures that the parameter regular expression correctly recognizes
/// a switch using the "--" prefix and a separating space.
/// </summary>
[Test]
public void MatchParameter_04()
{
string arguments = "--a b";
Regex argument = new Regex(this.ParameterRegex);
Match match = argument.Match(arguments);
HelperFunction.ValidateArguments(match, 1);
HelperFunction.ValidateParameter(match, 0, "a", "b");
}
/// <summary>
/// Ensures that the parameter regular expression correctly recognizes
/// a switch using the "--" prefix and a separating colon.
/// </summary>
[Test]
public void MatchParameter_05()
{
string arguments = "--a:b";
Regex argument = new Regex(this.ParameterRegex);
Match match = argument.Match(arguments);
HelperFunction.ValidateArguments(match, 1);
HelperFunction.ValidateParameter(match, 0, "a", "b");
}
/// <summary>
/// Ensures that the parameter regular expression correctly recognizes
/// a switch using the "--" prefix and a separating equals sign.
/// </summary>
[Test]
public void MatchParameter_06()
{
string arguments = "--a=b";
Regex argument = new Regex(this.ParameterRegex);
Match match = argument.Match(arguments);
HelperFunction.ValidateArguments(match, 1);
HelperFunction.ValidateParameter(match, 0, "a", "b");
}
/// <summary>
/// Ensures that the parameter regular expression correctly recognizes
/// a switch using the "/" prefix and a seperating space.
/// </summary>
[Test]
public void MatchParameter_07()
{
string arguments = "/a b";
Regex argument = new Regex(this.ParameterRegex);
Match match = argument.Match(arguments);
HelperFunction.ValidateArguments(match, 1);
HelperFunction.ValidateParameter(match, 0, "a", "b");
}
/// <summary>
/// Ensures that the parameter regular expression correctly recognizes
/// a switch using the "/" prefix and a seperating colon.
/// </summary>
[Test]
public void MatchParameter_08()
{
string arguments = "/a:b";
Regex argument = new Regex(this.ParameterRegex);
Match match = argument.Match(arguments);
HelperFunction.ValidateArguments(match, 1);
HelperFunction.ValidateParameter(match, 0, "a", "b");
}
/// <summary>
/// Ensures that the parameter regular expression correctly recognizes
/// a switch using the "/" prefix and a seperating equals sign.
/// </summary>
[Test]
public void MatchParameter_09()
{
string arguments = "/a=b";
Regex argument = new Regex(this.ParameterRegex);
Match match = argument.Match(arguments);
HelperFunction.ValidateArguments(match, 1);
HelperFunction.ValidateParameter(match, 0, "a", "b");
}
}
/// <summary>
/// Performs basic testing on the sub-expressions of the command line pattern
/// using the basic regular expression for the parameter tests.
///
/// </summary>
[TestFixture]
public class PatternTest_Basic_UsingBasicPattern : PatternTest_Basic
{
/// <summary>
/// Constructor.
/// </summary>
public PatternTest_Basic_UsingBasicPattern()
: base(Pattern.ApplicationPattern, Pattern.BasicParameterPattern)
{
}
}
/// <summary>
/// Performs basic testing on the sub-expressions of the command line pattern
/// using the advances regular expression for the parameter tests.
/// </summary>
[TestFixture]
public class PatternTest_Basic_UsingAdvancedPattern : PatternTest_Basic
{
/// <summary>
/// Constructor
/// </summary>
public PatternTest_Basic_UsingAdvancedPattern()
: base(Pattern.ApplicationPattern, Pattern.AdvancedParameterPattern)
{
}
/// <summary>
/// The start of name pattern should match a single dash
/// </summary>
[Test]
public void StartOfNamePatternTest()
{
Regex regex = new Regex("^" + Pattern.StartOfNamedParamPattern + "$");
HelperFunction.ShouldMatch(regex, "-");
HelperFunction.ShouldMatch(regex, "--");
HelperFunction.ShouldMatch(regex, "/");
}
/// <summary>
/// Test the NameValueSeparatorPattern
/// </summary>
[Test]
public void NameValueSeparatorPatternTest()
{
Regex regex = new Regex("^" + Pattern.NameValueSeparatorPattern + "$");
HelperFunction.ShouldMatch(regex, ":");
HelperFunction.ShouldMatch(regex, " ");
HelperFunction.ShouldMatch(regex, " ");
HelperFunction.ShouldMatch(regex, "=");
}
/// <summary>
/// Test the IdentifirePattern
/// </summary>
public void IdentifierPatternTest()
{
Regex regex = new Regex("^" + Pattern.IdentifierPattern + "$");
HelperFunction.ShouldMatch(regex, "roger123");
HelperFunction.ShouldMatch(regex, "_hello");
HelperFunction.ShouldMatch(regex, "funky_chicken");
HelperFunction.ShouldMatch(regex, "_1_2_3");
HelperFunction.ShouldNotMatch(regex, "Te.St.5_4");
HelperFunction.ShouldNotMatch(regex, ".ab");
HelperFunction.ShouldNotMatch(regex, ".ab");
HelperFunction.ShouldNotMatch(regex, " ");
HelperFunction.ShouldNotMatch(regex, "roger ");
HelperFunction.ShouldNotMatch(regex, " roger");
HelperFunction.ShouldNotMatch(regex, " roger ");
}
/// <summary>
/// Test the NamePattern
/// </summary>
public void NamePatternTest()
{
Regex regex = new Regex("^" + Pattern.NamePattern + "$");
HelperFunction.ShouldMatch(regex, "roger123");
HelperFunction.ShouldMatch(regex, "_hello");
HelperFunction.ShouldMatch(regex, "funky_chicken");
HelperFunction.ShouldMatch(regex, "_1_2_3");
HelperFunction.ShouldMatch(regex, "Te.St.5_4");
HelperFunction.ShouldNotMatch(regex, ".ab");
HelperFunction.ShouldNotMatch(regex, ".ab");
HelperFunction.ShouldNotMatch(regex, " ");
HelperFunction.ShouldNotMatch(regex, "roger ");
HelperFunction.ShouldNotMatch(regex, " roger");
HelperFunction.ShouldNotMatch(regex, " roger ");
}
/// <summary>
/// Test the UnQuotedValuePattern
/// </summary>
[Test]
public void UnQuotedValuePatternTest()
{
Regex regex = new Regex("^" + Pattern.UnQuotedValuePattern + "$");
HelperFunction.ShouldMatch(regex, "roger123");
HelperFunction.ShouldMatch(regex, "_hello");
HelperFunction.ShouldMatch(regex, "funky_chicken");
HelperFunction.ShouldMatch(regex, "_1_2_3");
HelperFunction.ShouldMatch(regex, "Te.St.5_4");
HelperFunction.ShouldMatch(regex, "\\");
HelperFunction.ShouldMatch(regex, "C:\\Test");
HelperFunction.ShouldMatch(regex, "C:\\Test\\");
HelperFunction.ShouldMatch(regex, "\\\\Domain\\host");
HelperFunction.ShouldMatch(regex, "Test\\ Directory");
HelperFunction.ShouldMatch(regex, "@\\\\Domain\\host");
HelperFunction.ShouldMatch(regex, "@Test\\ Directory");
HelperFunction.ShouldNotMatch(regex, String.Empty);
HelperFunction.ShouldNotMatch(regex, " ");
HelperFunction.ShouldNotMatch(regex, "' '");
HelperFunction.ShouldNotMatch(regex, "\" \"");
HelperFunction.ShouldNotMatch(regex, "\\ .ab'");
HelperFunction.ShouldNotMatch(regex, " ");
HelperFunction.ShouldNotMatch(regex, "roger ");
HelperFunction.ShouldNotMatch(regex, " roger");
HelperFunction.ShouldNotMatch(regex, " roger ");
}
/// <summary>
/// Test the SingleQuotedValuePattern
/// </summary>
[Test]
public void SingleQuotedValuePatternTest()
{
Regex regex = new Regex("^" + Pattern.SingleQuotedValuePattern + "$");
HelperFunction.ShouldMatch(regex, "'roger'");
HelperFunction.ShouldMatch(regex, "'_hello'");
HelperFunction.ShouldMatch(regex, "' test test'");
HelperFunction.ShouldMatch(regex, "' foo\\ bar'");
HelperFunction.ShouldMatch(regex, "' foo\" bar'");
HelperFunction.ShouldMatch(regex, "@' foo\\ bar'");
HelperFunction.ShouldMatch(regex, "@' foo\" bar'");
HelperFunction.ShouldNotMatch(regex, "roger");
HelperFunction.ShouldNotMatch(regex, "_hello");
HelperFunction.ShouldNotMatch(regex, "' test test");
HelperFunction.ShouldNotMatch(regex, "' foo\\ bar' '");
}
/// <summary>
/// Test the DoubleQuotedValuePattern
/// </summary>
[Test]
public void DoubleQuotedValuePatternTest()
{
Regex regex = new Regex("^" + Pattern.DoubleQuotedValuePattern + "$");
HelperFunction.ShouldMatch(regex, "\"roger\"");
HelperFunction.ShouldMatch(regex, "\"_hello\"");
HelperFunction.ShouldMatch(regex, "\" test test\"");
HelperFunction.ShouldMatch(regex, "\" foo\\ bar\"");
HelperFunction.ShouldMatch(regex, "\" foo' bar\"");
HelperFunction.ShouldMatch(regex, "@\" foo\\ bar\"");
HelperFunction.ShouldMatch(regex, "@\" foo' bar\"");
HelperFunction.ShouldNotMatch(regex, "roger");
HelperFunction.ShouldNotMatch(regex, "_hello");
HelperFunction.ShouldNotMatch(regex, "' test test");
HelperFunction.ShouldNotMatch(regex, "' foo\\ bar' '");
}
/// <summary>
/// Tests the ValuePattern
/// </summary>
[Test]
public void ValuePatternTest()
{
Regex regex = new Regex("^" + Pattern.ValuePattern + "$");
// Not quotes
HelperFunction.ShouldMatch(regex, "roger123");
HelperFunction.ShouldMatch(regex, "_hello");
HelperFunction.ShouldMatch(regex, "funky_chicken");
HelperFunction.ShouldMatch(regex, "_1_2_3");
HelperFunction.ShouldMatch(regex, "Te.St.5_4");
HelperFunction.ShouldMatch(regex, "\\");
HelperFunction.ShouldMatch(regex, "C:\\Test");
HelperFunction.ShouldMatch(regex, "C:\\Test\\");
HelperFunction.ShouldMatch(regex, "\\\\Domain\\host");
HelperFunction.ShouldMatch(regex, "Test\\ Directory");
// Single quotes
HelperFunction.ShouldMatch(regex, "'roger'");
HelperFunction.ShouldMatch(regex, "'_hello'");
HelperFunction.ShouldMatch(regex, "' test test'");
HelperFunction.ShouldMatch(regex, "' foo\\ bar'");
HelperFunction.ShouldMatch(regex, "' foo\" bar'");
HelperFunction.ShouldMatch(regex, "@' foo\\ bar'");
HelperFunction.ShouldMatch(regex, "@' foo\" bar'");
// Double quotes
HelperFunction.ShouldMatch(regex, "\"roger\"");
HelperFunction.ShouldMatch(regex, "\"_hello\"");
HelperFunction.ShouldMatch(regex, "\" test test\"");
HelperFunction.ShouldMatch(regex, "\" foo\\ bar\"");
HelperFunction.ShouldMatch(regex, "\" foo' bar\"");
HelperFunction.ShouldMatch(regex, "@\" foo\\ bar\"");
HelperFunction.ShouldMatch(regex, "@\" foo' bar\"");
// Mismatches
HelperFunction.ShouldNotMatch(regex, "\\ .ab'");
}
}
/// <summary>
/// Performs basic testing on the sub-expressions of the command line pattern
/// using the basic regular expression for the parameter tests.
///
/// </summary>
[TestFixture]
public class PatternTest_Complex_UsingBasicPattern : PatternTest_Complex
{
/// <summary>
/// Constructor.
/// </summary>
public PatternTest_Complex_UsingBasicPattern()
: base(Pattern.BasicRegex)
{
}
}
/// <summary>
/// Performs basic testing on the sub-expressions of the command line pattern
/// using the advances regular expression for the parameter tests.
/// </summary>
[TestFixture]
public class PatternTest_Complex_UsingAdvancedPattern : PatternTest_Complex
{
/// <summary>
/// Constructor
/// </summary>
public PatternTest_Complex_UsingAdvancedPattern()
: base(Pattern.AdvancedRegex)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ViewEngines
{
public class CompositeViewEngineTest
{
[Fact]
public void ViewEngines_UsesListOfViewEnginesFromOptions()
{
// Arrange
var viewEngine1 = Mock.Of<IViewEngine>();
var viewEngine2 = Mock.Of<IViewEngine>();
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(viewEngine1);
optionsAccessor.Value.ViewEngines.Add(viewEngine2);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.ViewEngines;
// Assert
Assert.Equal(new[] { viewEngine1, viewEngine2 }, result);
}
[Fact]
public void FindView_IsMainPage_Throws_WhenNoViewEnginesAreRegistered()
{
// Arrange
var expected = $"'{typeof(MvcViewOptions).FullName}.{nameof(MvcViewOptions.ViewEngines)}' must not be " +
$"empty. At least one '{typeof(IViewEngine).FullName}' is required to locate a view for rendering.";
var viewName = "test-view";
var actionContext = GetActionContext();
var optionsAccessor = Options.Create(new MvcViewOptions());
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => compositeViewEngine.FindView(actionContext, viewName, isMainPage: true));
Assert.Equal(expected, exception.Message);
}
[Fact]
public void FindView_IsMainPage_ReturnsNotFoundResult_WhenExactlyOneViewEngineIsRegisteredWhichReturnsNotFoundResult()
{
// Arrange
var viewName = "test-view";
var engine = new Mock<IViewEngine>(MockBehavior.Strict);
engine
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ true))
.Returns(ViewEngineResult.NotFound(viewName, new[] { "controller/test-view" }));
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(engine.Object);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.FindView(GetActionContext(), viewName, isMainPage: true);
// Assert
Assert.False(result.Success);
Assert.Equal(new[] { "controller/test-view" }, result.SearchedLocations);
}
[Fact]
public void FindView_IsMainPage_ReturnsView_WhenExactlyOneViewEngineIsRegisteredWhichReturnsAFoundResult()
{
// Arrange
var viewName = "test-view";
var engine = new Mock<IViewEngine>(MockBehavior.Strict);
var view = Mock.Of<IView>();
engine
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ true))
.Returns(ViewEngineResult.Found(viewName, view));
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(engine.Object);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.FindView(GetActionContext(), viewName, isMainPage: true);
// Assert
Assert.True(result.Success);
Assert.Same(view, result.View);
}
[Fact]
public void FindView_IsMainPage_ReturnsViewFromFirstViewEngineWithFoundResult()
{
// Arrange
var viewName = "foo";
var engine1 = new Mock<IViewEngine>(MockBehavior.Strict);
var engine2 = new Mock<IViewEngine>(MockBehavior.Strict);
var engine3 = new Mock<IViewEngine>(MockBehavior.Strict);
var view2 = Mock.Of<IView>();
var view3 = Mock.Of<IView>();
engine1
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ true))
.Returns(ViewEngineResult.NotFound(viewName, Enumerable.Empty<string>()));
engine2
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ true))
.Returns(ViewEngineResult.Found(viewName, view2));
engine3
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ true))
.Returns(ViewEngineResult.Found(viewName, view3));
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(engine1.Object);
optionsAccessor.Value.ViewEngines.Add(engine2.Object);
optionsAccessor.Value.ViewEngines.Add(engine3.Object);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.FindView(GetActionContext(), viewName, isMainPage: true);
// Assert
Assert.True(result.Success);
Assert.Same(view2, result.View);
Assert.Equal(viewName, result.ViewName);
}
[Fact]
public void FindView_IsMainPage_ReturnsNotFound_IfAllViewEnginesReturnNotFound()
{
// Arrange
var viewName = "foo";
var engine1 = new Mock<IViewEngine>(MockBehavior.Strict);
var engine2 = new Mock<IViewEngine>(MockBehavior.Strict);
var engine3 = new Mock<IViewEngine>(MockBehavior.Strict);
engine1
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ true))
.Returns(ViewEngineResult.NotFound(viewName, new[] { "1", "2" }));
engine2
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ true))
.Returns(ViewEngineResult.NotFound(viewName, new[] { "3" }));
engine3
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ true))
.Returns(ViewEngineResult.NotFound(viewName, new[] { "4", "5" }));
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(engine1.Object);
optionsAccessor.Value.ViewEngines.Add(engine2.Object);
optionsAccessor.Value.ViewEngines.Add(engine3.Object);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.FindView(GetActionContext(), viewName, isMainPage: true);
// Assert
Assert.False(result.Success);
Assert.Equal(new[] { "1", "2", "3", "4", "5" }, result.SearchedLocations);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void GetView_ReturnsNotFoundResult_WhenNoViewEnginesAreRegistered(bool isMainPage)
{
// Arrange
var expected = $"'{typeof(MvcViewOptions).FullName}.{nameof(MvcViewOptions.ViewEngines)}' must not be " +
$"empty. At least one '{typeof(IViewEngine).FullName}' is required to locate a view for rendering.";
var viewName = "test-view.cshtml";
var optionsAccessor = Options.Create(new MvcViewOptions());
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => compositeViewEngine.GetView("~/Index.html", viewName, isMainPage));
Assert.Equal(expected, exception.Message);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void GetView_ReturnsNotFoundResult_WhenExactlyOneViewEngineIsRegisteredWhichReturnsNotFoundResult(
bool isMainPage)
{
// Arrange
var viewName = "test-view.cshtml";
var expectedViewName = "~/" + viewName;
var engine = new Mock<IViewEngine>(MockBehavior.Strict);
engine
.Setup(e => e.GetView("~/Index.html", viewName, isMainPage))
.Returns(ViewEngineResult.NotFound(expectedViewName, new[] { expectedViewName }));
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(engine.Object);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.GetView("~/Index.html", viewName, isMainPage);
// Assert
Assert.False(result.Success);
Assert.Equal(new[] { expectedViewName }, result.SearchedLocations);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void GetView_ReturnsView_WhenExactlyOneViewEngineIsRegisteredWhichReturnsAFoundResult(bool isMainPage)
{
// Arrange
var viewName = "test-view.cshtml";
var expectedViewName = "~/" + viewName;
var engine = new Mock<IViewEngine>(MockBehavior.Strict);
var view = Mock.Of<IView>();
engine
.Setup(e => e.GetView("~/Index.html", viewName, isMainPage))
.Returns(ViewEngineResult.Found(expectedViewName, view));
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(engine.Object);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.GetView("~/Index.html", viewName, isMainPage);
// Assert
Assert.True(result.Success);
Assert.Same(view, result.View);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void GetView_ReturnsViewFromFirstViewEngineWithFoundResult(bool isMainPage)
{
// Arrange
var viewName = "foo.cshtml";
var expectedViewName = "~/" + viewName;
var engine1 = new Mock<IViewEngine>(MockBehavior.Strict);
var engine2 = new Mock<IViewEngine>(MockBehavior.Strict);
var engine3 = new Mock<IViewEngine>(MockBehavior.Strict);
var view2 = Mock.Of<IView>();
var view3 = Mock.Of<IView>();
engine1
.Setup(e => e.GetView("~/Index.html", viewName, isMainPage))
.Returns(ViewEngineResult.NotFound(expectedViewName, Enumerable.Empty<string>()));
engine2
.Setup(e => e.GetView("~/Index.html", viewName, isMainPage))
.Returns(ViewEngineResult.Found(expectedViewName, view2));
engine3
.Setup(e => e.GetView("~/Index.html", viewName, isMainPage))
.Returns(ViewEngineResult.Found(expectedViewName, view3));
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(engine1.Object);
optionsAccessor.Value.ViewEngines.Add(engine2.Object);
optionsAccessor.Value.ViewEngines.Add(engine3.Object);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.GetView("~/Index.html", viewName, isMainPage);
// Assert
Assert.True(result.Success);
Assert.Same(view2, result.View);
Assert.Equal(expectedViewName, result.ViewName);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void GetView_ReturnsNotFound_IfAllViewEnginesReturnNotFound(bool isMainPage)
{
// Arrange
var viewName = "foo.cshtml";
var expectedViewName = "~/" + viewName;
var engine1 = new Mock<IViewEngine>(MockBehavior.Strict);
var engine2 = new Mock<IViewEngine>(MockBehavior.Strict);
var engine3 = new Mock<IViewEngine>(MockBehavior.Strict);
engine1
.Setup(e => e.GetView("~/Index.html", viewName, isMainPage))
.Returns(ViewEngineResult.NotFound(expectedViewName, new[] { "1", "2" }));
engine2
.Setup(e => e.GetView("~/Index.html", viewName, isMainPage))
.Returns(ViewEngineResult.NotFound(expectedViewName, new[] { "3" }));
engine3
.Setup(e => e.GetView("~/Index.html", viewName, isMainPage))
.Returns(ViewEngineResult.NotFound(expectedViewName, new[] { "4", "5" }));
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(engine1.Object);
optionsAccessor.Value.ViewEngines.Add(engine2.Object);
optionsAccessor.Value.ViewEngines.Add(engine3.Object);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.GetView("~/Index.html", viewName, isMainPage);
// Assert
Assert.False(result.Success);
Assert.Equal(new[] { "1", "2", "3", "4", "5" }, result.SearchedLocations);
}
[Fact]
public void FindView_ReturnsNotFoundResult_WhenNoViewEnginesAreRegistered()
{
// Arrange
var expected = $"'{typeof(MvcViewOptions).FullName}.{nameof(MvcViewOptions.ViewEngines)}' must not be " +
$"empty. At least one '{typeof(IViewEngine).FullName}' is required to locate a view for rendering.";
var viewName = "my-partial-view";
var optionsAccessor = Options.Create(new MvcViewOptions());
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act & AssertS
var exception = Assert.Throws<InvalidOperationException>(
() => compositeViewEngine.FindView(GetActionContext(), viewName, isMainPage: false));
Assert.Equal(expected, exception.Message);
}
[Fact]
public void FindView_ReturnsNotFoundResult_WhenExactlyOneViewEngineIsRegisteredWhichReturnsNotFoundResult()
{
// Arrange
var viewName = "partial-view";
var engine = new Mock<IViewEngine>(MockBehavior.Strict);
engine
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(viewName, new[] { "Shared/partial-view" }));
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(engine.Object);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.FindView(GetActionContext(), viewName, isMainPage: false);
// Assert
Assert.False(result.Success);
Assert.Equal(new[] { "Shared/partial-view" }, result.SearchedLocations);
}
[Fact]
public void FindView_ReturnsView_WhenExactlyOneViewEngineIsRegisteredWhichReturnsAFoundResult()
{
// Arrange
var viewName = "test-view";
var engine = new Mock<IViewEngine>(MockBehavior.Strict);
var view = Mock.Of<IView>();
engine
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ false))
.Returns(ViewEngineResult.Found(viewName, view));
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(engine.Object);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.FindView(GetActionContext(), viewName, isMainPage: false);
// Assert
Assert.True(result.Success);
Assert.Same(view, result.View);
}
[Fact]
public void FindView_ReturnsViewFromFirstViewEngineWithFoundResult()
{
// Arrange
var viewName = "bar";
var engine1 = new Mock<IViewEngine>(MockBehavior.Strict);
var engine2 = new Mock<IViewEngine>(MockBehavior.Strict);
var engine3 = new Mock<IViewEngine>(MockBehavior.Strict);
var view2 = Mock.Of<IView>();
var view3 = Mock.Of<IView>();
engine1
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(viewName, Enumerable.Empty<string>()));
engine2
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ false))
.Returns(ViewEngineResult.Found(viewName, view2));
engine3
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ false))
.Returns(ViewEngineResult.Found(viewName, view3));
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(engine1.Object);
optionsAccessor.Value.ViewEngines.Add(engine2.Object);
optionsAccessor.Value.ViewEngines.Add(engine3.Object);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.FindView(GetActionContext(), viewName, isMainPage: false);
// Assert
Assert.True(result.Success);
Assert.Same(view2, result.View);
Assert.Equal(viewName, result.ViewName);
}
[Fact]
public void FindView_ReturnsNotFound_IfAllViewEnginesReturnNotFound()
{
// Arrange
var viewName = "foo";
var engine1 = new Mock<IViewEngine>(MockBehavior.Strict);
var engine2 = new Mock<IViewEngine>(MockBehavior.Strict);
var engine3 = new Mock<IViewEngine>(MockBehavior.Strict);
engine1
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(viewName, new[] { "1", "2" }));
engine2
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(viewName, new[] { "3" }));
engine3
.Setup(e => e.FindView(It.IsAny<ActionContext>(), viewName, /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(viewName, new[] { "4", "5" }));
var optionsAccessor = Options.Create(new MvcViewOptions());
optionsAccessor.Value.ViewEngines.Add(engine1.Object);
optionsAccessor.Value.ViewEngines.Add(engine2.Object);
optionsAccessor.Value.ViewEngines.Add(engine3.Object);
var compositeViewEngine = new CompositeViewEngine(optionsAccessor);
// Act
var result = compositeViewEngine.FindView(GetActionContext(), viewName, isMainPage: false);
// Assert
Assert.False(result.Success);
Assert.Equal(new[] { "1", "2", "3", "4", "5" }, result.SearchedLocations);
}
private static ActionContext GetActionContext()
{
return new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
}
private class TestViewEngine : IViewEngine
{
public TestViewEngine(ITestService service)
{
Service = service;
}
public ITestService Service { get; private set; }
public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage)
{
throw new NotImplementedException();
}
public ViewEngineResult GetView(string executingFilePath, string viewPath, bool isMainPage)
{
throw new NotImplementedException();
}
}
public interface ITestService
{
}
}
}
| |
using System;
using NUnit.Framework;
using Whois.Parsers;
namespace Whois.Parsing.Whois.Cira.Ca.Ca
{
[TestFixture]
public class CaParsingTests : ParsingTests
{
private WhoisParser parser;
[SetUp]
public void SetUp()
{
SerilogConfig.Init();
parser = new WhoisParser();
}
[Test]
public void Test_found()
{
var sample = SampleReader.Read("whois.cira.ca", "ca", "found.txt");
var response = parser.Parse("whois.cira.ca", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Found, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cira.ca/ca/Found", response.TemplateName);
Assert.AreEqual("glu.ca", response.DomainName.ToString());
// Registrar Details
Assert.AreEqual("Webnames.ca Inc.", response.Registrar.Name);
Assert.AreEqual("70", response.Registrar.IanaId);
Assert.AreEqual(new DateTime(2010, 12, 04, 00, 00, 00, DateTimeKind.Utc), response.Updated);
Assert.AreEqual(new DateTime(2004, 10, 30, 00, 00, 00, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2010, 10, 29, 00, 00, 00, DateTimeKind.Utc), response.Expiration);
// Registrant Details
Assert.AreEqual("Sanamato Inc.", response.Registrant.Name);
// AdminContact Details
Assert.AreEqual("Ross Vito", response.AdminContact.Name);
Assert.AreEqual("1 (647) 964-4544", response.AdminContact.TelephoneNumber);
Assert.AreEqual("mail@sanamato.com", response.AdminContact.Email);
// AdminContact Address
Assert.AreEqual(2, response.AdminContact.Address.Count);
Assert.AreEqual("405 Queen Street South, P.O. Box 75004", response.AdminContact.Address[0]);
Assert.AreEqual("Bolton ON L7E2B5 Canada", response.AdminContact.Address[1]);
// TechnicalContact Details
Assert.AreEqual("Ross Vito", response.TechnicalContact.Name);
Assert.AreEqual("1 (647) 964-4544", response.TechnicalContact.TelephoneNumber);
Assert.AreEqual("mail@sanamato.com", response.TechnicalContact.Email);
// TechnicalContact Address
Assert.AreEqual(2, response.TechnicalContact.Address.Count);
Assert.AreEqual("405 Queen Street South, P.O. Box 75004", response.TechnicalContact.Address[0]);
Assert.AreEqual("Bolton ON L7E2B5 Canada", response.TechnicalContact.Address[1]);
// Nameservers
Assert.AreEqual(3, response.NameServers.Count);
Assert.AreEqual("ns1.webnames.ca", response.NameServers[0]);
Assert.AreEqual("ns2.webnames.ca", response.NameServers[1]);
Assert.AreEqual("ns3.webnames.ca", response.NameServers[2]);
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("registered", response.DomainStatus[0]);
Assert.AreEqual(22, response.FieldsParsed);
}
[Test]
public void Test_not_assigned()
{
var sample = SampleReader.Read("whois.cira.ca", "ca", "not_assigned.txt");
var response = parser.Parse("whois.cira.ca", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.NotAssigned, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cira.ca/ca/Found", response.TemplateName);
Assert.AreEqual("abbylane.pe.ca", response.DomainName.ToString());
// Registrar Details
Assert.AreEqual("easyDNS Technologies Inc.", response.Registrar.Name);
Assert.AreEqual("88", response.Registrar.IanaId);
Assert.AreEqual(new DateTime(2000, 10, 26, 00, 00, 00, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2011, 11, 30, 00, 00, 00, DateTimeKind.Utc), response.Expiration);
// Registrant Details
Assert.AreEqual("Abbylane Summer Homes", response.Registrant.Name);
// AdminContact Details
Assert.AreEqual("Jeff Carmody", response.AdminContact.Name);
Assert.AreEqual("+1 902-621-0244", response.AdminContact.TelephoneNumber);
Assert.AreEqual("+1 902-566-0823", response.AdminContact.FaxNumber);
Assert.AreEqual("jeff@abbylane.pe.ca", response.AdminContact.Email);
// AdminContact Address
Assert.AreEqual(3, response.AdminContact.Address.Count);
Assert.AreEqual("Abbylane Summer Homes", response.AdminContact.Address[0]);
Assert.AreEqual("8 Birchill Drive", response.AdminContact.Address[1]);
Assert.AreEqual("Ch-town PE C1A 6W5 Canada", response.AdminContact.Address[2]);
// TechnicalContact Details
Assert.AreEqual("Jeff Carmody", response.TechnicalContact.Name);
Assert.AreEqual("+1 902 566 0829", response.TechnicalContact.TelephoneNumber);
Assert.AreEqual("+1 902-628-4355", response.TechnicalContact.FaxNumber);
Assert.AreEqual("jeff@abbylane.pe.ca", response.TechnicalContact.Email);
// TechnicalContact Address
Assert.AreEqual(2, response.TechnicalContact.Address.Count);
Assert.AreEqual("550 University Ave", response.TechnicalContact.Address[0]);
Assert.AreEqual("Charlottetown PE C1A4p3 Canada", response.TechnicalContact.Address[1]);
// Nameservers
Assert.AreEqual(6, response.NameServers.Count);
Assert.AreEqual("ns1.easydns.com", response.NameServers[0]);
Assert.AreEqual("ns2.easydns.com", response.NameServers[1]);
Assert.AreEqual("ns3.easydns.org", response.NameServers[2]);
Assert.AreEqual("ns6.easydns.net", response.NameServers[3]);
Assert.AreEqual("remote1.easydns.com", response.NameServers[4]);
Assert.AreEqual("remote2.easydns.com", response.NameServers[5]);
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("auto-renew grace", response.DomainStatus[0]);
Assert.AreEqual(27, response.FieldsParsed);
AssertWriter.Write(response);
}
[Test]
public void Test_not_found()
{
var sample = SampleReader.Read("whois.cira.ca", "ca", "not_found.txt");
var response = parser.Parse("whois.cira.ca", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.NotFound, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cira.ca/ca/NotFound", response.TemplateName);
Assert.AreEqual("u34jedzcq.ca", response.DomainName.ToString());
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("available", response.DomainStatus[0]);
Assert.AreEqual(3, response.FieldsParsed);
}
[Test]
public void Test_pending_delete()
{
var sample = SampleReader.Read("whois.cira.ca", "ca", "pending_delete.txt");
var response = parser.Parse("whois.cira.ca", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.PendingDelete, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cira.ca/ca/Found", response.TemplateName);
Assert.AreEqual("sagespa.ca", response.DomainName.ToString());
// Registrar Details
Assert.AreEqual("Go Daddy Domains Canada, Inc", response.Registrar.Name);
Assert.AreEqual("2316042", response.Registrar.IanaId);
Assert.AreEqual(new DateTime(2013, 07, 31, 00, 00, 00, DateTimeKind.Utc), response.Updated);
Assert.AreEqual(new DateTime(2011, 05, 12, 00, 00, 00, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2013, 05, 12, 00, 00, 00, DateTimeKind.Utc), response.Expiration);
// Nameservers
Assert.AreEqual(2, response.NameServers.Count);
Assert.AreEqual("ns75.domaincontrol.com", response.NameServers[0]);
Assert.AreEqual("ns76.domaincontrol.com", response.NameServers[1]);
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("pending delete", response.DomainStatus[0]);
Assert.AreEqual(10, response.FieldsParsed);
}
[Test]
public void Test_redemption()
{
var sample = SampleReader.Read("whois.cira.ca", "ca", "redemption.txt");
var response = parser.Parse("whois.cira.ca", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Redemption, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cira.ca/ca/Found", response.TemplateName);
Assert.AreEqual("glu.ca", response.DomainName.ToString());
// Registrar Details
Assert.AreEqual("Webnames.ca Inc.", response.Registrar.Name);
Assert.AreEqual("70", response.Registrar.IanaId);
Assert.AreEqual(new DateTime(2010, 12, 04, 00, 00, 00, DateTimeKind.Utc), response.Updated);
Assert.AreEqual(new DateTime(2004, 10, 30, 00, 00, 00, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2010, 10, 29, 00, 00, 00, DateTimeKind.Utc), response.Expiration);
// Registrant Details
Assert.AreEqual("Sanamato Inc.", response.Registrant.Name);
// AdminContact Details
Assert.AreEqual("Ross Vito", response.AdminContact.Name);
Assert.AreEqual("1 (647) 964-4544", response.AdminContact.TelephoneNumber);
Assert.AreEqual("mail@sanamato.com", response.AdminContact.Email);
// AdminContact Address
Assert.AreEqual(2, response.AdminContact.Address.Count);
Assert.AreEqual("405 Queen Street South, P.O. Box 75004", response.AdminContact.Address[0]);
Assert.AreEqual("Bolton ON L7E2B5 Canada", response.AdminContact.Address[1]);
// TechnicalContact Details
Assert.AreEqual("Ross Vito", response.TechnicalContact.Name);
Assert.AreEqual("1 (647) 964-4544", response.TechnicalContact.TelephoneNumber);
Assert.AreEqual("mail@sanamato.com", response.TechnicalContact.Email);
// TechnicalContact Address
Assert.AreEqual(2, response.TechnicalContact.Address.Count);
Assert.AreEqual("405 Queen Street South, P.O. Box 75004", response.TechnicalContact.Address[0]);
Assert.AreEqual("Bolton ON L7E2B5 Canada", response.TechnicalContact.Address[1]);
// Nameservers
Assert.AreEqual(3, response.NameServers.Count);
Assert.AreEqual("ns1.webnames.ca", response.NameServers[0]);
Assert.AreEqual("ns2.webnames.ca", response.NameServers[1]);
Assert.AreEqual("ns3.webnames.ca", response.NameServers[2]);
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("redemption", response.DomainStatus[0]);
Assert.AreEqual(22, response.FieldsParsed);
}
[Test]
public void Test_found_status_registered_2()
{
var sample = SampleReader.Read("whois.cira.ca", "ca", "found_status_registered_2.txt");
var response = parser.Parse("whois.cira.ca", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Found, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cira.ca/ca/Found", response.TemplateName);
Assert.AreEqual("google.ca", response.DomainName.ToString());
// Registrar Details
Assert.AreEqual("Webnames.ca Inc.", response.Registrar.Name);
Assert.AreEqual("70", response.Registrar.IanaId);
Assert.AreEqual(new DateTime(2000, 10, 03, 00, 00, 00, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2011, 04, 28, 00, 00, 00, DateTimeKind.Utc), response.Expiration);
// Registrant Details
Assert.AreEqual("Google Inc.", response.Registrant.Name);
// AdminContact Details
Assert.AreEqual("Rose Hagan", response.AdminContact.Name);
Assert.AreEqual("1 416 8653361", response.AdminContact.TelephoneNumber);
Assert.AreEqual("1 416 9456616", response.AdminContact.FaxNumber);
Assert.AreEqual("dns-admin@google.com", response.AdminContact.Email);
// AdminContact Address
Assert.AreEqual(2, response.AdminContact.Address.Count);
Assert.AreEqual("130 King St. W., Suite 1800", response.AdminContact.Address[0]);
Assert.AreEqual("Toronto ON M5X 1E3 Canada", response.AdminContact.Address[1]);
// TechnicalContact Details
Assert.AreEqual("Matt Serlin", response.TechnicalContact.Name);
Assert.AreEqual("1.2083895740", response.TechnicalContact.TelephoneNumber);
Assert.AreEqual("1.2083895771", response.TechnicalContact.FaxNumber);
Assert.AreEqual("ccops@markmonitor.com", response.TechnicalContact.Email);
// TechnicalContact Address
Assert.AreEqual(2, response.TechnicalContact.Address.Count);
Assert.AreEqual("Domain Provisioning,10400 Overland Rd. PMB 155", response.TechnicalContact.Address[0]);
Assert.AreEqual("Boise ID 83709 United States", response.TechnicalContact.Address[1]);
// Nameservers
Assert.AreEqual(4, response.NameServers.Count);
Assert.AreEqual("ns1.google.com", response.NameServers[0]);
Assert.AreEqual("ns2.google.com", response.NameServers[1]);
Assert.AreEqual("ns3.google.com", response.NameServers[2]);
Assert.AreEqual("ns4.google.com", response.NameServers[3]);
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("registered", response.DomainStatus[0]);
Assert.AreEqual(24, response.FieldsParsed);
}
[Test]
public void Test_to_be_released()
{
var sample = SampleReader.Read("whois.cira.ca", "ca", "to_be_released.txt");
var response = parser.Parse("whois.cira.ca", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.ToBeReleased, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cira.ca/ca/ToBeReleased", response.TemplateName);
Assert.AreEqual("thomascraft.ca", response.DomainName.ToString());
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("to be released", response.DomainStatus[0]);
Assert.AreEqual(3, response.FieldsParsed);
}
[Test]
public void Test_unavailable()
{
var sample = SampleReader.Read("whois.cira.ca", "ca", "unavailable.txt");
var response = parser.Parse("whois.cira.ca", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Unavailable, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cira.ca/ca/Unavailable", response.TemplateName);
Assert.AreEqual("mediom.ca", response.DomainName.ToString());
Assert.AreEqual(2, response.FieldsParsed);
}
[Test]
public void Test_not_found_status_available()
{
var sample = SampleReader.Read("whois.cira.ca", "ca", "not_found_status_available.txt");
var response = parser.Parse("whois.cira.ca", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.NotFound, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cira.ca/ca/NotFound", response.TemplateName);
Assert.AreEqual("u34jedzcq.ca", response.DomainName.ToString());
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("available", response.DomainStatus[0]);
Assert.AreEqual(3, response.FieldsParsed);
}
[Test]
public void Test_invalid()
{
var sample = SampleReader.Read("whois.cira.ca", "ca", "invalid.txt");
var response = parser.Parse("whois.cira.ca", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Unavailable, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cira.ca/ca/Unavailable", response.TemplateName);
Assert.AreEqual("mediom.ca", response.DomainName.ToString());
Assert.AreEqual(2, response.FieldsParsed);
}
[Test]
public void Test_found_status_registered()
{
var sample = SampleReader.Read("whois.cira.ca", "ca", "found_status_registered.txt");
var response = parser.Parse("whois.cira.ca", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Found, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cira.ca/ca/Found", response.TemplateName);
Assert.AreEqual("google.ca", response.DomainName.ToString());
// Registrar Details
Assert.AreEqual("MarkMonitor International Canada Ltd.", response.Registrar.Name);
Assert.AreEqual("5000040", response.Registrar.IanaId);
Assert.AreEqual(new DateTime(2014, 02, 13, 00, 00, 00, DateTimeKind.Utc), response.Updated);
Assert.AreEqual(new DateTime(2000, 10, 03, 00, 00, 00, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2015, 04, 28, 00, 00, 00, DateTimeKind.Utc), response.Expiration);
// Registrant Details
Assert.AreEqual("Google Inc.", response.Registrant.Name);
// AdminContact Details
Assert.AreEqual("Christina Chiou", response.AdminContact.Name);
Assert.AreEqual("+1.4168653361", response.AdminContact.TelephoneNumber);
Assert.AreEqual("+1.4169456616", response.AdminContact.FaxNumber);
Assert.AreEqual("dns-admin@google.com", response.AdminContact.Email);
// AdminContact Address
Assert.AreEqual(2, response.AdminContact.Address.Count);
Assert.AreEqual("130 King St. W., Suite 1800,", response.AdminContact.Address[0]);
Assert.AreEqual("Toronto ON M5X1E3 Canada", response.AdminContact.Address[1]);
// TechnicalContact Details
Assert.AreEqual("Matt Serlin", response.TechnicalContact.Name);
Assert.AreEqual("+1.2083895740", response.TechnicalContact.TelephoneNumber);
Assert.AreEqual("+1.2083895771", response.TechnicalContact.FaxNumber);
Assert.AreEqual("ccops@markmonitor.com", response.TechnicalContact.Email);
// TechnicalContact Address
Assert.AreEqual(2, response.TechnicalContact.Address.Count);
Assert.AreEqual("Domain Provisioning,10400 Overland Rd. PMB 155", response.TechnicalContact.Address[0]);
Assert.AreEqual("Boise ID 83709 United States", response.TechnicalContact.Address[1]);
// Nameservers
Assert.AreEqual(4, response.NameServers.Count);
Assert.AreEqual("ns1.google.com", response.NameServers[0]);
Assert.AreEqual("ns2.google.com", response.NameServers[1]);
Assert.AreEqual("ns3.google.com", response.NameServers[2]);
Assert.AreEqual("ns4.google.com", response.NameServers[3]);
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("registered", response.DomainStatus[0]);
Assert.AreEqual(25, response.FieldsParsed);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApiHelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(void), index => "" },
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
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 WebApp170603.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;
}
}
}
| |
using System.Collections;
using System.Collections.Immutable;
using NQuery.Iterators;
using NQuery.Symbols;
using NQuery.Syntax;
using NQuery.Text;
namespace NQuery.Binding
{
partial class Binder
{
public virtual BoundQueryState QueryState
{
get { return Parent?.QueryState; }
}
private static SelectQuerySyntax GetFirstSelectQuery(QuerySyntax node)
{
return node switch
{
ParenthesizedQuerySyntax p => GetFirstSelectQuery(p.Query),
UnionQuerySyntax u => GetFirstSelectQuery(u.LeftQuery),
ExceptQuerySyntax e => GetFirstSelectQuery(e.LeftQuery),
IntersectQuerySyntax i => GetFirstSelectQuery(i.LeftQuery),
OrderedQuerySyntax o => GetFirstSelectQuery(o.Query),
_ => (SelectQuerySyntax)node
};
}
private static bool IsRecursive(CommonTableExpressionSyntax commonTableExpression)
{
return IsRecursive(commonTableExpression, commonTableExpression.Query);
}
private static bool IsRecursive(CommonTableExpressionSyntax commonTableExpression, QuerySyntax query)
{
return query.DescendantNodes().OfType<NamedTableReferenceSyntax>().Any(n => n.TableName.Matches(commonTableExpression.Name.ValueText));
}
private string InferColumnName(ExpressionSyntax expressionSyntax)
{
var columnExpression = GetBoundNode<BoundColumnExpression>(expressionSyntax);
return columnExpression?.Symbol.Name ?? string.Empty;
}
private BoundQueryState FindQueryState(TableInstanceSymbol tableInstanceSymbol)
{
var queryState = QueryState;
while (queryState is not null)
{
if (queryState.IntroducedTables.ContainsKey(tableInstanceSymbol))
return queryState;
queryState = queryState.Parent;
}
return null;
}
private bool TryReplaceExpression(ExpressionSyntax expression, BoundExpression boundExpression, out ValueSlot valueSlot)
{
var queryState = QueryState;
// If the expression refers to a column we already know the value slot.
var columnInstance = boundExpression is not BoundColumnExpression columnExpression ? null : columnExpression.Symbol;
if (columnInstance is not null && queryState is not null)
{
valueSlot = columnInstance.ValueSlot;
queryState.ReplacedExpression.Add(expression, valueSlot);
return true;
}
// Replace existing expression for which we've already allocated
// a value slot, such as aggregates and groups.
while (queryState is not null)
{
var candidates = queryState.AccessibleComputedValues
.Concat(queryState.ComputedAggregates);
valueSlot = FindComputedValue(expression, candidates);
if (valueSlot is not null)
{
queryState.ReplacedExpression.Add(expression, valueSlot);
return true;
}
queryState = queryState.Parent;
}
valueSlot = null;
return false;
}
private static bool TryGetExistingValue(BoundExpression boundExpression, out ValueSlot valueSlot)
{
if (boundExpression is not BoundValueSlotExpression boundValueSlot)
{
valueSlot = null;
return false;
}
valueSlot = boundValueSlot.ValueSlot;
return true;
}
private static ValueSlot FindComputedValue(ExpressionSyntax expressionSyntax, IEnumerable<BoundComputedValueWithSyntax> candidates)
{
return (from c in candidates
where c.Syntax.IsEquivalentTo(expressionSyntax) // TODO: We need to compare symbols as well!
select c.Result).FirstOrDefault();
}
private void EnsureAllColumnReferencesAreLegal(SelectQuerySyntax node, OrderedQuerySyntax orderedQueryNode)
{
var isAggregated = QueryState.ComputedAggregates.Count > 0;
var isGrouped = QueryState.ComputedGroupings.Count > 0;
if (!isAggregated && !isGrouped)
return;
var selectDiagnosticId = isGrouped
? DiagnosticId.SelectExpressionNotAggregatedOrGrouped
: DiagnosticId.SelectExpressionNotAggregatedAndNoGroupBy;
EnsureAllColumnReferencesAreAggregatedOrGrouped(node.SelectClause, selectDiagnosticId);
if (node.HavingClause is not null)
EnsureAllColumnReferencesAreAggregatedOrGrouped(node.HavingClause,
DiagnosticId.HavingExpressionNotAggregatedOrGrouped);
if (orderedQueryNode is not null)
{
var orderByDiagnosticId = isGrouped
? DiagnosticId.OrderByExpressionNotAggregatedOrGrouped
: DiagnosticId.OrderByExpressionNotAggregatedAndNoGroupBy;
foreach (var column in orderedQueryNode.Columns)
EnsureAllColumnReferencesAreAggregatedOrGrouped(column, orderByDiagnosticId);
}
}
private void EnsureAllColumnReferencesAreAggregatedOrGrouped(SyntaxNode node, DiagnosticId diagnosticId)
{
// TODO: This is not entirely true. EXISTS (SELECT * FROM GROUP BY ...) is considered valid.
//
// For example, the following query is valid:
//
// SELECT *
// FROM Employees e
// WHERE EXISTS (
// SELECT *
// FROM Orders o
// INNER JOIN [Order Details] od ON od.OrderID = o.OrderID
// WHERE o.EmployeeID = e.EmployeeID
// GROUP BY o.OrderID
// HAVING SUM(od.UnitPrice * od.Quantity) > 12000
// )
//
// Please note that explicitly expanding the * is not valid though. For example the
// following query should generate an error:
//
// SELECT *
// FROM Employees e
// WHERE EXISTS (
// SELECT od.UnitPrice,
// od.Quantity
// FROM Orders o
// INNER JOIN [Order Details] od ON od.OrderID = o.OrderID
// WHERE o.EmployeeID = e.EmployeeID
// GROUP BY o.OrderID
// HAVING SUM(od.UnitPrice * od.Quantity) > 12000
// )
//
// This also includes the qualified asterisk. For example, this query is also invalid:
//
// SELECT *
// FROM Employees e
// WHERE EXISTS (
// SELECT o.*
// FROM Orders o
// INNER JOIN [Order Details] od ON od.OrderID = o.OrderID
// WHERE o.EmployeeID = e.EmployeeID
// GROUP BY o.OrderID
// HAVING SUM(od.UnitPrice * od.Quantity) > 12000
// )
//
// Also SELECT * is only considered valid if the direct parent is EXISTS. For example,
// the following query is invalid:
//
// SELECT *
// FROM Employees e
// WHERE EXISTS (
// SELECT *
// FROM Orders o
// INNER JOIN [Order Details] od ON od.OrderID = o.OrderID
// WHERE o.EmployeeID = e.EmployeeID
// GROUP BY o.OrderID
// HAVING SUM(od.UnitPrice * od.Quantity) > 12000
//
// UNION ALL
//
// SELECT *
// FROM Orders o
// INNER JOIN [Order Details] od ON od.OrderID = o.OrderID
// )
var wildcardReferences = from n in node.DescendantNodes().OfType<WildcardSelectColumnSyntax>()
let bw = GetBoundNode<BoundWildcardSelectColumn>(n)
where bw is not null
from c in bw.TableColumns
where !IsGroupedOrAggregated(c.ValueSlot)
select (Syntax: (SyntaxNode)n, Symbol: c);
var expressionReferences = from n in node.DescendantNodes().OfType<ExpressionSyntax>()
where !n.AncestorsAndSelf().OfType<ExpressionSyntax>().Any(IsGroupedOrAggregated)
let e = GetBoundNode<BoundColumnExpression>(n)
where e is not null
let c = e.Symbol as TableColumnInstanceSymbol
where c is not null
select (Syntax: (SyntaxNode)n, Symbol: c);
var invalidColumnReferences = from t in wildcardReferences.Concat(expressionReferences)
where QueryState.IntroducedTables.ContainsKey(t.Symbol.TableInstance)
select t;
foreach (var (syntax, symbol) in invalidColumnReferences)
Diagnostics.Report(syntax.Span, diagnosticId, symbol.Name);
}
private bool IsGroupedOrAggregated(ExpressionSyntax expressionSyntax)
{
if (QueryState is null)
return false;
if (!QueryState.ReplacedExpression.TryGetValue(expressionSyntax, out var valueSlot))
return false;
return IsGroupedOrAggregated(valueSlot);
}
private bool IsGroupedOrAggregated(ValueSlot valueSlot)
{
var groupsAndAggregates = QueryState.ComputedGroupings.Concat(QueryState.ComputedAggregates);
return groupsAndAggregates.Select(c => c.Result).Contains(valueSlot);
}
private IComparer BindComparer(TextSpan diagnosticSpan, Type type, DiagnosticId errorId)
{
var missingComparer = Comparer.Default;
if (type.IsError())
return missingComparer;
var comparer = LookupComparer(type);
if (comparer is null)
{
comparer = missingComparer;
Diagnostics.Report(diagnosticSpan, errorId, type.ToDisplayName());
}
return comparer;
}
private BoundQuery BindSubquery(QuerySyntax querySyntax)
{
if (InGroupByClause)
{
Diagnostics.ReportGroupByCannotContainSubquery(querySyntax.Span);
}
else if (InAggregateArgument)
{
Diagnostics.ReportAggregateCannotContainSubquery(querySyntax.Span);
}
return BindQuery(querySyntax);
}
private BoundQuery BindQuery(QuerySyntax node)
{
return Bind(node, BindQueryInternal);
}
private BoundQuery BindQueryInternal(QuerySyntax node)
{
switch (node.Kind)
{
case SyntaxKind.UnionQuery:
return BindUnionQuery((UnionQuerySyntax)node);
case SyntaxKind.IntersectQuery:
return BindIntersectQuery((IntersectQuerySyntax)node);
case SyntaxKind.ExceptQuery:
return BindExceptQuery((ExceptQuerySyntax)node);
case SyntaxKind.OrderedQuery:
return BindOrderedQuery((OrderedQuerySyntax)node);
case SyntaxKind.ParenthesizedQuery:
return BindParenthesizedQuery((ParenthesizedQuerySyntax)node);
case SyntaxKind.CommonTableExpressionQuery:
return BindCommonTableExpressionQuery((CommonTableExpressionQuerySyntax)node);
case SyntaxKind.SelectQuery:
return BindSelectQuery((SelectQuerySyntax)node);
default:
throw ExceptionBuilder.UnexpectedValue(node.Kind);
}
}
private static BoundNode BindEmptyQuery()
{
var relation = new BoundEmptyRelation();
var output = Enumerable.Empty<QueryColumnInstanceSymbol>();
return new BoundQuery(relation, output);
}
private BoundQuery BindUnionQuery(UnionQuerySyntax node)
{
var diagnosticSpan = node.UnionKeyword.Span;
var isUnionAll = node.AllKeyword is not null;
var queries = BindUnionInputs(node);
return BindUnionOrUnionAllQuery(diagnosticSpan, isUnionAll, queries);
}
private BoundQuery BindUnionOrUnionAllQuery(TextSpan diagnosticSpan, bool isUnionAll, ImmutableArray<BoundQuery> queries)
{
var firstQuery = queries.First();
if (queries.Length == 1 && isUnionAll)
return firstQuery;
foreach (var otherQuery in queries.Skip(1))
{
if (otherQuery.OutputColumns.Length != firstQuery.OutputColumns.Length)
Diagnostics.ReportDifferentExpressionCountInBinaryQuery(diagnosticSpan);
}
var inputs = BindToCommonTypes(diagnosticSpan, queries);
var columnCount = queries.Select(q => q.OutputColumns.Length).Min();
var outputValues = inputs.First()
.GetOutputValues()
.Take(columnCount)
.Select(v => ValueSlotFactory.CreateTemporary(v.Type))
.ToImmutableArray();
var definedValues = outputValues.Select((valueSlot, columnIndex) => new BoundUnifiedValue(valueSlot, inputs.Select(input => input.GetOutputValues().ElementAt(columnIndex))));
var outputColumns = BindOutputColumns(queries.First().OutputColumns, outputValues);
var comparers = isUnionAll
? Enumerable.Empty<IComparer>()
: outputColumns.Select(c => BindComparer(diagnosticSpan, c.Type, DiagnosticId.InvalidDataTypeInUnion));
var relation = new BoundUnionRelation(isUnionAll, inputs, definedValues, comparers);
return new BoundQuery(relation, outputColumns);
}
private ImmutableArray<BoundQuery> BindUnionInputs(UnionQuerySyntax node)
{
var queries = new List<QuerySyntax>();
FlattenUnionQueries(queries, node);
return queries.Select(BindQuery).ToImmutableArray();
}
private static void FlattenUnionQueries(ICollection<QuerySyntax> receiver, UnionQuerySyntax node)
{
if (node.LeftQuery is UnionQuerySyntax leftAsUnion && HasSameUnionKind(node, leftAsUnion))
FlattenUnionQueries(receiver, leftAsUnion);
else
receiver.Add(node.LeftQuery);
if (node.RightQuery is UnionQuerySyntax rightAsUnion && HasSameUnionKind(node, rightAsUnion))
FlattenUnionQueries(receiver, rightAsUnion);
else
receiver.Add(node.RightQuery);
}
private static bool HasSameUnionKind(UnionQuerySyntax left, UnionQuerySyntax right)
{
return (left.AllKeyword is null) == (right.AllKeyword is null);
}
private BoundQuery BindIntersectQuery(IntersectQuerySyntax node)
{
var diagnosticSpan = node.IntersectKeyword.Span;
var left = node.LeftQuery;
var right = node.RightQuery;
return BindIntersectOrExceptQuery(diagnosticSpan, true, left, right);
}
private BoundQuery BindExceptQuery(ExceptQuerySyntax node)
{
var diagnosticSpan = node.ExceptKeyword.Span;
var left = node.LeftQuery;
var right = node.RightQuery;
return BindIntersectOrExceptQuery(diagnosticSpan, false, left, right);
}
private BoundQuery BindIntersectOrExceptQuery(TextSpan diagnosticSpan, bool isIntersect, QuerySyntax left, QuerySyntax right)
{
var boundLeft = BindQuery(left);
var boundRight = BindQuery(right);
var columns = boundLeft.OutputColumns;
if (boundLeft.OutputColumns.Length != boundRight.OutputColumns.Length)
Diagnostics.ReportDifferentExpressionCountInBinaryQuery(diagnosticSpan);
BindToCommonTypes(diagnosticSpan, boundLeft, boundRight, out var leftInput, out var rightInput, out var leftValues, out _);
var outputValues = leftValues;
var outputColumns = BindOutputColumns(columns, outputValues);
var diagnosticId = isIntersect
? DiagnosticId.InvalidDataTypeInIntersect
: DiagnosticId.InvalidDataTypeInExcept;
var comparers = outputColumns.Select(c => BindComparer(diagnosticSpan, c.Type, diagnosticId));
var relation = new BoundIntersectOrExceptRelation(isIntersect, leftInput, rightInput, comparers);
return new BoundQuery(relation, outputColumns);
}
private void BindToCommonTypes(TextSpan diagnosticSpan, BoundQuery left, BoundQuery right, out BoundRelation newLeft, out BoundRelation newRight, out ImmutableArray<ValueSlot> leftValues, out ImmutableArray<ValueSlot> rightValues)
{
var columnCount = Math.Min(left.OutputColumns.Length, right.OutputColumns.Length);
var leftComputedValues = new List<BoundComputedValue>(columnCount);
var leftOutputs = new List<ValueSlot>(columnCount);
var rightComputedValues = new List<BoundComputedValue>(columnCount);
var rightOutputs = new List<ValueSlot>(columnCount);
for (var i = 0; i < columnCount; i++)
{
var leftValue = left.OutputColumns[i].ValueSlot;
var rightValue = right.OutputColumns[i].ValueSlot;
BindToCommonType(diagnosticSpan, leftValue, rightValue, out var convertedLeft, out var convertedRight);
if (convertedLeft is null)
{
leftOutputs.Add(leftValue);
}
else
{
var newLeftValue = ValueSlotFactory.CreateTemporary(convertedLeft.Type);
var computedValue = new BoundComputedValue(convertedLeft, newLeftValue);
leftComputedValues.Add(computedValue);
leftOutputs.Add(newLeftValue);
}
if (convertedRight is null)
{
rightOutputs.Add(rightValue);
}
else
{
var newRightValue = ValueSlotFactory.CreateTemporary(convertedRight.Type);
var computedValue = new BoundComputedValue(convertedRight, newRightValue);
rightComputedValues.Add(computedValue);
rightOutputs.Add(newRightValue);
}
}
newLeft = leftComputedValues.Count == 0
? left.Relation
: new BoundProjectRelation(new BoundComputeRelation(left.Relation, leftComputedValues), leftOutputs);
newRight = rightComputedValues.Count == 0
? right.Relation
: new BoundProjectRelation(new BoundComputeRelation(right.Relation, rightComputedValues), rightOutputs);
leftValues = leftOutputs.ToImmutableArray();
rightValues = rightOutputs.ToImmutableArray();
}
private ImmutableArray<BoundRelation> BindToCommonTypes(TextSpan diagnosticSpan, ImmutableArray<BoundQuery> queries)
{
var columnCount = queries.Select(q => q.OutputColumns.Length).Min();
var computations = new List<BoundComputedValue>[queries.Length];
var outputs = new List<ValueSlot>[queries.Length];
for (var i = 0; i < outputs.Length; i++)
outputs[i] = new List<ValueSlot>();
for (var columnIndex = 0; columnIndex < columnCount; columnIndex++)
{
var expressions = queries.Select(q => new BoundValueSlotExpression(q.OutputColumns[columnIndex].ValueSlot)).OfType<BoundExpression>().ToImmutableArray();
var convertedExpressions = BindToCommonType(expressions, diagnosticSpan);
for (var queryIndex = 0; queryIndex < expressions.Length; queryIndex++)
{
var input = expressions[queryIndex];
var converted = convertedExpressions[queryIndex];
if (input == converted)
{
// Nothing to do.
var originalValueSlot = queries[queryIndex].OutputColumns[columnIndex].ValueSlot;
outputs[queryIndex].Add(originalValueSlot);
}
else
{
computations[queryIndex] ??= new List<BoundComputedValue>();
var computedValueSlot = ValueSlotFactory.CreateTemporary(converted.Type);
var computedValue = new BoundComputedValue(converted, computedValueSlot);
computations[queryIndex].Add(computedValue);
outputs[queryIndex].Add(computedValueSlot);
}
}
}
var result = new List<BoundRelation>();
for (var queryIndex = 0; queryIndex < queries.Length; queryIndex++)
{
var computedValues = computations[queryIndex];
var queryRelation = queries[queryIndex].Relation;
if (computedValues is null)
{
result.Add(queryRelation);
}
else
{
var computeRelation = new BoundComputeRelation(queryRelation, computedValues);
var projectedOutputs = outputs[queryIndex];
var projectRelation = new BoundProjectRelation(computeRelation, projectedOutputs);
result.Add(projectRelation);
}
}
return result.ToImmutableArray();
}
private static ImmutableArray<QueryColumnInstanceSymbol> BindOutputColumns(ImmutableArray<QueryColumnInstanceSymbol> inputColumns, ImmutableArray<ValueSlot> outputValues)
{
var result = new List<QueryColumnInstanceSymbol>(inputColumns.Length);
for (var i = 0; i < inputColumns.Length; i++)
{
if (i >= outputValues.Length)
break;
var queryColumn = inputColumns[i];
var valueSlot = outputValues[i];
var resultColumn = queryColumn.ValueSlot == valueSlot
? queryColumn
: new QueryColumnInstanceSymbol(queryColumn.Name, valueSlot);
result.Add(resultColumn);
}
return result.ToImmutableArray();
}
private BoundQuery BindOrderedQuery(OrderedQuerySyntax node)
{
// Depending on the query the ORDER BY was applied on, the binding rules
// differ.
//
// (1) If the query is applied to a SELECT query, then ORDER BY may have
// more expressions than the underlying SELECT list.
//
// (2) If the query is applied to a query combined with UNION, INTERSECT
// or EXCEPT all expressions must already be present in the underlying
// select list.
//
// We implement both cases differently. The first case is actually handled
// directly when binding the SELECT query because the underlying query has
// to differentiate between computed columns and output columns.
//
// However, both cases eventually call into BindOrderByClause.
var selectQuery = node.GetAppliedSelectQuery();
if (selectQuery is not null)
{
// This is case (1). We bind the select query and pass in ourselves.
var boundQuery = BindSelectQuery(selectQuery, node);
// Since we've potentially skipped a bunch of parenthesized queries
// our regular binder hasn't seen those queries. In order to make
// sure that subsequent requests for GetBoundNode() will return a
// valid instance we must manually bind them to the bound query.
var queries = selectQuery.AncestorsAndSelf().OfType<QuerySyntax>().TakeWhile(n => n != node);
foreach (var queryNodes in queries)
Bind(queryNodes, boundQuery);
return boundQuery;
}
// Alright, this is case (2) where we're applied to some sort of combined
// query.
//
// We will first bind the query in the regular way and then retrieve the
// bound node for the first query. That node has all the information we
// need, in particular the binder that has the table context we need to
// bind the ORDER BY columns.
var query = BindQuery(node.Query);
var firstQuerySyntax = GetFirstSelectQuery(node);
var firstQuery = GetBoundNode<BoundQuery>(firstQuerySyntax);
var firstFromClauseSyntax = firstQuerySyntax.FromClause;
var firstFromClause = firstFromClauseSyntax is null
? null
: GetBoundNode<BoundRelation>(firstFromClauseSyntax);
var binder = firstFromClause is null
? this
: _sharedBinderState.BinderFromBoundNode[firstFromClause];
// Now, when we bind the ORDER BY clause we have to bind the expressions in
// in the context of the first query. This also means that all value slots
// will be local to that query. However, the bound ORDER BY we want to return
// here has to use the value slots that correspond to our input query.
// The correspondence is based on their position. Fortunately, BindOrderByClause
// will perform that mapping for us, but we have to pass in the value slots
// of the first query and the query columns of our input.
var inputQueryColumns = firstQuery.OutputColumns;
var outputQueryColumns = query.OutputColumns;
var orderByClause = binder.BindOrderByClause(node, inputQueryColumns, outputQueryColumns);
var relation = new BoundSortRelation(false, query.Relation, orderByClause.Columns.Select(c => c.ComparedValue).ToImmutableArray());
return new BoundQuery(relation, outputQueryColumns);
}
private BoundQuery BindParenthesizedQuery(ParenthesizedQuerySyntax node)
{
return BindQuery(node.Query);
}
private BoundQuery BindCommonTableExpressionQuery(CommonTableExpressionQuerySyntax node)
{
// Each CTE has access to all tables plus any CTE specified previously.
//
// This means each CTE will produce a new binder that will contain the
// introduced table symbol.
//
// We will also verify that there are no duplicate table names.
var currentBinder = this;
var uniqueTableNames = new HashSet<string>();
foreach (var commonTableExpression in node.CommonTableExpressions)
{
var boundCommonTableExpression = currentBinder.BindCommonTableExpression(commonTableExpression);
var tableSymbol = boundCommonTableExpression.TableSymbol;
if (!uniqueTableNames.Add(tableSymbol.Name))
Diagnostics.ReportCteHasDuplicateTableName(commonTableExpression.Name);
currentBinder = currentBinder.CreateLocalBinder(tableSymbol);
}
return currentBinder.BindQuery(node.Query);
}
private BoundCommonTableExpression BindCommonTableExpression(CommonTableExpressionSyntax commonTableExpression)
{
return Bind(commonTableExpression, BindCommonTableExpressionInternal);
}
private BoundCommonTableExpression BindCommonTableExpressionInternal(CommonTableExpressionSyntax commonTableExpression)
{
var isRecursive = IsRecursive(commonTableExpression);
return isRecursive
? BindCommonTableExpressionRecursive(commonTableExpression)
: BindCommonTableExpressionNonRecursive(commonTableExpression);
}
private BoundCommonTableExpression BindCommonTableExpressionNonRecursive(CommonTableExpressionSyntax commonTableExpression)
{
var name = commonTableExpression.Name.ValueText;
var symbol = new CommonTableExpressionSymbol(name, s =>
{
var binder = CreateLocalBinder(s);
var boundQuery = binder.BindQuery(commonTableExpression.Query);
var columns = binder.BindCommonTableExpressionColumns(commonTableExpression, boundQuery);
return (boundQuery, columns);
});
return new BoundCommonTableExpression(symbol);
}
private BoundCommonTableExpression BindCommonTableExpressionRecursive(CommonTableExpressionSyntax commonTableExpression)
{
// Recursive CTEs must have the following structure:
//
// {One or more anchor members}
// UNION ALL
// {One or more recursive members}
var rootQuery = commonTableExpression.Query as UnionQuerySyntax;
if (rootQuery?.AllKeyword is null)
{
Diagnostics.ReportCteDoesNotHaveUnionAll(commonTableExpression.Name);
if (rootQuery is null)
return BindErrorCommonTableExpression(commonTableExpression);
}
var members = new List<QuerySyntax>();
FlattenUnionQueries(members, rootQuery);
var anchorMembers = new List<QuerySyntax>();
var recursiveMembers = new List<QuerySyntax>();
foreach (var member in members)
{
if (IsRecursive(commonTableExpression, member))
{
recursiveMembers.Add(member);
}
else
{
if (recursiveMembers.Any())
Diagnostics.ReportCteContainsUnexpectedAnchorMember(commonTableExpression.Name);
anchorMembers.Add(member);
}
}
// Ensure we have at least one anchor.
if (anchorMembers.Count == 0)
{
Diagnostics.ReportCteDoesNotHaveAnchorMember(commonTableExpression.Name);
return BindErrorCommonTableExpression(commonTableExpression);
}
var symbol = new CommonTableExpressionSymbol(commonTableExpression.Name.ValueText, s =>
{
var binder = CreateLocalBinder(s);
var boundAnchor = binder.BindCommonTableExpressionAnchorMember(commonTableExpression, anchorMembers);
var columns = binder.BindCommonTableExpressionColumns(commonTableExpression, boundAnchor);
return (boundAnchor, columns);
}, s =>
{
var binder = CreateLocalBinder(s);
return binder.BindCommonTableExpressionRecursiveMembers(commonTableExpression, s, recursiveMembers);
});
return new BoundCommonTableExpression(symbol);
}
private BoundQuery BindCommonTableExpressionAnchorMember(CommonTableExpressionSyntax commonTableExpression, IEnumerable<QuerySyntax> anchorMembers)
{
var diagnosticSpan = commonTableExpression.Name.Span;
var boundAnchorMembers = anchorMembers.Select(BindQuery).ToImmutableArray();
return BindUnionOrUnionAllQuery(diagnosticSpan, true, boundAnchorMembers);
}
private ImmutableArray<BoundQuery> BindCommonTableExpressionRecursiveMembers(CommonTableExpressionSyntax commonTableExpression, CommonTableExpressionSymbol symbol, IEnumerable<QuerySyntax> recursiveMembers)
{
return recursiveMembers.Select(r => BindCommonTableExpressionRecursiveMember(commonTableExpression, symbol, r))
.ToImmutableArray();
}
private BoundQuery BindCommonTableExpressionRecursiveMember(CommonTableExpressionSyntax commonTableExpression, CommonTableExpressionSymbol symbol, QuerySyntax recursiveMember)
{
var boundAnchorQuery = symbol.Anchor;
var name = commonTableExpression.Name;
var diagnosticSpan = name.Span;
var boundRecursiveMember = BindQuery(recursiveMember);
if (boundRecursiveMember.OutputColumns.Length != boundAnchorQuery.OutputColumns.Length)
Diagnostics.ReportDifferentExpressionCountInBinaryQuery(diagnosticSpan);
var columnCount = Math.Min(boundAnchorQuery.OutputColumns.Length, boundRecursiveMember.OutputColumns.Length);
for (var i = 0; i < columnCount; i++)
{
var anchorColumn = boundAnchorQuery.OutputColumns[i];
var recursiveColumn = boundRecursiveMember.OutputColumns[i];
if (anchorColumn.Type != recursiveColumn.Type)
Diagnostics.ReportCteHasTypeMismatchBetweenAnchorAndRecursivePart(diagnosticSpan, anchorColumn.Name, recursiveColumn.Name);
}
var checker = new RecursiveCommonTableExpressionChecker(commonTableExpression, Diagnostics, symbol);
checker.VisitRelation(boundRecursiveMember.Relation);
return boundRecursiveMember;
}
private static BoundCommonTableExpression BindErrorCommonTableExpression(CommonTableExpressionSyntax commonTableExpression)
{
var symbol = new CommonTableExpressionSymbol(
commonTableExpression.Name.ValueText,
_ => (null, ImmutableArray<ColumnSymbol>.Empty),
_ => ImmutableArray<BoundQuery>.Empty
);
return new BoundCommonTableExpression(symbol);
}
private ImmutableArray<ColumnSymbol> BindCommonTableExpressionColumns(CommonTableExpressionSyntax commonTableExpression, BoundQuery boundQuery)
{
// Now let's figure out the column names we want to give result.
var specifiedColumnNames = commonTableExpression.ColumnNameList?.ColumnNames;
var queryColumns = boundQuery.OutputColumns;
if (specifiedColumnNames is null)
{
// If the CTE doesn't have a column list, the query must have names for all columns.
for (var i = 0; i < queryColumns.Length; i++)
{
if (string.IsNullOrEmpty(queryColumns[i].Name))
Diagnostics.ReportNoColumnAliasSpecified(commonTableExpression.Name, i);
}
}
else
{
// If the CTE has a column list we need to make sure the number of
// names matches the number of columns in the underlying query.
var specifiedCount = specifiedColumnNames.Count;
var actualCount = queryColumns.Length;
if (actualCount > specifiedCount)
{
Diagnostics.ReportCteHasMoreColumnsThanSpecified(commonTableExpression.Name);
}
else if (actualCount < specifiedCount)
{
Diagnostics.ReportCteHasFewerColumnsThanSpecified(commonTableExpression.Name);
}
}
// Given the names let's construct the list of columns.
//
// We need to make sure that we produce a sensible result even if the
// syntax is slightly inconsistent:
//
// (1) The number of columns should neither exceed an explicit column list
// nor the number of columns provided by the underlying query.
//
// (2) The column list shouldn't contain any columns without a name.
//
// (3) The column list shouldn't contain duplicate names.
var columnCount = specifiedColumnNames is null
? queryColumns.Length
: Math.Min(specifiedColumnNames.Count, queryColumns.Length);
var columnNames = specifiedColumnNames is null
? queryColumns.Select(c => c.Name)
: specifiedColumnNames.Select(t => t.Identifier.ValueText);
var columns = queryColumns.Take(columnCount)
.Zip(columnNames, (c, n) => new ColumnSymbol(n, c.Type))
.Where(c => !string.IsNullOrEmpty(c.Name))
.ToImmutableArray();
var uniqueColumnNames = new HashSet<string>();
foreach (var column in columns.Where(c => !uniqueColumnNames.Add(c.Name)))
Diagnostics.ReportCteHasDuplicateColumnName(commonTableExpression.Name, column.Name);
return columns;
}
private BoundQuery BindSelectQuery(SelectQuerySyntax node)
{
return BindSelectQuery(node, null);
}
private BoundQuery BindSelectQuery(SelectQuerySyntax node, OrderedQuerySyntax orderedQueryNode)
{
var queryBinder = CreateQueryBinder();
var fromClause = queryBinder.BindFromClause(node.FromClause);
var fromAwareBinder = fromClause is null
? queryBinder
: _sharedBinderState.BinderFromBoundNode[fromClause];
var whereClause = fromAwareBinder.BindWhereClause(node.WhereClause);
var groupByClause = fromAwareBinder.BindGroupByClause(node.GroupByClause);
var havingClause = fromAwareBinder.BindHavingClause(node.HavingClause);
var selectColumns = fromAwareBinder.BindSelectColumns(node.SelectClause.Columns);
var outputColumns = selectColumns.Select(s => s.Column).ToImmutableArray();
var orderByClause = fromAwareBinder.BindOrderByClause(orderedQueryNode, outputColumns, outputColumns);
queryBinder.EnsureAllColumnReferencesAreLegal(node, orderedQueryNode);
var aggregates = (from t in queryBinder.QueryState.ComputedAggregates
let expression = (BoundAggregateExpression)t.Expression
select new BoundAggregatedValue(t.Result, expression.Aggregate, expression.Aggregatable, expression.Argument)).ToImmutableArray();
var groups = groupByClause?.Groups ?? ImmutableArray<BoundComparedValue>.Empty;
var projections = (from t in queryBinder.QueryState.ComputedProjections
select new BoundComputedValue(t.Expression, t.Result)).ToImmutableArray();
var distinctKeyword = node.SelectClause.DistinctAllKeyword;
var isDistinct = distinctKeyword is not null &&
distinctKeyword.Kind == SyntaxKind.DistinctKeyword;
var distinctComparer = isDistinct
? BindDistinctComparers(node.SelectClause.Columns, outputColumns)
: ImmutableArray<IComparer>.Empty;
ImmutableArray<BoundComparedValue> distinctSortValues;
if (!isDistinct || orderByClause is null)
{
distinctSortValues = ImmutableArray<BoundComparedValue>.Empty;
}
else
{
var outputValueSet = new HashSet<ValueSlot>(outputColumns.Select(c => c.ValueSlot));
for (var i = 0; i < orderByClause.Columns.Length; i++)
{
var column = orderedQueryNode.Columns[i];
var boundColumn = orderByClause.Columns[i];
var orderedValue = boundColumn.ComparedValue.ValueSlot;
if (!outputValueSet.Contains(orderedValue))
Diagnostics.ReportOrderByItemsMustBeInSelectListIfDistinctSpecified(column.Span);
}
var orderByValueSet = new HashSet<ValueSlot>(orderByClause.Columns.Select(c => c.ComparedValue.ValueSlot));
distinctSortValues = outputColumns.Select((c, i) => new BoundComparedValue(c.ValueSlot, distinctComparer[i]))
.Where(s => !orderByValueSet.Contains(s.ValueSlot))
.ToImmutableArray();
}
// NOTE: We rely on the fact that the parser already ensured the argument to TOP is a valid integer
// literal. Thus, we can simply ignore the case where topClause.Value.Value cannot be casted
// to an int -- the parser added the diagnostics already. However, we cannot perform a hard
// cast because we also bind input the parser reported errors for.
var topClause = node.SelectClause.TopClause;
var top = topClause?.Value.Value as int?;
var withTies = topClause?.WithKeyword is not null;
if (withTies && orderedQueryNode is null)
Diagnostics.ReportTopWithTiesRequiresOrderBy(topClause.Span);
// Putting it together
var fromRelation = fromClause ?? new BoundConstantRelation();
var whereRelation = whereClause is null
? fromRelation
: new BoundFilterRelation(fromRelation, whereClause);
var computedGroups = queryBinder.QueryState
.ComputedGroupings
.Where(g => g.Expression is not BoundValueSlotExpression)
.Select(g => new BoundComputedValue(g.Expression, g.Result))
.ToImmutableArray();
var groupComputeRelation = !computedGroups.Any()
? whereRelation
: new BoundComputeRelation(whereRelation, computedGroups);
var groupByAndAggregationRelation = !groups.Any() && !aggregates.Any()
? groupComputeRelation
: new BoundGroupByAndAggregationRelation(groupComputeRelation, groups, aggregates);
var havingRelation = havingClause is null
? groupByAndAggregationRelation
: new BoundFilterRelation(groupByAndAggregationRelation, havingClause);
var selectComputeRelation = projections.Length == 0
? havingRelation
: new BoundComputeRelation(havingRelation, projections);
var sortedValues = orderByClause is null
? ImmutableArray<BoundComparedValue>.Empty
: orderByClause.Columns.Select(c => c.ComparedValue).Concat(distinctSortValues).ToImmutableArray();
var sortRelation = sortedValues.IsEmpty
? selectComputeRelation
: new BoundSortRelation(isDistinct, selectComputeRelation, sortedValues);
var tieEntries = top is null || sortedValues.IsEmpty || !withTies
? ImmutableArray<BoundComparedValue>.Empty
: sortedValues;
var topRelation = top is null
? sortRelation
: new BoundTopRelation(sortRelation, top.Value, tieEntries);
var projectRelation = new BoundProjectRelation(topRelation, outputColumns.Select(c => c.ValueSlot).ToImmutableArray());
BoundRelation distinctRelation;
if (!isDistinct || orderByClause is not null)
{
distinctRelation = projectRelation;
}
else
{
var distinctValues = from column in outputColumns
let comparer = BindComparer(distinctKeyword.Span, column.Type, DiagnosticId.InvalidDataTypeInSelectDistinct)
select new BoundComparedValue(column.ValueSlot, comparer);
distinctRelation = new BoundGroupByAndAggregationRelation(projectRelation, distinctValues, Enumerable.Empty<BoundAggregatedValue>());
}
return new BoundQuery(distinctRelation, outputColumns);
}
private IEnumerable<BoundSelectColumn> BindSelectColumns(IEnumerable<SelectColumnSyntax> nodes)
{
var result = new List<BoundSelectColumn>();
foreach (var node in nodes)
{
switch (node.Kind)
{
case SyntaxKind.ExpressionSelectColumn:
var boundColumn = BindExpressionSelectColumn((ExpressionSelectColumnSyntax)node);
result.Add(boundColumn);
break;
case SyntaxKind.WildcardSelectColumn:
var wildcardSelectColumn = BindWildcardSelectColumn((WildcardSelectColumnSyntax)node);
var boundColumns = BindSelectColumns(wildcardSelectColumn);
result.AddRange(boundColumns);
break;
default:
throw ExceptionBuilder.UnexpectedValue(node.Kind);
}
}
QueryState.AccessibleComputedValues.AddRange(QueryState.ComputedProjections);
return result;
}
private BoundSelectColumn BindExpressionSelectColumn(ExpressionSelectColumnSyntax node)
{
return Bind(node, BindExpressionSelectColumnInternal);
}
private BoundSelectColumn BindExpressionSelectColumnInternal(ExpressionSelectColumnSyntax node)
{
var expression = node.Expression;
var boundExpression = BindExpression(expression);
var name = node.Alias is not null
? node.Alias.Identifier.ValueText
: InferColumnName(expression);
if (!TryGetExistingValue(boundExpression, out var valueSlot))
{
valueSlot = ValueSlotFactory.CreateTemporary(boundExpression.Type);
QueryState.ComputedProjections.Add(new BoundComputedValueWithSyntax(expression, boundExpression, valueSlot));
}
var queryColumn = new QueryColumnInstanceSymbol(name, valueSlot);
return new BoundSelectColumn(queryColumn);
}
private BoundWildcardSelectColumn BindWildcardSelectColumn(WildcardSelectColumnSyntax node)
{
return Bind(node, BindWildcardSelectColumnInternal);
}
private BoundWildcardSelectColumn BindWildcardSelectColumnInternal(WildcardSelectColumnSyntax node)
{
return node.TableName is not null
? BindWildcardSelectColumnForTable(node.TableName)
: BindWildcardSelectColumnForAllTables(node.AsteriskToken);
}
private BoundWildcardSelectColumn BindWildcardSelectColumnForTable(SyntaxToken tableName)
{
var symbols = LookupTableInstance(tableName).ToImmutableArray();
if (symbols.Length == 0)
{
Diagnostics.ReportUndeclaredTableInstance(tableName);
return new BoundWildcardSelectColumn(null, Array.Empty<TableColumnInstanceSymbol>());
}
if (symbols.Length > 1)
Diagnostics.ReportAmbiguousName(tableName, symbols);
var tableInstance = symbols[0];
var columnInstances = tableInstance.ColumnInstances;
return new BoundWildcardSelectColumn(tableInstance, columnInstances);
}
private BoundWildcardSelectColumn BindWildcardSelectColumnForAllTables(SyntaxToken asteriskToken)
{
var tableInstances = LookupTableInstances().ToImmutableArray();
if (tableInstances.Length == 0)
{
// Normally, SELECT * is disallowed.
//
// But if the current query is contained in an EXISTS query, that's considered OK.
// Please note that finding our parent doesn't require handling query combinators,
// such as UNION/EXCEPT/INTERSECT, as those are invalid. Same is true for ordered
// queries.
//
// We want, however, skip any parenthesized queries in the process.
var query = asteriskToken.Parent.AncestorsAndSelf()
.OfType<SelectQuerySyntax>()
.First();
var firstRealParent = query.Parent.AncestorsAndSelf()
.SkipWhile(n => n is ParenthesizedQuerySyntax)
.FirstOrDefault();
var isInExists = firstRealParent is ExistsSubselectSyntax;
if (!isInExists)
Diagnostics.ReportMustSpecifyTableToSelectFrom(asteriskToken.Span);
}
var columnInstances = tableInstances.SelectMany(t => t.ColumnInstances).ToImmutableArray();
return new BoundWildcardSelectColumn(null, columnInstances);
}
private static IEnumerable<BoundSelectColumn> BindSelectColumns(BoundWildcardSelectColumn selectColumn)
{
return selectColumn.QueryColumns.Select(c => new BoundSelectColumn(c));
}
private ImmutableArray<IComparer> BindDistinctComparers(IReadOnlyList<SelectColumnSyntax> columns, ImmutableArray<QueryColumnInstanceSymbol> outputColumns)
{
var comparers = new List<IComparer>();
for (var columnIndex = 0; columnIndex < columns.Count; columnIndex++)
{
var column = columns[columnIndex];
var columnType = outputColumns[columnIndex].ValueSlot.Type;
var comparer = BindComparer(column.Span, columnType, DiagnosticId.InvalidDataTypeInSelectDistinct);
comparers.Add(comparer);
}
return comparers.ToImmutableArray();
}
private BoundRelation BindFromClause(FromClauseSyntax node)
{
if (node is null)
return null;
var boundNode = BindFromClauseInternal(node);
var binder = CreateLocalBinder(boundNode.GetDeclaredTableInstances());
_sharedBinderState.BoundNodeFromSyntaxNode.Add(node, boundNode);
_sharedBinderState.BinderFromBoundNode[boundNode] = binder;
// Ensure that there are no duplicates.
var introducedTables = QueryState.IntroducedTables;
var lookup = introducedTables.Values.ToLookup(t => t.ValueText, StringComparer.OrdinalIgnoreCase);
foreach (var name in introducedTables.Values)
{
var matches = lookup[name.ValueText];
if (name.IsQuotedIdentifier())
matches = matches.Where(t => string.Equals(t.ValueText, name.ValueText, StringComparison.Ordinal));
var isDuplicate = matches.Skip(1).Any();
if (isDuplicate)
Diagnostics.ReportDuplicateTableRefInFrom(name);
}
return boundNode;
}
private BoundRelation BindFromClauseInternal(FromClauseSyntax node)
{
BoundRelation lastTableReference = null;
foreach (var tableReference in node.TableReferences)
{
var boundTableReference = BindTableReference(tableReference);
if (lastTableReference is null)
{
lastTableReference = boundTableReference;
}
else
{
lastTableReference = new BoundJoinRelation(BoundJoinType.Inner, lastTableReference, boundTableReference, null, null, null);
}
}
return lastTableReference;
}
private BoundExpression BindWhereClause(WhereClauseSyntax node)
{
if (node is null)
return null;
var binder = CreateWhereClauseBinder();
var predicate = binder.BindExpression(node.Predicate);
if (predicate.Type.IsNonBoolean())
Diagnostics.ReportWhereClauseMustEvaluateToBool(node.Predicate.Span);
return predicate;
}
private BoundGroupByClause BindGroupByClause(GroupByClauseSyntax groupByClause)
{
if (groupByClause is null)
return null;
var groupByBinder = CreateGroupByClauseBinder();
var groups = new List<BoundComparedValue>(groupByClause.Columns.Count);
foreach (var column in groupByClause.Columns)
{
var expression = column.Expression;
var boundExpression = groupByBinder.BindExpression(expression);
var expressionType = boundExpression.Type;
// TODO: We need to ensure every expression references at least one column that is not an outer reference.
var comparer = BindComparer(expression.Span, expressionType, DiagnosticId.InvalidDataTypeInGroupBy);
if (!TryGetExistingValue(boundExpression, out var valueSlot))
valueSlot = ValueSlotFactory.CreateTemporary(expressionType);
// NOTE: Keep this outside the if check because we assume all groups are recorded
// -- independent from whether they are based on existing values or not.
QueryState.ComputedGroupings.Add(new BoundComputedValueWithSyntax(expression, boundExpression, valueSlot));
var group = new BoundComparedValue(valueSlot, comparer);
groups.Add(group);
}
QueryState.AccessibleComputedValues.AddRange(QueryState.ComputedAggregates);
QueryState.AccessibleComputedValues.AddRange(QueryState.ComputedGroupings);
return new BoundGroupByClause(groups.ToImmutableArray());
}
private BoundExpression BindHavingClause(HavingClauseSyntax node)
{
if (node is null)
return null;
var predicate = BindExpression(node.Predicate);
if (predicate.Type.IsNonBoolean())
Diagnostics.ReportHavingClauseMustEvaluateToBool(node.Predicate.Span);
return predicate;
}
private BoundOrderByClause BindOrderByClause(OrderedQuerySyntax node, ImmutableArray<QueryColumnInstanceSymbol> selectorQueryColumns, ImmutableArray<QueryColumnInstanceSymbol> resultQueryColumns)
{
if (node is null)
return null;
// We are called from two places:
//
// (1) An ORDER BY applied to a SELECT query
// (2) An ORDER BY applied to a combined query
//
// In the first case, selectorQueryColumns and resultQueryColumns are the same.
// In the second case, they are different. The selectorQueryColumns represent
// the output columns of the first SELECT query the ORDER BY is applied to.
// The resultQueryColumns represent the output columns of the query the ORDER BY
// is actually applied to (such as a UNION query).
//
// We want to return a bound ORDER BY which has the columns bound against the
// actual query. In order to map from the selectors to the result query columns
// we will use their ordinals.
var selectorsMustBeInInput = selectorQueryColumns != resultQueryColumns;
var getOrdinalFromSelectorValueSlot = selectorQueryColumns.Select((c, i) => (c.ValueSlot, Index: i))
.GroupBy(t => t.ValueSlot, t => t.Index)
.ToDictionary(g => g.Key, g => g.First());
var selectorBinder = CreateLocalBinder(selectorQueryColumns);
var boundColumns = new List<BoundOrderByColumn>();
foreach (var column in node.Columns)
{
var selector = column.ColumnSelector;
var isAscending = column.Modifier is null ||
column.Modifier.Kind == SyntaxKind.AscKeyword;
// Let's bind the selector against the query columns of the first SELECT query
// we are applied to.
var boundSelector = selectorBinder.BindOrderBySelector(selectorQueryColumns, column.ColumnSelector);
// If the expression didn't exist in the query output already, we need to
// compute it. This is only possible if we don't require selectors being
// present already.
if (boundSelector.ComputedValue is not null && !selectorsMustBeInInput)
QueryState.ComputedProjections.Add(boundSelector.ComputedValue.Value);
// We need to find the corresponding result query column for the selector.
// Please note that it might not exist and this is in fact valid. For example,
// This query is perfectly valid:
//
// SELECT e.FirstName, e.LastName
// FROM Employees e
// ORDER BY e.FirstName + ' ' + e.LastName
//
// However, if the query we are applied to is a combined query, it must exist
// in the input.
if (!getOrdinalFromSelectorValueSlot.TryGetValue(boundSelector.ValueSlot, out var columnOrdinal))
{
columnOrdinal = -1;
if (selectorsMustBeInInput)
Diagnostics.ReportOrderByItemsMustBeInSelectListIfUnionSpecified(selector.Span);
}
var queryColumn = columnOrdinal >= 0
? resultQueryColumns[columnOrdinal]
: null;
var valueSlot = queryColumn is not null
? queryColumn.ValueSlot
: boundSelector.ValueSlot;
// Almost there. Now the only thing left for us to do is getting
// the associated comparer.
var baseComparer = BindComparer(selector.Span, valueSlot.Type, DiagnosticId.InvalidDataTypeInOrderBy);
var comparer = isAscending || baseComparer is null
? baseComparer
: new NegatedComparer(baseComparer);
var sortedValue = new BoundComparedValue(valueSlot, comparer);
var boundColumn = new BoundOrderByColumn(queryColumn, sortedValue);
Bind(column, boundColumn);
boundColumns.Add(boundColumn);
}
return new BoundOrderByClause(boundColumns);
}
private BoundOrderBySelector BindOrderBySelector(ImmutableArray<QueryColumnInstanceSymbol> queryColumns, ExpressionSyntax selector)
{
// Although ORDER BY can contain arbitrary expressions, there are special rules to how those
// expressions relate to the SELECT list of a query:
//
// (1) By position
// If the selector is a literal integer we'll resolve to a query column by position.
//
// (2) By name
// If the selector is a NameExpression we'll try to resolve a SELECT column by name.
//
// (3) By structure
// If the selector matches an expression in the SELECT list, it will bind to it as well.
//
// If none of the above is true, ORDER BY may compute a new expression that will be used for
// ordering the query, but this requires that the query it's applied to is a SELECT query.
// In other words it can't be a query combined with UNION, EXCEPT, or INTERSECT. However,
// we don't have to check for that case, our caller is responsible for doing it.
// Case (1): Check for positional form.
if (selector is LiteralExpressionSyntax { Value: int position })
{
var index = position - 1;
var indexValid = 0 <= index && index < queryColumns.Length;
if (indexValid)
return new BoundOrderBySelector(queryColumns[index].ValueSlot, null);
// Report that the given position isn't valid.
Diagnostics.ReportOrderByColumnPositionIsOutOfRange(selector.Span, position, queryColumns.Length);
// And to avoid cascading errors, we'll fake up an invalid slot.
var errorSlot = ValueSlotFactory.CreateTemporary(TypeFacts.Missing);
return new BoundOrderBySelector(errorSlot, null);
}
// Case (2): Check for query column name.
if (selector is NameExpressionSyntax selectorAsName)
{
var columnSymbols = LookupQueryColumn(selectorAsName.Name).ToImmutableArray();
if (columnSymbols.Length > 0)
{
if (columnSymbols.Length > 1)
Diagnostics.ReportAmbiguousColumnInstance(selectorAsName.Name, columnSymbols);
var queryColumn = columnSymbols[0];
// Since this name isn't bound as a regular expression we simple fake this one up.
// This ensures that this name appears to be bound like any other expression.
Bind(selectorAsName, new BoundColumnExpression(queryColumn));
return new BoundOrderBySelector(queryColumn.ValueSlot, null);
}
}
// Case (3): Bind regular expression.
var boundSelector = BindExpression(selector);
if (boundSelector is BoundLiteralExpression)
Diagnostics.ReportConstantExpressionInOrderBy(selector.Span);
if (TryGetExistingValue(boundSelector, out var valueSlot))
return new BoundOrderBySelector(valueSlot, null);
valueSlot = ValueSlotFactory.CreateTemporary(boundSelector.Type);
var computedValue = new BoundComputedValueWithSyntax(selector, boundSelector, valueSlot);
return new BoundOrderBySelector(valueSlot, computedValue);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using AutoMapper;
using Examine;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using Umbraco.Web.Models.ContentEditing;
namespace Umbraco.Web.Search
{
internal class UmbracoTreeSearcher
{
/// <summary>
/// Searches for results based on the entity type
/// </summary>
/// <param name="umbracoHelper"></param>
/// <param name="query"></param>
/// <param name="entityType"></param>
/// <param name="totalFound"></param>
/// <param name="searchFrom">
/// A starting point for the search, generally a node id, but for members this is a member type alias
/// </param>
/// <param name="pageSize"></param>
/// <param name="pageIndex"></param>
/// <returns></returns>
public IEnumerable<SearchResultItem> ExamineSearch(
UmbracoHelper umbracoHelper,
string query,
UmbracoEntityTypes entityType,
int pageSize,
long pageIndex, out long totalFound, string searchFrom = null)
{
var sb = new StringBuilder();
string type;
var searcher = Constants.Examine.InternalSearcher;
var fields = new[] { "id", "__NodeId" };
var umbracoContext = umbracoHelper.UmbracoContext;
var appContext = umbracoContext.Application;
//TODO: WE should really just allow passing in a lucene raw query
switch (entityType)
{
case UmbracoEntityTypes.Member:
searcher = Constants.Examine.InternalMemberSearcher;
type = "member";
fields = new[] { "id", "__NodeId", "email", "loginName" };
if (searchFrom != null && searchFrom != Constants.Conventions.MemberTypes.AllMembersListId && searchFrom.Trim() != "-1")
{
sb.Append("+__NodeTypeAlias:");
sb.Append(searchFrom);
sb.Append(" ");
}
break;
case UmbracoEntityTypes.Media:
type = "media";
var allMediaStartNodes = umbracoContext.Security.CurrentUser.CalculateMediaStartNodeIds(appContext.Services.EntityService);
AppendPath(sb, UmbracoObjectTypes.Media, allMediaStartNodes, searchFrom, appContext.Services.EntityService);
break;
case UmbracoEntityTypes.Document:
type = "content";
var allContentStartNodes = umbracoContext.Security.CurrentUser.CalculateContentStartNodeIds(appContext.Services.EntityService);
AppendPath(sb, UmbracoObjectTypes.Document, allContentStartNodes, searchFrom, appContext.Services.EntityService);
break;
default:
throw new NotSupportedException("The " + typeof(UmbracoTreeSearcher) + " currently does not support searching against object type " + entityType);
}
var internalSearcher = ExamineManager.Instance.SearchProviderCollection[searcher];
//build a lucene query:
// the __nodeName will be boosted 10x without wildcards
// then __nodeName will be matched normally with wildcards
// the rest will be normal without wildcards
//check if text is surrounded by single or double quotes, if so, then exact match
var surroundedByQuotes = Regex.IsMatch(query, "^\".*?\"$")
|| Regex.IsMatch(query, "^\'.*?\'$");
if (surroundedByQuotes)
{
//strip quotes, escape string, the replace again
query = query.Trim(new[] { '\"', '\'' });
query = Lucene.Net.QueryParsers.QueryParser.Escape(query);
//nothing to search
if (searchFrom.IsNullOrWhiteSpace() && query.IsNullOrWhiteSpace())
{
totalFound = 0;
return new List<SearchResultItem>();
}
//update the query with the query term
if (query.IsNullOrWhiteSpace() == false)
{
//add back the surrounding quotes
query = string.Format("{0}{1}{0}", "\"", query);
//node name exactly boost x 10
sb.Append("+(__nodeName: (");
sb.Append(query.ToLower());
sb.Append(")^10.0 ");
foreach (var f in fields)
{
//additional fields normally
sb.Append(f);
sb.Append(": (");
sb.Append(query);
sb.Append(") ");
}
sb.Append(") ");
}
}
else
{
var trimmed = query.Trim(new[] { '\"', '\'' });
//nothing to search
if (searchFrom.IsNullOrWhiteSpace() && trimmed.IsNullOrWhiteSpace())
{
totalFound = 0;
return new List<SearchResultItem>();
}
//update the query with the query term
if (trimmed.IsNullOrWhiteSpace() == false)
{
query = Lucene.Net.QueryParsers.QueryParser.Escape(query);
var querywords = query.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
//node name exactly boost x 10
sb.Append("+(__nodeName:");
sb.Append("\"");
sb.Append(query.ToLower());
sb.Append("\"");
sb.Append("^10.0 ");
//node name normally with wildcards
sb.Append(" __nodeName:");
sb.Append("(");
foreach (var w in querywords)
{
sb.Append(w.ToLower());
sb.Append("* ");
}
sb.Append(") ");
foreach (var f in fields)
{
//additional fields normally
sb.Append(f);
sb.Append(":");
sb.Append("(");
foreach (var w in querywords)
{
sb.Append(w.ToLower());
sb.Append("* ");
}
sb.Append(")");
sb.Append(" ");
}
sb.Append(") ");
}
}
//must match index type
sb.Append("+__IndexType:");
sb.Append(type);
var raw = internalSearcher.CreateSearchCriteria().RawQuery(sb.ToString());
var result = internalSearcher
//only return the number of items specified to read up to the amount of records to fill from 0 -> the number of items on the page requested
.Search(raw, Convert.ToInt32(pageSize * (pageIndex + 1)));
totalFound = result.TotalItemCount;
var pagedResult = result.Skip(Convert.ToInt32(pageIndex));
switch (entityType)
{
case UmbracoEntityTypes.Member:
return MemberFromSearchResults(pagedResult.ToArray());
case UmbracoEntityTypes.Media:
return MediaFromSearchResults(pagedResult);
case UmbracoEntityTypes.Document:
return ContentFromSearchResults(umbracoHelper, pagedResult);
default:
throw new NotSupportedException("The " + typeof(UmbracoTreeSearcher) + " currently does not support searching against object type " + entityType);
}
}
private void AppendPath(StringBuilder sb, UmbracoObjectTypes objectType, int[] startNodeIds, string searchFrom, IEntityService entityService)
{
if (sb == null) throw new ArgumentNullException("sb");
if (entityService == null) throw new ArgumentNullException("entityService");
int searchFromId;
var entityPath = int.TryParse(searchFrom, out searchFromId) && searchFromId > 0
? entityService.GetAllPaths(objectType, searchFromId).FirstOrDefault()
: null;
if (entityPath != null)
{
// find... only what's underneath
sb.Append("+__Path:");
AppendPath(sb, entityPath.Path, false);
sb.Append(" ");
}
else if (startNodeIds.Length == 0)
{
// make sure we don't find anything
sb.Append("+__Path:none ");
}
else if (startNodeIds.Contains(-1) == false) // -1 = no restriction
{
var entityPaths = entityService.GetAllPaths(objectType, startNodeIds);
// for each start node, find the start node, and what's underneath
// +__Path:(-1*,1234 -1*,1234,* -1*,5678 -1*,5678,* ...)
sb.Append("+__Path:(");
var first = true;
foreach (var ep in entityPaths)
{
if (first)
first = false;
else
sb.Append(" ");
AppendPath(sb, ep.Path, true);
}
sb.Append(") ");
}
}
private void AppendPath(StringBuilder sb, string path, bool includeThisNode)
{
path = path.Replace("-", "\\-").Replace(",", "\\,");
if (includeThisNode)
{
sb.Append(path);
sb.Append(" ");
}
sb.Append(path);
sb.Append("\\,*");
}
/// <summary>
/// Returns a collection of entities for media based on search results
/// </summary>
/// <param name="results"></param>
/// <returns></returns>
private IEnumerable<SearchResultItem> MemberFromSearchResults(SearchResult[] results)
{
var mapped = Mapper.Map<IEnumerable<SearchResultItem>>(results).ToArray();
//add additional data
foreach (var m in mapped)
{
//if no icon could be mapped, it will be set to document, so change it to picture
if (m.Icon == "icon-document")
{
m.Icon = "icon-user";
}
var searchResult = results.First(x => x.Id.ToInvariantString() == m.Id.ToString());
if (searchResult.Fields.ContainsKey("email") && searchResult.Fields["email"] != null)
{
m.AdditionalData["Email"] = results.First(x => x.Id.ToInvariantString() == m.Id.ToString()).Fields["email"];
}
if (searchResult.Fields.ContainsKey("__key") && searchResult.Fields["__key"] != null)
{
Guid key;
if (Guid.TryParse(searchResult.Fields["__key"], out key))
{
m.Key = key;
}
}
}
return mapped;
}
/// <summary>
/// Returns a collection of entities for media based on search results
/// </summary>
/// <param name="results"></param>
/// <returns></returns>
private IEnumerable<SearchResultItem> MediaFromSearchResults(IEnumerable<SearchResult> results)
{
var mapped = Mapper.Map<IEnumerable<SearchResultItem>>(results).ToArray();
//add additional data
foreach (var m in mapped)
{
//if no icon could be mapped, it will be set to document, so change it to picture
if (m.Icon == "icon-document")
{
m.Icon = "icon-picture";
}
}
return mapped;
}
/// <summary>
/// Returns a collection of entities for content based on search results
/// </summary>
/// <param name="umbracoHelper"></param>
/// <param name="results"></param>
/// <returns></returns>
private IEnumerable<SearchResultItem> ContentFromSearchResults(UmbracoHelper umbracoHelper, IEnumerable<SearchResult> results)
{
var mapped = Mapper.Map<IEnumerable<SearchResultItem>>(results).ToArray();
//add additional data
foreach (var m in mapped)
{
var intId = m.Id.TryConvertTo<int>();
if (intId.Success)
{
m.AdditionalData["Url"] = umbracoHelper.NiceUrl(intId.Result);
}
}
return mapped;
}
}
}
| |
/*
* 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 DotNetOpenMail;
using DotNetOpenMail.SmtpAuth;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
namespace OpenSim.Region.CoreModules.Scripting.EmailModules
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EmailModule")]
public class EmailModule : ISharedRegionModule, IEmailModule
{
//
// Log
//
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//
// Module vars
//
private IConfigSource m_Config;
private string m_HostName = string.Empty;
//private string m_RegionName = string.Empty;
private string SMTP_SERVER_HOSTNAME = string.Empty;
private int SMTP_SERVER_PORT = 25;
private string SMTP_SERVER_LOGIN = string.Empty;
private string SMTP_SERVER_PASSWORD = string.Empty;
class EmailQueue
{
public DateTime m_LastCall;
public ThreadedClasses.RwLockedList<Email> m_Queue = new ThreadedClasses.RwLockedList<Email>();
public EmailQueue()
{
m_LastCall = DateTime.Now;
}
}
private int m_MaxQueueSize = 50; // maximum size of an object mail queue
private ThreadedClasses.RwLockedDictionary<UUID, EmailQueue> m_MailQueues = new ThreadedClasses.RwLockedDictionary<UUID, EmailQueue>();
private TimeSpan m_QueueTimeout = new TimeSpan(2, 0, 0); // 2 hours without llGetNextEmail drops the queue
private string m_InterObjectHostname = "lsl.opensim.local";
private int m_MaxEmailSize = 4096; // largest email allowed by default, as per lsl docs.
// Scenes by Region Handle
private ThreadedClasses.RwLockedDictionary<ulong, Scene> m_Scenes =
new ThreadedClasses.RwLockedDictionary<ulong, Scene>();
private bool m_Enabled = false;
#region ISharedRegionModule
public void Initialise(IConfigSource config)
{
m_Config = config;
IConfig SMTPConfig;
//FIXME: RegionName is correct??
//m_RegionName = scene.RegionInfo.RegionName;
IConfig startupConfig = m_Config.Configs["Startup"];
m_Enabled = (startupConfig.GetString("emailmodule", "DefaultEmailModule") == "DefaultEmailModule");
//Load SMTP SERVER config
try
{
if ((SMTPConfig = m_Config.Configs["SMTP"]) == null)
{
m_Enabled = false;
return;
}
if (!SMTPConfig.GetBoolean("enabled", false))
{
m_Enabled = false;
return;
}
m_HostName = SMTPConfig.GetString("host_domain_header_from", m_HostName);
m_InterObjectHostname = SMTPConfig.GetString("internal_object_host", m_InterObjectHostname);
SMTP_SERVER_HOSTNAME = SMTPConfig.GetString("SMTP_SERVER_HOSTNAME", SMTP_SERVER_HOSTNAME);
SMTP_SERVER_PORT = SMTPConfig.GetInt("SMTP_SERVER_PORT", SMTP_SERVER_PORT);
SMTP_SERVER_LOGIN = SMTPConfig.GetString("SMTP_SERVER_LOGIN", SMTP_SERVER_LOGIN);
SMTP_SERVER_PASSWORD = SMTPConfig.GetString("SMTP_SERVER_PASSWORD", SMTP_SERVER_PASSWORD);
m_MaxEmailSize = SMTPConfig.GetInt("email_max_size", m_MaxEmailSize);
}
catch (Exception e)
{
m_log.Error("[EMAIL] DefaultEmailModule not configured: " + e.Message);
m_Enabled = false;
return;
}
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
// It's a go!
// Claim the interface slot
scene.RegisterModuleInterface<IEmailModule>(this);
// Add to scene list
m_Scenes.Add(scene.RegionInfo.RegionHandle, scene);
m_log.Info("[EMAIL] Activated DefaultEmailModule");
}
public void RemoveRegion(Scene scene)
{
m_Scenes.Remove(scene.RegionInfo.RegionHandle);
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "DefaultEmailModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void RegionLoaded(Scene scene)
{
}
#endregion
public void InsertEmail(UUID to, Email email)
{
// It's tempting to create the queue here. Don't; objects which have
// not yet called GetNextEmail should have no queue, and emails to them
// should be silently dropped.
EmailQueue val;
if(m_MailQueues.TryGetValue(to, out val))
{
if (val.m_Queue.Count >= m_MaxQueueSize)
{
// fail silently
return;
}
val.m_LastCall = DateTime.Now;
val.m_Queue.Add(email);
}
}
private bool IsLocal(UUID objectID)
{
string unused;
return (null != findPrim(objectID, out unused));
}
private SceneObjectPart findPrim(UUID objectID, out string ObjectRegionName)
{
try
{
m_Scenes.ForEach(delegate(Scene s)
{
SceneObjectPart part = s.GetSceneObjectPart(objectID);
if (part != null)
{
string _ObjectRegionName = s.RegionInfo.RegionName;
uint localX = s.RegionInfo.WorldLocX;
uint localY = s.RegionInfo.WorldLocY;
_ObjectRegionName = _ObjectRegionName + " (" + localX + ", " + localY + ")";
throw new ThreadedClasses.ReturnValueException<KeyValuePair<string, SceneObjectPart>>(new KeyValuePair<string, SceneObjectPart>(_ObjectRegionName, part));
}
});
}
catch (ThreadedClasses.ReturnValueException<KeyValuePair<string, SceneObjectPart>> e)
{
ObjectRegionName = e.Value.Key;
return e.Value.Value;
}
ObjectRegionName = string.Empty;
return null;
}
private void resolveNamePositionRegionName(UUID objectID, out string ObjectName, out string ObjectAbsolutePosition, out string ObjectRegionName)
{
string m_ObjectRegionName;
int objectLocX;
int objectLocY;
int objectLocZ;
SceneObjectPart part = findPrim(objectID, out m_ObjectRegionName);
if (part != null)
{
objectLocX = (int)part.AbsolutePosition.X;
objectLocY = (int)part.AbsolutePosition.Y;
objectLocZ = (int)part.AbsolutePosition.Z;
ObjectAbsolutePosition = "(" + objectLocX + ", " + objectLocY + ", " + objectLocZ + ")";
ObjectName = part.Name;
ObjectRegionName = m_ObjectRegionName;
return;
}
objectLocX = (int)part.AbsolutePosition.X;
objectLocY = (int)part.AbsolutePosition.Y;
objectLocZ = (int)part.AbsolutePosition.Z;
ObjectAbsolutePosition = "(" + objectLocX + ", " + objectLocY + ", " + objectLocZ + ")";
ObjectName = part.Name;
ObjectRegionName = m_ObjectRegionName;
return;
}
/// <summary>
/// SendMail function utilized by llEMail
/// </summary>
/// <param name="objectID"></param>
/// <param name="address"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
public void SendEmail(UUID objectID, string address, string subject, string body)
{
//Check if address is empty
if (address == string.Empty)
return;
//FIXED:Check the email is correct form in REGEX
string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
+ @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
+ @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
+ @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
+ @"[a-zA-Z]{2,}))$";
Regex EMailreStrict = new Regex(EMailpatternStrict);
bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
if (!isEMailStrictMatch)
{
m_log.Error("[EMAIL] REGEX Problem in EMail Address: "+address);
return;
}
if ((subject.Length + body.Length) > m_MaxEmailSize)
{
m_log.Error("[EMAIL] subject + body larger than limit of " + m_MaxEmailSize + " bytes");
return;
}
string LastObjectName = string.Empty;
string LastObjectPosition = string.Empty;
string LastObjectRegionName = string.Empty;
resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
if (!address.EndsWith(m_InterObjectHostname))
{
// regular email, send it out
try
{
//Creation EmailMessage
EmailMessage emailMessage = new EmailMessage();
//From
emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName);
//To - Only One
emailMessage.AddToAddress(new EmailAddress(address));
//Subject
emailMessage.Subject = subject;
//TEXT Body
resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
emailMessage.BodyText = "Object-Name: " + LastObjectName +
"\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
LastObjectPosition + "\n\n" + body;
//Config SMTP Server
//Set SMTP SERVER config
SmtpServer smtpServer=new SmtpServer(SMTP_SERVER_HOSTNAME,SMTP_SERVER_PORT);
// Add authentication only when requested
//
if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
{
//Authentication
smtpServer.SmtpAuthToken=new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
}
//Send Email Message
emailMessage.Send(smtpServer);
//Log
m_log.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName);
}
catch (Exception e)
{
m_log.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
}
}
else
{
// inter object email, keep it in the family
Email email = new Email();
email.time = ((int)((DateTime.UtcNow - new DateTime(1970,1,1,0,0,0)).TotalSeconds)).ToString();
email.subject = subject;
email.sender = objectID.ToString() + "@" + m_InterObjectHostname;
email.message = "Object-Name: " + LastObjectName +
"\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
LastObjectPosition + "\n\n" + body;
string guid = address.Substring(0, address.IndexOf("@"));
UUID toID = new UUID(guid);
if (IsLocal(toID)) // TODO FIX check to see if it is local
{
// object in this region
InsertEmail(toID, email);
}
else
{
// object on another region
// TODO FIX
}
}
}
/// <summary>
///
/// </summary>
/// <param name="objectID"></param>
/// <param name="sender"></param>
/// <param name="subject"></param>
/// <returns></returns>
public Email GetNextEmail(UUID objectID, string sender, string subject)
{
EmailQueue queue = m_MailQueues.GetOrAddIfNotExists(objectID, delegate() { return new EmailQueue(); });
queue.m_LastCall = DateTime.Now;
// Hopefully this isn't too time consuming. If it is, we can always push it into a worker thread.
DateTime now = DateTime.Now;
foreach (UUID uuid in m_MailQueues.Keys)
{
if (m_MailQueues.TryGetValue(uuid, out queue))
{
if ((now - queue.m_LastCall) > m_QueueTimeout)
{
m_MailQueues.Remove(uuid);
}
}
}
queue = m_MailQueues.GetOrAddIfNotExists(objectID, delegate() { return new EmailQueue(); });
return queue.m_Queue.RemoveMatch(delegate(Email m)
{
return ((sender == null || sender.Equals("") || sender.Equals(m.sender)) &&
(subject == null || subject.Equals("") || subject.Equals(m.subject)));
});
}
}
}
| |
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Amazon Software License (the "License").
// You may not use this file except in compliance with the
// License. A copy of the License is located at
//
// http://aws.amazon.com/asl/
//
// or in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, express or implied. See the License
// for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using Amazon.DynamoDBv2.DocumentModel;
using Amazon.DynamoDBv2.Model;
using System.Globalization;
using Amazon.Util;
namespace Amazon.DynamoDBv2.DataModel
{
/// <summary>
/// Interface for converting arbitrary objects to DynamoDB-supported
/// object types.
///
/// Implementing type must be public, instantiable, and should have
/// a zero-parameter constructor.
/// </summary>
public interface IPropertyConverter
{
/// <summary>
/// Convert object to DynamoDBEntry
/// </summary>
/// <param name="value">Object to be deserialized</param>
/// <returns>Object deserialized as DynamoDBEntry</returns>
DynamoDBEntry ToEntry(object value);
/// <summary>
/// Convert DynamoDBEntry to the specified object
/// </summary>
/// <param name="entry">DynamoDBEntry to be serialized</param>
/// <returns>Serialized object</returns>
object FromEntry(DynamoDBEntry entry);
}
/// <summary>
/// Configuration object for setting options on the DynamoDBContext.
/// and individual operations.
/// </summary>
public class DynamoDBContextConfig
{
public DynamoDBContextConfig()
{
TableNamePrefix = AWSConfigsDynamoDB.Context.TableNamePrefix;
Conversion = DynamoDBEntryConversion.CurrentConversion;
}
/// <summary>
/// Property that directs DynamoDBContext to use consistent reads.
/// If property is not set, behavior defaults to non-consistent reads.
/// </summary>
public bool? ConsistentRead { get; set; }
/// <summary>
/// Property that directs DynamoDBContext to skip version checks
/// when saving or deleting an object with a version attribute.
/// If property is not set, version checks are performed.
/// </summary>
public bool? SkipVersionCheck { get; set; }
/// <summary>
/// Property that directs DynamoDBContext to prefix all table names
/// with a specific string.
/// If property is null or empty, no prefix is used and default
/// table names are used.
/// </summary>
public string TableNamePrefix { get; set; }
/// <summary>
/// Property that directs DynamoDBContext to ignore null values
/// on attributes during a Save operation.
/// If the property is false (or not set), null values will be
/// interpreted as directives to delete the specific attribute.
/// </summary>
public bool? IgnoreNullValues { get; set; }
/// <summary>
/// Conversion specification which controls how conversion between
/// .NET and DynamoDB types happens.
/// </summary>
public DynamoDBEntryConversion Conversion { get; set; }
}
/// <summary>
/// Configuration object for setting options for individual operations.
/// This will override any settings specified by the DynamoDBContext's DynamoDBContextConfig object.
/// </summary>
public class DynamoDBOperationConfig : DynamoDBContextConfig
{
/// <summary>
/// Property that indicates the table to save an object to overriding the DynamoDBTable attribute
/// declared for the type.
/// </summary>
public string OverrideTableName { get; set; }
/// <summary>
/// Property that indicates a query should traverse the index backward.
/// If the property is false (or not set), traversal shall be forward.
/// </summary>
public bool? BackwardQuery { get; set; }
/// <summary>
/// Property indicating the name of the index to query or scan against.
/// This value is optional if the index name can be inferred from the call.
/// </summary>
public string IndexName { get; set; }
/// <summary>
/// A logical operator to apply to the filter conditions:
/// AND - If all of the conditions evaluate to true, then the entire filter evaluates to true.
/// OR - If at least one of the conditions evaluate to true, then the entire filter evaluates to true.
///
/// Default value is AND.
/// </summary>
public ConditionalOperatorValues ConditionalOperator { get; set; }
/// <summary>
/// Query filter for the Query operation operation. Evaluates the query results and returns only
/// the matching values. If you specify more than one condition, then by default all of the
/// conditions must evaluate to true. To match only some conditions, set ConditionalOperator to Or.
/// Note: Conditions must be against non-key properties.
/// </summary>
public List<ScanCondition> QueryFilter { get; set; }
public DynamoDBOperationConfig()
{
QueryFilter = new List<ScanCondition>();
}
// Checks if the IndexName is set on the config
internal bool IsIndexOperation { get { return !string.IsNullOrEmpty(IndexName); } }
}
/// <summary>
/// Class describing a single scan condition
/// </summary>
public class ScanCondition
{
#region Public properties
/// <summary>
/// Name of the property being tested
/// </summary>
public string PropertyName { get; set; }
/// <summary>
/// Comparison operator
/// </summary>
public ScanOperator Operator { get; set; }
/// <summary>
/// Values being tested against.
///
/// The values should be of the same type as the property.
/// In the cases where the property is a collection, the values
/// should be of the same type as the items in the collection.
/// </summary>
public object[] Values { get; set; }
#endregion
#region Constructor
/// <summary>
/// Initializes a ScanCondition with the target property, the
/// comparison operator and values being tested against.
/// </summary>
/// <param name="propertyName">Name of the property</param>
/// <param name="op">Comparison operator</param>
/// <param name="values">
/// Value(s) being tested against.
///
/// The values should be of the same type as the property.
/// In the cases where the property is a collection, the values
/// should be of the same type as the items in the collection.
/// </param>
public ScanCondition(string propertyName, ScanOperator op, params object[] values)
{
PropertyName = propertyName;
Operator = op;
Values = values;
}
#endregion
}
/// <summary>
/// Class describing a single query condition
/// </summary>
public class QueryCondition
{
#region Public properties
/// <summary>
/// Name of the property being tested
/// </summary>
public string PropertyName { get; set; }
/// <summary>
/// Comparison operator
/// </summary>
public QueryOperator Operator { get; set; }
/// <summary>
/// Values being tested against.
///
/// The values should be of the same type as the property.
/// In the cases where the property is a collection, the values
/// should be of the same type as the items in the collection.
/// </summary>
public object[] Values { get; set; }
#endregion
#region Constructor
/// <summary>
/// Initializes a ScanCondition with the target property, the
/// comparison operator and values being tested against.
/// </summary>
/// <param name="propertyName">Name of the property</param>
/// <param name="op">Comparison operator</param>
/// <param name="values">
/// Value(s) being tested against.
///
/// The values should be of the same type as the property.
/// In the cases where the property is a collection, the values
/// should be of the same type as the items in the collection.
/// </param>
public QueryCondition(string propertyName, QueryOperator op, params object[] values)
{
PropertyName = propertyName;
Operator = op;
Values = values;
}
#endregion
}
internal class DynamoDBFlatConfig
{
public static string DefaultIndexName = string.Empty;
private static DynamoDBOperationConfig _emptyOperationConfig = new DynamoDBOperationConfig
{
ConsistentRead = null,
OverrideTableName = null,
SkipVersionCheck = null,
TableNamePrefix = null,
IgnoreNullValues = null,
BackwardQuery = null,
IndexName = null,
ConditionalOperator = ConditionalOperatorValues.And,
Conversion = null
};
private static DynamoDBContextConfig _emptyContextConfig = new DynamoDBContextConfig
{
ConsistentRead = null,
SkipVersionCheck = null,
TableNamePrefix = null,
IgnoreNullValues = null,
Conversion = null
};
public DynamoDBFlatConfig(DynamoDBOperationConfig operationConfig, DynamoDBContextConfig contextConfig)
{
if (operationConfig == null)
operationConfig = _emptyOperationConfig;
if (contextConfig == null)
contextConfig = _emptyContextConfig;
bool consistentRead = operationConfig.ConsistentRead ?? contextConfig.ConsistentRead ?? false;
bool skipVersionCheck = operationConfig.SkipVersionCheck ?? contextConfig.SkipVersionCheck ?? false;
bool ignoreNullValues = operationConfig.IgnoreNullValues ?? contextConfig.IgnoreNullValues ?? false;
string overrideTableName =
!string.IsNullOrEmpty(operationConfig.OverrideTableName) ? operationConfig.OverrideTableName : string.Empty;
string tableNamePrefix =
!string.IsNullOrEmpty(operationConfig.TableNamePrefix) ? operationConfig.TableNamePrefix :
!string.IsNullOrEmpty(contextConfig.TableNamePrefix) ? contextConfig.TableNamePrefix : string.Empty;
bool backwardQuery = operationConfig.BackwardQuery ?? false;
string indexName =
!string.IsNullOrEmpty(operationConfig.IndexName) ? operationConfig.IndexName : DefaultIndexName;
List<ScanCondition> queryFilter = operationConfig.QueryFilter ?? new List<ScanCondition>();
ConditionalOperatorValues conditionalOperator = operationConfig.ConditionalOperator;
DynamoDBEntryConversion conversion = operationConfig.Conversion ?? contextConfig.Conversion ?? DynamoDBEntryConversion.CurrentConversion;
ConsistentRead = consistentRead;
SkipVersionCheck = skipVersionCheck;
IgnoreNullValues = ignoreNullValues;
OverrideTableName = overrideTableName;
TableNamePrefix = tableNamePrefix;
BackwardQuery = backwardQuery;
IndexName = indexName;
QueryFilter = queryFilter;
ConditionalOperator = conditionalOperator;
Conversion = conversion;
State = new OperationState();
}
/// <summary>
/// Property that directs DynamoDBContext to use consistent reads.
/// If property is not set, behavior defaults to non-consistent reads.
/// </summary>
public bool? ConsistentRead { get; set; }
/// <summary>
/// Property that directs DynamoDBContext to skip version checks
/// when saving or deleting an object with a version attribute.
/// If property is not set, version checks are performed.
/// </summary>
public bool? SkipVersionCheck { get; set; }
/// <summary>
/// Property that directs DynamoDBContext to prefix all table names
/// with a specific string.
/// If property is null or empty, no prefix is used and default
/// table names are used.
/// </summary>
public string TableNamePrefix { get; set; }
/// <summary>
/// Property that directs DynamoDBContext to ignore null values
/// on attributes during a Save operation.
/// If the property is false (or not set), null values will be
/// interpreted as directives to delete the specific attribute.
/// </summary>
public bool? IgnoreNullValues { get; set; }
/// <summary>
/// Property that indicates the table to save an object to overriding the DynamoDBTable attribute
/// declared for the type.
/// </summary>
public string OverrideTableName { get; set; }
/// <summary>
/// Property that indicates a query should traverse the index backward.
/// If the property is false (or not set), traversal shall be forward.
/// </summary>
public bool? BackwardQuery { get; set; }
/// <summary>
/// Property indicating the name of the index to query or scan against.
/// This value is optional if the index name can be inferred from the call.
/// </summary>
public string IndexName { get; set; }
/// <summary>
/// A logical operator to apply to the filter conditions:
/// AND - If all of the conditions evaluate to true, then the entire filter evaluates to true.
/// OR - If at least one of the conditions evaluate to true, then the entire filter evaluates to true.
///
/// Default value is AND.
/// </summary>
public ConditionalOperatorValues ConditionalOperator { get; set; }
/// <summary>
/// Query filter for the Query operation operation. Evaluates the query results and returns only
/// the matching values. If you specify more than one condition, then by default all of the
/// conditions must evaluate to true. To match only some conditions, set ConditionalOperator to Or.
/// Note: Conditions must be against non-key properties.
/// </summary>
public List<ScanCondition> QueryFilter { get; set; }
/// <summary>
/// Conversion specification which controls how conversion between
/// .NET and DynamoDB types happens.
/// </summary>
public DynamoDBEntryConversion Conversion { get; set; }
// Checks if the IndexName is set on the config
internal bool IsIndexOperation { get { return !string.IsNullOrEmpty(IndexName); } }
// State of the operation using this config
internal OperationState State { get; private set; }
public class OperationState
{
private CircularReferenceTracking referenceTracking;
public OperationState()
{
referenceTracking = new CircularReferenceTracking();
}
public CircularReferenceTracking.Tracker Track(object target)
{
return referenceTracking.Track(target);
}
}
}
}
| |
using System.Linq;
using NUnit.Framework;
namespace Trie
{
[TestFixture]
public class OptimizedTrieTests
{
[Test]
public void WriteLastItemWorks()
{
var storage = new byte[13];
var undertest = new OptimizedTrie(storage);
var result = undertest.TryWrite("test", 123);
Assert.That(result, "expected success");
CollectionAssert.AreEqual(new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
}, storage);
}
[Test]
public void WriteLargeItemFails()
{
var storage = new byte[13];
var undertest = new OptimizedTrie(storage);
var result = undertest.TryWrite("test2", 123); //1+5+8 bytes
Assert.IsFalse(result, "expected failure");
CollectionAssert.AreEqual(new byte[13], storage);
}
[Test]
public void WriteFirstItemWorks()
{
var storage = new byte[18];
var undertest = new OptimizedTrie(storage);
var result = undertest.TryWrite("test", 123);
Assert.That(result, "expected success");
CollectionAssert.AreEqual(new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
0,0,0,0,
0
}, storage);
}
[Test]
public void WriteSecondItemWorks()
{
var storage = new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
0,
0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,
0,
};
var undertest = new OptimizedTrie(storage);
var result = undertest.TryWrite("Work", 99);
Assert.That(result, "expected success");
CollectionAssert.AreEqual(new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
4|1<<7,
(byte)'W',(byte)'o',(byte)'r',(byte)'k',
99,0,0,0,
0,0,0,0,
0,0,
0,
}, storage);
}
[Test]
public void DeleteLastItemWorks()
{
var storage = new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
0, 0,
0, 0, 0, 0,
0, 0,
0,
0, 0, 0, 0,
0, 0, 0, 0,
};
var undertest = new OptimizedTrie(storage);
undertest.Delete("test");
CollectionAssert.AreEqual(new byte[]
{
0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0,
0, 0, 0, 0,
0, 0,
0,
0, 0, 0, 0,
0, 0, 0, 0,
}, storage);
}
[Test]
public void WriteSecondItemWithSameSubstringWorks()
{
var storage = new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
0,0,
0,0,0,0,
0,0,
0,
0,0,0,0,
0,0,0,0
};
var undertest = new OptimizedTrie(storage);
var result = undertest.TryWrite("testing", 99);
Assert.That(result, "expected success");
CollectionAssert.AreEqual(new byte[]
{
4|1<<7|1<<6,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
12,0,
3|1<<7,
(byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
0,0,0,
}, storage);
}
[Test]
public void Delete_last_child_works()
{
var storage = new byte[]
{
4|1<<7|1<<6,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
12,0,
3|1<<7,
(byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
0,0,0,
};
var undertest = new OptimizedTrie(storage);
undertest.Delete("testing");
CollectionAssert.AreEqual(new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
0,0,
0,
0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,
}, storage);
}
[Test]
public void Delete_parent_works()
{
var storage = new byte[]
{
4|1<<7|1<<6,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
12,0,
3|1<<7,
(byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
0,0,0,
};
var undertest = new OptimizedTrie(storage);
undertest.Delete("test");
CollectionAssert.AreEqual(new byte[]
{
7|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t', (byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
0,0,
0,0,0,0,
0,0,
0,
0,0,0,0,
0
}, storage);
}
[Test]
public void WriteSecondItemWithSamePrefixWorks()
{
var storage = new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
0, 0,
0, 0, 0, 0,
0, 0,
0,
0, 0, 0,
0, 0
};
var undertest = new OptimizedTrie(storage);
var result = undertest.TryWrite("team", 99);
Assert.That(result, "expected success");
CollectionAssert.AreEqual(new byte[]
{
2|1<<6,
(byte)'t',(byte)'e',
22, 0,
2|1<<7,
(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
2|1<<7,
(byte)'a',(byte)'m',
99,0,0,0,
0,0,0,0,
}, storage);
}
[Test]
public void WriteSecondItemWithJustSamePrefixWorks()
{
var storage = new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
0, 0,
0, 0, 0, 0,
0, 0,
0,
0, 0, 0
};
var undertest = new OptimizedTrie(storage);
var result = undertest.TryWrite("te", 99);
Assert.That(result, "expected success");
CollectionAssert.AreEqual(new byte[]
{
2|1<<6|1<<7,
(byte)'t',(byte)'e',
99,0,0,0,
0,0,0,0,
11, 0,
2|1<<7,
(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
0,
}, storage);
}
[Test]
public void ReadFirstItemWorks()
{
var undertest = new OptimizedTrie(new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0,
});
long value;
var result = undertest.TryRead("test", out value);
Assert.That(result, "expected success");
Assert.That(value, Is.EqualTo(123));
}
[Test]
public void ReadSecondItemWorks()
{
var undertest = new OptimizedTrie(new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
7|1<<7,
(byte)'W',(byte)'o',(byte)'r',(byte)'k',(byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
});
long value;
var result = undertest.TryRead("Working", out value);
Assert.That(result, "expected success");
Assert.That(value, Is.EqualTo(99));
}
[Test]
public void ReadFirstOfTwoItemsWorks()
{
var undertest = new OptimizedTrie(new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
7|1<<7,
(byte)'W',(byte)'o',(byte)'r',(byte)'k',(byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
});
long value;
var result = undertest.TryRead("test", out value);
Assert.That(result, "expected success");
Assert.That(value, Is.EqualTo(123));
}
[Test]
public void ReadFirstOfSubItemsWorks()
{
var undertest = new OptimizedTrie(new byte[]
{
4|1<<7|1<<6,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
12,0,
3|1<<7,
(byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
0,0,0,
});
long value;
var result = undertest.TryRead("test", out value);
Assert.That(result, "expected success");
Assert.That(value, Is.EqualTo(123));
}
[Test]
public void ParseWithSubItemsWorks()
{
var undertest = new byte[]
{
4 | 1 << 7 | 1 << 6,
(byte) 't', (byte) 'e', (byte) 's', (byte) 't',
123, 0, 0, 0,
0, 0, 0, 0,
12, 0,
3 | 1 << 7,
(byte) 'i', (byte) 'n', (byte) 'g',
99, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0,
};
int i = 0;
var result = OptimizedTrie.TrieItem.Read(undertest, ref i);
Assert.That(result, Is.Not.Null);
Assert.That(result.Key.ToStringUtf8(), Is.EqualTo("test"));
Assert.That(result.HasChildren);
Assert.That(result.HasValue);
Assert.That(result.Value, Is.EqualTo(123));
Assert.That(result.PayloadSize, Is.EqualTo(12));
Assert.That(result.ItemSize, Is.EqualTo(13+2+12));
var child = result.Children.Single();
Assert.That(child, Is.Not.Null);
Assert.That(child.Key.ToStringUtf8(), Is.EqualTo("ing"));
Assert.That(child.HasChildren, Is.False);
Assert.That(child.HasValue);
Assert.That(child.Value, Is.EqualTo(99));
Assert.That(child.PayloadSize, Is.EqualTo(0));
}
[Test]
public void ParseWithValuelessParentItemsWorks()
{
var undertest = new byte[]
{
4|1<<6,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
1+3+8,0,
3|1<<7,
(byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
};
int i = 0;
var result = OptimizedTrie.TrieItem.Read(undertest, ref i);
Assert.That(result, Is.Not.Null);
Assert.That(result.Key.ToStringUtf8(), Is.EqualTo("test"));
Assert.That(result.HasChildren);
Assert.That(result.HasValue, Is.False);
Assert.That(result.PayloadSize, Is.EqualTo(12));
Assert.That(result.ItemSize, Is.EqualTo(1 + 4 + 2 + 12));
var child = result.Children.Single();
Assert.That(child, Is.Not.Null);
Assert.That(child.Key.ToStringUtf8(), Is.EqualTo("ing"));
Assert.That(child.HasChildren, Is.False);
Assert.That(child.HasValue);
Assert.That(child.Value, Is.EqualTo(99));
Assert.That(child.PayloadSize, Is.EqualTo(0));
}
[Test]
public void ReadSecondOfSubItemsWorks()
{
var undertest = new OptimizedTrie(new byte[]
{
4|1<<6|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
1 +3+8,0,
3|1<<7,
(byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
});
long value;
var result = undertest.TryRead("testing", out value);
Assert.That(result, "expected success");
Assert.That(value, Is.EqualTo(99));
}
[Test]
public void ReadSecondOfSubItems_with_empty_parentWorks()
{
var undertest = new OptimizedTrie(new byte[]
{
4|1<<6,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
1+3+8+1+2+8,0,
3|1<<7,
(byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
2|1<<7,
(byte)'e',(byte)'r',
66,0,0,0,
0,0,0,0,
});
long value;
var result = undertest.TryRead("tester", out value);
Assert.That(result, "expected success");
Assert.That(value, Is.EqualTo(66));
}
[Test]
public void Read_item_that_only_exists_as_subitem_fails()
{
var undertest = new OptimizedTrie(new byte[]
{
4|1<<6,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
1+3+8+1+2+8,0,
3|1<<7,
(byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
2|1<<7,
(byte)'e',(byte)'r',
66,0,0,0,
0,0,0,0,
});
long value;
var result = undertest.TryRead("ing", out value);
Assert.IsFalse(result, "expected failure");
}
[Test]
public void ReadNonExistingKeyFails()
{
var undertest = new OptimizedTrie(new byte[]
{
4|1<<6,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
12,0,
3|1<<7,
(byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
2|1<<7,
(byte)'e',(byte)'r',
66,0,0,0,
0,0,0,0,
});
long value;
var result = undertest.TryRead("does not exist", out value);
Assert.IsFalse(result, "expected failure");
}
[Test]
public void ReadNonExistingKey_but_existing_prefix_does_Fails()
{
var undertest = new OptimizedTrie(new byte[]
{
4|1<<6,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
12,0,
3|1<<7,
(byte)'i',(byte)'n',(byte)'g',
99,0,0,0,
0,0,0,0,
2|1<<7,
(byte)'e',(byte)'r',
66,0,0,0,
0,0,0,0,
});
long value;
var result = undertest.TryRead("test does not exist", out value);
Assert.IsFalse(result, "expected failure");
}
[Test]
public void OverwriteKeyWorks()
{
var storage = new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
4|1<<7,
(byte)'W',(byte)'o',(byte)'r',(byte)'k',
99,0,0,0,
0,0,0,0,
};
var undertest = new OptimizedTrie(storage);
var result = undertest.TryWrite("Work", 0xabcdef01);
Assert.IsTrue(result, "expected success");
CollectionAssert.AreEqual(new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
4|1<<7,
(byte)'W',(byte)'o',(byte)'r',(byte)'k',
0x01,0xef,0xcd,0xab,
0,0,0,0,
}, storage);
}
[Test]
public void DeleteSecondKeyWorks()
{
var storage = new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
4|1<<7,
(byte)'W',(byte)'o',(byte)'r',(byte)'k',
99,0,0,0,
0,0,0,0,
};
var undertest = new OptimizedTrie(storage);
undertest.Delete("Work");
CollectionAssert.AreEquivalent(new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
0,
0,0,0,0,
0,0,0,0,
0,0,0,0,
}, storage);
}
[Test]
public void DeleteFirstKeyWorks()
{
var storage = new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
4|1<<7,
(byte)'W',(byte)'o',(byte)'r',(byte)'k',
99,0,0,0,
0,0,0,0,
};
var undertest = new OptimizedTrie(storage);
undertest.Delete("test");
CollectionAssert.AreEquivalent(new byte[]
{
4|1<<7,
(byte)'W',(byte)'o',(byte)'r',(byte)'k',
99,0,0,0,
0,0,0,0,
0,
0,0,0,0,
0,0,0,0,
0,0,0,0,
}, storage);
}
[Test]
public void DeleteNonExistingKeySilentlyFails()
{
var storage = new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
4|1<<7,
(byte)'W',(byte)'o',(byte)'r',(byte)'k',
99,0,0,0,
0,0,0,0,
};
var undertest = new OptimizedTrie(storage);
undertest.Delete("DoesNotExist");
CollectionAssert.AreEquivalent(new byte[]
{
4|1<<7,
(byte)'t',(byte)'e',(byte)'s',(byte)'t',
123,0,0,0,
0,0,0,0,
4|1<<7,
(byte)'W',(byte)'o',(byte)'r',(byte)'k',
99,0,0,0,
0,0,0,0,
}, storage);
}
[Test]
public void AddFiles()
{
var undertest = new OptimizedTrie();
WriteAndReadBack(undertest, @"A-zip.ch", 92392);
WriteAndReadBack(undertest, @"A-zip.dl", 88064);
WriteAndReadBack(undertest, @"A-zip3", 56320);
WriteAndReadBack(undertest, @"Az", 1478656);
}
[Test]
public void AddFiles_readback_works()
{
var trie = new OptimizedTrie();
trie.TryWrite(@"dll.hpsign", 256);
trie.TryWrite(@"dll", 99);
long value;
Assert.That(trie.TryRead(@"dll", out value));
}
[Test]
//[Timeout(200)]
public void AddFiles_readback_fails()
{
var undertest = new OptimizedTrie();
undertest.TryWrite(@"C:\Program Files\Hewlett-Packard\Drive Encryption\el\WinMagicSecurityPlugin.resources.dll", 17088);
undertest.TryWrite(@"C:\Program Files\Hewlett-Packard\Drive Encryption\lv\HPDriveEncryption.chm", 46492);
undertest.TryWrite(@"C:\Program Files\Hewlett-Packard\HP ProtectTools Security Manager\Bin\es\DPTokens01.dll.mui", 20992);
undertest.TryWrite(@"C:\Program Files\Hewlett-Packard\Drive Encryption\he\WinMagic.HP.SecurityManagerPlugin.resources.dll", 24256);
undertest.TryWrite(@"C:\Program Files\Hewlett-Packard\HP ProtectTools Security Manager\Bin\lt\DPTokensSCa.dll.mui", 7168);
undertest.TryWrite(@"C:\Program Files\Microsoft SQL Server\120\KeyFile\1033\sql_common_core_loc_keyfile.dll", 57024);
undertest.TryWrite(@"C:\Program Files\Hewlett-Packard\Drive Encryption\et\WinMagic.HP.SecurityManagerPlugin.resources.dll", 22720);
undertest.TryWrite(@"C:\Program Files\Hewlett-Packard\Drive Encryption\h2.bin", 19968);
undertest.TryWrite(@"C:\Program Files\Hewlett-Packard\Drive Encryption\es\HPDriveEncryption.chm", 46804);
}
private static void WriteAndReadBack(ITrie undertest, string key, int v)
{
undertest.TryWrite(key, v);
long value;
Assert.That(undertest.TryRead(key, out value));
Assert.That(value, Is.EqualTo(v));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml;
using Orleans.GrainDirectory;
using Orleans.Providers;
using Orleans.Storage;
using Orleans.Streams;
using Orleans.LogConsistency;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
namespace Orleans.Runtime.Configuration
{
// helper utility class to handle default vs. explicitly set config value.
[Serializable]
internal class ConfigValue<T>
{
public T Value;
public bool IsDefaultValue;
public ConfigValue(T val, bool isDefaultValue)
{
Value = val;
IsDefaultValue = isDefaultValue;
}
}
/// <summary>
/// Data object holding Silo global configuration parameters.
/// </summary>
[Serializable]
public class GlobalConfiguration : MessagingConfiguration
{
private const string DefaultClusterId = "DefaultClusterID"; // if no id is configured, we pick a nonempty default.
/// <summary>
/// Liveness configuration that controls the type of the liveness protocol that silo use for membership.
/// </summary>
public enum LivenessProviderType
{
/// <summary>Default value to allow discrimination of override values.</summary>
NotSpecified,
/// <summary>Grain is used to store membership information.
/// This option is not reliable and thus should only be used in local development setting.</summary>
MembershipTableGrain,
/// <summary>AzureTable is used to store membership information.
/// This option can be used in production.</summary>
AzureTable,
/// <summary>SQL Server is used to store membership information.
/// This option can be used in production.</summary>
SqlServer,
/// <summary>Apache ZooKeeper is used to store membership information.
/// This option can be used in production.</summary>
ZooKeeper,
/// <summary>Use custom provider from third-party assembly</summary>
Custom
}
/// <summary>
/// Reminders configuration that controls the type of the protocol that silo use to implement Reminders.
/// </summary>
public enum ReminderServiceProviderType
{
/// <summary>Default value to allow discrimination of override values.</summary>
NotSpecified,
/// <summary>Grain is used to store reminders information.
/// This option is not reliable and thus should only be used in local development setting.</summary>
ReminderTableGrain,
/// <summary>AzureTable is used to store reminders information.
/// This option can be used in production.</summary>
AzureTable,
/// <summary>SQL Server is used to store reminders information.
/// This option can be used in production.</summary>
SqlServer,
/// <summary>Used for benchmarking; it simply delays for a specified delay during each operation.</summary>
MockTable,
/// <summary>Reminder Service is disabled.</summary>
Disabled,
/// <summary>Use custom Reminder Service from third-party assembly</summary>
Custom
}
/// <summary>
/// Configuration for Gossip Channels
/// </summary>
public enum GossipChannelType
{
/// <summary>Default value to allow discrimination of override values.</summary>
NotSpecified,
/// <summary>An Azure Table serving as a channel. </summary>
AzureTable,
}
/// <summary>
/// Gossip channel configuration.
/// </summary>
[Serializable]
public class GossipChannelConfiguration
{
/// <summary>Gets or sets the gossip channel type.</summary>
public GossipChannelType ChannelType { get; set; }
/// <summary>Gets or sets the credential information used by the channel implementation.</summary>
public string ConnectionString { get; set; }
}
/// <summary>
/// Configuration type that controls the type of the grain directory caching algorithm that silo use.
/// </summary>
public enum DirectoryCachingStrategyType
{
/// <summary>Don't cache.</summary>
None,
/// <summary>Standard fixed-size LRU.</summary>
LRU,
/// <summary>Adaptive caching with fixed maximum size and refresh. This option should be used in production.</summary>
Adaptive
}
public ApplicationConfiguration Application { get; private set; }
/// <summary>
/// SeedNodes are only used in local development setting with LivenessProviderType.MembershipTableGrain
/// SeedNodes are never used in production.
/// </summary>
public IList<IPEndPoint> SeedNodes { get; private set; }
/// <summary>
/// The subnet on which the silos run.
/// This option should only be used when running on multi-homed cluster. It should not be used when running in Azure.
/// </summary>
public byte[] Subnet { get; set; }
/// <summary>
/// Determines if primary node is required to be configured as a seed node.
/// True if LivenessType is set to MembershipTableGrain, false otherwise.
/// </summary>
public bool PrimaryNodeIsRequired
{
get { return LivenessType == LivenessProviderType.MembershipTableGrain; }
}
/// <summary>
/// Global switch to disable silo liveness protocol (should be used only for testing).
/// The LivenessEnabled attribute, if provided and set to "false", suppresses liveness enforcement.
/// If a silo is suspected to be dead, but this attribute is set to "false", the suspicions will not propagated to the system and enforced,
/// This parameter is intended for use only for testing and troubleshooting.
/// In production, liveness should always be enabled.
/// Default is true (eanabled)
/// </summary>
public bool LivenessEnabled { get; set; }
/// <summary>
/// The number of seconds to periodically probe other silos for their liveness or for the silo to send "I am alive" heartbeat messages about itself.
/// </summary>
public TimeSpan ProbeTimeout { get; set; }
/// <summary>
/// The number of seconds to periodically fetch updates from the membership table.
/// </summary>
public TimeSpan TableRefreshTimeout { get; set; }
/// <summary>
/// Expiration time in seconds for death vote in the membership table.
/// </summary>
public TimeSpan DeathVoteExpirationTimeout { get; set; }
/// <summary>
/// The number of seconds to periodically write in the membership table that this silo is alive. Used ony for diagnostics.
/// </summary>
public TimeSpan IAmAliveTablePublishTimeout { get; set; }
/// <summary>
/// The number of seconds to attempt to join a cluster of silos before giving up.
/// </summary>
public TimeSpan MaxJoinAttemptTime { get; set; }
/// <summary>
/// The number of seconds to refresh the cluster grain interface map
/// </summary>
public TimeSpan TypeMapRefreshInterval { get; set; }
internal ConfigValue<int> ExpectedClusterSizeConfigValue { get; set; }
/// <summary>
/// The expected size of a cluster. Need not be very accurate, can be an overestimate.
/// </summary>
public int ExpectedClusterSize { get { return ExpectedClusterSizeConfigValue.Value; } set { ExpectedClusterSizeConfigValue = new ConfigValue<int>(value, false); } }
/// <summary>
/// The number of missed "I am alive" heartbeat messages from a silo or number of un-replied probes that lead to suspecting this silo as dead.
/// </summary>
public int NumMissedProbesLimit { get; set; }
/// <summary>
/// The number of silos each silo probes for liveness.
/// </summary>
public int NumProbedSilos { get; set; }
/// <summary>
/// The number of non-expired votes that are needed to declare some silo as dead (should be at most NumMissedProbesLimit)
/// </summary>
public int NumVotesForDeathDeclaration { get; set; }
/// <summary>
/// The number of missed "I am alive" updates in the table from a silo that causes warning to be logged. Does not impact the liveness protocol.
/// </summary>
public int NumMissedTableIAmAliveLimit { get; set; }
/// <summary>
/// Whether to use the gossip optimization to speed up spreading liveness information.
/// </summary>
public bool UseLivenessGossip { get; set; }
/// <summary>
/// Whether new silo that joins the cluster has to validate the initial connectivity with all other Active silos.
/// </summary>
public bool ValidateInitialConnectivity { get; set; }
/// <summary>
/// Service Id.
/// </summary>
public Guid ServiceId { get; set; }
/// <summary>
/// Deployment Id.
/// </summary>
public string DeploymentId { get; set; }
#region MultiClusterNetwork
private string clusterId;
/// <summary>
/// Whether this cluster is configured to be part of a multicluster network
/// </summary>
public bool HasMultiClusterNetwork
{
get
{
return !(string.IsNullOrEmpty(this.clusterId));
}
}
/// <summary>
/// Cluster id (one per deployment, unique across all the deployments/clusters)
/// </summary>
public string ClusterId
{
get
{
var configuredId = this.HasMultiClusterNetwork ? this.clusterId : this.DeploymentId;
return string.IsNullOrEmpty(configuredId) ? DefaultClusterId : configuredId;
}
set
{
this.clusterId = value;
}
}
/// <summary>
///A list of cluster ids, to be used if no multicluster configuration is found in gossip channels.
/// </summary>
public IReadOnlyList<string> DefaultMultiCluster { get; set; }
/// <summary>
/// The maximum number of silos per cluster should be designated to serve as gateways.
/// </summary>
public int MaxMultiClusterGateways { get; set; }
/// <summary>
/// The time between background gossips.
/// </summary>
public TimeSpan BackgroundGossipInterval { get; set; }
/// <summary>
/// Whether to use the global single instance protocol as the default
/// multicluster registration strategy.
/// </summary>
public bool UseGlobalSingleInstanceByDefault { get; set; }
/// <summary>
/// The number of quick retries before going into DOUBTFUL state.
/// </summary>
public int GlobalSingleInstanceNumberRetries { get; set; }
/// <summary>
/// The time between the slow retries for DOUBTFUL activations.
/// </summary>
public TimeSpan GlobalSingleInstanceRetryInterval { get; set; }
/// <summary>
/// A list of connection strings for gossip channels.
/// </summary>
public IReadOnlyList<GossipChannelConfiguration> GossipChannels { get; set; }
#endregion
/// <summary>
/// Connection string for the underlying data provider for liveness and reminders. eg. Azure Storage, ZooKeeper, SQL Server, ect.
/// In order to override this value for reminders set <see cref="DataConnectionStringForReminders"/>
/// </summary>
public string DataConnectionString { get; set; }
/// <summary>
/// When using ADO, identifies the underlying data provider for liveness and reminders. This three-part naming syntax is also used
/// when creating a new factory and for identifying the provider in an application configuration file so that the provider name,
/// along with its associated connection string, can be retrieved at run time. https://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.110%29.aspx
/// In order to override this value for reminders set <see cref="AdoInvariantForReminders"/>
/// </summary>
public string AdoInvariant { get; set; }
/// <summary>
/// Set this property to override <see cref="DataConnectionString"/> for reminders.
/// </summary>
public string DataConnectionStringForReminders
{
get
{
return string.IsNullOrWhiteSpace(dataConnectionStringForReminders) ? DataConnectionString : dataConnectionStringForReminders;
}
set { dataConnectionStringForReminders = value; }
}
/// <summary>
/// Set this property to override <see cref="AdoInvariant"/> for reminders.
/// </summary>
public string AdoInvariantForReminders
{
get
{
return string.IsNullOrWhiteSpace(adoInvariantForReminders) ? AdoInvariant : adoInvariantForReminders;
}
set { adoInvariantForReminders = value; }
}
internal TimeSpan CollectionQuantum { get; set; }
/// <summary>
/// Specifies the maximum time that a request can take before the activation is reported as "blocked"
/// </summary>
public TimeSpan MaxRequestProcessingTime { get; set; }
/// <summary>
/// The CacheSize attribute specifies the maximum number of grains to cache directory information for.
/// </summary>
public int CacheSize { get; set; }
/// <summary>
/// The InitialTTL attribute specifies the initial (minimum) time, in seconds, to keep a cache entry before revalidating.
/// </summary>
public TimeSpan InitialCacheTTL { get; set; }
/// <summary>
/// The MaximumTTL attribute specifies the maximum time, in seconds, to keep a cache entry before revalidating.
/// </summary>
public TimeSpan MaximumCacheTTL { get; set; }
/// <summary>
/// The TTLExtensionFactor attribute specifies the factor by which cache entry TTLs should be extended when they are found to be stable.
/// </summary>
public double CacheTTLExtensionFactor { get; set; }
/// <summary>
/// Retry count for Azure Table operations.
/// </summary>
public int MaxStorageBusyRetries { get; private set; }
/// <summary>
/// The DirectoryCachingStrategy attribute specifies the caching strategy to use.
/// The options are None, which means don't cache directory entries locally;
/// LRU, which indicates that a standard fixed-size least recently used strategy should be used; and
/// Adaptive, which indicates that an adaptive strategy with a fixed maximum size should be used.
/// The Adaptive strategy is used by default.
/// </summary>
public DirectoryCachingStrategyType DirectoryCachingStrategy { get; set; }
public bool UseVirtualBucketsConsistentRing { get; set; }
public int NumVirtualBucketsConsistentRing { get; set; }
/// <summary>
/// The LivenessType attribute controls the liveness method used for silo reliability.
/// </summary>
private LivenessProviderType livenessServiceType;
public LivenessProviderType LivenessType
{
get
{
return livenessServiceType;
}
set
{
if (value == LivenessProviderType.NotSpecified)
throw new ArgumentException("Cannot set LivenessType to " + LivenessProviderType.NotSpecified, "LivenessType");
livenessServiceType = value;
}
}
/// <summary>
/// Assembly to use for custom MembershipTable implementation
/// </summary>
public string MembershipTableAssembly { get; set; }
/// <summary>
/// Assembly to use for custom ReminderTable implementation
/// </summary>
public string ReminderTableAssembly { get; set; }
/// <summary>
/// The ReminderServiceType attribute controls the type of the reminder service implementation used by silos.
/// </summary>
private ReminderServiceProviderType reminderServiceType;
public ReminderServiceProviderType ReminderServiceType
{
get
{
return reminderServiceType;
}
set
{
SetReminderServiceType(value);
}
}
// It's a separate function so we can clearly see when we set the value.
// With property you can't seaprate getter from setter in intellicense.
internal void SetReminderServiceType(ReminderServiceProviderType reminderType)
{
if (reminderType == ReminderServiceProviderType.NotSpecified)
throw new ArgumentException("Cannot set ReminderServiceType to " + ReminderServiceProviderType.NotSpecified, "ReminderServiceType");
reminderServiceType = reminderType;
}
public TimeSpan MockReminderTableTimeout { get; set; }
internal bool UseMockReminderTable;
/// <summary>
/// Configuration for various runtime providers.
/// </summary>
public IDictionary<string, ProviderCategoryConfiguration> ProviderConfigurations { get; set; }
/// <summary>
/// Configuration for grain services.
/// </summary>
public GrainServiceConfigurations GrainServiceConfigurations { get; set; }
/// <summary>
/// The time span between when we have added an entry for an activation to the grain directory and when we are allowed
/// to conditionally remove that entry.
/// Conditional deregistration is used for lazy clean-up of activations whose prompt deregistration failed for some reason (e.g., message failure).
/// This should always be at least one minute, since we compare the times on the directory partition, so message delays and clcks skues have
/// to be allowed.
/// </summary>
public TimeSpan DirectoryLazyDeregistrationDelay { get; set; }
public TimeSpan ClientRegistrationRefresh { get; set; }
internal bool PerformDeadlockDetection { get; set; }
public string DefaultPlacementStrategy { get; set; }
public CompatibilityStrategy DefaultCompatibilityStrategy { get; set; }
public VersionSelectorStrategy DefaultVersionSelectorStrategy { get; set; }
public TimeSpan DeploymentLoadPublisherRefreshTime { get; set; }
public int ActivationCountBasedPlacementChooseOutOf { get; set; }
public bool AssumeHomogenousSilosForTesting { get; set; }
public bool FastKillOnCancelKeyPress { get; set; }
/// <summary>
/// Determines if ADO should be used for storage of Membership and Reminders info.
/// True if either or both of LivenessType and ReminderServiceType are set to SqlServer, false otherwise.
/// </summary>
internal bool UseSqlSystemStore
{
get
{
return !String.IsNullOrWhiteSpace(DataConnectionString) && (
(LivenessEnabled && LivenessType == LivenessProviderType.SqlServer)
|| ReminderServiceType == ReminderServiceProviderType.SqlServer);
}
}
/// <summary>
/// Determines if ZooKeeper should be used for storage of Membership and Reminders info.
/// True if LivenessType is set to ZooKeeper, false otherwise.
/// </summary>
internal bool UseZooKeeperSystemStore
{
get
{
return !String.IsNullOrWhiteSpace(DataConnectionString) && (
(LivenessEnabled && LivenessType == LivenessProviderType.ZooKeeper));
}
}
/// <summary>
/// Determines if Azure Storage should be used for storage of Membership and Reminders info.
/// True if either or both of LivenessType and ReminderServiceType are set to AzureTable, false otherwise.
/// </summary>
internal bool UseAzureSystemStore
{
get
{
return !String.IsNullOrWhiteSpace(DataConnectionString)
&& !UseSqlSystemStore && !UseZooKeeperSystemStore;
}
}
internal bool RunsInAzure { get { return UseAzureSystemStore && !String.IsNullOrWhiteSpace(DeploymentId); } }
private static readonly TimeSpan DEFAULT_LIVENESS_PROBE_TIMEOUT = TimeSpan.FromSeconds(10);
private static readonly TimeSpan DEFAULT_LIVENESS_TABLE_REFRESH_TIMEOUT = TimeSpan.FromSeconds(60);
private static readonly TimeSpan DEFAULT_LIVENESS_DEATH_VOTE_EXPIRATION_TIMEOUT = TimeSpan.FromSeconds(120);
private static readonly TimeSpan DEFAULT_LIVENESS_I_AM_ALIVE_TABLE_PUBLISH_TIMEOUT = TimeSpan.FromMinutes(5);
private static readonly TimeSpan DEFAULT_LIVENESS_MAX_JOIN_ATTEMPT_TIME = TimeSpan.FromMinutes(5); // 5 min
private static readonly TimeSpan DEFAULT_REFRESH_CLUSTER_INTERFACEMAP_TIME = TimeSpan.FromMinutes(1);
private const int DEFAULT_LIVENESS_NUM_MISSED_PROBES_LIMIT = 3;
private const int DEFAULT_LIVENESS_NUM_PROBED_SILOS = 3;
private const int DEFAULT_LIVENESS_NUM_VOTES_FOR_DEATH_DECLARATION = 2;
private const int DEFAULT_LIVENESS_NUM_TABLE_I_AM_ALIVE_LIMIT = 2;
private const bool DEFAULT_LIVENESS_USE_LIVENESS_GOSSIP = true;
private const bool DEFAULT_VALIDATE_INITIAL_CONNECTIVITY = true;
private const int DEFAULT_MAX_MULTICLUSTER_GATEWAYS = 10;
private const bool DEFAULT_USE_GLOBAL_SINGLE_INSTANCE = true;
private static readonly TimeSpan DEFAULT_BACKGROUND_GOSSIP_INTERVAL = TimeSpan.FromSeconds(30);
private static readonly TimeSpan DEFAULT_GLOBAL_SINGLE_INSTANCE_RETRY_INTERVAL = TimeSpan.FromSeconds(30);
private const int DEFAULT_GLOBAL_SINGLE_INSTANCE_NUMBER_RETRIES = 10;
private const int DEFAULT_LIVENESS_EXPECTED_CLUSTER_SIZE = 20;
private const int DEFAULT_CACHE_SIZE = 1000000;
private static readonly TimeSpan DEFAULT_INITIAL_CACHE_TTL = TimeSpan.FromSeconds(30);
private static readonly TimeSpan DEFAULT_MAXIMUM_CACHE_TTL = TimeSpan.FromSeconds(240);
private const double DEFAULT_TTL_EXTENSION_FACTOR = 2.0;
private const DirectoryCachingStrategyType DEFAULT_DIRECTORY_CACHING_STRATEGY = DirectoryCachingStrategyType.Adaptive;
internal static readonly TimeSpan DEFAULT_COLLECTION_QUANTUM = TimeSpan.FromMinutes(1);
internal static readonly TimeSpan DEFAULT_COLLECTION_AGE_LIMIT = TimeSpan.FromHours(2);
public static bool ENFORCE_MINIMUM_REQUIREMENT_FOR_AGE_LIMIT = true;
private static readonly TimeSpan DEFAULT_UNREGISTER_RACE_DELAY = TimeSpan.FromMinutes(1);
private static readonly TimeSpan DEFAULT_CLIENT_REGISTRATION_REFRESH = TimeSpan.FromMinutes(5);
public const bool DEFAULT_PERFORM_DEADLOCK_DETECTION = false;
public static readonly string DEFAULT_PLACEMENT_STRATEGY = typeof(RandomPlacement).Name;
public static readonly string DEFAULT_MULTICLUSTER_REGISTRATION_STRATEGY = typeof(GlobalSingleInstanceRegistration).Name;
private static readonly TimeSpan DEFAULT_DEPLOYMENT_LOAD_PUBLISHER_REFRESH_TIME = TimeSpan.FromSeconds(1);
private const int DEFAULT_ACTIVATION_COUNT_BASED_PLACEMENT_CHOOSE_OUT_OF = 2;
private const bool DEFAULT_USE_VIRTUAL_RING_BUCKETS = true;
private const int DEFAULT_NUM_VIRTUAL_RING_BUCKETS = 30;
private static readonly TimeSpan DEFAULT_MOCK_REMINDER_TABLE_TIMEOUT = TimeSpan.FromMilliseconds(50);
private string dataConnectionStringForReminders;
private string adoInvariantForReminders;
internal GlobalConfiguration()
: base(true)
{
Application = new ApplicationConfiguration();
SeedNodes = new List<IPEndPoint>();
livenessServiceType = LivenessProviderType.NotSpecified;
LivenessEnabled = true;
ProbeTimeout = DEFAULT_LIVENESS_PROBE_TIMEOUT;
TableRefreshTimeout = DEFAULT_LIVENESS_TABLE_REFRESH_TIMEOUT;
DeathVoteExpirationTimeout = DEFAULT_LIVENESS_DEATH_VOTE_EXPIRATION_TIMEOUT;
IAmAliveTablePublishTimeout = DEFAULT_LIVENESS_I_AM_ALIVE_TABLE_PUBLISH_TIMEOUT;
NumMissedProbesLimit = DEFAULT_LIVENESS_NUM_MISSED_PROBES_LIMIT;
NumProbedSilos = DEFAULT_LIVENESS_NUM_PROBED_SILOS;
NumVotesForDeathDeclaration = DEFAULT_LIVENESS_NUM_VOTES_FOR_DEATH_DECLARATION;
NumMissedTableIAmAliveLimit = DEFAULT_LIVENESS_NUM_TABLE_I_AM_ALIVE_LIMIT;
UseLivenessGossip = DEFAULT_LIVENESS_USE_LIVENESS_GOSSIP;
ValidateInitialConnectivity = DEFAULT_VALIDATE_INITIAL_CONNECTIVITY;
MaxJoinAttemptTime = DEFAULT_LIVENESS_MAX_JOIN_ATTEMPT_TIME;
TypeMapRefreshInterval = DEFAULT_REFRESH_CLUSTER_INTERFACEMAP_TIME;
MaxMultiClusterGateways = DEFAULT_MAX_MULTICLUSTER_GATEWAYS;
BackgroundGossipInterval = DEFAULT_BACKGROUND_GOSSIP_INTERVAL;
UseGlobalSingleInstanceByDefault = DEFAULT_USE_GLOBAL_SINGLE_INSTANCE;
GlobalSingleInstanceRetryInterval = DEFAULT_GLOBAL_SINGLE_INSTANCE_RETRY_INTERVAL;
GlobalSingleInstanceNumberRetries = DEFAULT_GLOBAL_SINGLE_INSTANCE_NUMBER_RETRIES;
ExpectedClusterSizeConfigValue = new ConfigValue<int>(DEFAULT_LIVENESS_EXPECTED_CLUSTER_SIZE, true);
ServiceId = Guid.Empty;
DeploymentId = "";
DataConnectionString = "";
// Assume the ado invariant is for sql server storage if not explicitly specified
AdoInvariant = Constants.INVARIANT_NAME_SQL_SERVER;
MaxRequestProcessingTime = DEFAULT_COLLECTION_AGE_LIMIT;
CollectionQuantum = DEFAULT_COLLECTION_QUANTUM;
CacheSize = DEFAULT_CACHE_SIZE;
InitialCacheTTL = DEFAULT_INITIAL_CACHE_TTL;
MaximumCacheTTL = DEFAULT_MAXIMUM_CACHE_TTL;
CacheTTLExtensionFactor = DEFAULT_TTL_EXTENSION_FACTOR;
DirectoryCachingStrategy = DEFAULT_DIRECTORY_CACHING_STRATEGY;
DirectoryLazyDeregistrationDelay = DEFAULT_UNREGISTER_RACE_DELAY;
ClientRegistrationRefresh = DEFAULT_CLIENT_REGISTRATION_REFRESH;
PerformDeadlockDetection = DEFAULT_PERFORM_DEADLOCK_DETECTION;
reminderServiceType = ReminderServiceProviderType.NotSpecified;
DefaultPlacementStrategy = DEFAULT_PLACEMENT_STRATEGY;
DeploymentLoadPublisherRefreshTime = DEFAULT_DEPLOYMENT_LOAD_PUBLISHER_REFRESH_TIME;
ActivationCountBasedPlacementChooseOutOf = DEFAULT_ACTIVATION_COUNT_BASED_PLACEMENT_CHOOSE_OUT_OF;
UseVirtualBucketsConsistentRing = DEFAULT_USE_VIRTUAL_RING_BUCKETS;
NumVirtualBucketsConsistentRing = DEFAULT_NUM_VIRTUAL_RING_BUCKETS;
UseMockReminderTable = false;
MockReminderTableTimeout = DEFAULT_MOCK_REMINDER_TABLE_TIMEOUT;
AssumeHomogenousSilosForTesting = false;
ProviderConfigurations = new Dictionary<string, ProviderCategoryConfiguration>();
GrainServiceConfigurations = new GrainServiceConfigurations();
DefaultCompatibilityStrategy = BackwardCompatible.Singleton;
DefaultVersionSelectorStrategy = AllCompatibleVersions.Singleton;
FastKillOnCancelKeyPress = true;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendFormat(" System Ids:").AppendLine();
sb.AppendFormat(" ServiceId: {0}", ServiceId).AppendLine();
sb.AppendFormat(" DeploymentId: {0}", DeploymentId).AppendLine();
sb.Append(" Subnet: ").Append(Subnet == null ? "" : Subnet.ToStrings(x => x.ToString(CultureInfo.InvariantCulture), ".")).AppendLine();
sb.Append(" Seed nodes: ");
bool first = true;
foreach (IPEndPoint node in SeedNodes)
{
if (!first)
{
sb.Append(", ");
}
sb.Append(node.ToString());
first = false;
}
sb.AppendLine();
sb.AppendFormat(base.ToString());
sb.AppendFormat(" Liveness:").AppendLine();
sb.AppendFormat(" LivenessEnabled: {0}", LivenessEnabled).AppendLine();
sb.AppendFormat(" LivenessType: {0}", LivenessType).AppendLine();
sb.AppendFormat(" ProbeTimeout: {0}", ProbeTimeout).AppendLine();
sb.AppendFormat(" TableRefreshTimeout: {0}", TableRefreshTimeout).AppendLine();
sb.AppendFormat(" DeathVoteExpirationTimeout: {0}", DeathVoteExpirationTimeout).AppendLine();
sb.AppendFormat(" NumMissedProbesLimit: {0}", NumMissedProbesLimit).AppendLine();
sb.AppendFormat(" NumProbedSilos: {0}", NumProbedSilos).AppendLine();
sb.AppendFormat(" NumVotesForDeathDeclaration: {0}", NumVotesForDeathDeclaration).AppendLine();
sb.AppendFormat(" UseLivenessGossip: {0}", UseLivenessGossip).AppendLine();
sb.AppendFormat(" ValidateInitialConnectivity: {0}", ValidateInitialConnectivity).AppendLine();
sb.AppendFormat(" IAmAliveTablePublishTimeout: {0}", IAmAliveTablePublishTimeout).AppendLine();
sb.AppendFormat(" NumMissedTableIAmAliveLimit: {0}", NumMissedTableIAmAliveLimit).AppendLine();
sb.AppendFormat(" MaxJoinAttemptTime: {0}", MaxJoinAttemptTime).AppendLine();
sb.AppendFormat(" ExpectedClusterSize: {0}", ExpectedClusterSize).AppendLine();
if (HasMultiClusterNetwork)
{
sb.AppendLine(" MultiClusterNetwork:");
sb.AppendFormat(" ClusterId: {0}", ClusterId ?? "").AppendLine();
sb.AppendFormat(" DefaultMultiCluster: {0}", DefaultMultiCluster != null ? string.Join(",", DefaultMultiCluster) : "null").AppendLine();
sb.AppendFormat(" MaxMultiClusterGateways: {0}", MaxMultiClusterGateways).AppendLine();
sb.AppendFormat(" BackgroundGossipInterval: {0}", BackgroundGossipInterval).AppendLine();
sb.AppendFormat(" UseGlobalSingleInstanceByDefault: {0}", UseGlobalSingleInstanceByDefault).AppendLine();
sb.AppendFormat(" GlobalSingleInstanceRetryInterval: {0}", GlobalSingleInstanceRetryInterval).AppendLine();
sb.AppendFormat(" GlobalSingleInstanceNumberRetries: {0}", GlobalSingleInstanceNumberRetries).AppendLine();
sb.AppendFormat(" GossipChannels: {0}", string.Join(",", GossipChannels.Select(conf => conf.ChannelType.ToString() + ":" + conf.ConnectionString))).AppendLine();
}
else
{
sb.AppendLine(" MultiClusterNetwork: N/A");
}
sb.AppendFormat(" SystemStore:").AppendLine();
// Don't print connection credentials in log files, so pass it through redactment filter
string connectionStringForLog = ConfigUtilities.RedactConnectionStringInfo(DataConnectionString);
sb.AppendFormat(" SystemStore ConnectionString: {0}", connectionStringForLog).AppendLine();
string remindersConnectionStringForLog = ConfigUtilities.RedactConnectionStringInfo(DataConnectionStringForReminders);
sb.AppendFormat(" Reminders ConnectionString: {0}", remindersConnectionStringForLog).AppendLine();
sb.Append(Application.ToString()).AppendLine();
sb.Append(" PlacementStrategy: ").AppendLine();
sb.Append(" ").Append(" Default Placement Strategy: ").Append(DefaultPlacementStrategy).AppendLine();
sb.Append(" ").Append(" Deployment Load Publisher Refresh Time: ").Append(DeploymentLoadPublisherRefreshTime).AppendLine();
sb.Append(" ").Append(" Activation CountBased Placement Choose Out Of: ").Append(ActivationCountBasedPlacementChooseOutOf).AppendLine();
sb.AppendFormat(" Grain directory cache:").AppendLine();
sb.AppendFormat(" Maximum size: {0} grains", CacheSize).AppendLine();
sb.AppendFormat(" Initial TTL: {0}", InitialCacheTTL).AppendLine();
sb.AppendFormat(" Maximum TTL: {0}", MaximumCacheTTL).AppendLine();
sb.AppendFormat(" TTL extension factor: {0:F2}", CacheTTLExtensionFactor).AppendLine();
sb.AppendFormat(" Directory Caching Strategy: {0}", DirectoryCachingStrategy).AppendLine();
sb.AppendFormat(" Grain directory:").AppendLine();
sb.AppendFormat(" Lazy deregistration delay: {0}", DirectoryLazyDeregistrationDelay).AppendLine();
sb.AppendFormat(" Client registration refresh: {0}", ClientRegistrationRefresh).AppendLine();
sb.AppendFormat(" Reminder Service:").AppendLine();
sb.AppendFormat(" ReminderServiceType: {0}", ReminderServiceType).AppendLine();
if (ReminderServiceType == ReminderServiceProviderType.MockTable)
{
sb.AppendFormat(" MockReminderTableTimeout: {0}ms", MockReminderTableTimeout.TotalMilliseconds).AppendLine();
}
sb.AppendFormat(" Consistent Ring:").AppendLine();
sb.AppendFormat(" Use Virtual Buckets Consistent Ring: {0}", UseVirtualBucketsConsistentRing).AppendLine();
sb.AppendFormat(" Num Virtual Buckets Consistent Ring: {0}", NumVirtualBucketsConsistentRing).AppendLine();
sb.AppendFormat(" Providers:").AppendLine();
sb.Append(ProviderConfigurationUtility.PrintProviderConfigurations(ProviderConfigurations));
return sb.ToString();
}
internal override void Load(XmlElement root)
{
SeedNodes = new List<IPEndPoint>();
XmlElement child;
foreach (XmlNode c in root.ChildNodes)
{
child = c as XmlElement;
if (child != null && child.LocalName == "Networking")
{
Subnet = child.HasAttribute("Subnet")
? ConfigUtilities.ParseSubnet(child.GetAttribute("Subnet"), "Invalid Subnet")
: null;
}
}
foreach (XmlNode c in root.ChildNodes)
{
child = c as XmlElement;
if (child == null) continue; // Skip comment lines
switch (child.LocalName)
{
case "Liveness":
if (child.HasAttribute("LivenessEnabled"))
{
LivenessEnabled = ConfigUtilities.ParseBool(child.GetAttribute("LivenessEnabled"),
"Invalid boolean value for the LivenessEnabled attribute on the Liveness element");
}
if (child.HasAttribute("ProbeTimeout"))
{
ProbeTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ProbeTimeout"),
"Invalid time value for the ProbeTimeout attribute on the Liveness element");
}
if (child.HasAttribute("TableRefreshTimeout"))
{
TableRefreshTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("TableRefreshTimeout"),
"Invalid time value for the TableRefreshTimeout attribute on the Liveness element");
}
if (child.HasAttribute("DeathVoteExpirationTimeout"))
{
DeathVoteExpirationTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DeathVoteExpirationTimeout"),
"Invalid time value for the DeathVoteExpirationTimeout attribute on the Liveness element");
}
if (child.HasAttribute("NumMissedProbesLimit"))
{
NumMissedProbesLimit = ConfigUtilities.ParseInt(child.GetAttribute("NumMissedProbesLimit"),
"Invalid integer value for the NumMissedIAmAlive attribute on the Liveness element");
}
if (child.HasAttribute("NumProbedSilos"))
{
NumProbedSilos = ConfigUtilities.ParseInt(child.GetAttribute("NumProbedSilos"),
"Invalid integer value for the NumProbedSilos attribute on the Liveness element");
}
if (child.HasAttribute("NumVotesForDeathDeclaration"))
{
NumVotesForDeathDeclaration = ConfigUtilities.ParseInt(child.GetAttribute("NumVotesForDeathDeclaration"),
"Invalid integer value for the NumVotesForDeathDeclaration attribute on the Liveness element");
}
if (child.HasAttribute("UseLivenessGossip"))
{
UseLivenessGossip = ConfigUtilities.ParseBool(child.GetAttribute("UseLivenessGossip"),
"Invalid boolean value for the UseLivenessGossip attribute on the Liveness element");
}
if (child.HasAttribute("ValidateInitialConnectivity"))
{
ValidateInitialConnectivity = ConfigUtilities.ParseBool(child.GetAttribute("ValidateInitialConnectivity"),
"Invalid boolean value for the ValidateInitialConnectivity attribute on the Liveness element");
}
if (child.HasAttribute("IAmAliveTablePublishTimeout"))
{
IAmAliveTablePublishTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("IAmAliveTablePublishTimeout"),
"Invalid time value for the IAmAliveTablePublishTimeout attribute on the Liveness element");
}
if (child.HasAttribute("NumMissedTableIAmAliveLimit"))
{
NumMissedTableIAmAliveLimit = ConfigUtilities.ParseInt(child.GetAttribute("NumMissedTableIAmAliveLimit"),
"Invalid integer value for the NumMissedTableIAmAliveLimit attribute on the Liveness element");
}
if (child.HasAttribute("MaxJoinAttemptTime"))
{
MaxJoinAttemptTime = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaxJoinAttemptTime"),
"Invalid time value for the MaxJoinAttemptTime attribute on the Liveness element");
}
if (child.HasAttribute("ExpectedClusterSize"))
{
int expectedClusterSize = ConfigUtilities.ParseInt(child.GetAttribute("ExpectedClusterSize"),
"Invalid integer value for the ExpectedClusterSize attribute on the Liveness element");
ExpectedClusterSizeConfigValue = new ConfigValue<int>(expectedClusterSize, false);
}
break;
case "Azure":
case "SystemStore":
if (child.HasAttribute("SystemStoreType"))
{
var sst = child.GetAttribute("SystemStoreType");
if (!"None".Equals(sst, StringComparison.OrdinalIgnoreCase))
{
LivenessType = (LivenessProviderType)Enum.Parse(typeof(LivenessProviderType), sst);
ReminderServiceProviderType reminderServiceProviderType;
if (LivenessType == LivenessProviderType.MembershipTableGrain)
{
// Special case for MembershipTableGrain -> ReminderTableGrain since we use the same setting
// for LivenessType and ReminderServiceType even if the enum are not 100% compatible
reminderServiceProviderType = ReminderServiceProviderType.ReminderTableGrain;
}
else
{
// If LivenessType = ZooKeeper then we set ReminderServiceType to disabled
reminderServiceProviderType = Enum.TryParse(sst, out reminderServiceProviderType)
? reminderServiceProviderType
: ReminderServiceProviderType.Disabled;
}
SetReminderServiceType(reminderServiceProviderType);
}
}
if (child.HasAttribute("MembershipTableAssembly"))
{
MembershipTableAssembly = child.GetAttribute("MembershipTableAssembly");
if (LivenessType != LivenessProviderType.Custom)
throw new FormatException("SystemStoreType should be \"Custom\" when MembershipTableAssembly is specified");
if (MembershipTableAssembly.EndsWith(".dll"))
throw new FormatException("Use fully qualified assembly name for \"MembershipTableAssembly\"");
}
if (child.HasAttribute("ReminderTableAssembly"))
{
ReminderTableAssembly = child.GetAttribute("ReminderTableAssembly");
if (ReminderServiceType != ReminderServiceProviderType.Custom)
throw new FormatException("ReminderServiceType should be \"Custom\" when ReminderTableAssembly is specified");
if (ReminderTableAssembly.EndsWith(".dll"))
throw new FormatException("Use fully qualified assembly name for \"ReminderTableAssembly\"");
}
if (LivenessType == LivenessProviderType.Custom && string.IsNullOrEmpty(MembershipTableAssembly))
throw new FormatException("MembershipTableAssembly should be set when SystemStoreType is \"Custom\"");
if (ReminderServiceType == ReminderServiceProviderType.Custom && String.IsNullOrEmpty(ReminderTableAssembly))
{
SetReminderServiceType(ReminderServiceProviderType.Disabled);
}
if (child.HasAttribute("ServiceId"))
{
ServiceId = ConfigUtilities.ParseGuid(child.GetAttribute("ServiceId"),
"Invalid Guid value for the ServiceId attribute on the Azure element");
}
if (child.HasAttribute("DeploymentId"))
{
DeploymentId = child.GetAttribute("DeploymentId");
}
if (child.HasAttribute(Constants.DATA_CONNECTION_STRING_NAME))
{
DataConnectionString = child.GetAttribute(Constants.DATA_CONNECTION_STRING_NAME);
if (String.IsNullOrWhiteSpace(DataConnectionString))
{
throw new FormatException("SystemStore.DataConnectionString cannot be blank");
}
}
if (child.HasAttribute(Constants.DATA_CONNECTION_FOR_REMINDERS_STRING_NAME))
{
DataConnectionStringForReminders = child.GetAttribute(Constants.DATA_CONNECTION_FOR_REMINDERS_STRING_NAME);
if (String.IsNullOrWhiteSpace(DataConnectionStringForReminders))
{
throw new FormatException("SystemStore.DataConnectionStringForReminders cannot be blank");
}
}
if (child.HasAttribute(Constants.ADO_INVARIANT_NAME))
{
var adoInvariant = child.GetAttribute(Constants.ADO_INVARIANT_NAME);
if (String.IsNullOrWhiteSpace(adoInvariant))
{
throw new FormatException("SystemStore.AdoInvariant cannot be blank");
}
AdoInvariant = adoInvariant;
}
if (child.HasAttribute(Constants.ADO_INVARIANT_FOR_REMINDERS_NAME))
{
var adoInvariantForReminders = child.GetAttribute(Constants.ADO_INVARIANT_FOR_REMINDERS_NAME);
if (String.IsNullOrWhiteSpace(adoInvariantForReminders))
{
throw new FormatException("SystemStore.adoInvariantForReminders cannot be blank");
}
AdoInvariantForReminders = adoInvariantForReminders;
}
if (child.HasAttribute("MaxStorageBusyRetries"))
{
MaxStorageBusyRetries = ConfigUtilities.ParseInt(child.GetAttribute("MaxStorageBusyRetries"),
"Invalid integer value for the MaxStorageBusyRetries attribute on the SystemStore element");
}
if (child.HasAttribute("UseMockReminderTable"))
{
MockReminderTableTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("UseMockReminderTable"), "Invalid timeout value");
UseMockReminderTable = true;
}
break;
case "MultiClusterNetwork":
ClusterId = child.GetAttribute("ClusterId");
// we always trim cluster ids to avoid surprises when parsing comma-separated lists
if (ClusterId != null)
ClusterId = ClusterId.Trim();
if (string.IsNullOrEmpty(ClusterId))
throw new FormatException("MultiClusterNetwork.ClusterId cannot be blank");
if (ClusterId.Contains(","))
throw new FormatException("MultiClusterNetwork.ClusterId cannot contain commas: " + ClusterId);
if (child.HasAttribute("DefaultMultiCluster"))
{
var toparse = child.GetAttribute("DefaultMultiCluster").Trim();
if (string.IsNullOrEmpty(toparse))
{
DefaultMultiCluster = new List<string>(); // empty cluster
}
else
{
DefaultMultiCluster = toparse.Split(',').Select(id => id.Trim()).ToList();
foreach (var id in DefaultMultiCluster)
if (string.IsNullOrEmpty(id))
throw new FormatException("MultiClusterNetwork.DefaultMultiCluster cannot contain blank cluster ids: " + toparse);
}
}
if (child.HasAttribute("BackgroundGossipInterval"))
{
BackgroundGossipInterval = ConfigUtilities.ParseTimeSpan(child.GetAttribute("BackgroundGossipInterval"),
"Invalid time value for the BackgroundGossipInterval attribute on the MultiClusterNetwork element");
}
if (child.HasAttribute("UseGlobalSingleInstanceByDefault"))
{
UseGlobalSingleInstanceByDefault = ConfigUtilities.ParseBool(child.GetAttribute("UseGlobalSingleInstanceByDefault"),
"Invalid boolean for the UseGlobalSingleInstanceByDefault attribute on the MultiClusterNetwork element");
}
if (child.HasAttribute("GlobalSingleInstanceRetryInterval"))
{
GlobalSingleInstanceRetryInterval = ConfigUtilities.ParseTimeSpan(child.GetAttribute("GlobalSingleInstanceRetryInterval"),
"Invalid time value for the GlobalSingleInstanceRetryInterval attribute on the MultiClusterNetwork element");
}
if (child.HasAttribute("GlobalSingleInstanceNumberRetries"))
{
GlobalSingleInstanceNumberRetries = ConfigUtilities.ParseInt(child.GetAttribute("GlobalSingleInstanceNumberRetries"),
"Invalid value for the GlobalSingleInstanceRetryInterval attribute on the MultiClusterNetwork element");
}
if (child.HasAttribute("MaxMultiClusterGateways"))
{
MaxMultiClusterGateways = ConfigUtilities.ParseInt(child.GetAttribute("MaxMultiClusterGateways"),
"Invalid value for the MaxMultiClusterGateways attribute on the MultiClusterNetwork element");
}
var channels = new List<GossipChannelConfiguration>();
foreach (XmlNode childchild in child.ChildNodes)
{
var channelspec = childchild as XmlElement;
if (channelspec == null || channelspec.LocalName != "GossipChannel")
continue;
channels.Add(new GossipChannelConfiguration()
{
ChannelType = (GlobalConfiguration.GossipChannelType)
Enum.Parse(typeof(GlobalConfiguration.GossipChannelType), channelspec.GetAttribute("Type")),
ConnectionString = channelspec.GetAttribute("ConnectionString")
});
}
GossipChannels = channels;
break;
case "SeedNode":
SeedNodes.Add(ConfigUtilities.ParseIPEndPoint(child, Subnet).GetResult());
break;
case "Messaging":
base.Load(child);
break;
case "Application":
Application.Load(child);
break;
case "PlacementStrategy":
if (child.HasAttribute("DefaultPlacementStrategy"))
DefaultPlacementStrategy = child.GetAttribute("DefaultPlacementStrategy");
if (child.HasAttribute("DeploymentLoadPublisherRefreshTime"))
DeploymentLoadPublisherRefreshTime = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DeploymentLoadPublisherRefreshTime"),
"Invalid time span value for PlacementStrategy.DeploymentLoadPublisherRefreshTime");
if (child.HasAttribute("ActivationCountBasedPlacementChooseOutOf"))
ActivationCountBasedPlacementChooseOutOf = ConfigUtilities.ParseInt(child.GetAttribute("ActivationCountBasedPlacementChooseOutOf"),
"Invalid ActivationCountBasedPlacementChooseOutOf setting");
break;
case "Caching":
if (child.HasAttribute("CacheSize"))
CacheSize = ConfigUtilities.ParseInt(child.GetAttribute("CacheSize"),
"Invalid integer value for Caching.CacheSize");
if (child.HasAttribute("InitialTTL"))
InitialCacheTTL = ConfigUtilities.ParseTimeSpan(child.GetAttribute("InitialTTL"),
"Invalid time value for Caching.InitialTTL");
if (child.HasAttribute("MaximumTTL"))
MaximumCacheTTL = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaximumTTL"),
"Invalid time value for Caching.MaximumTTL");
if (child.HasAttribute("TTLExtensionFactor"))
CacheTTLExtensionFactor = ConfigUtilities.ParseDouble(child.GetAttribute("TTLExtensionFactor"),
"Invalid double value for Caching.TTLExtensionFactor");
if (CacheTTLExtensionFactor <= 1.0)
{
throw new FormatException("Caching.TTLExtensionFactor must be greater than 1.0");
}
if (child.HasAttribute("DirectoryCachingStrategy"))
DirectoryCachingStrategy = ConfigUtilities.ParseEnum<DirectoryCachingStrategyType>(child.GetAttribute("DirectoryCachingStrategy"),
"Invalid value for Caching.Strategy");
break;
case "Directory":
if (child.HasAttribute("DirectoryLazyDeregistrationDelay"))
{
DirectoryLazyDeregistrationDelay = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DirectoryLazyDeregistrationDelay"),
"Invalid time span value for Directory.DirectoryLazyDeregistrationDelay");
}
if (child.HasAttribute("ClientRegistrationRefresh"))
{
ClientRegistrationRefresh = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ClientRegistrationRefresh"),
"Invalid time span value for Directory.ClientRegistrationRefresh");
}
break;
default:
if (child.LocalName.Equals("GrainServices", StringComparison.Ordinal))
{
GrainServiceConfigurations = GrainServiceConfigurations.Load(child);
}
if (child.LocalName.EndsWith("Providers", StringComparison.Ordinal))
{
var providerCategory = ProviderCategoryConfiguration.Load(child);
if (ProviderConfigurations.ContainsKey(providerCategory.Name))
{
var existingCategory = ProviderConfigurations[providerCategory.Name];
existingCategory.Merge(providerCategory);
}
else
{
ProviderConfigurations.Add(providerCategory.Name, providerCategory);
}
}
break;
}
}
}
/// <summary>
/// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is bootstrap provider
/// </summary>
/// <typeparam name="T">Non-abstract type which implements <see cref="IBootstrapProvider"/> interface</typeparam>
/// <param name="providerName">Name of the bootstrap provider</param>
/// <param name="properties">Properties that will be passed to bootstrap provider upon initialization</param>
public void RegisterBootstrapProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : IBootstrapProvider
{
Type providerType = typeof(T);
var providerTypeInfo = providerType.GetTypeInfo();
if (providerTypeInfo.IsAbstract ||
providerTypeInfo.IsGenericType ||
!typeof(IBootstrapProvider).IsAssignableFrom(providerType))
throw new ArgumentException("Expected non-generic, non-abstract type which implements IBootstrapProvider interface", "typeof(T)");
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.BOOTSTRAP_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties);
}
/// <summary>
/// Registers a given bootstrap provider.
/// </summary>
/// <param name="providerTypeFullName">Full name of the bootstrap provider type</param>
/// <param name="providerName">Name of the bootstrap provider</param>
/// <param name="properties">Properties that will be passed to the bootstrap provider upon initialization </param>
public void RegisterBootstrapProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null)
{
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.BOOTSTRAP_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties);
}
/// <summary>
/// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is stream provider
/// </summary>
/// <typeparam name="T">Non-abstract type which implements <see cref="Orleans.Streams.IStreamProvider"/> stream</typeparam>
/// <param name="providerName">Name of the stream provider</param>
/// <param name="properties">Properties that will be passed to stream provider upon initialization</param>
public void RegisterStreamProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : Orleans.Streams.IStreamProvider
{
Type providerType = typeof(T);
var providerTypeInfo = providerType.GetTypeInfo();
if (providerTypeInfo.IsAbstract ||
providerTypeInfo.IsGenericType ||
!typeof(Orleans.Streams.IStreamProvider).IsAssignableFrom(providerType))
throw new ArgumentException("Expected non-generic, non-abstract type which implements IStreamProvider interface", "typeof(T)");
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerType.FullName, providerName, properties);
}
/// <summary>
/// Registers a given stream provider.
/// </summary>
/// <param name="providerTypeFullName">Full name of the stream provider type</param>
/// <param name="providerName">Name of the stream provider</param>
/// <param name="properties">Properties that will be passed to the stream provider upon initialization </param>
public void RegisterStreamProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null)
{
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties);
}
/// <summary>
/// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is storage provider
/// </summary>
/// <typeparam name="T">Non-abstract type which implements <see cref="IStorageProvider"/> storage</typeparam>
/// <param name="providerName">Name of the storage provider</param>
/// <param name="properties">Properties that will be passed to storage provider upon initialization</param>
public void RegisterStorageProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : IStorageProvider
{
Type providerType = typeof(T);
var providerTypeInfo = providerType.GetTypeInfo();
if (providerTypeInfo.IsAbstract ||
providerTypeInfo.IsGenericType ||
!typeof(IStorageProvider).IsAssignableFrom(providerType))
throw new ArgumentException("Expected non-generic, non-abstract type which implements IStorageProvider interface", "typeof(T)");
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STORAGE_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties);
}
/// <summary>
/// Registers a given storage provider.
/// </summary>
/// <param name="providerTypeFullName">Full name of the storage provider type</param>
/// <param name="providerName">Name of the storage provider</param>
/// <param name="properties">Properties that will be passed to the storage provider upon initialization </param>
public void RegisterStorageProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null)
{
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STORAGE_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties);
}
public void RegisterStatisticsProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : IStatisticsPublisher, ISiloMetricsDataPublisher
{
Type providerType = typeof(T);
var providerTypeInfo = providerType.GetTypeInfo();
if (providerTypeInfo.IsAbstract ||
providerTypeInfo.IsGenericType ||
!(
typeof(IStatisticsPublisher).IsAssignableFrom(providerType) &&
typeof(ISiloMetricsDataPublisher).IsAssignableFrom(providerType)
))
throw new ArgumentException("Expected non-generic, non-abstract type which implements IStatisticsPublisher, ISiloMetricsDataPublisher interface", "typeof(T)");
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STATISTICS_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties);
}
public void RegisterStatisticsProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null)
{
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STATISTICS_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties);
}
/// <summary>
/// Registers a given log-consistency provider.
/// </summary>
/// <param name="providerTypeFullName">Full name of the log-consistency provider type</param>
/// <param name="providerName">Name of the log-consistency provider</param>
/// <param name="properties">Properties that will be passed to the log-consistency provider upon initialization </param>
public void RegisterLogConsistencyProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null)
{
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.LOG_CONSISTENCY_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties);
}
/// <summary>
/// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is a log-consistency provider
/// </summary>
/// <typeparam name="T">Non-abstract type which implements <see cref="ILogConsistencyProvider"/> a log-consistency storage interface</typeparam>
/// <param name="providerName">Name of the log-consistency provider</param>
/// <param name="properties">Properties that will be passed to log-consistency provider upon initialization</param>
public void RegisterLogConsistencyProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : ILogConsistencyProvider
{
Type providerType = typeof(T);
var providerTypeInfo = providerType.GetTypeInfo();
if (providerTypeInfo.IsAbstract ||
providerTypeInfo.IsGenericType ||
!typeof(ILogConsistencyProvider).IsAssignableFrom(providerType))
throw new ArgumentException("Expected non-generic, non-abstract type which implements ILogConsistencyProvider interface", "typeof(T)");
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.LOG_CONSISTENCY_PROVIDER_CATEGORY_NAME, providerType.FullName, providerName, properties);
}
/// <summary>
/// Retrieves an existing provider configuration
/// </summary>
/// <param name="providerTypeFullName">Full name of the stream provider type</param>
/// <param name="providerName">Name of the stream provider</param>
/// <param name="config">The provider configuration, if exists</param>
/// <returns>True if a configuration for this provider already exists, false otherwise.</returns>
public bool TryGetProviderConfiguration(string providerTypeFullName, string providerName, out IProviderConfiguration config)
{
return ProviderConfigurationUtility.TryGetProviderConfiguration(ProviderConfigurations, providerTypeFullName, providerName, out config);
}
/// <summary>
/// Retrieves an enumeration of all currently configured provider configurations.
/// </summary>
/// <returns>An enumeration of all currently configured provider configurations.</returns>
public IEnumerable<IProviderConfiguration> GetAllProviderConfigurations()
{
return ProviderConfigurationUtility.GetAllProviderConfigurations(ProviderConfigurations);
}
public void RegisterGrainService(string serviceName, string serviceType, IDictionary<string, string> properties = null)
{
GrainServiceConfigurationsUtility.RegisterGrainService(GrainServiceConfigurations, serviceName, serviceType, properties);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
#if __UNIFIED__
using Foundation;
using UIKit;
using ObjCRuntime;
#else
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.ObjCRuntime;
using nuint = global::System.UInt32;
#endif
using MBProgressHUD;
using MonoTouch.Dialog;
namespace MBProgressHUDDemo
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow window;
UINavigationController navController;
DialogViewController dvcDialog;
MTMBProgressHUD hud;
// vars for managing NSUrlConnection Demo
public long expectedLength;
public nuint currentLength;
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
window = new UIWindow (UIScreen.MainScreen.Bounds);
var root = new RootElement("MBProgressHUD")
{
new Section ("Samples")
{
new StringElement ("Simple indeterminate progress", ShowSimple),
new StringElement ("With label", ShowWithLabel),
new StringElement ("With details label", ShowWithDetailsLabel),
new StringElement ("Determinate mode", ShowWithLabelDeterminate),
new StringElement ("Annular determinate mode", ShowWithLabelAnnularDeterminate),
new StringElement ("Horizontal determinate mode", ShowWithLabelDeterminateHorizontalBar),
new StringElement ("Custom view", ShowWithCustomView),
new StringElement ("Mode switching", ShowWithLabelMixed),
new StringElement ("Using handlers", ShowUsingHandlers),
new StringElement ("On Window", ShowOnWindow),
new StringElement ("NSURLConnection", ShowUrl),
new StringElement ("Dim background", ShowWithGradient),
new StringElement ("Text only", ShowTextOnly),
new StringElement ("Colored", ShowWithColor),
}
};
dvcDialog = new DialogViewController(UITableViewStyle.Grouped, root, false);
navController = new UINavigationController(dvcDialog);
window.RootViewController = navController;
window.MakeKeyAndVisible ();
return true;
}
#region Button Actions
void ShowSimple ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Show the HUD while the provided method executes in a new thread
hud.Show (new Selector("MyTask"), this, null, true);
}
void ShowWithLabel ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Loading";
// Show the HUD while the provided method executes in a new thread
hud.Show (new Selector ("MyTask"), this, null, true);
}
void ShowWithDetailsLabel ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Loading";
hud.DetailsLabelText = "updating data";
hud.Square = true;
// Show the HUD while the provided method executes in a new thread
hud.Show (new Selector ("MyTask"), this, null, true);
}
void ShowWithLabelDeterminate ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Set determinate mode
hud.Mode = MBProgressHUDMode.Determinate;
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Loading";
// Show the HUD while the provided method executes in a new thread
hud.Show (new Selector ("MyProgressTask"), this, null, true);
}
void ShowWithLabelAnnularDeterminate ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview(hud);
// Set determinate mode
hud.Mode = MBProgressHUDMode.AnnularDeterminate;
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Loading";
// Show the HUD while the provided method executes in a new thread
hud.Show (new Selector ("MyProgressTask"), this, null, true);
}
void ShowWithLabelDeterminateHorizontalBar ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview(hud);
// Set determinate mode
hud.Mode = MBProgressHUDMode.DeterminateHorizontalBar;
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Loading";
// Show the HUD while the provided method executes in a new thread
hud.Show (new Selector ("MyProgressTask"), this, null, true);
}
void ShowWithCustomView ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Set custom view mode
hud.Mode = MBProgressHUDMode.CustomView;
// The sample image is based on the work by http://www.pixelpressicons.com, http://creativecommons.org/licenses/by/2.5/ca/
// Make the customViews 37 by 37 pixels for best results (those are the bounds of the build-in progress indicators)
hud.CustomView = new UIImageView (UIImage.FromBundle ("37x-Checkmark.png"));
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Completed";
// Show the HUD
hud.Show(true);
// Hide the HUD after 3 seconds
hud.Hide (true, 3);
}
void ShowWithLabelMixed ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Connecting";
hud.MinSize = new System.Drawing.SizeF (135f, 135f);
// Show the HUD while the provided method executes in a new thread
hud.Show (new Selector ("MyMixedTask"), this, null, true);
}
void ShowUsingHandlers ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Add information to your HUD
hud.LabelText = "With a handler";
// We show the hud while executing MyTask, and then we clean up
hud.Show (true, () => {
MyTask();
}, () => {
hud.RemoveFromSuperview();
hud = null;
});
}
void ShowOnWindow ()
{
// The hud will dispable all input on the window
hud = new MTMBProgressHUD (window);
this.window.AddSubview (hud);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Loading";
// Show the HUD while the provided method executes in a new thread
hud.Show (new Selector ("MyTask"), this, null, true);
}
void ShowUrl ()
{
// Show the hud on top most view
hud = MTMBProgressHUD.ShowHUD (this.navController.View, true);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
NSUrl url = new NSUrl ("https://github.com/matej/MBProgressHUD/zipball/master");
NSUrlRequest request = new NSUrlRequest (url);
NSUrlConnection connection = new NSUrlConnection (request, new MyNSUrlConnectionDelegete (this, hud));
connection.Start();
}
void ShowWithGradient ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Set HUD to dim Background
hud.DimBackground = true;
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Show the HUD while the provided method executes in a new thread
hud.Show(new Selector ("MyTask"), this, null, true);
}
void ShowTextOnly ()
{
// Show the hud on top most view
hud = MTMBProgressHUD.ShowHUD (this.navController.View, true);
// Configure for text only and offset down
hud.Mode = MBProgressHUDMode.Text;
hud.LabelText = "Some message...";
hud.Margin = 10f;
hud.YOffset = 150f;
hud.RemoveFromSuperViewOnHide = true;
hud.Hide (true, 3);
}
void ShowWithColor ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Set the hud to display with a color
hud.Color = new UIColor (0.23f, 0.5f, 0.82f, 0.90f);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Show the HUD while the provided method executes in a new thread
hud.Show(new Selector ("MyTask"), this, null, true);
}
#endregion
#region fake tasks and Hide Handler
[Export ("MyTask")]
void MyTask ()
{
System.Threading.Thread.Sleep(3000);
}
[Export ("MyProgressTask")]
void MyProgressTask ()
{
float progress = 0.0f;
while (progress < 1.0f) {
progress += 0.01f;
hud.Progress = progress;
System.Threading.Thread.Sleep(50);
}
}
[Export ("MyMixedTask")]
void MyMixedTask ()
{
// Indeterminate mode
System.Threading.Thread.Sleep(2000);
// Switch to determinate mode
hud.Mode = MBProgressHUDMode.Determinate;
hud.LabelText = "Progress";
float progress = 0.0f;
while (progress < 1.0f)
{
progress += 0.01f;
hud.Progress = progress;
System.Threading.Thread.Sleep(50);
}
// Back to indeterminate mode
hud.Mode = MBProgressHUDMode.Indeterminate;
hud.LabelText = "Cleaning up";
System.Threading.Thread.Sleep(2000);
// The sample image is based on the work by www.pixelpressicons.com, http://creativecommons.org/licenses/by/2.5/ca/
// Make the customViews 37 by 37 pixels for best results (those are the bounds of the build-in progress indicators)
// Since HUD is already on screen, we must set It's custom vien on Main Thread
BeginInvokeOnMainThread ( ()=> {
hud.CustomView = new UIImageView (UIImage.FromBundle ("37x-Checkmark.png"));
});
hud.Mode = MBProgressHUDMode.CustomView;
hud.LabelText = "Completed";
System.Threading.Thread.Sleep (2000);
}
void HandleDidHide (object sender, EventArgs e)
{
hud.RemoveFromSuperview();
hud = null;
}
#endregion
}
}
| |
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 Sunny.Services.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;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet("New", "AzureRmContainerServiceConfig", SupportsShouldProcess = true)]
[OutputType(typeof(ContainerService))]
public class NewAzureRmContainerServiceConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
{
[Parameter(
Mandatory = false,
Position = 0,
ValueFromPipelineByPropertyName = true)]
public string Location { get; set; }
[Parameter(
Mandatory = false,
Position = 1,
ValueFromPipelineByPropertyName = true)]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
Position = 2,
ValueFromPipelineByPropertyName = true)]
public ContainerServiceOchestratorTypes? OrchestratorType { get; set; }
[Parameter(
Mandatory = false,
Position = 3,
ValueFromPipelineByPropertyName = true)]
public int? MasterCount { get; set; }
[Parameter(
Mandatory = false,
Position = 4,
ValueFromPipelineByPropertyName = true)]
public string MasterDnsPrefix { get; set; }
[Parameter(
Mandatory = false,
Position = 5,
ValueFromPipelineByPropertyName = true)]
public ContainerServiceAgentPoolProfile[] AgentPoolProfile { get; set; }
[Parameter(
Mandatory = false,
Position = 6,
ValueFromPipelineByPropertyName = true)]
public string WindowsProfileAdminUsername { get; set; }
[Parameter(
Mandatory = false,
Position = 7,
ValueFromPipelineByPropertyName = true)]
public string WindowsProfileAdminPassword { get; set; }
[Parameter(
Mandatory = false,
Position = 8,
ValueFromPipelineByPropertyName = true)]
public string AdminUsername { get; set; }
[Parameter(
Mandatory = false,
Position = 9,
ValueFromPipelineByPropertyName = true)]
public string[] SshPublicKey { get; set; }
[Parameter(
Mandatory = false,
Position = 10,
ValueFromPipelineByPropertyName = true)]
public bool VmDiagnosticsEnabled { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string CustomProfileOrchestrator { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string ServicePrincipalProfileClientId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string ServicePrincipalProfileSecret { get; set; }
protected override void ProcessRecord()
{
if (ShouldProcess("ContainerService", "New"))
{
Run();
}
}
private void Run()
{
// OrchestratorProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceOrchestratorProfile vOrchestratorProfile = null;
// CustomProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceCustomProfile vCustomProfile = null;
// ServicePrincipalProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceServicePrincipalProfile vServicePrincipalProfile = null;
// MasterProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile vMasterProfile = null;
// WindowsProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile vWindowsProfile = null;
// LinuxProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile vLinuxProfile = null;
// DiagnosticsProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceDiagnosticsProfile vDiagnosticsProfile = null;
if (this.OrchestratorType.HasValue)
{
if (vOrchestratorProfile == null)
{
vOrchestratorProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceOrchestratorProfile();
}
vOrchestratorProfile.OrchestratorType = this.OrchestratorType.Value;
}
if (this.CustomProfileOrchestrator != null)
{
if (vCustomProfile == null)
{
vCustomProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceCustomProfile();
}
vCustomProfile.Orchestrator = this.CustomProfileOrchestrator;
}
if (this.ServicePrincipalProfileClientId != null)
{
if (vServicePrincipalProfile == null)
{
vServicePrincipalProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceServicePrincipalProfile();
}
vServicePrincipalProfile.ClientId = this.ServicePrincipalProfileClientId;
}
if (this.ServicePrincipalProfileSecret != null)
{
if (vServicePrincipalProfile == null)
{
vServicePrincipalProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceServicePrincipalProfile();
}
vServicePrincipalProfile.Secret = this.ServicePrincipalProfileSecret;
}
if (this.MasterCount != null)
{
if (vMasterProfile == null)
{
vMasterProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile();
}
vMasterProfile.Count = this.MasterCount;
}
if (this.MasterDnsPrefix != null)
{
if (vMasterProfile == null)
{
vMasterProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile();
}
vMasterProfile.DnsPrefix = this.MasterDnsPrefix;
}
if (this.WindowsProfileAdminUsername != null)
{
if (vWindowsProfile == null)
{
vWindowsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile();
}
vWindowsProfile.AdminUsername = this.WindowsProfileAdminUsername;
}
if (this.WindowsProfileAdminPassword != null)
{
if (vWindowsProfile == null)
{
vWindowsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile();
}
vWindowsProfile.AdminPassword = this.WindowsProfileAdminPassword;
}
if (this.AdminUsername != null)
{
if (vLinuxProfile == null)
{
vLinuxProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile();
}
vLinuxProfile.AdminUsername = this.AdminUsername;
}
if (this.SshPublicKey != null)
{
if (vLinuxProfile == null)
{
vLinuxProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile();
}
if (vLinuxProfile.Ssh == null)
{
vLinuxProfile.Ssh = new Microsoft.Azure.Management.Compute.Models.ContainerServiceSshConfiguration();
}
if (vLinuxProfile.Ssh.PublicKeys == null)
{
vLinuxProfile.Ssh.PublicKeys = new List<Microsoft.Azure.Management.Compute.Models.ContainerServiceSshPublicKey>();
}
foreach (var element in this.SshPublicKey)
{
var vPublicKeys = new Microsoft.Azure.Management.Compute.Models.ContainerServiceSshPublicKey();
vPublicKeys.KeyData = element;
vLinuxProfile.Ssh.PublicKeys.Add(vPublicKeys);
}
}
if (vDiagnosticsProfile == null)
{
vDiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceDiagnosticsProfile();
}
if (vDiagnosticsProfile.VmDiagnostics == null)
{
vDiagnosticsProfile.VmDiagnostics = new Microsoft.Azure.Management.Compute.Models.ContainerServiceVMDiagnostics();
}
vDiagnosticsProfile.VmDiagnostics.Enabled = this.VmDiagnosticsEnabled;
var vContainerService = new ContainerService
{
Location = this.Location,
Tags = (this.Tag == null) ? null : this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value),
AgentPoolProfiles = this.AgentPoolProfile,
OrchestratorProfile = vOrchestratorProfile,
CustomProfile = vCustomProfile,
ServicePrincipalProfile = vServicePrincipalProfile,
MasterProfile = vMasterProfile,
WindowsProfile = vWindowsProfile,
LinuxProfile = vLinuxProfile,
DiagnosticsProfile = vDiagnosticsProfile,
};
WriteObject(vContainerService);
}
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System.Collections;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net.Sockets
{
public partial class Socket
{
private DynamicWinsockMethods _dynamicWinsockMethods;
internal void ReplaceHandleIfNecessaryAfterFailedConnect() { /* nop on Windows */ }
private void EnsureDynamicWinsockMethods()
{
if (_dynamicWinsockMethods == null)
{
_dynamicWinsockMethods = DynamicWinsockMethods.GetMethods(_addressFamily, _socketType, _protocolType);
}
}
internal unsafe bool AcceptEx(SafeCloseSocket listenSocketHandle,
SafeCloseSocket acceptSocketHandle,
IntPtr buffer,
int len,
int localAddressLength,
int remoteAddressLength,
out int bytesReceived,
NativeOverlapped* overlapped)
{
EnsureDynamicWinsockMethods();
AcceptExDelegate acceptEx = _dynamicWinsockMethods.GetDelegate<AcceptExDelegate>(listenSocketHandle);
return acceptEx(listenSocketHandle,
acceptSocketHandle,
buffer,
len,
localAddressLength,
remoteAddressLength,
out bytesReceived,
overlapped);
}
internal void GetAcceptExSockaddrs(IntPtr buffer,
int receiveDataLength,
int localAddressLength,
int remoteAddressLength,
out IntPtr localSocketAddress,
out int localSocketAddressLength,
out IntPtr remoteSocketAddress,
out int remoteSocketAddressLength)
{
EnsureDynamicWinsockMethods();
GetAcceptExSockaddrsDelegate getAcceptExSockaddrs = _dynamicWinsockMethods.GetDelegate<GetAcceptExSockaddrsDelegate>(_handle);
getAcceptExSockaddrs(buffer,
receiveDataLength,
localAddressLength,
remoteAddressLength,
out localSocketAddress,
out localSocketAddressLength,
out remoteSocketAddress,
out remoteSocketAddressLength);
}
internal unsafe bool DisconnectEx(SafeCloseSocket socketHandle, NativeOverlapped* overlapped, int flags, int reserved)
{
EnsureDynamicWinsockMethods();
DisconnectExDelegate disconnectEx = _dynamicWinsockMethods.GetDelegate<DisconnectExDelegate>(socketHandle);
return disconnectEx(socketHandle, overlapped, flags, reserved);
}
internal bool DisconnectExBlocking(SafeCloseSocket socketHandle, IntPtr overlapped, int flags, int reserved)
{
EnsureDynamicWinsockMethods();
DisconnectExDelegateBlocking disconnectEx_Blocking = _dynamicWinsockMethods.GetDelegate<DisconnectExDelegateBlocking>(socketHandle);
return disconnectEx_Blocking(socketHandle, overlapped, flags, reserved);
}
internal unsafe bool ConnectEx(SafeCloseSocket socketHandle,
IntPtr socketAddress,
int socketAddressSize,
IntPtr buffer,
int dataLength,
out int bytesSent,
NativeOverlapped* overlapped)
{
EnsureDynamicWinsockMethods();
ConnectExDelegate connectEx = _dynamicWinsockMethods.GetDelegate<ConnectExDelegate>(socketHandle);
return connectEx(socketHandle, socketAddress, socketAddressSize, buffer, dataLength, out bytesSent, overlapped);
}
internal unsafe SocketError WSARecvMsg(SafeCloseSocket socketHandle, IntPtr msg, out int bytesTransferred, NativeOverlapped* overlapped, IntPtr completionRoutine)
{
EnsureDynamicWinsockMethods();
WSARecvMsgDelegate recvMsg = _dynamicWinsockMethods.GetDelegate<WSARecvMsgDelegate>(socketHandle);
return recvMsg(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
}
internal SocketError WSARecvMsgBlocking(IntPtr socketHandle, IntPtr msg, out int bytesTransferred, IntPtr overlapped, IntPtr completionRoutine)
{
EnsureDynamicWinsockMethods();
WSARecvMsgDelegateBlocking recvMsg_Blocking = _dynamicWinsockMethods.GetDelegate<WSARecvMsgDelegateBlocking>(_handle);
return recvMsg_Blocking(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
}
internal unsafe bool TransmitPackets(SafeCloseSocket socketHandle, IntPtr packetArray, int elementCount, int sendSize, NativeOverlapped* overlapped, TransmitFileOptions flags)
{
EnsureDynamicWinsockMethods();
TransmitPacketsDelegate transmitPackets = _dynamicWinsockMethods.GetDelegate<TransmitPacketsDelegate>(socketHandle);
return transmitPackets(socketHandle, packetArray, elementCount, sendSize, overlapped, flags);
}
internal static IntPtr[] SocketListToFileDescriptorSet(IList socketList)
{
if (socketList == null || socketList.Count == 0)
{
return null;
}
IntPtr[] fileDescriptorSet = new IntPtr[socketList.Count + 1];
fileDescriptorSet[0] = (IntPtr)socketList.Count;
for (int current = 0; current < socketList.Count; current++)
{
if (!(socketList[current] is Socket))
{
throw new ArgumentException(SR.Format(SR.net_sockets_select, socketList[current].GetType().FullName, typeof(System.Net.Sockets.Socket).FullName), nameof(socketList));
}
fileDescriptorSet[current + 1] = ((Socket)socketList[current])._handle.DangerousGetHandle();
}
return fileDescriptorSet;
}
// Transform the list socketList such that the only sockets left are those
// with a file descriptor contained in the array "fileDescriptorArray".
internal static void SelectFileDescriptor(IList socketList, IntPtr[] fileDescriptorSet)
{
// Walk the list in order.
//
// Note that the counter is not necessarily incremented at each step;
// when the socket is removed, advancing occurs automatically as the
// other elements are shifted down.
if (socketList == null || socketList.Count == 0)
{
return;
}
if ((int)fileDescriptorSet[0] == 0)
{
// No socket present, will never find any socket, remove them all.
socketList.Clear();
return;
}
lock (socketList)
{
for (int currentSocket = 0; currentSocket < socketList.Count; currentSocket++)
{
Socket socket = socketList[currentSocket] as Socket;
// Look for the file descriptor in the array.
int currentFileDescriptor;
for (currentFileDescriptor = 0; currentFileDescriptor < (int)fileDescriptorSet[0]; currentFileDescriptor++)
{
if (fileDescriptorSet[currentFileDescriptor + 1] == socket._handle.DangerousGetHandle())
{
break;
}
}
if (currentFileDescriptor == (int)fileDescriptorSet[0])
{
// Descriptor not found: remove the current socket and start again.
socketList.RemoveAt(currentSocket--);
}
}
}
}
private Socket GetOrCreateAcceptSocket(Socket acceptSocket, bool checkDisconnected, string propertyName, out SafeCloseSocket handle)
{
// If an acceptSocket isn't specified, then we need to create one.
if (acceptSocket == null)
{
acceptSocket = new Socket(_addressFamily, _socketType, _protocolType);
}
else if (acceptSocket._rightEndPoint != null && (!checkDisconnected || !acceptSocket._isDisconnected))
{
throw new InvalidOperationException(SR.Format(SR.net_sockets_namedmustnotbebound, propertyName));
}
handle = acceptSocket._handle;
return acceptSocket;
}
private void SendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
{
// Open the file, if any
FileStream fileStream = OpenFile(fileName);
SocketError errorCode;
using (fileStream)
{
SafeFileHandle fileHandle = fileStream?.SafeFileHandle;
// This can throw ObjectDisposedException.
errorCode = SocketPal.SendFile(_handle, fileHandle, preBuffer, postBuffer, flags);
}
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
// If the user passed the Disconnect and/or ReuseSocket flags, then TransmitFile disconnected the socket.
// Update our state to reflect this.
if ((flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0)
{
SetToDisconnected();
_remoteEndPoint = null;
}
}
private IAsyncResult BeginSendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
{
FileStream fileStream = OpenFile(fileName);
TransmitFileAsyncResult asyncResult = new TransmitFileAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
SocketError errorCode = SocketPal.SendFileAsync(_handle, fileStream, preBuffer, postBuffer, flags, asyncResult);
// Check for synchronous exception
if (!CheckErrorAndUpdateStatus(errorCode))
{
throw new SocketException((int)errorCode);
}
asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
return asyncResult;
}
private void EndSendFileInternal(IAsyncResult asyncResult)
{
TransmitFileAsyncResult castedAsyncResult = asyncResult as TransmitFileAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndSendFile"));
}
castedAsyncResult.InternalWaitForCompletion();
castedAsyncResult.EndCalled = true;
// If the user passed the Disconnect and/or ReuseSocket flags, then TransmitFile disconnected the socket.
// Update our state to reflect this.
if (castedAsyncResult.DoDisconnect)
{
SetToDisconnected();
_remoteEndPoint = null;
}
if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException((SocketError)castedAsyncResult.ErrorCode);
}
}
internal ThreadPoolBoundHandle GetOrAllocateThreadPoolBoundHandle()
{
// There is a known bug that exists through Windows 7 with UDP and
// SetFileCompletionNotificationModes.
// So, don't try to enable skipping the completion port on success in this case.
bool trySkipCompletionPortOnSuccess = !(CompletionPortHelper.PlatformHasUdpIssue && _protocolType == ProtocolType.Udp);
return _handle.GetOrAllocateThreadPoolBoundHandle(trySkipCompletionPortOnSuccess);
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 the Outercurve Foundation 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 HOLDER 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.Data;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using Microsoft.Web.Services3;
namespace WebsitePanel.EnterpriseServer
{
/// <summary>
/// Summary description for esApplicationsInstaller
/// </summary>
[WebService(Namespace = "http://smbsaas/websitepanel/enterpriseserver")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Policy("ServerPolicy")]
[ToolboxItem(false)]
public class esUsers : System.Web.Services.WebService
{
[WebMethod(Description = "Checks if the account with the specified username exists.")]
public bool UserExists(string username)
{
return UserController.UserExists(username);
}
[WebMethod]
public UserInfo GetUserById(int userId)
{
UserInfoInternal uinfo = UserController.GetUser(userId);
return (uinfo != null) ? new UserInfo(uinfo) : null;
}
[WebMethod]
public UserInfo GetUserByUsername(string username)
{
UserInfoInternal uinfo = UserController.GetUser(username);
return (uinfo != null) ? new UserInfo(uinfo) : null;
}
[WebMethod]
public List<UserInfo> GetUsers(int ownerId, bool recursive)
{
return UserController.GetUsers(ownerId, recursive);
}
[WebMethod]
public void AddUserVLan(int userId, UserVlan vLan)
{
UserController.AddUserVLan(userId, vLan);
}
[WebMethod]
public void DeleteUserVLan(int userId, ushort vLanId)
{
UserController.DeleteUserVLan(userId, vLanId);
}
[WebMethod]
public DataSet GetRawUsers(int ownerId, bool recursive)
{
return UserController.GetRawUsers(ownerId, recursive);
}
[WebMethod]
public DataSet GetUsersPaged(int userId, string filterColumn, string filterValue,
int statusId, int roleId, string sortColumn, int startRow, int maximumRows)
{
return UserController.GetUsersPaged(userId, filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows);
}
[WebMethod]
public DataSet GetUsersPagedRecursive(int userId, string filterColumn, string filterValue,
int statusId, int roleId, string sortColumn, int startRow, int maximumRows)
{
return UserController.GetUsersPagedRecursive(userId, filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows);
}
[WebMethod]
public DataSet GetUsersSummary(int userId)
{
return UserController.GetUsersSummary(userId);
}
[WebMethod]
public DataSet GetUserDomainsPaged(int userId, string filterColumn, string filterValue,
string sortColumn, int startRow, int maximumRows)
{
return UserController.GetUserDomainsPaged(userId, filterColumn, filterValue, sortColumn, startRow, maximumRows);
}
[WebMethod]
public DataSet GetRawUserPeers(int userId)
{
return UserController.GetRawUserPeers(userId);
}
[WebMethod]
public List<UserInfo> GetUserPeers(int userId)
{
return UserController.GetUserPeers(userId);
}
[WebMethod]
public List<UserInfo> GetUserParents(int userId)
{
return UserController.GetUserParents(userId);
}
[WebMethod]
public int AddUser(UserInfo user, bool sendLetter, string password)
{
return UserController.AddUser(user, sendLetter, password);
}
[WebMethod]
public int AddUserLiteral(
int ownerId,
int roleId,
int statusId,
bool isPeer,
bool isDemo,
string username,
string password,
string firstName,
string lastName,
string email,
string secondaryEmail,
string address,
string city,
string country,
string state,
string zip,
string primaryPhone,
string secondaryPhone,
string fax,
string instantMessenger,
bool htmlMail,
string companyName,
bool ecommerceEnabled,
bool sendLetter)
{
UserInfo user = new UserInfo();
user.OwnerId = ownerId;
user.RoleId = roleId;
user.StatusId = statusId;
user.IsPeer = isPeer;
user.IsDemo = isDemo;
user.Username = username;
// user.Password = password;
user.FirstName = firstName;
user.LastName = lastName;
user.Email = email;
user.SecondaryEmail = secondaryEmail;
user.Address = address;
user.City = city;
user.Country = country;
user.State = state;
user.Zip = zip;
user.PrimaryPhone = primaryPhone;
user.SecondaryPhone = secondaryPhone;
user.Fax = fax;
user.InstantMessenger = instantMessenger;
user.HtmlMail = htmlMail;
user.CompanyName = companyName;
user.EcommerceEnabled = ecommerceEnabled;
return UserController.AddUser(user, sendLetter, password);
}
[WebMethod]
public int UpdateUserTask(string taskId, UserInfo user)
{
return UserController.UpdateUser(taskId, user);
}
[WebMethod]
public int UpdateUserTaskAsynchronously(string taskId, UserInfo user)
{
return UserController.UpdateUserAsync(taskId, user);
}
[WebMethod]
public int UpdateUser(UserInfo user)
{
return UserController.UpdateUser(user);
}
[WebMethod]
public int UpdateUserLiteral(int userId,
int roleId,
int statusId,
bool isPeer,
bool isDemo,
string firstName,
string lastName,
string email,
string secondaryEmail,
string address,
string city,
string country,
string state,
string zip,
string primaryPhone,
string secondaryPhone,
string fax,
string instantMessenger,
bool htmlMail,
string companyName,
bool ecommerceEnabled)
{
UserInfo user = new UserInfo();
user.UserId = userId;
user.RoleId = roleId;
user.StatusId = statusId;
user.IsPeer = isPeer;
user.IsDemo = isDemo;
user.FirstName = firstName;
user.LastName = lastName;
user.Email = email;
user.SecondaryEmail = secondaryEmail;
user.Address = address;
user.City = city;
user.Country = country;
user.State = state;
user.Zip = zip;
user.PrimaryPhone = primaryPhone;
user.SecondaryPhone = secondaryPhone;
user.Fax = fax;
user.InstantMessenger = instantMessenger;
user.HtmlMail = htmlMail;
user.CompanyName = companyName;
user.EcommerceEnabled = ecommerceEnabled;
return UserController.UpdateUser(user);
}
[WebMethod]
public int DeleteUser(int userId)
{
return UserController.DeleteUser(userId);
}
[WebMethod]
public int ChangeUserPassword(int userId, string password)
{
return UserController.ChangeUserPassword(userId, password);
}
[WebMethod]
public int ChangeUserStatus(int userId, UserStatus status)
{
return UserController.ChangeUserStatus(userId, status);
}
#region User Settings
[WebMethod]
public UserSettings GetUserSettings(int userId, string settingsName)
{
return UserController.GetUserSettings(userId, settingsName);
}
[WebMethod]
public int UpdateUserSettings(UserSettings settings)
{
return UserController.UpdateUserSettings(settings);
}
#endregion
}
}
| |
/*
* Copyright (c) 2015, iLearnRW. Licensed under Modified BSD Licence. See licence.txt for details.
*/using UnityEngine;
using System.Collections.Generic;
public class AcDropChopScenarioV2 : ILearnRWActivityScenario, CustomActionListener
{
public Transform textPlanePrefab;
public Transform splitDetectorPrefab;
public Transform[] itemToSplitPrefabArr;
public Transform[] crackPrefabArr;
public Transform framePrefab;
public Transform sfxPrefab;
public Transform sparksPrefab;
public Transform scalableGlowPrefab;
public Transform planePrefab;
public Transform skeletonSwipeHandPrefab;
public Transform nettingPrefab;
public Transform blockToObjectEffect;
public Transform[] oneSyllPrefabs;
public Transform[] twoSyllPrefabs;
public Transform[] threeSyllPrefabs;
public Transform[] fourSyllPrefabs;
public Transform[] fiveSyllPrefabs;
public bool showSparksEffect;
SJLevelConfig currLvlConfig;
SJWordItem currWordItem;
Dictionary<int,SJWordItem> wordItemCache;
int gridWidthInCells = 11;//17;
int gridHeightInCells = 6;
int numPrequelRows = 1;
float borderThicknessPerc = 0f;//0.1f;
GridProperties dropGrid_GuiGProp;
GridProperties dropGrid_WorldGProp;
string conveyorWordObjID;
HashSet<string> conveyorWordGObjLookup;
int nxtWordID = 1;
int[,] gridState;
string[,] debugGridState;
string currConvWordBeingDropped;
HashSet<string> droppingWords;
HashSet<string> stationaryWords;
Dictionary<string,TetrisInfo> tetrisInfMap;
Dictionary<int,string> numIDToStrIDMap;
Dictionary<string,string> blockToWDataMap;
float wordDropStepTimerStart_Sec;
float wordDropStepTime_Sec = 0.1f;
bool conveyorOpen;
bool updateStationaryBlocks;
bool playItemCollideSound;
bool performLineCheck = false;
List<GameObject> cracksGObjs;
float growScale;
List<string> orderedFullySplitConvObjNames;
int nxtIndexForOp;
bool isPerformingPositioningSequence = false;
bool isInAutoSplitMode;
string itemForAutoSplit;
List<int> syllsForAutoSplit;
List<int> splitsDoneByGame;
Color unmovableBlockColor = new Color(0.2f,0.16f,0.16f,1f);
bool isWaitingForConveyorRowClearence;
bool playerHasLost = false;
bool chuteBusy = false;
float wordChopTimerDuration_Sec = 30;
List<GameObject> objsToUnPause;
bool pause = false;
bool[] upAxisArr = new bool[3] {false,true,false};
//int maxAttemptsPerConveyorWord = 3;
bool[] conWordAttemptsStates;
int currNumOfWordsDone = 0;
int reqNumOfWordsDone; // Initialised when generator is initalised below.
int numHooveredLines = 0;
int numCorrectWordSplits = 0;
int numIncorrectWordSplits = 0;
List<int> playerSplitPattern;
bool wordUnattempted = true;
bool whistleVisible = false;
bool firstTimeFlag = true;
void Start()
{
acID = ApplicationID.DROP_CHOPS;
loadActivitySessionMetaData();
this.loadTextures();
prepUIBounds();
initWorld();
this.initLevelConfigGenerator();
reqNumOfWordsDone = lvlConfigGen.getConfigCount();
genNextLevel();
showInfoSlideshow();
initPersonHelperPortraitPic();
recordActivityStart();
}
void Update()
{
if(isInitialised)
{
if( ! pause)
{
// Move existing blocks down:
//int nwLineToClear = -1;
//bool moveMade = false;
//bool cameToRestOccurred = false;
HashSet<string> nwStationaryBlocks = new HashSet<string>();
HashSet<string> nwDestroyedBlocks = new HashSet<string>();
HashSet<string> nwDroppingBlocks = new HashSet<string>();
if((Time.time - wordDropStepTimerStart_Sec) > wordDropStepTime_Sec)
{
List<string> blocksToCheck = new List<string>();
blocksToCheck.AddRange(droppingWords);
if(updateStationaryBlocks)
{
blocksToCheck.AddRange(stationaryWords);
}
bool changeOccurred = false;
Vector3 movDownVect = new Vector3(0,-(dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness),0);
for(int i=0; i<blocksToCheck.Count; i++)
{
//Debug.Log("ToCheck: "+blocksToCheck[i]);
if(tetrisInfMap.ContainsKey(blocksToCheck[i]))
{
TetrisInfo tInfo = tetrisInfMap[blocksToCheck[i]];
int nwRow = tInfo.coords[1]+1;
if(nwRow < (gridState.GetLength(1)+1))
{
bool canMoveDown = true;
if(nwRow >= gridState.GetLength(1))
{
canMoveDown = false;
}
else
{
for(int x=tInfo.coords[0]; x<(tInfo.coords[0]+tInfo.wordSize); x++)
{
if(gridState[x,nwRow] != 0)
{
canMoveDown = false;
break;
}
}
}
if(canMoveDown)
{
GameObject reqGObj = GameObject.Find(blocksToCheck[i]);
reqGObj.transform.Translate(movDownVect);
for(int x=tInfo.coords[0]; x<(tInfo.coords[0]+tInfo.wordSize); x++)
{
gridState[x,tInfo.coords[1]] = 0;
gridState[x,nwRow] = tInfo.id;
debugGridState[x,tInfo.coords[1]] = "0";
debugGridState[x,nwRow] = ""+tInfo.id;
}
tInfo.coords[1] = nwRow;
tetrisInfMap[blocksToCheck[i]] = tInfo;
if(stationaryWords.Contains(blocksToCheck[i]))
{
nwDroppingBlocks.Add(blocksToCheck[i]);
}
changeOccurred = true;
//moveMade = true;
}
else
{
//cameToRestOccurred = true;
if( ! stationaryWords.Contains(blocksToCheck[i]))
{
nwStationaryBlocks.Add(blocksToCheck[i]);
performLineCheck = true;
playItemCollideSound = true;
}
}
}
}
}
if( ! changeOccurred)
{
if(!isWaitingForConveyorRowClearence)
{
updateStationaryBlocks = false;
if(!playerHasLost)
{
checkNHandleLosingCondition();
}
}
}
if( ! changeOccurred)
{
if(isPerformingPositioningSequence)
{
if(nxtIndexForOp < orderedFullySplitConvObjNames.Count)
{
if(isRowFree(0))
{
isWaitingForConveyorRowClearence = false;
moveNextBlockToGrid();
}
}
}
}
wordDropStepTimerStart_Sec = Time.time;
}
foreach(string deletedItem in nwDestroyedBlocks)
{
droppingWords.Remove(deletedItem);
}
foreach(string dItem in nwDroppingBlocks)
{
if(!droppingWords.Contains(dItem))
{
droppingWords.Add(dItem);
}
stationaryWords.Remove(dItem);
}
foreach(string statItem in nwStationaryBlocks)
{
if(!stationaryWords.Contains(statItem))
{
stationaryWords.Add(statItem);
}
droppingWords.Remove(statItem);
}
if(performLineCheck)
{
int lineToClear = searchForLinesToClear();
if(lineToClear != -1)
{
performClearLineEffect(lineToClear);
updateStationaryBlocks = true;
numHooveredLines++;
}
performLineCheck = false;
}
// Check if Conveyor is free.
if(! chuteBusy)
{
if(conveyorWordGObjLookup.Count == 0)
{
if((isRowFree(0)))//&&(isRowFree(1)))
{
conveyorOpen = true;
}
}
}
// Conveyor Script. When the current block is at rest, send the next block down.
if(conveyorOpen)
{
if( ! droppingWords.Contains(currConvWordBeingDropped))
{
if(conveyorOpen)
{
currNumOfWordsDone++;
genNextLevel();
}
}
}
if(playItemCollideSound) { triggerSoundAtCamera("Blop"); playItemCollideSound = false; }
}// end of pause bracket.
}// end of isInitialised bracket.
}
void OnGUI()
{
if( ! pause)
{
if(whistleVisible)
{
GUI.color = Color.clear;
if(GUI.Button(uiBounds["WhistleIcon"],""))
{
triggerSoundAtCamera("whistle1");
getDeliveryChuteScript().hurryUp();
setWhistleVisibility(false);
}
}
GUI.color = Color.clear;
if(uiBounds.ContainsKey("PauseBtn"))
{
if(GUI.Button(uiBounds["PersonPortrait"],""))
{
showPersonHelperWindow();
}
if(GUI.Button(uiBounds["PauseBtn"],""))
{
showActivityPauseWindow();
}
}
}
/*// Debugging: Display Grid State:
for(int r=0; r<debugGridState.GetLength(1); r++)
{
for(int c=0; c<debugGridState.GetLength(0); c++)
{
if(debugGridState[c,r] != "0") { GUI.color = Color.black; } else { GUI.color = Color.white; }
GUI.Label(new Rect((c * 20f),(r * 20),200,20),debugGridState[c,r]);
GUI.color = Color.white;
}
}*/
}
protected override void initWorld()
{
// Auto Adjust.
GameObject tmpPersonPortrait = GameObject.Find("PersonPortrait");
GameObject tmpPauseButton = GameObject.Find("PauseButton");
GameObject tmpBackdrop = GameObject.Find("Background").gameObject;
SpawnNormaliser.adjustGameObjectsToNwBounds(SpawnNormaliser.get2DBounds(tmpBackdrop.renderer.bounds),
WorldSpawnHelper.getCameraViewWorldBounds(tmpBackdrop.transform.position.z,true),
new List<GameObject>() { tmpPersonPortrait, tmpPauseButton });
//tmpExitBtnObj.transform.parent = Camera.main.transform;
tmpPersonPortrait.transform.parent = GameObject.Find("Main Camera").transform;
tmpPauseButton.transform.parent = GameObject.Find("Main Camera").transform;
uiBounds.Add("PersonPortrait",WorldSpawnHelper.getWorldToGUIBounds(tmpPersonPortrait.renderer.bounds,upAxisArr));
uiBounds.Add("PauseBtn",WorldSpawnHelper.getWorldToGUIBounds(tmpPauseButton.renderer.bounds,upAxisArr));
// Mechanics Vars Init:
// (1) Junk Grid:
int totalRows = (gridHeightInCells+numPrequelRows);
gridState = new int[gridWidthInCells,totalRows];
debugGridState = new string[gridWidthInCells,totalRows];
for(int r=0; r<totalRows; r++)
{
for(int c=0; c<gridWidthInCells; c++)
{
gridState[c,r] = 0;
debugGridState[c,r] = "0";
}
}
currConvWordBeingDropped = "";
droppingWords = new HashSet<string>();
stationaryWords = new HashSet<string>();
tetrisInfMap = new Dictionary<string, TetrisInfo>();
numIDToStrIDMap = new Dictionary<int, string>();
blockToWDataMap = new Dictionary<string, string>();
wordItemCache = new Dictionary<int, SJWordItem>();
wordDropStepTimerStart_Sec = Time.time;
conveyorOpen = true;
updateStationaryBlocks = false;
GameObject mainPitGObj = GameObject.Find("MainPit");
//Vector3 mainPitTopLeft = new Vector3(mainPitGObj.transform.position.x - (mainPitGObj.renderer.bounds.size.x/2f),
// mainPitGObj.transform.position.y + (mainPitGObj.renderer.bounds.size.y/2f),
// mainPitGObj.transform.position.z);
//dropGrid_WorldGProp = new GridProperties(dropMainGridBox_world,gridWidthInCells,gridHeightInCells,borderThicknessPerc,mainPitGObj.transform.position.z);
//dropGrid_WorldGProp = new GridProperties(new float[] {mainPitTopLeft.x,mainPitTopLeft.y,mainPitTopLeft.z},borderThicknessPerc,0.72f,0.72f,gridWidthInCells,gridHeightInCells);
// Height is fixed.
float reqHeightForCell = mainPitGObj.renderer.bounds.size.y/(gridHeightInCells * 1.0f);
float reqWidthForCell = reqHeightForCell;
float reqTotalWidthForGrid = reqWidthForCell * (gridWidthInCells * 1.0f);
float reqTotalHeightForGrid = reqHeightForCell * (gridHeightInCells * 1.0f);
Vector3 tmpLocalScale = mainPitGObj.transform.localScale;
tmpLocalScale.x *= reqTotalWidthForGrid/mainPitGObj.renderer.bounds.size.x;
tmpLocalScale.y *= reqTotalHeightForGrid/mainPitGObj.renderer.bounds.size.y;
//tmpLocalScale.z = tmpLocalScale.z;
mainPitGObj.transform.localScale = tmpLocalScale;
Rect dropMainGridBox_world = CommonUnityUtils.get2DBounds(mainPitGObj.renderer.bounds);
dropGrid_WorldGProp = new GridProperties(dropMainGridBox_world,gridWidthInCells,gridHeightInCells,borderThicknessPerc,mainPitGObj.transform.position.z);
GridRenderer.createGridRender(dropGrid_WorldGProp,planePrefab,upAxisArr);
createRandomStartGrid();
// (2) Other vars:
conveyorWordObjID = null;
conveyorWordGObjLookup = new HashSet<string>();
cracksGObjs = new List<GameObject>();
playItemCollideSound = false;
conWordAttemptsStates = new bool[3] {false,false,false};
isInAutoSplitMode = false;
itemForAutoSplit = null;
syllsForAutoSplit = null;
splitsDoneByGame = new List<int>();
playerSplitPattern = new List<int>();
isWaitingForConveyorRowClearence = false;
wordDropStepTimerStart_Sec = Time.time;
getChopTimerScript().setVisibilityState(false);
PlayerBlockMovementScript pbms = transform.gameObject.GetComponent<PlayerBlockMovementScript>();
pbms.init();
LineDragActiveNDraw ldand = (GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>());
ldand.init(WorldSpawnHelper.getWorldToGUIBounds(GameObject.Find("Background").renderer.bounds,upAxisArr),
0.1f,dropGrid_WorldGProp.z,dropGrid_WorldGProp.z,"SplitDetect",0);
ldand.registerListener("AcScen",this);
ldand.setPause(true);
ScoreBoardScript sbs = getScoreBoardScript();
sbs.reset();
updateLineCounterDisplay();
setWhistleVisibility(false);
SoundOptionsDisplay sod = GameObject.Find("GlobObj").GetComponent<SoundOptionsDisplay>();
sod.registerListener("AcScen",this);
}
protected override void genNextLevel()
{
// Perhaps we will need to add a error message if the config list was empty.
bool winFlag = checkNHandleWinningCondition();
if( ! winFlag)
{
if( ! firstTimeFlag)
{
conveyorOpen = false;
chuteBusy = true;
currLvlConfig = (SJLevelConfig) lvlConfigGen.getNextLevelConfig(null);
wordItemCache.Add(currLvlConfig.getWordItem().getID(),currLvlConfig.getWordItem());
wordChopTimerDuration_Sec = 10f*(3-currLvlConfig.getSpeed());
if(serverCommunication != null) { serverCommunication.wordDisplayed(currLvlConfig.getWordItem().getWordAsString(),currLvlConfig.getWordItem().languageArea,currLvlConfig.getWordItem().difficulty); }
playerSplitPattern = new List<int>();
openGate();
resetAttempts();
triggerChuteToFetchAndReturnWord();
}
}
}
protected new bool initLevelConfigGenerator()
{
if( ! base.initLevelConfigGenerator())
{
// Fallback.
lvlConfigGen = new SJLevelConfigGeneratorServer(null); //new SJLevelConfigGeneratorHardCoded();
Debug.LogWarning("Warning: Using Level Gen Fallback");
}
return true;
}
protected override bool checkNHandleWinningCondition()
{
updateActivityProgressMetaData(currNumOfWordsDone/(reqNumOfWordsDone*1.0f));
if(currNumOfWordsDone >= reqNumOfWordsDone)
{
pauseScene(true);
performDefaultWinProcedure();
return true;
}
return false;
}
protected override bool checkNHandleLosingCondition()
{
playerHasLost = !(isRowFree(numPrequelRows-1,true));
if(playerHasLost)
{
pauseScene(true);
performDefaultLoseProcedure();
return true;
}
return false;
}
protected override void buildNRecordConfigOutcome(System.Object[] para_extraParams)
{
// Build outcome object.
bool positiveFlag = (bool) para_extraParams[0];
// Trigger record outcome.
SJLevelOutcome reqOutcomeObj = null;
if(positiveFlag)
{
reqOutcomeObj = new SJLevelOutcome(true);
}
else
{
reqOutcomeObj = new SJLevelOutcome(false,playerSplitPattern);
}
recordOutcomeForConfig(reqOutcomeObj);
}
protected override GameyResultData buildGameyData()
{
SJGameyResultData reqData = new SJGameyResultData(numHooveredLines,numCorrectWordSplits,numIncorrectWordSplits);
return reqData;
}
protected override string generateGoalTextAppend()
{
return (" "+reqNumOfWordsDone);
}
protected override void pauseScene(bool para_state)
{
if(para_state)
{
pause = true;
//LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>();
//swipeMang.setPause(true);
PlayerBlockMovementScript pbms = GameObject.Find("GlobObj").GetComponent<PlayerBlockMovementScript>();
if(pbms != null) { pbms.enabled = false; }
/*if(objsToUnPause == null) { objsToUnPause = new List<GameObject>(); } else { objsToUnPause.Clear(); }
foreach(string convItem in conveyorWordGObjLookup)
{
GameObject tmpObj = GameObject.Find(convItem);
if(tmpObj != null)
{
objsToUnPause.Add(tmpObj);
tmpObj.SetActive(false);
}
}*/
getDeliveryChuteScript().setPauseState(pause);
CircleTimerScript chopTimerScript = getChopTimerScript();
if(chopTimerScript != null) { chopTimerScript.setPause(pause); }
}
else
{
pause = false;
if(firstTimeFlag)
{
firstTimeFlag = false;
genNextLevel();
}
//LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>();
//swipeMang.setPause(false);
PlayerBlockMovementScript pbms = GameObject.Find("GlobObj").GetComponent<PlayerBlockMovementScript>();
if(pbms != null) { pbms.enabled = true; }
/*for(int i=0; i<objsToUnPause.Count;i++)
{
objsToUnPause[i].SetActive(true);
}
objsToUnPause.Clear();*/
//conveyorCurrentTime = Time.time;
getDeliveryChuteScript().setPauseState(pause);
CircleTimerScript chopTimerScript = getChopTimerScript();
if(chopTimerScript != null) { chopTimerScript.setPause(pause); }
}
}
public new void respondToEvent(string para_sourceID, string para_eventID, System.Object para_eventData)
{
base.respondToEvent(para_sourceID,para_eventID,para_eventData);
if(para_sourceID == "BigPipe")
{
if(para_eventID == "EnterStart")
{
setWhistleVisibility(true);
}
else if(para_eventID == "DeliveryChuteEnter")
{
DeliveryChuteScript dcs = getDeliveryChuteScript();
GameObject nwWordBlock = dcs.getAttachedWordGObj();
nwWordBlock.transform.parent = null;
growScale = dcs.getGrowScale();
registerNewWordBlock(nwWordBlock,currWordItem.getWordLength(),new int[] {0,-1},currWordItem.getID());
registerNewConveyorWord(nwWordBlock);
recordPresentedConfig(currLvlConfig);
LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>();
swipeMang.setPause(false);
SplittableBlockUtil.setStateOfSplitDetectsForWord(nwWordBlock,true);
// Switch timer back on.
//conveyorCurrentTime = Time.time;
//conveyorTimerOn = true;
ScoreBoardScript sbs = getScoreBoardScript();
sbs.resetCrosses();
getChopTimerScript().reset();
closeGate();
}
}
else if(para_eventID == "SwipeHit")
{
string[] swipeLocInfo = (string[]) para_eventData;
handleSplitterHit(swipeLocInfo[0],swipeLocInfo[1]);
}
else if(para_eventID == "SwipeComplete")
{
if(GameObject.Find(para_sourceID).transform.parent != null)
{
if(GameObject.Find(para_sourceID).transform.parent.name == "SkeletonSwipeHand")//
{
if((isInAutoSplitMode)&&(GameObject.Find("SkeletonSwipeHand") != null))
{
Destroy(GameObject.Find("SkeletonSwipeHand"));
if(syllsForAutoSplit.Count > 0)
{
performNextAutoSwipe();
}
else
{
isInAutoSplitMode = false;
LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>();
swipeMang.setPause(true);
}
}
}
}
}
else if(para_eventID == "HighlightSequence")
{
if(nxtIndexForOp < orderedFullySplitConvObjNames.Count)
{
performNextHighlightSequence();
}
else
{
//
if((!wordUnattempted)&&( ! hasGotWrongAttemptOnCurrentWord()))
{
ScoreBoardScript sbs = getScoreBoardScript();
sbs.registerListener("AcScen",this);
getScoreBoardScript().addStar();
}
else
{
respondToEvent("Scoreboard","ScoreboardUpdate",null);
}
}
}
else if(para_eventID == "ScoreboardUpdate")
{
// All clear to open the gate and start placing
// the cut blocks automatically in the grid.
openGate();
isPerformingPositioningSequence = true;
nxtIndexForOp = 0;
isWaitingForConveyorRowClearence = false;
moveNextBlockToGrid();
}
else if(para_eventID == "MoveToGridAndTransformSequence")
{
// Delete Crack.
if(cracksGObjs.Count > 0)
{
Destroy(cracksGObjs[0]);
cracksGObjs.RemoveAt(0);
}
performIndivisibleSpawn(GameObject.Find(para_sourceID));
droppingWords.Add(para_sourceID);
isWaitingForConveyorRowClearence = false;
if(nxtIndexForOp == orderedFullySplitConvObjNames.Count)
{
// End of placement sequence.
isPerformingPositioningSequence = false;
chuteBusy = false;
nxtIndexForOp = 0;
}
}
else if(para_sourceID == "SkeletonSwipeHand")
{
if(para_eventID == "MoveToLocation")
{
LineFollowActiveNDraw lfand = GameObject.Find(para_sourceID).transform.FindChild("FingerTip").GetComponent<LineFollowActiveNDraw>();
lfand.triggerSwipeComplete();
Destroy(GameObject.Find(para_sourceID));
}
}
else if(para_eventID == "GateOpenAni")
{
}
else if(para_eventID == "GateCloseAni")
{
// If tts is needed then say the word.
if(currLvlConfig.getUseTtsFlag())
{
try
{
if(gameObject.GetComponent<AudioSource>() == null) { gameObject.AddComponent<AudioSource>(); }
audio.PlayOneShot(WorldViewServerCommunication.tts.say(currLvlConfig.getWordItem().getWordAsString()));
}
catch(System.Exception ex)
{
Debug.LogError("Failed to use TTS. "+ex.Message);
}
}
// Restart Timer.
getChopTimerScript().init(wordChopTimerDuration_Sec);
getChopTimerScript().setVisibilityState(true);
}
else if(para_eventID == "CircleTimerFinished")
{
buildNRecordConfigOutcome(new object[] { false });
triggerAutoSwipeSequence(conveyorWordObjID);
}
}
// LOGIC FUNCTIONS.
private void openGate()
{
getChopTimerScript().setVisibilityState(false);
ScoreBoardScript sbs = getScoreBoardScript();
sbs.resetCrosses();
GateScript gs = transform.gameObject.GetComponent<GateScript>();
if(gs == null) { gs = transform.gameObject.AddComponent<GateScript>(); } else { gs.enabled = true; }
gs.registerListener("AcScen",this);
gs.openGate();
}
private void closeGate()
{
setWhistleVisibility(false);
GateScript gs = transform.gameObject.GetComponent<GateScript>();
if(gs == null) { gs = transform.gameObject.AddComponent<GateScript>(); } else { gs.enabled = true; }
gs.registerListener("AcScen",this);
gs.closeGate();
}
private void triggerChuteToFetchAndReturnWord()
{
DeliveryChuteScript dcs = getDeliveryChuteScript();
currWordItem = currLvlConfig.getWordItem();
dcs.performFetchWordSequence(currWordItem.getWordAsString(),
dropGrid_WorldGProp,
textPlanePrefab,
splitDetectorPrefab,
itemToSplitPrefabArr,
framePrefab,
scalableGlowPrefab,
nettingPrefab);
}
private void registerNewWordBlock(GameObject para_wordBlockGObj,
int para_wordLength,
int[] para_gridCoords,
int para_lvlID)
{
string suffix = (para_wordBlockGObj.name.Split(':'))[1];
string wordBlockName = "Block-"+nxtWordID+":"+suffix;
para_wordBlockGObj.name = wordBlockName;
int assignedID = nxtWordID;
nxtWordID++;
tetrisInfMap.Add(wordBlockName,new TetrisInfo(assignedID,para_gridCoords,para_wordLength,false));
numIDToStrIDMap.Add(assignedID,wordBlockName);
blockToWDataMap.Add("Block-"+(assignedID), ""+para_lvlID);
}
// WARNING: Call registerNewWordBlock before this.
private void registerNewConveyorWord(GameObject para_nwConveyorBlock)
{
// Clear items.
conveyorWordObjID = null;
conveyorWordGObjLookup.Clear();
currConvWordBeingDropped = null;
// Update items.
conveyorWordObjID = para_nwConveyorBlock.name.Split(':')[0];
conveyorWordGObjLookup.Add(para_nwConveyorBlock.name);
currConvWordBeingDropped = para_nwConveyorBlock.name;
splitsDoneByGame = new List<int>();
//resetConveyorTimerAndAttempts();
conveyorOpen = false;
}
private bool hasGotWrongAttemptOnCurrentWord()
{
bool flag = false;
if(conWordAttemptsStates != null)
{
for(int i=0; i<conWordAttemptsStates.Length; i++)
{
if(conWordAttemptsStates[i])
{
flag = true;
break;
}
}
}
return flag;
}
private void triggerWrongSplitConsequences(string para_parentObjName, ref GameObject para_hitSplitDetector)
{
triggerSoundAtCamera("Buzzer_wrong_split");
ScoreBoardScript sbs = getScoreBoardScript();
if(sbs != null) { sbs.addWrongCross(); }
string prefix1 = para_parentObjName.Split(':')[0];
string prefix2 = currConvWordBeingDropped.Split(':')[0];
if(prefix1 == prefix2)
{
if(conWordAttemptsStates[conWordAttemptsStates.Length-2] == true)
{
// Has reached max amount of tries.
conWordAttemptsStates[conWordAttemptsStates.Length-1] = true;
// Record outcome for this config.
numIncorrectWordSplits++;
buildNRecordConfigOutcome(new object[] { false });
// Trigger Auto Swipe.
// Prevent User Swipes.
LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>();
swipeMang.setPause(true);
// Trigger Auto Swipes.
triggerAutoSwipeSequence(prefix1);
}
else
{
for(int i=0; i<conWordAttemptsStates.Length; i++)
{
if(conWordAttemptsStates[i] == false)
{
conWordAttemptsStates[i] = true;
break;
}
}
}
}
}
private List<GameObject> triggerCorrectSplitConsequences(string para_wordObjName, int para_splitID)
{
GameObject wordObj = GameObject.Find(para_wordObjName);
Transform wOverlay = wordObj.transform.FindChild("WordOverlay");
GameObject reqSplitDetector = (wOverlay.FindChild("SplitDet-"+para_splitID)).gameObject;
return triggerCorrectSplitConsequences(para_wordObjName,ref reqSplitDetector);
}
private List<GameObject> triggerCorrectSplitConsequences(string para_parentObjName, ref GameObject para_hitSplitDetector)
{
int splitID = int.Parse((para_hitSplitDetector.name.Split('-'))[1]);
// Trigger Sparks:
if(showSparksEffect)
{
Vector3 sparksLoc = new Vector3(para_hitSplitDetector.transform.position.x,para_hitSplitDetector.transform.position.y,Camera.main.transform.position.z + 1);
Instantiate(sparksPrefab,sparksLoc,Quaternion.identity);
}
// Trigger Sound:
triggerSoundAtCamera("sfx_Swipe");
// Display Crack:
Transform reqCrack = crackPrefabArr[Random.Range(0,crackPrefabArr.Length)];
float cWidth = dropGrid_WorldGProp.cellWidth * growScale;
//Vector3 crackLoc = new Vector3(para_hitSplitDetector.transform.position.x,para_hitSplitDetector.transform.position.y,transform.position.z - 1);
GameObject nwCrack = WorldSpawnHelper.initObjWithinWorldBounds(reqCrack,1f,1f,
"Crack"+splitID,
new Rect(para_hitSplitDetector.transform.position.x - (cWidth/2f),
para_hitSplitDetector.transform.position.y + ((dropGrid_WorldGProp.cellHeight * growScale)/2f),
cWidth,
(dropGrid_WorldGProp.cellHeight * growScale)),
null,
para_hitSplitDetector.transform.position.z,
upAxisArr);
//Transform nwCrack = (Transform) Instantiate(reqCrack,crackLoc,Quaternion.identity);
cracksGObjs.Add(nwCrack);
// Split Word:
// Switch layer type to default in order to prevent further input from this split detector.
para_hitSplitDetector.layer = 0;
// Color Green.
MeshRenderer tmpRend = (MeshRenderer) para_hitSplitDetector.GetComponent(typeof(MeshRenderer));
Material nwMat = new Material(Shader.Find("Diffuse"));
nwMat.color = Color.green;
tmpRend.material = nwMat;
tmpRend.enabled = true;
// Split and register child blocks.
List<GameObject> splitObjs = WordFactoryYUp.performSplitOnWordBoard(ref para_hitSplitDetector,framePrefab,scalableGlowPrefab);
for(int i=0; i<splitObjs.Count; i++)
{
string splitObjName = splitObjs[i].name;
string prefix = splitObjName.Split(':')[0];
string suffix = splitObjName.Split(':')[1];
TetrisInfo parentTetInf = tetrisInfMap[para_parentObjName];
int parentX = parentTetInf.coords[0];
int parentY = parentTetInf.coords[1];
int parentSuffixStart = int.Parse((para_parentObjName.Split(':')[1]).Split('-')[0]);
string tmpWDataMapFullKey = blockToWDataMap[prefix];
SJWordItem parentWData = findWordInCache(int.Parse(tmpWDataMapFullKey));
//int sourceBlockID = int.Parse(prefix.Split('-')[1]);
int childX1_FromParent = int.Parse(suffix.Split('-')[0]);
int childX2_FromParent = int.Parse(suffix.Split('-')[1]);
int[] childCoords = { (parentX + (childX1_FromParent - parentSuffixStart)), parentY };
// Check if child is indivisible.
bool isIndivisible = parentWData.checkIfWordSegmentIsIndivisible(childX1_FromParent,childX2_FromParent);
// Decide whether to drop or not.
if(prefix == conveyorWordObjID)
{
conveyorWordGObjLookup.Add(splitObjName);
conveyorWordGObjLookup.Remove(para_parentObjName);
}
else
{
droppingWords.Add(splitObjName);
}
tetrisInfMap.Add(splitObjName,new TetrisInfo(nxtWordID, childCoords, (childX2_FromParent - childX1_FromParent + 1),isIndivisible));
int assignedID = nxtWordID;
nxtWordID++;
numIDToStrIDMap.Add(assignedID,splitObjName);
}
// Delete parent block references.
droppingWords.Remove(para_parentObjName);
stationaryWords.Remove(para_parentObjName);
tetrisInfMap.Remove(para_parentObjName);
// Trigger block updates as some may have become free.
updateStationaryBlocks = true;
return splitObjs;
}
private void moveNextBlockToGrid()
{
if(nxtIndexForOp < orderedFullySplitConvObjNames.Count)
{
string blockName = orderedFullySplitConvObjNames[nxtIndexForOp];
TetrisInfo tInf = tetrisInfMap[blockName];
GameObject reqGObj = GameObject.Find(blockName);
int gridColForBlock = ((int) (gridWidthInCells/2f)) - ((int) (tInf.wordSize/2f));
if((gridColForBlock < 0)||(gridColForBlock >= gridWidthInCells))
{
gridColForBlock = 0;
}
int[] nwGridCoords = new int[2] {gridColForBlock,0};
tInf.coords = nwGridCoords;
tetrisInfMap[blockName] = tInf;
if(conveyorWordGObjLookup.Contains(blockName))
{
conveyorWordGObjLookup.Remove(blockName);
if(conveyorWordGObjLookup.Count == 0)
{
conveyorWordObjID = null;
currConvWordBeingDropped = null;
}
}
for(int c=tInf.coords[0]; c<(tInf.coords[0] + tInf.wordSize); c++)
{
if(c < (gridWidthInCells-1))
{
gridState[c,tInf.coords[1]] = tInf.id;
debugGridState[c,tInf.coords[1]] = ""+tInf.id;
}
}
Rect gridBoundsForBlock = new Rect(dropGrid_WorldGProp.x + (tInf.coords[0] * (dropGrid_WorldGProp.cellWidth + dropGrid_WorldGProp.borderThickness)) + dropGrid_WorldGProp.borderThickness,
dropGrid_WorldGProp.y + ((dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness)) + dropGrid_WorldGProp.borderThickness,
(tInf.wordSize * dropGrid_WorldGProp.cellWidth) + ((tInf.wordSize-1) * dropGrid_WorldGProp.borderThickness),
dropGrid_WorldGProp.cellHeight);
Vector3 movDest = new Vector3(gridBoundsForBlock.x + (gridBoundsForBlock.width/2f),
gridBoundsForBlock.y - (gridBoundsForBlock.height/2f),
dropGrid_WorldGProp.z);
float initWidthOfBlock = (dropGrid_WorldGProp.cellWidth * tInf.wordSize * growScale);
float initHeightOfBlock = (dropGrid_WorldGProp.cellHeight * growScale);
CustomAnimationManager caMang = reqGObj.AddComponent<CustomAnimationManager>();
List<List<AniCommandPrep>> cmdBatchList = new List<List<AniCommandPrep>>();
List<AniCommandPrep> cmdBatch1 = new List<AniCommandPrep>();
cmdBatch1.Add(new AniCommandPrep("TeleportToLocation",1,new List<System.Object>() { new float[3] {movDest.x,movDest.y,movDest.z} }));
cmdBatch1.Add(new AniCommandPrep("ResizeToWorldSize",1,new List<System.Object>() { new float[3] {gridBoundsForBlock.width,gridBoundsForBlock.height,1},
new float[3] {initWidthOfBlock,initHeightOfBlock,1}}));
List<AniCommandPrep> cmdBatch2 = new List<AniCommandPrep>();
cmdBatch2.Add(new AniCommandPrep("ColorTransition",1,new List<System.Object>() { new float[4] {0,1,0,1}, 2f }));
cmdBatchList.Add(cmdBatch1);
cmdBatchList.Add(cmdBatch2);
caMang.init("MoveToGridAndTransformSequence",cmdBatchList);
caMang.registerListener("AcScen",this);
nxtIndexForOp++;
isWaitingForConveyorRowClearence = true;
}
}
private List<string> performClearLineEffect(int para_hooveLine)
{
HashSet<string> nwDestroyedBlocks = new HashSet<string>();
float tmpY = dropGrid_WorldGProp.y - dropGrid_WorldGProp.borderThickness - (dropGrid_WorldGProp.cellHeight/2f);
Vector3 hooveLineCentrePos = new Vector3(dropGrid_WorldGProp.x + (dropGrid_WorldGProp.totalWidth/2f),
tmpY - ((dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness) * (para_hooveLine-numPrequelRows)),
dropGrid_WorldGProp.z);
Rect highlighterWorldBounds = new Rect(dropGrid_WorldGProp.x,hooveLineCentrePos.y + (dropGrid_WorldGProp.cellHeight/2f),dropGrid_WorldGProp.totalWidth,dropGrid_WorldGProp.cellHeight);
GameObject rowHighlighter = WorldSpawnHelper.initObjWithinWorldBounds(planePrefab,1,1,"HooveRowHighlighter",highlighterWorldBounds,null,dropGrid_WorldGProp.z + 0.1f,upAxisArr);
rowHighlighter.renderer.material.color = new Color(0,0.4f,0); //new Color(0.9f,0.7f,0.05f);
GameObject hooveLineCollection = new GameObject("HooveLineCollection");
hooveLineCollection.transform.position = hooveLineCentrePos;
for(int i=0; i<gridWidthInCells; i++)
{
string blockName = numIDToStrIDMap[gridState[i,para_hooveLine]];
int wordLength = tetrisInfMap[blockName].wordSize;
GameObject tmpBlockToRemove = GameObject.Find(blockName);
tmpBlockToRemove.transform.parent = hooveLineCollection.transform;
nwDestroyedBlocks.Add(blockName);
tetrisInfMap.Remove(blockName);
numIDToStrIDMap.Remove(gridState[i,para_hooveLine]);
stationaryWords.Remove(blockName);
droppingWords.Remove(blockName);
for(int k=0; k<wordLength; k++)
{
gridState[i + k,para_hooveLine] = 0;
debugGridState[i + k,para_hooveLine] = "0";
}
i += (wordLength-1); // -1 because the for loop will increment i once anyway.
}
pause = true;
// Trigger hoove.
GameObject solomonWholeGObj = GameObject.Find("SolomonWhole");
GameObject hooveCntr = (solomonWholeGObj.transform.FindChild("HooveCentre")).gameObject;
Vector3 hooveSpot = new Vector3(solomonWholeGObj.transform.position.x,
hooveLineCentrePos.y + (solomonWholeGObj.transform.position.y - hooveCntr.transform.position.y),
solomonWholeGObj.transform.position.z);
float hooveMoveSpeed = 3f;
float hooveSuctionSpeed = 15f;
Vector3 hooveMovVectWithSpeed = (new Vector3(0,1,0)) * (dropGrid_WorldGProp.cellHeight * hooveMoveSpeed);
Vector3 hooveSuctionVectWithSpeed = (new Vector3(-1,0,0)) * (dropGrid_WorldGProp.cellWidth * hooveSuctionSpeed);
HooveScript hScript = solomonWholeGObj.AddComponent<HooveScript>();
hScript.triggerHoove(hooveSpot,hooveMovVectWithSpeed,hooveSuctionVectWithSpeed,dropGrid_WorldGProp.x - (dropGrid_WorldGProp.totalWidth/2f),hooveLineCollection,sfxPrefab);
LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>();
swipeMang.setPause(true);
return (new List<string>(nwDestroyedBlocks));
}
private int searchForLinesToClear()
{
int rowID = -1;
for(int r=(gridState.GetLength(1)-1); r>0; r--)
{
bool fullLineFormed = true;
for(int c=0; c<gridWidthInCells; c++)
{
if(gridState[c,r] == 0)
{
c = gridWidthInCells; // tmp hack.
fullLineFormed = false;
break;
}
else
{
string blockName = numIDToStrIDMap[gridState[c,r]];
TetrisInfo tmpTInf = tetrisInfMap[blockName];
if((! tmpTInf.isIndivisible))
{
c = gridWidthInCells; // tmp hack.
fullLineFormed = false;
break;
}
}
}
if(fullLineFormed)
{
rowID = r;
break;
}
}
return rowID;
}
private bool isRowFree(int para_rowID)
{
bool retVal = true;
for(int i=0; i<gridState.GetLength(0); i++)
{
if(gridState[i,para_rowID] != 0)
{
retVal = false;
break;
}
}
return retVal;
}
private bool isRowFree(int para_rowID, bool para_ignoreConveyorObjs)
{
bool retVal = true;
for(int i=0; i<gridState.GetLength(0); i++)
{
if(gridState[i,para_rowID] != 0)
{
if(para_ignoreConveyorObjs)
{
if(conveyorWordGObjLookup.Contains(numIDToStrIDMap[gridState[i,para_rowID]]))
{
}
else
{
retVal = false;
break;
}
}
else
{
retVal = false;
break;
}
}
}
return retVal;
}
private void handleSplitterHit(GameObject para_splitDetectObj)
{
GameObject tmpOverlayObj = (para_splitDetectObj.transform.parent).gameObject;
GameObject tmpMasterObj = (tmpOverlayObj.transform.parent).gameObject;
handleSplitterHit(tmpMasterObj.name,para_splitDetectObj.name);
}
private void handleSplitterHit(string para_masterObjName, string para_splitDetectObjName)
{
// *** Check Where Split Event Occurred ***
if( ! isInAutoSplitMode)
{
wordUnattempted = false;
}
GameObject tmpMasterObj = GameObject.Find(para_masterObjName);
GameObject tmpOverlayObj = (tmpMasterObj.transform.FindChild("WordOverlay")).gameObject;
GameObject hitSplitDetector = (tmpOverlayObj.transform.FindChild(para_splitDetectObjName)).gameObject;
int splitIndex = int.Parse(hitSplitDetector.name.Split('-')[1]);
string tmpWDatabaseWholeKey = blockToWDataMap[((tmpMasterObj.name).Split(':')[0])];
SJWordItem reqWord = findWordInCache(int.Parse(tmpWDatabaseWholeKey));
if( ! isInAutoSplitMode)
{
playerSplitPattern.Add(splitIndex);
}
if(! reqWord.isValidSplitIndex(splitIndex))
{
// Invalid split.
triggerWrongSplitConsequences(tmpMasterObj.name,ref hitSplitDetector);
if(serverCommunication != null) { serverCommunication.wordSolvedCorrectly(reqWord.getWordAsString(),false,"Invalid splits",reqWord.languageArea,reqWord.difficulty); }
}
else
{
// Valid split.
// Perform split.
triggerCorrectSplitConsequences(tmpMasterObj.name,ref hitSplitDetector);
if(serverCommunication != null) { serverCommunication.wordSolvedCorrectly(reqWord.getWordAsString(),true,"",reqWord.languageArea,reqWord.difficulty); }
// If this is the final split in the word then trigger the transformation sequence.
List<List<string>> wordSegmentExistenceLists = getExistenceOfWordSegments(para_masterObjName);
List<string> existingSegments = wordSegmentExistenceLists[0];
List<string> nonExistingSegments = wordSegmentExistenceLists[1];
bool completeStatus = (nonExistingSegments.Count == 0);
if(completeStatus)
{
LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>();
swipeMang.setPause(true);
orderedFullySplitConvObjNames = existingSegments;
nxtIndexForOp = 0;
// Tmp Switch Off Conveyor Timer.
//conveyorTimerOn = false;
getChopTimerScript().setPause(true);
if( !isInAutoSplitMode)
{
// Record outcome for this config.
numCorrectWordSplits++;
buildNRecordConfigOutcome(new object[] { true });
}
performNextHighlightSequence();
}
}
}
private List<List<string>> getExistenceOfWordSegments(string para_masterObjName)
{
string wordID = para_masterObjName.Split(':')[0];
string wDataFullKey = blockToWDataMap[wordID];
SJWordItem reqWord = findWordInCache(int.Parse(wDataFullKey));
string wordStr = reqWord.getWordAsString();
int[] databaseSyllPositions = reqWord.getSyllSplitPositions();
List<int> syllSplitPositions = new List<int>();
for(int i=0; i<databaseSyllPositions.Length; i++)
{
syllSplitPositions.Add(databaseSyllPositions[i]);
}
syllSplitPositions.Add(wordStr.Length-1);
List<string> existingSegments = new List<string>();
List<string> nonExistingSegments = new List<string>();
int startLetterIndex = 0;
for(int i=0; i<syllSplitPositions.Count; i++)
{
int endLetterIndex = syllSplitPositions[i];
string segmentUniqueID = wordID + ":" + "" + startLetterIndex + "-" + endLetterIndex;
if(tetrisInfMap.ContainsKey(segmentUniqueID))
{
if(! existingSegments.Contains(segmentUniqueID))
{
existingSegments.Add(segmentUniqueID);
}
}
else
{
if(! nonExistingSegments.Contains(segmentUniqueID))
{
nonExistingSegments.Add(segmentUniqueID);
}
}
startLetterIndex = endLetterIndex + 1;
}
List<List<string>> retData = new List<List<string>>();
retData.Add(existingSegments);
retData.Add(nonExistingSegments);
return retData;
}
private void performNextHighlightSequence()
{
string para_segmentID = orderedFullySplitConvObjNames[nxtIndexForOp];
GameObject reqSeg = GameObject.Find(para_segmentID);
CustomAnimationManager caMang = reqSeg.AddComponent<CustomAnimationManager>();
List<List<AniCommandPrep>> cmdBatchList = new List<List<AniCommandPrep>>();
List<AniCommandPrep> cmdBatch1 = new List<AniCommandPrep>();
cmdBatch1.Add(new AniCommandPrep("ColorTransition",1, new List<System.Object>() { new float[4] {0,1,0,1}, 0.25f }));
List<AniCommandPrep> cmdBatch2 = new List<AniCommandPrep>();
cmdBatch2.Add(new AniCommandPrep("ColorTransition",1, new List<System.Object>() { new float[4] {1,1,1,1}, 0.25f }));
cmdBatchList.Add(cmdBatch1);
cmdBatchList.Add(cmdBatch2);
caMang.init("HighlightSequence",cmdBatchList);
caMang.registerListener("AcScen",this);
nxtIndexForOp++;
}
private void createRandomStartGrid()
{
int rowsFromBottomToFill = 3;
int maxSyllLength = 5;
float[] whiteSpaceProbPerRow = new float[3] { 0.1f, 0.1f, 0.1f };
for(int tmpRCounter=0; tmpRCounter<rowsFromBottomToFill; tmpRCounter++)
{
bool rowHasWhite = false;
List<string> rowBlocks = new List<string>();
for(int c=0; c<gridWidthInCells; c++)
{
int maxBound = maxSyllLength;
if((c+maxBound) > gridWidthInCells)
{
maxBound = gridWidthInCells - c;
}
int nxtBlockSize = Random.Range(1,maxBound);
if(nxtBlockSize > 0)
{
bool isWhiteSpace = (Random.Range(0,1.0f) <= whiteSpaceProbPerRow[tmpRCounter]);
if(!isWhiteSpace)
{
//Debug.Log("Creating Brick at: {"+c+","+((gridHeightInCells+numPrequelRows)-1-tmpRCounter)+"}");
string nwRBlock = createIndivisibleAtGridLocation(new int[2] {c,(gridHeightInCells+numPrequelRows)-1 - tmpRCounter},nxtBlockSize);
rowBlocks.Add(nwRBlock);
}
else
{
rowHasWhite = true;
}
c += nxtBlockSize;
}
}
if( ! rowHasWhite)
{
int randIndex = Random.Range(0,rowBlocks.Count);
destroyAndDeregisterBlock(rowBlocks[randIndex]);
}
}
}
private void destroyAndDeregisterBlock(string para_existingBlockName)
{
GameObject reqObj = GameObject.Find(para_existingBlockName);
if(reqObj != null)
{
// Destroy from world.
Destroy(reqObj);
// Update Datastructures.
TetrisInfo tmpTInf = tetrisInfMap[para_existingBlockName];
numIDToStrIDMap.Remove(tmpTInf.id);
int[] gCoords = tmpTInf.coords;
for(int c=gCoords[0]; c<(gCoords[0] + tmpTInf.wordSize); c++)
{
if((c >= 0)&&(c < gridWidthInCells))
{
gridState[c,gCoords[1]] = 0;
debugGridState[c,gCoords[1]] = "0";
}
}
tetrisInfMap.Remove(para_existingBlockName);
if(droppingWords.Contains(para_existingBlockName))
{
droppingWords.Remove(para_existingBlockName);
}
}
}
private string createIndivisibleAtGridLocation(int[] para_startLetterCoords, int para_length)
{
// Create new name and key.
int assignedID = nxtWordID;
string blkName = "Block-"+assignedID+":"+"0-"+(para_length-1);
nxtWordID++;
// Spawn the object.
float boundsWidth = (para_length * dropGrid_WorldGProp.cellWidth);
float boundsHeight = dropGrid_WorldGProp.cellHeight;
Rect spawnWorldBounds = new Rect(dropGrid_WorldGProp.x + ((dropGrid_WorldGProp.borderThickness + dropGrid_WorldGProp.cellWidth) * para_startLetterCoords[0]),
dropGrid_WorldGProp.y - ((dropGrid_WorldGProp.borderThickness + dropGrid_WorldGProp.cellHeight) * para_startLetterCoords[1])
+ ((dropGrid_WorldGProp.borderThickness + dropGrid_WorldGProp.cellHeight) * 1),
boundsWidth,
boundsHeight);
Transform reqSyllPrefab = selectRandomPrefabForSyll(para_length);
GameObject nwIndiObj = WorldSpawnHelper.initObjWithinWorldBounds(reqSyllPrefab,
reqSyllPrefab.renderer.bounds.size.x,
reqSyllPrefab.renderer.bounds.size.y,
blkName,
spawnWorldBounds,
null,
dropGrid_WorldGProp.z,
upAxisArr);
//WorldSpawnHelper.initObjWithinWorldBounds(planePrefab,"DebugPlane",spawnWorldBounds,dropGrid_WorldGProp.z,upAxisArr);
nwIndiObj.tag = "Indivisible";
SpriteRenderer tmpSR = nwIndiObj.GetComponent<SpriteRenderer>();
tmpSR.sortingOrder = 6;
tmpSR.sprite.texture.wrapMode = TextureWrapMode.Clamp;
applyMovableIndivisibleEffect(nwIndiObj);
// Update Datastructures.
tetrisInfMap.Add(blkName,new TetrisInfo(assignedID,new int[2] {para_startLetterCoords[0],para_startLetterCoords[1]},para_length,true));
numIDToStrIDMap.Add(assignedID,blkName);
for(int c=para_startLetterCoords[0]; c<(para_startLetterCoords[0] + para_length); c++)
{
gridState[c,para_startLetterCoords[1]] = assignedID;
debugGridState[c,para_startLetterCoords[1]] = ""+assignedID;
}
droppingWords.Add(blkName);
return nwIndiObj.name;
}
private void performIndivisibleSpawn(GameObject para_objToChange)
{
TetrisInfo tInf = tetrisInfMap[para_objToChange.name];
int syllLength = tInf.wordSize;
if(syllLength >= gridWidthInCells)
{
//int overflowLength = gridWidthInCells - syllLength;
//tInf.coords[0] = 3;
syllLength = 6;
}
Vector3 objCentrePos = new Vector3(para_objToChange.transform.position.x,
para_objToChange.transform.position.y,
para_objToChange.transform.position.z);
// Determine if this is a moveable or fixed block.
string prefix = para_objToChange.name.Split(':')[0];
string wDataFullKey = blockToWDataMap[prefix];
SJWordItem reqFullWord = findWordInCache(int.Parse(wDataFullKey));
string[] blockLetterRangeStrArr = (para_objToChange.name.Split(':')[1]).Split('-');
int[] blockLetterRange = new int[2] { int.Parse(blockLetterRangeStrArr[0]), int.Parse(blockLetterRangeStrArr[1]) };
int lastLetterIDForWord = blockLetterRange[1];
int boundarySplitToCheck = lastLetterIDForWord;
if(lastLetterIDForWord == (reqFullWord.getWordLength()-1))
{
boundarySplitToCheck = blockLetterRange[0] - 1;
}
bool isFixedBlock = (splitsDoneByGame.Contains(boundarySplitToCheck));
destroyAndDeregisterBlock(para_objToChange.name);
//Destroy(para_objToChange);
// Create indivisibles to replace the object.
int maxIndivisibleLength = 4;
List<int[]> itemStartCoords = new List<int[]>();
List<int> itemLengths = new List<int>();
//List<string> itemNames = new List<string>();
if(syllLength <= maxIndivisibleLength)
{
itemStartCoords.Add(tInf.coords);
itemLengths.Add(tInf.wordSize);
}
else
{
int[] tmpCoords = new int[2];
tmpCoords[0] = tInf.coords[0];
tmpCoords[1] = 0;
int remLength = syllLength;
while(remLength > 0)
{
int maxL = 2;// maxIndivisibleLength;
if(remLength < maxL) { maxL = remLength; }
int chosenLength = Random.Range(1,(maxL+1));
itemStartCoords.Add(new int[2] {tmpCoords[0],tmpCoords[1]});
itemLengths.Add(chosenLength);
tmpCoords[0] += chosenLength;
remLength -= chosenLength;
}
}
for(int i=0; i<itemStartCoords.Count; i++)
{
string nwItemName = createIndivisibleAtGridLocation(itemStartCoords[i],itemLengths[i]);
GameObject nwIndiObj = GameObject.Find(nwItemName);
if(isFixedBlock) { applyFixedIndivisibleEffect(nwIndiObj); }
else { applyMovableIndivisibleEffect(nwIndiObj); }
}
// Apply sound effect and cloud prefab.
triggerSoundAtCamera("sfx_BlockToObject");
if(blockToObjectEffect != null)
{
Vector3 effectSpawnPt = new Vector3(objCentrePos.x,objCentrePos.y,objCentrePos.z - 0.5f);
Transform nwEffect = (Transform) Instantiate(blockToObjectEffect,effectSpawnPt,Quaternion.identity);
nwEffect.localEulerAngles = new Vector3(blockToObjectEffect.localEulerAngles.x,
blockToObjectEffect.localEulerAngles.y,
blockToObjectEffect.localEulerAngles.z);
}
}
private void applyMovableIndivisibleEffect(GameObject para_indiObj)
{
if(para_indiObj.GetComponent<BoxCollider>() == null) { para_indiObj.AddComponent<BoxCollider>(); }
}
private void applyFixedIndivisibleEffect(GameObject para_indiObj)
{
// Mark this object as wrong, i.e. immovable.
SplittableBlockUtil.applyColorToBlock(para_indiObj,unmovableBlockColor);
// Remove collider to make this object immovable by the player.
if(para_indiObj.GetComponent<BoxCollider>() != null) { Destroy(para_indiObj.GetComponent<BoxCollider>()); }
if(para_indiObj.GetComponent<MeshCollider>() != null) { Destroy(para_indiObj.GetComponent<MeshCollider>()); }
}
private Transform selectRandomPrefabForSyll(int para_syllLength)
{
bool isUsingDefault = false;
Transform[] tmpArr = null;
switch(para_syllLength)
{
case 1: tmpArr = oneSyllPrefabs; break;
case 2: tmpArr = twoSyllPrefabs; break;
case 3: tmpArr = threeSyllPrefabs; break;
case 4: tmpArr = fourSyllPrefabs; break;
case 5: tmpArr = fiveSyllPrefabs; break;
default: isUsingDefault = true; break;
}
if(isUsingDefault)
{
return planePrefab;
}
else
{
int chosenTexIndex = Random.Range(0,tmpArr.Length);
return tmpArr[chosenTexIndex];
}
}
// Handlers for player block movement.
public void intakeObjectDragStart()
{
LineDragActiveNDraw ldand = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>();
ldand.setPause(true);
}
public void intakeObjectDragCommand(ref GameObject para_indivisibleGObj, int para_dragCommand)
{
if(pause)
{
return;
}
if( ! conveyorWordGObjLookup.Contains(para_indivisibleGObj.name))
{
TetrisInfo tInfo = tetrisInfMap[para_indivisibleGObj.name];
bool canPerformOp = true;
DPadDir cmd = (DPadDir) para_dragCommand;
switch(cmd)
{
case DPadDir.NORTH: // North.
if(tInfo.coords[1] > 0)
{
int tmpX = tInfo.coords[0];
int tmpY = tInfo.coords[1]-1;
for(int i=tmpX; i<(tmpX + tInfo.wordSize); i++)
{
if((gridState[i,tmpY] != 0)||(tmpY < numPrequelRows))
{
canPerformOp = false;
break;
}
}
if(canPerformOp)
{
Vector3 movUpV = new Vector3(0,(dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness),0);
para_indivisibleGObj.transform.position += movUpV;
for(int x=tmpX; x<(tmpX + tInfo.wordSize); x++)
{
gridState[x,tInfo.coords[1]] = 0;
gridState[x,tmpY] = tInfo.id;
debugGridState[x,tInfo.coords[1]] = "0";
debugGridState[x,tmpY] = ""+tInfo.id;
}
tInfo.coords[1] = tmpY;
tetrisInfMap[para_indivisibleGObj.name] = tInfo;
//updateStationaryBlocks = true;
}
else
{
break;
}
}
break;
case DPadDir.SOUTH:
if(tInfo.coords[1] < (gridState.GetLength(1)-1))
{
int tmpX = tInfo.coords[0];
int tmpY = tInfo.coords[1]+1;
for(int i=tmpX; i<(tmpX + tInfo.wordSize); i++)
{
if((gridState[i,tmpY] != 0)||(tmpY < numPrequelRows))
{
canPerformOp = false;
break;
}
}
if(canPerformOp)
{
Vector3 movDownV = new Vector3(0,-(dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness),0);
para_indivisibleGObj.transform.position += movDownV;
for(int x=tmpX; x<(tmpX + tInfo.wordSize); x++)
{
gridState[x,tInfo.coords[1]] = 0;
gridState[x,tmpY] = tInfo.id;
debugGridState[x,tInfo.coords[1]] = "0";
debugGridState[x,tmpY] = ""+tInfo.id;
}
tInfo.coords[1] = tmpY;
tetrisInfMap[para_indivisibleGObj.name] = tInfo;
//updateStationaryBlocks = true;
}
else
{
break;
}
}
break;
case DPadDir.WEST:
if(tInfo.coords[0] > 0)
{
int tmpX = tInfo.coords[0];
int tmpY = tInfo.coords[1];
if((gridState[tmpX-1,tmpY] != 0)||(tmpY < numPrequelRows))
{
canPerformOp = false;
}
if(canPerformOp)
{
Vector3 movWestV = new Vector3(-(dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness),0,0);
para_indivisibleGObj.transform.position += movWestV;
gridState[tmpX + tInfo.wordSize -1,tmpY] = 0;
gridState[tmpX-1,tmpY] = tInfo.id;
debugGridState[tmpX + tInfo.wordSize -1,tmpY] = "0";
debugGridState[tmpX-1,tmpY] = ""+tInfo.id;
tInfo.coords[0]--;
tetrisInfMap[para_indivisibleGObj.name] = tInfo;
//updateStationaryBlocks = true;
}
else
{
break;
}
}
break;
case DPadDir.EAST:
int nwX = tInfo.coords[0]+tInfo.wordSize;
if(nwX <= (gridState.GetLength(0)-1))
{
int tmpX = tInfo.coords[0];
int tmpY = tInfo.coords[1];
if((gridState[nwX,tmpY] != 0)||(tmpY < numPrequelRows))
{
canPerformOp = false;
}
if(canPerformOp)
{
Vector3 movEastV = new Vector3((dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness),0,0);
para_indivisibleGObj.transform.position += movEastV;
gridState[tmpX,tmpY] = 0;
gridState[nwX,tmpY] = tInfo.id;
debugGridState[tmpX,tmpY] = "0";
debugGridState[nwX,tmpY] = ""+tInfo.id;
tInfo.coords[0]++;
tetrisInfMap[para_indivisibleGObj.name] = tInfo;
//updateStationaryBlocks = true;
}
else
{
break;
}
}
break;
}
}
}
public void intakeObjectDragStop(string para_blockReleased)
{
if(pause)
{
return;
}
stationaryWords.Remove(para_blockReleased);
droppingWords.Add(para_blockReleased);
LineDragActiveNDraw ldand = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>();
ldand.setPause(false);
updateStationaryBlocks = true;
}
public void noticeHooveTermination()
{
Destroy(GameObject.Find("SolomonWhole").GetComponent(typeof(HooveScript)));
Destroy(GameObject.Find("HooveRowHighlighter"));
updateStationaryBlocks = true;
pause = false;
updateLineCounterDisplay();
LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>();
swipeMang.setPause(false);
}
private void updateLineCounterDisplay()
{
TextMesh tMesh = getLineCounterTMesh();
tMesh.text = ""+numHooveredLines;
tMesh.renderer.sortingOrder = 100;
tMesh.renderer.material.color = Color.black;
}
private void setWhistleVisibility(bool para_state)
{
whistleVisible = para_state;
if(uiBounds == null) { uiBounds = new Dictionary<string, Rect>(); }
GameObject whistleIcon = GameObject.Find("PitRight").transform.FindChild("WhistleIcon").gameObject;
whistleIcon.renderer.enabled = para_state;
whistleIcon.SetActive(para_state);
Rect whistleIconGUIBounds = WorldSpawnHelper.getWorldToGUIBounds(whistleIcon.renderer.bounds,upAxisArr);
if(uiBounds.ContainsKey("WhistleIcon")) { uiBounds["WhistleIcon"] = whistleIconGUIBounds; } else { uiBounds.Add("WhistleIcon",whistleIconGUIBounds); }
}
private void spawnSkeletonSwipeHand(Vector3 para_swipeStartPt, Vector3 para_swipeDestPt)
{
float skeleSwipeHand_Width = dropGrid_WorldGProp.cellWidth * 3;
float skeleSwipeHand_Height = skeleSwipeHand_Width;
float skeleSwipeHand_X = para_swipeStartPt.x;
float skeleSwipeHand_Y = para_swipeStartPt.y;
GameObject skeleSwipeHandObj = WorldSpawnHelper.initObjWithinWorldBounds(skeletonSwipeHandPrefab,
skeletonSwipeHandPrefab.renderer.bounds.size.x,
skeletonSwipeHandPrefab.renderer.bounds.size.y,
"SkeletonSwipeHand",
new Rect (skeleSwipeHand_X,skeleSwipeHand_Y,skeleSwipeHand_Width,skeleSwipeHand_Height),
null,
para_swipeStartPt.z,
upAxisArr);
GameObject skeleFingerTipObj = (skeleSwipeHandObj.transform.FindChild("FingerTip")).gameObject;
LineFollowActiveNDraw lfand = skeleFingerTipObj.GetComponent<LineFollowActiveNDraw>();
lfand.init(WorldSpawnHelper.getWorldToGUIBounds(GameObject.Find("Background").renderer.bounds,upAxisArr),0.1f,dropGrid_WorldGProp.z - (dropGrid_WorldGProp.cellWidth * 1.75f),dropGrid_WorldGProp.z,"SplitDetect",0);
lfand.registerListener("AcScen",this);
MoveToLocation skeleMovScript = skeleSwipeHandObj.AddComponent<MoveToLocation>();
skeleMovScript.initScript(new Vector3(para_swipeDestPt.x + (skeleSwipeHandObj.renderer.bounds.size.x/2f),
para_swipeDestPt.y - (skeleSwipeHandObj.renderer.bounds.size.y/2f),
para_swipeDestPt.z),
2f);
skeleMovScript.registerListener("AcScen",this);
}
private void triggerAutoSwipeSequence(string para_blockNamePrefix)
{
splitsDoneByGame = new List<int>();
isInAutoSplitMode = true;
itemForAutoSplit = para_blockNamePrefix;
string wDatabaseFullKey = blockToWDataMap[itemForAutoSplit];
SJWordItem reqWord = findWordInCache(int.Parse(wDatabaseFullKey));
int[] tmpSyllSplitArr = reqWord.getSyllSplitPositions();
if(syllsForAutoSplit == null) { syllsForAutoSplit = new List<int>(); } else { syllsForAutoSplit.Clear(); }
for(int k=0; k<tmpSyllSplitArr.Length; k++)
{
syllsForAutoSplit.Add(tmpSyllSplitArr[k]);
}
if(syllsForAutoSplit.Count > 0)
{
performNextAutoSwipe();
}
}
private void performNextAutoSwipe()
{
bool foundBlockToSplit = false;
while((foundBlockToSplit == false)&&(syllsForAutoSplit.Count > 0))
{
int nxtTargetSplitDetID = syllsForAutoSplit[0];
foreach(string tmpConvWordID in conveyorWordGObjLookup)
{
string[] suffix = (tmpConvWordID.Split(':')[1]).Split('-');
int[] suffixNums = new int[2] { int.Parse(suffix[0]), int.Parse(suffix[1]) };
if((nxtTargetSplitDetID >= suffixNums[0])&&(nxtTargetSplitDetID < suffixNums[1]))
{
Bounds splitDetBounds = SplittableBlockUtil.getSplitDetectWorldBounds(tmpConvWordID,nxtTargetSplitDetID);
float zVal = Camera.main.transform.position.z + 2f;
Rect topOfPitWorld = CommonUnityUtils.get2DBounds(GameObject.Find("TopOfPit").renderer.bounds);
Vector3 swipeStartPos = new Vector3(splitDetBounds.min.x + (splitDetBounds.size.x * 0.25f),topOfPitWorld.y - topOfPitWorld.height,zVal);
Vector3 swipeEndPos = new Vector3(splitDetBounds.min.x + (splitDetBounds.size.x * 0.75f),topOfPitWorld.y,zVal);
spawnSkeletonSwipeHand(swipeStartPos,swipeEndPos);
foundBlockToSplit = true;
splitsDoneByGame.Add(nxtTargetSplitDetID);
break;
}
}
syllsForAutoSplit.RemoveAt(0);
}
}
private void resetAttempts()
{
wordUnattempted = true;
for(int i=0; i<conWordAttemptsStates.Length; i++)
{
conWordAttemptsStates[i] = false;
}
}
private ScoreBoardScript getScoreBoardScript()
{
ScoreBoardScript sbs = transform.GetComponent<ScoreBoardScript>();
if(sbs == null) { sbs = transform.gameObject.AddComponent<ScoreBoardScript>(); } else { sbs.enabled = true; }
return sbs;
}
private DeliveryChuteScript getDeliveryChuteScript()
{
DeliveryChuteScript dcs = transform.GetComponent<DeliveryChuteScript>();
if(dcs == null) { dcs = transform.gameObject.AddComponent<DeliveryChuteScript>(); } else { dcs.enabled = true; }
dcs.registerListener("AcScen",this);
return dcs;
}
private CircleTimerScript getChopTimerScript()
{
CircleTimerScript reqScript = null;
Transform wordChopTimer = GameObject.Find("WordChopTimer").transform;
if(wordChopTimer != null)
{
reqScript = wordChopTimer.FindChild("Timer").GetComponent<CircleTimerScript>();
if(reqScript != null)
{
reqScript.enabled = true;
reqScript.registerListener("AcScen",this);
}
}
return reqScript;
}
private TextMesh getLineCounterTMesh()
{
TextMesh retScript = null;
GameObject solomonGObj = GameObject.Find("SolomonWhole");
if(solomonGObj != null)
{
retScript = solomonGObj.transform.FindChild("LineCounter").GetComponent<TextMesh>();
}
return retScript;
}
private void triggerSoundAtCamera(string para_soundFileName)
{
GameObject camGObj = Camera.main.gameObject;
GameObject nwSFX = ((Transform) Instantiate(sfxPrefab,camGObj.transform.position,Quaternion.identity)).gameObject;
DontDestroyOnLoad(nwSFX);
AudioSource audS = (AudioSource) nwSFX.GetComponent(typeof(AudioSource));
audS.clip = (AudioClip) Resources.Load("Sounds/"+para_soundFileName,typeof(AudioClip));
audS.volume = 0.5f;
audS.Play();
}
protected new void loadTextures()
{
availableTextures = new Dictionary<string, Texture2D>();
Texture2D progressBarTex = new Texture2D(1,1);
progressBarTex.SetPixel(1,1,Color.green);
progressBarTex.Apply();
Texture2D progressBarTexDark = new Texture2D(1,1);
progressBarTexDark.SetPixel(1,1,new Color(0,0.2f,0));
progressBarTexDark.Apply();
availableTextures.Add("PortraitProgFore",progressBarTex);
availableTextures.Add("PortraitProgForeDark",progressBarTexDark);
}
private SJWordItem findWordInCache(int para_id)
{
SJWordItem retData = null;
if(wordItemCache.ContainsKey(para_id))
{
retData = wordItemCache[para_id];
}
return retData;
}
class TetrisInfo
{
public int id;
public int[] coords;
public int wordSize;
public bool isIndivisible;
public TetrisInfo(int para_id, int[] para_startingCoords, int para_wordSize, bool para_isIndivisible)
{
id = para_id;
coords = para_startingCoords;
wordSize = para_wordSize;
isIndivisible = para_isIndivisible;
}
}
class WordSegmentComparer : System.Collections.Generic.IComparer<string>
{
public int Compare(string x, string y)
{
string[] x_suffixParts = ((x.Split(':')[1]).Split('-'));
string[] y_suffixParts = ((y.Split(':')[1]).Split('-'));
int[] x_parsedLetterRange = new int[2] { int.Parse(x_suffixParts[0]), int.Parse(x_suffixParts[1]) };
int[] y_parsedLetterRange = new int[2] { int.Parse(y_suffixParts[0]), int.Parse(y_suffixParts[1]) };
if(x_parsedLetterRange[1] < y_parsedLetterRange[0])
{
return -1;
}
else if(x_parsedLetterRange[0] > y_parsedLetterRange[1])
{
return 1;
}
else
{
return 0;
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookChartSeriesPointsCollectionRequest.
/// </summary>
public partial class WorkbookChartSeriesPointsCollectionRequest : BaseRequest, IWorkbookChartSeriesPointsCollectionRequest
{
/// <summary>
/// Constructs a new WorkbookChartSeriesPointsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookChartSeriesPointsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified WorkbookChartPoint to the collection via POST.
/// </summary>
/// <param name="workbookChartPoint">The WorkbookChartPoint to add.</param>
/// <returns>The created WorkbookChartPoint.</returns>
public System.Threading.Tasks.Task<WorkbookChartPoint> AddAsync(WorkbookChartPoint workbookChartPoint)
{
return this.AddAsync(workbookChartPoint, CancellationToken.None);
}
/// <summary>
/// Adds the specified WorkbookChartPoint to the collection via POST.
/// </summary>
/// <param name="workbookChartPoint">The WorkbookChartPoint to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookChartPoint.</returns>
public System.Threading.Tasks.Task<WorkbookChartPoint> AddAsync(WorkbookChartPoint workbookChartPoint, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<WorkbookChartPoint>(workbookChartPoint, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IWorkbookChartSeriesPointsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IWorkbookChartSeriesPointsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<WorkbookChartSeriesPointsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartSeriesPointsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartSeriesPointsCollectionRequest Expand(Expression<Func<WorkbookChartPoint, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartSeriesPointsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartSeriesPointsCollectionRequest Select(Expression<Func<WorkbookChartPoint, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartSeriesPointsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartSeriesPointsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartSeriesPointsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartSeriesPointsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
// 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.Immutable;
using System.Diagnostics;
using System.IO;
using System.Reflection.Internal;
using System.Reflection.Metadata;
using System.Threading;
namespace System.Reflection.PortableExecutable
{
/// <summary>
/// Portable Executable format reader.
/// </summary>
/// <remarks>
/// The implementation is thread-safe, that is multiple threads can read data from the reader in parallel.
/// Disposal of the reader is not thread-safe (see <see cref="Dispose"/>).
/// </remarks>
public sealed class PEReader : IDisposable
{
// May be null in the event that the entire image is not
// deemed necessary and we have been instructed to read
// the image contents without being lazy.
private MemoryBlockProvider peImage;
// If we read the data from the image lazily (peImage != null) we defer reading the PE headers.
private PEHeaders lazyPEHeaders;
private AbstractMemoryBlock lazyMetadataBlock;
private AbstractMemoryBlock lazyImageBlock;
private AbstractMemoryBlock[] lazyPESectionBlocks;
/// <summary>
/// Creates a Portable Executable reader over a PE image stored in memory.
/// </summary>
/// <param name="peImage">Pointer to the start of the PE image.</param>
/// <param name="size">The size of the PE image.</param>
/// <exception cref="ArgumentNullException"><paramref name="peImage"/> is <see cref="IntPtr.Zero"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> is negative.</exception>
/// <remarks>
/// The memory is owned by the caller and not released on disposal of the <see cref="PEReader"/>.
/// The caller is responsible for keeping the memory alive and unmodified throughout the lifetime of the <see cref="PEReader"/>.
/// The content of the image is not read during the construction of the <see cref="PEReader"/>
/// </remarks>
public unsafe PEReader(byte* peImage, int size)
{
if (peImage == null)
{
throw new ArgumentNullException("peImage");
}
if (size < 0)
{
throw new ArgumentOutOfRangeException("size");
}
this.peImage = new ExternalMemoryBlockProvider(peImage, size);
}
/// <summary>
/// Creates a Portable Executable reader over a PE image stored in a stream.
/// </summary>
/// <param name="peStream">PE image stream.</param>
/// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception>
/// <exception cref="BadImageFormatException">
/// <see cref="PEStreamOptions.PrefetchMetadata"/> is specified and the PE headers of the image are invalid.
/// </exception>
/// <remarks>
/// Ownership of the stream is transferred to the <see cref="PEReader"/> upon successful validation of constructor arguments. It will be
/// disposed by the <see cref="PEReader"/> and the caller must not manipulate it.
/// </remarks>
public PEReader(Stream peStream)
: this(peStream, PEStreamOptions.Default)
{
}
/// <summary>
/// Creates a Portable Executable reader over a PE image stored in a stream beginning at its current position and ending at the end of the stream.
/// </summary>
/// <param name="peStream">PE image stream.</param>
/// <param name="options">
/// Options specifying how sections of the PE image are read from the stream.
///
/// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="PEReader"/>
/// upon successful argument validation. It will be disposed by the <see cref="PEReader"/> and the caller must not manipulate it.
///
/// Unless <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified no data
/// is read from the stream during the construction of the <see cref="PEReader"/>. Furthermore, the stream must not be manipulated
/// by caller while the <see cref="PEReader"/> is alive and undisposed.
///
/// If <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/>, the <see cref="PEReader"/>
/// will have read all of the data requested during construction. As such, if <see cref="PEStreamOptions.LeaveOpen"/> is also
/// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="PEReader"/>
/// after construction.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="options"/> has an invalid value.</exception>
/// <exception cref="BadImageFormatException">
/// <see cref="PEStreamOptions.PrefetchMetadata"/> is specified and the PE headers of the image are invalid.
/// </exception>
public PEReader(Stream peStream, PEStreamOptions options)
: this(peStream, options, (int?)null)
{
}
/// <summary>
/// Creates a Portable Executable reader over a PE image of the given size beginning at the stream's current position.
/// </summary>
/// <param name="peStream">PE image stream.</param>
/// <param name="size">PE image size.</param>
/// <param name="options">
/// Options specifying how sections of the PE image are read from the stream.
///
/// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="PEReader"/>
/// upon successful argument validation. It will be disposed by the <see cref="PEReader"/> and the caller must not manipulate it.
///
/// Unless <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified no data
/// is read from the stream during the construction of the <see cref="PEReader"/>. Furthermore, the stream must not be manipulated
/// by caller while the <see cref="PEReader"/> is alive and undisposed.
///
/// If <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/>, the <see cref="PEReader"/>
/// will have read all of the data requested during construction. As such, if <see cref="PEStreamOptions.LeaveOpen"/> is also
/// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="PEReader"/>
/// after construction.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception>
public PEReader(Stream peStream, PEStreamOptions options, int size)
: this(peStream, options, (int?)size)
{
}
private unsafe PEReader(Stream peStream, PEStreamOptions options, int? sizeOpt)
{
if (peStream == null)
{
throw new ArgumentNullException("peStream");
}
if (!peStream.CanRead || !peStream.CanSeek)
{
throw new ArgumentException(MetadataResources.StreamMustSupportReadAndSeek, "peStream");
}
if (!options.IsValid())
{
throw new ArgumentOutOfRangeException("options");
}
long start = peStream.Position;
int size = PEBinaryReader.GetAndValidateSize(peStream, sizeOpt);
bool closeStream = true;
try
{
bool isFileStream = FileStreamReadLightUp.IsFileStream(peStream);
if ((options & (PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage)) == 0)
{
this.peImage = new StreamMemoryBlockProvider(peStream, start, size, isFileStream, (options & PEStreamOptions.LeaveOpen) != 0);
closeStream = false;
}
else
{
// Read in the entire image or metadata blob:
if ((options & PEStreamOptions.PrefetchEntireImage) != 0)
{
var imageBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, isFileStream, 0, (int)Math.Min(peStream.Length, int.MaxValue));
this.lazyImageBlock = imageBlock;
this.peImage = new ExternalMemoryBlockProvider(imageBlock.Pointer, imageBlock.Size);
// if the caller asked for metadata initialize the PE headers (calculates metadata offset):
if ((options & PEStreamOptions.PrefetchMetadata) != 0)
{
InitializePEHeaders();
}
}
else
{
// The peImage is left null, but the lazyMetadataBlock is initialized up front.
this.lazyPEHeaders = new PEHeaders(peStream);
this.lazyMetadataBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, isFileStream, lazyPEHeaders.MetadataStartOffset, lazyPEHeaders.MetadataSize);
}
// We read all we need, the stream is going to be closed.
}
}
finally
{
if (closeStream && (options & PEStreamOptions.LeaveOpen) == 0)
{
peStream.Dispose();
}
}
}
/// <summary>
/// Creates a Portable Executable reader over a PE image stored in a byte array.
/// </summary>
/// <param name="peImage">PE image.</param>
/// <remarks>
/// The content of the image is not read during the construction of the <see cref="PEReader"/>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception>
public PEReader(ImmutableArray<byte> peImage)
{
if (peImage.IsDefault)
{
throw new ArgumentNullException("peImage");
}
this.peImage = new ByteArrayMemoryProvider(peImage);
}
/// <summary>
/// Disposes all memory allocated by the reader.
/// </summary>
/// <remarks>
/// <see cref="Dispose"/> can be called multiple times (even in parallel).
/// However, it is not safe to call <see cref="Dispose"/> in parallel with any other operation on the <see cref="PEReader"/>
/// or reading from <see cref="PEMemoryBlock"/>s retrieved from the reader.
/// </remarks>
public void Dispose()
{
var image = peImage;
if (image != null)
{
image.Dispose();
peImage = null;
}
var imageBlock = lazyImageBlock;
if (imageBlock != null)
{
imageBlock.Dispose();
lazyImageBlock = null;
}
var metadataBlock = lazyMetadataBlock;
if (metadataBlock != null)
{
metadataBlock.Dispose();
lazyMetadataBlock = null;
}
var peSectionBlocks = lazyPESectionBlocks;
if (peSectionBlocks != null)
{
foreach (var block in peSectionBlocks)
{
if (block != null)
{
block.Dispose();
}
}
lazyPESectionBlocks = null;
}
}
/// <summary>
/// Gets the PE headers.
/// </summary>
/// <exception cref="BadImageFormatException">The headers contain invalid data.</exception>
public PEHeaders PEHeaders
{
get
{
if (lazyPEHeaders == null)
{
InitializePEHeaders();
}
return lazyPEHeaders;
}
}
private void InitializePEHeaders()
{
Debug.Assert(peImage != null);
StreamConstraints constraints;
Stream stream = peImage.GetStream(out constraints);
PEHeaders headers;
if (constraints.GuardOpt != null)
{
lock (constraints.GuardOpt)
{
headers = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize);
}
}
else
{
headers = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize);
}
Interlocked.CompareExchange(ref lazyPEHeaders, headers, null);
}
private static PEHeaders ReadPEHeadersNoLock(Stream stream, long imageStartPosition, int imageSize)
{
Debug.Assert(imageStartPosition >= 0 && imageStartPosition <= stream.Length);
stream.Seek(imageStartPosition, SeekOrigin.Begin);
return new PEHeaders(stream, imageSize);
}
/// <summary>
/// Returns a view of the entire image as a pointer and length.
/// </summary>
/// <exception cref="InvalidOperationException">PE image not available.</exception>
private AbstractMemoryBlock GetEntireImageBlock()
{
if (lazyImageBlock == null)
{
if (peImage == null)
{
throw new InvalidOperationException(MetadataResources.PEImageNotAvailable);
}
var newBlock = peImage.GetMemoryBlock();
if (Interlocked.CompareExchange(ref lazyImageBlock, newBlock, null) != null)
{
// another thread created the block already, we need to dispose ours:
newBlock.Dispose();
}
}
return lazyImageBlock;
}
private AbstractMemoryBlock GetMetadataBlock()
{
if (!HasMetadata)
{
throw new InvalidOperationException(MetadataResources.PEImageDoesNotHaveMetadata);
}
if (lazyMetadataBlock == null)
{
Debug.Assert(peImage != null, "We always have metadata if peImage is not available.");
var newBlock = peImage.GetMemoryBlock(PEHeaders.MetadataStartOffset, PEHeaders.MetadataSize);
if (Interlocked.CompareExchange(ref lazyMetadataBlock, newBlock, null) != null)
{
// another thread created the block already, we need to dispose ours:
newBlock.Dispose();
}
}
return lazyMetadataBlock;
}
private AbstractMemoryBlock GetPESectionBlock(int index)
{
Debug.Assert(index >= 0 && index < PEHeaders.SectionHeaders.Length);
Debug.Assert(peImage != null);
if (lazyPESectionBlocks == null)
{
Interlocked.CompareExchange(ref lazyPESectionBlocks, new AbstractMemoryBlock[PEHeaders.SectionHeaders.Length], null);
}
var newBlock = peImage.GetMemoryBlock(
PEHeaders.SectionHeaders[index].PointerToRawData,
PEHeaders.SectionHeaders[index].SizeOfRawData);
if (Interlocked.CompareExchange(ref lazyPESectionBlocks[index], newBlock, null) != null)
{
// another thread created the block already, we need to dispose ours:
newBlock.Dispose();
}
return lazyPESectionBlocks[index];
}
/// <summary>
/// Return true if the reader can access the entire PE image.
/// </summary>
/// <remarks>
/// Returns false if the <see cref="PEReader"/> is constructed from a stream and only part of it is prefetched into memory.
/// </remarks>
public bool IsEntireImageAvailable
{
get { return lazyImageBlock != null || peImage != null; }
}
/// <summary>
/// Gets a pointer to and size of the PE image if available (<see cref="IsEntireImageAvailable"/>).
/// </summary>
/// <exception cref="InvalidOperationException">The entire PE image is not available.</exception>
public PEMemoryBlock GetEntireImage()
{
return new PEMemoryBlock(GetEntireImageBlock());
}
/// <summary>
/// Returns true if the PE image contains CLI metadata.
/// </summary>
/// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception>
public bool HasMetadata
{
get { return PEHeaders.MetadataSize > 0; }
}
/// <summary>
/// Loads PE section that contains CLI metadata.
/// </summary>
/// <exception cref="InvalidOperationException">The PE image doesn't contain metadata (<see cref="HasMetadata"/> returns false).</exception>
/// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception>
public PEMemoryBlock GetMetadata()
{
return new PEMemoryBlock(GetMetadataBlock());
}
/// <summary>
/// Loads PE section that contains the specified <paramref name="relativeVirtualAddress"/> into memory
/// and returns a memory block that starts at <paramref name="relativeVirtualAddress"/> and ends at the end of the containing section.
/// </summary>
/// <param name="relativeVirtualAddress">Relative Virtual Address of the data to read.</param>
/// <returns>
/// An empty block if <paramref name="relativeVirtualAddress"/> doesn't represent a location in any of the PE sections of this PE image.
/// </returns>
/// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception>
public PEMemoryBlock GetSectionData(int relativeVirtualAddress)
{
var sectionIndex = PEHeaders.GetContainingSectionIndex(relativeVirtualAddress);
if (sectionIndex < 0)
{
return default(PEMemoryBlock);
}
int relativeOffset = relativeVirtualAddress - PEHeaders.SectionHeaders[sectionIndex].VirtualAddress;
int size = PEHeaders.SectionHeaders[sectionIndex].VirtualSize - relativeOffset;
AbstractMemoryBlock block;
if (peImage != null)
{
block = GetPESectionBlock(sectionIndex);
}
else
{
block = GetEntireImageBlock();
relativeOffset += PEHeaders.SectionHeaders[sectionIndex].PointerToRawData;
}
return new PEMemoryBlock(block, relativeOffset);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Razor.Serialization;
using Newtonsoft.Json;
using Xunit;
namespace Microsoft.AspNetCore.Razor.Language
{
public class TagHelperDescriptorComparerTest
{
private static readonly TestFile TagHelpersTestFile = TestFile.Create("TestFiles/taghelpers.json", typeof(TagHelperDescriptorComparerTest));
[Fact]
public void GetHashCode_SameTagHelperDescriptors_HashCodeMatches()
{
// Arrange
var descriptor1 = CreateTagHelperDescriptor(
tagName: "input",
typeName: "InputTagHelper",
assemblyName: "TestAssembly",
attributes: new Action<BoundAttributeDescriptorBuilder>[]
{
builder => builder
.Name("value")
.PropertyName("FooProp")
.TypeName("System.String"),
});
var descriptor2 = CreateTagHelperDescriptor(
tagName: "input",
typeName: "InputTagHelper",
assemblyName: "TestAssembly",
attributes: new Action<BoundAttributeDescriptorBuilder>[]
{
builder => builder
.Name("value")
.PropertyName("FooProp")
.TypeName("System.String"),
});
// Act
var hashCode1 = descriptor1.GetHashCode();
var hashCode2 = descriptor2.GetHashCode();
// Assert
Assert.Equal(hashCode1, hashCode2);
}
[Fact]
public void GetHashCode_FQNAndNameTagHelperDescriptors_HashCodeDoesNotMatch()
{
// Arrange
var descriptorName = CreateTagHelperDescriptor(
tagName: "input",
typeName: "InputTagHelper",
assemblyName: "TestAssembly",
tagMatchingRuleName: "Input",
attributes: new Action<BoundAttributeDescriptorBuilder>[]
{
builder => builder
.Name("value")
.PropertyName("FooProp")
.TypeName("System.String"),
});
var descriptorFQN = CreateTagHelperDescriptor(
tagName: "input",
typeName: "InputTagHelper",
assemblyName: "TestAssembly",
tagMatchingRuleName: "Microsoft.AspNetCore.Components.Forms.Input",
attributes: new Action<BoundAttributeDescriptorBuilder>[]
{
builder => builder
.Name("value")
.PropertyName("FooProp")
.TypeName("System.String"),
});
// Act
var hashCodeName = descriptorName.GetHashCode();
var hashCodeFQN = descriptorFQN.GetHashCode();
// Assert
Assert.NotEqual(hashCodeName, hashCodeFQN);
}
[Fact]
public void GetHashCode_DifferentTagHelperDescriptors_HashCodeDoesNotMatch()
{
// Arrange
var counterTagHelper = CreateTagHelperDescriptor(
tagName: "Counter",
typeName: "CounterTagHelper",
assemblyName: "Components.Component",
tagMatchingRuleName: "Input",
attributes: new Action<BoundAttributeDescriptorBuilder>[]
{
builder => builder
.Name("IncrementBy")
.PropertyName("IncrementBy")
.TypeName("System.Int32"),
});
var inputTagHelper = CreateTagHelperDescriptor(
tagName: "input",
typeName: "InputTagHelper",
assemblyName: "TestAssembly",
tagMatchingRuleName: "Microsoft.AspNetCore.Components.Forms.Input",
attributes: new Action<BoundAttributeDescriptorBuilder>[]
{
builder => builder
.Name("value")
.PropertyName("FooProp")
.TypeName("System.String"),
});
// Act
var hashCodeCounter = counterTagHelper.GetHashCode();
var hashCodeInput = inputTagHelper.GetHashCode();
// Assert
Assert.NotEqual(hashCodeCounter, hashCodeInput);
}
[Fact]
public void GetHashCode_AllTagHelpers_NoHashCodeCollisions()
{
// Arrange
var tagHelpers = ReadTagHelpers(TagHelpersTestFile.OpenRead());
// Act
var hashes = new HashSet<int>(tagHelpers.Select(t => t.GetHashCode()));
// Assert
Assert.Equal(hashes.Count, tagHelpers.Count);
}
[Fact]
public void GetHashCode_DuplicateTagHelpers_NoHashCodeCollisions()
{
// Arrange
var tagHelpers = new List<TagHelperDescriptor>();
var tagHelpersPerBatch = -1;
// Reads 5 copies of the TagHelpers (with 5x references)
// This ensures we don't have any dependencies on reference based GetHashCode
for (var i = 0; i < 5; ++i)
{
var tagHelpersBatch = ReadTagHelpers(TagHelpersTestFile.OpenRead());
tagHelpers.AddRange(tagHelpersBatch);
tagHelpersPerBatch = tagHelpersBatch.Count;
}
// Act
var hashes = new HashSet<int>(tagHelpers.Select(t => t.GetHashCode()));
// Assert
// Only 1 batch of taghelpers should remain after we filter by hash
Assert.Equal(hashes.Count, tagHelpersPerBatch);
}
private static TagHelperDescriptor CreateTagHelperDescriptor(
string tagName,
string typeName,
string assemblyName,
string tagMatchingRuleName = null,
IEnumerable<Action<BoundAttributeDescriptorBuilder>> attributes = null)
{
var builder = TagHelperDescriptorBuilder.Create(typeName, assemblyName) as DefaultTagHelperDescriptorBuilder;
builder.TypeName(typeName);
if (attributes != null)
{
foreach (var attributeBuilder in attributes)
{
builder.BoundAttributeDescriptor(attributeBuilder);
}
}
builder.TagMatchingRuleDescriptor(ruleBuilder => ruleBuilder.RequireTagName(tagMatchingRuleName ?? tagName));
var descriptor = builder.Build();
return descriptor;
}
private IReadOnlyList<TagHelperDescriptor> ReadTagHelpers(Stream stream)
{
var serializer = new JsonSerializer();
serializer.Converters.Add(new RazorDiagnosticJsonConverter());
serializer.Converters.Add(new TagHelperDescriptorJsonConverter());
IReadOnlyList<TagHelperDescriptor> result;
using var streamReader = new StreamReader(stream);
using (var reader = new JsonTextReader(streamReader))
{
result = serializer.Deserialize<IReadOnlyList<TagHelperDescriptor>>(reader);
}
stream.Dispose();
return result;
}
}
}
| |
using System;
using System.Drawing;
#if __UNIFIED__
using CoreAnimation;
using CoreGraphics;
using Foundation;
using UIKit;
#else
using MonoTouch.CoreAnimation;
using MonoTouch.CoreGraphics;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using CGPoint = global::System.Drawing.PointF;
#endif
using LoginScreen.Utils;
using LoginScreen.Views;
namespace LoginScreen.ViewControllers
{
abstract class BaseViewController : UIViewController
{
UIScrollView scrollView;
UIAlertView activityAlert;
BaseFormView formView;
protected BaseViewController (string title)
{
Title = title;
UIKeyboard.Notifications.ObserveWillChangeFrame (KeyboardWillChangeFrame);
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
View = new UIScrollView (View.Frame);
var gradientLayer = new CAGradientLayer ();
gradientLayer.Colors = new [] {
UIColor.FromRGB (241, 246, 250).CGColor,
UIColor.FromRGB (222, 231, 240).CGColor
};
View.Layer.InsertSublayer (gradientLayer, 0);
View.BackgroundColor = UIColor.FromRGB (230, 236, 245);
var endEditingGestureRecognizer = new UITapGestureRecognizer (() => View.EndEditing (true))
{
ShouldBegin = IsTouchOutsideOfAnyButton
};
View.AddGestureRecognizer (endEditingGestureRecognizer);
formView = CreateFormView ();
#if __UNIFIED__
formView.BackClick += (sender, e) => NavigationController.PopViewController (true);
#else
formView.BackClick += (sender, e) => NavigationController.PopViewControllerAnimated (true);
#endif
scrollView = new UIScrollView
{
Frame = View.Bounds,
ContentSize = formView.Bounds.Size,
AutoresizingMask = UIViewAutoresizing.FlexibleDimensions
};
scrollView.AddSubview (formView);
View.AddSubview (scrollView);
}
protected abstract BaseFormView CreateFormView ();
public override void ViewDidLayoutSubviews ()
{
base.ViewDidLayoutSubviews ();
formView.Center = scrollView.GetContentCenter ();
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
formView.Clear ();
}
public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations ()
{
return AutorotateHelper.GetSupportedInterfaceOrientations ();
}
#pragma warning disable 0672
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
#pragma warning restore 0672
{
return AutorotateHelper.ShouldAutorotateToInterfaceOrientation (toInterfaceOrientation);
}
protected bool IsEmailValid (string email)
{
try {
new System.Net.Mail.MailAddress (email);
} catch (FormatException) {
return false;
}
return true;
}
protected void StartActivityAnimation (string title)
{
if (activityAlert != null) {
StopActivityAnimation ();
}
activityAlert = new UIAlertView
{
Title = title
};
var indicator = new UIActivityIndicatorView
{
ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.White,
Center = new CGPoint(activityAlert.Bounds.GetMidX(), activityAlert.Bounds.GetMidY()),
AutoresizingMask = UIViewAutoresizing.FlexibleMargins
};
indicator.StartAnimating ();
activityAlert.AddSubview (indicator);
activityAlert.Show ();
}
protected void StopActivityAnimation ()
{
if (activityAlert != null) {
activityAlert.DismissWithClickedButtonIndex (0, true);
activityAlert = null;
}
}
protected void ShowAlert (string title, string text, string cancelButtonTitle)
{
var alert = new UIAlertView
{
Title = title,
Message = text
};
alert.AddButton (cancelButtonTitle);
alert.Show ();
}
public override void ViewWillDisappear (bool animated)
{
base.ViewWillDisappear (animated);
View.EndEditing (true);
}
#pragma warning disable 0672
public override void ViewDidUnload ()
#pragma warning restore 0672
{
#pragma warning disable 0618
base.ViewDidUnload ();
#pragma warning restore 0618
ReleaseOutlet (ref scrollView);
ReleaseOutlet (ref formView);
}
protected void ReleaseOutlet<T> (ref T view)
where T : UIView
{
if (view != null) {
view.Dispose ();
view = null;
}
}
void KeyboardWillChangeFrame (object sender, UIKeyboardEventArgs e)
{
if (IsViewLoaded && View.Window != null) {
scrollView.Frame = View.GetAreaAboveKeyboard (e.FrameBegin);
formView.Center = scrollView.GetContentCenter ();
UIView.Animate (e.AnimationDuration, 0, e.AnimationCurve.ToAnimationOptions (), () => {
scrollView.Frame = View.GetAreaAboveKeyboard (e.FrameEnd);
formView.Center = scrollView.GetContentCenter ();
}, null);
}
}
bool IsTouchOutsideOfAnyButton (UIGestureRecognizer recognizer)
{
var location = recognizer.LocationInView (recognizer.View);
var viewWithTouchInside = recognizer.View.HitTest (location, null);
return !(viewWithTouchInside is UIButton);
}
}
}
| |
// DeflaterEngine.cs
// Copyright (C) 2001 Mike Krueger
//
// 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.
#if CONFIG_COMPRESSION
using System;
using ICSharpCode.SharpZipLib.Checksums;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
internal enum DeflateStrategy
{
// The default strategy.
Default = 0,
// This strategy will only allow longer string repetitions. It is
// useful for random data with a small character set.
Filtered = 1,
// This strategy will not look for string repetitions at all. It
// only encodes with Huffman trees (which means, that more common
// characters get a smaller encoding.
HuffmanOnly = 2
}
internal class DeflaterEngine : DeflaterConstants
{
static int TOO_FAR = 4096;
int ins_h;
// private byte[] buffer;
short[] head;
short[] prev;
int matchStart, matchLen;
bool prevAvailable;
int blockStart;
int strstart, lookahead;
byte[] window;
DeflateStrategy strategy;
int max_chain, max_lazy, niceLength, goodLength;
/// <summary>
/// The current compression function.
/// </summary>
int comprFunc;
/// <summary>
/// The input data for compression.
/// </summary>
byte[] inputBuf;
/// <summary>
/// The total bytes of input read.
/// </summary>
int totalIn;
/// <summary>
/// The offset into inputBuf, where input data starts.
/// </summary>
int inputOff;
/// <summary>
/// The end offset of the input data.
/// </summary>
int inputEnd;
DeflaterPending pending;
DeflaterHuffman huffman;
/// <summary>
/// The adler checksum
/// </summary>
Adler32 adler;
public DeflaterEngine(DeflaterPending pending)
{
this.pending = pending;
huffman = new DeflaterHuffman(pending);
adler = new Adler32();
window = new byte[2 * WSIZE];
head = new short[HASH_SIZE];
prev = new short[WSIZE];
/* We start at index 1, to avoid a implementation deficiency, that
* we cannot build a repeat pattern at index 0.
*/
blockStart = strstart = 1;
}
public void Reset()
{
huffman.Reset();
adler.Reset();
blockStart = strstart = 1;
lookahead = 0;
totalIn = 0;
prevAvailable = false;
matchLen = MIN_MATCH - 1;
for (int i = 0; i < HASH_SIZE; i++)
{
head[i] = 0;
}
for (int i = 0; i < WSIZE; i++)
{
prev[i] = 0;
}
}
public void ResetAdler()
{
adler.Reset();
}
public int Adler
{
get
{
return (int)adler.Value;
}
}
public int TotalIn
{
get
{
return totalIn;
}
}
public DeflateStrategy Strategy
{
get
{
return strategy;
}
set
{
strategy = value;
}
}
public void SetLevel(int lvl)
{
goodLength = DeflaterConstants.GOOD_LENGTH[lvl];
max_lazy = DeflaterConstants.MAX_LAZY[lvl];
niceLength = DeflaterConstants.NICE_LENGTH[lvl];
max_chain = DeflaterConstants.MAX_CHAIN[lvl];
if (DeflaterConstants.COMPR_FUNC[lvl] != comprFunc)
{
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Change from "+comprFunc +" to "
// + DeflaterConstants.COMPR_FUNC[lvl]);
// }
switch (comprFunc)
{
case DEFLATE_STORED:
if (strstart > blockStart)
{
huffman.FlushStoredBlock(window, blockStart,
strstart - blockStart, false);
blockStart = strstart;
}
UpdateHash();
break;
case DEFLATE_FAST:
if (strstart > blockStart)
{
huffman.FlushBlock(window, blockStart, strstart - blockStart,
false);
blockStart = strstart;
}
break;
case DEFLATE_SLOW:
if (prevAvailable)
{
huffman.TallyLit(window[strstart-1] & 0xff);
}
if (strstart > blockStart)
{
huffman.FlushBlock(window, blockStart, strstart - blockStart,
false);
blockStart = strstart;
}
prevAvailable = false;
matchLen = MIN_MATCH - 1;
break;
}
comprFunc = COMPR_FUNC[lvl];
}
}
private void UpdateHash()
{
// if (DEBUGGING) {
// //Console.WriteLine("updateHash: "+strstart);
// }
ins_h = (window[strstart] << HASH_SHIFT) ^ window[strstart + 1];
}
private int InsertString()
{
short match;
int hash = ((ins_h << HASH_SHIFT) ^ window[strstart + (MIN_MATCH -1)]) & HASH_MASK;
// if (DEBUGGING) {
// if (hash != (((window[strstart] << (2*HASH_SHIFT)) ^
// (window[strstart + 1] << HASH_SHIFT) ^
// (window[strstart + 2])) & HASH_MASK)) {
// throw new Exception("hash inconsistent: "+hash+"/"
// +window[strstart]+","
// +window[strstart+1]+","
// +window[strstart+2]+","+HASH_SHIFT);
// }
// }
prev[strstart & WMASK] = match = head[hash];
head[hash] = (short)strstart;
ins_h = hash;
return match & 0xffff;
}
void SlideWindow()
{
Array.Copy(window, WSIZE, window, 0, WSIZE);
matchStart -= WSIZE;
strstart -= WSIZE;
blockStart -= WSIZE;
/* Slide the hash table (could be avoided with 32 bit values
* at the expense of memory usage).
*/
for (int i = 0; i < HASH_SIZE; ++i)
{
int m = head[i] & 0xffff;
head[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0);
}
/* Slide the prev table. */
for (int i = 0; i < WSIZE; i++)
{
int m = prev[i] & 0xffff;
prev[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0);
}
}
public void FillWindow()
{
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (strstart >= WSIZE + MAX_DIST)
{
SlideWindow();
}
/* If there is not enough lookahead, but still some input left,
* read in the input
*/
while (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd)
{
int more = 2 * WSIZE - lookahead - strstart;
if (more > inputEnd - inputOff)
{
more = inputEnd - inputOff;
}
System.Array.Copy(inputBuf, inputOff, window, strstart + lookahead, more);
adler.Update(inputBuf, inputOff, more);
inputOff += more;
totalIn += more;
lookahead += more;
}
if (lookahead >= MIN_MATCH)
{
UpdateHash();
}
}
private bool FindLongestMatch(int curMatch)
{
int chainLength = this.max_chain;
int niceLength = this.niceLength;
short[] prev = this.prev;
int scan = this.strstart;
int match;
int best_end = this.strstart + matchLen;
int best_len = Math.Max(matchLen, MIN_MATCH - 1);
int limit = Math.Max(strstart - MAX_DIST, 0);
int strend = strstart + MAX_MATCH - 1;
byte scan_end1 = window[best_end - 1];
byte scan_end = window[best_end];
/* Do not waste too much time if we already have a good match: */
if (best_len >= this.goodLength)
{
chainLength >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (niceLength > lookahead)
{
niceLength = lookahead;
}
if (DeflaterConstants.DEBUGGING && strstart > 2 * WSIZE - MIN_LOOKAHEAD)
{
throw new InvalidOperationException("need lookahead");
}
do
{
if (DeflaterConstants.DEBUGGING && curMatch >= strstart)
{
throw new InvalidOperationException("future match");
}
if (window[curMatch + best_len] != scan_end ||
window[curMatch + best_len - 1] != scan_end1 ||
window[curMatch] != window[scan] ||
window[curMatch + 1] != window[scan + 1])
{
continue;
}
match = curMatch + 2;
scan += 2;
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
while (window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] && scan < strend) ;
if (scan > best_end)
{
// if (DeflaterConstants.DEBUGGING && ins_h == 0)
// System.err.println("Found match: "+curMatch+"-"+(scan-strstart));
matchStart = curMatch;
best_end = scan;
best_len = scan - strstart;
if (best_len >= niceLength)
{
break;
}
scan_end1 = window[best_end - 1];
scan_end = window[best_end];
}
scan = strstart;
} while ((curMatch = (prev[curMatch & WMASK] & 0xffff)) > limit && --chainLength != 0);
matchLen = Math.Min(best_len, lookahead);
return matchLen >= MIN_MATCH;
}
public void SetDictionary(byte[] buffer, int offset, int length)
{
if (DeflaterConstants.DEBUGGING && strstart != 1)
{
throw new InvalidOperationException("strstart not 1");
}
adler.Update(buffer, offset, length);
if (length < MIN_MATCH)
{
return;
}
if (length > MAX_DIST)
{
offset += length - MAX_DIST;
length = MAX_DIST;
}
System.Array.Copy(buffer, offset, window, strstart, length);
UpdateHash();
--length;
while (--length > 0)
{
InsertString();
strstart++;
}
strstart += 2;
blockStart = strstart;
}
private bool DeflateStored(bool flush, bool finish)
{
if (!flush && lookahead == 0)
{
return false;
}
strstart += lookahead;
lookahead = 0;
int storedLen = strstart - blockStart;
if ((storedLen >= DeflaterConstants.MAX_BLOCK_SIZE) || /* Block is full */
(blockStart < WSIZE && storedLen >= MAX_DIST) || /* Block may move out of window */
flush)
{
bool lastBlock = finish;
if (storedLen > DeflaterConstants.MAX_BLOCK_SIZE)
{
storedLen = DeflaterConstants.MAX_BLOCK_SIZE;
lastBlock = false;
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("storedBlock["+storedLen+","+lastBlock+"]");
// }
huffman.FlushStoredBlock(window, blockStart, storedLen, lastBlock);
blockStart += storedLen;
return !lastBlock;
}
return true;
}
private bool DeflateFast(bool flush, bool finish)
{
if (lookahead < MIN_LOOKAHEAD && !flush)
{
return false;
}
while (lookahead >= MIN_LOOKAHEAD || flush)
{
if (lookahead == 0)
{
/* We are flushing everything */
huffman.FlushBlock(window, blockStart, strstart - blockStart, finish);
blockStart = strstart;
return false;
}
if (strstart > 2 * WSIZE - MIN_LOOKAHEAD)
{
/* slide window, as findLongestMatch need this.
* This should only happen when flushing and the window
* is almost full.
*/
SlideWindow();
}
int hashHead;
if (lookahead >= MIN_MATCH &&
(hashHead = InsertString()) != 0 &&
strategy != DeflateStrategy.HuffmanOnly &&
strstart - hashHead <= MAX_DIST &&
FindLongestMatch(hashHead))
{
/* longestMatch sets matchStart and matchLen */
// if (DeflaterConstants.DEBUGGING) {
// for (int i = 0 ; i < matchLen; i++) {
// if (window[strstart+i] != window[matchStart + i]) {
// throw new Exception();
// }
// }
// }
huffman.TallyDist(strstart - matchStart, matchLen);
lookahead -= matchLen;
if (matchLen <= max_lazy && lookahead >= MIN_MATCH)
{
while (--matchLen > 0)
{
++strstart;
InsertString();
}
++strstart;
}
else
{
strstart += matchLen;
if (lookahead >= MIN_MATCH - 1)
{
UpdateHash();
}
}
matchLen = MIN_MATCH - 1;
continue;
}
else
{
/* No match found */
huffman.TallyLit(window[strstart] & 0xff);
++strstart;
--lookahead;
}
if (huffman.IsFull())
{
bool lastBlock = finish && lookahead == 0;
huffman.FlushBlock(window, blockStart, strstart - blockStart,
lastBlock);
blockStart = strstart;
return !lastBlock;
}
}
return true;
}
private bool DeflateSlow(bool flush, bool finish)
{
if (lookahead < MIN_LOOKAHEAD && !flush)
{
return false;
}
while (lookahead >= MIN_LOOKAHEAD || flush)
{
if (lookahead == 0)
{
if (prevAvailable)
{
huffman.TallyLit(window[strstart-1] & 0xff);
}
prevAvailable = false;
/* We are flushing everything */
if (DeflaterConstants.DEBUGGING && !flush)
{
throw new Exception("Not flushing, but no lookahead");
}
huffman.FlushBlock(window, blockStart, strstart - blockStart,
finish);
blockStart = strstart;
return false;
}
if (strstart >= 2 * WSIZE - MIN_LOOKAHEAD)
{
/* slide window, as findLongestMatch need this.
* This should only happen when flushing and the window
* is almost full.
*/
SlideWindow();
}
int prevMatch = matchStart;
int prevLen = matchLen;
if (lookahead >= MIN_MATCH)
{
int hashHead = InsertString();
if (strategy != DeflateStrategy.HuffmanOnly && hashHead != 0 && strstart - hashHead <= MAX_DIST && FindLongestMatch(hashHead))
{
/* longestMatch sets matchStart and matchLen */
/* Discard match if too small and too far away */
if (matchLen <= 5 && (strategy == DeflateStrategy.Filtered || (matchLen == MIN_MATCH && strstart - matchStart > TOO_FAR)))
{
matchLen = MIN_MATCH - 1;
}
}
}
/* previous match was better */
if (prevLen >= MIN_MATCH && matchLen <= prevLen)
{
// if (DeflaterConstants.DEBUGGING) {
// for (int i = 0 ; i < matchLen; i++) {
// if (window[strstart-1+i] != window[prevMatch + i])
// throw new Exception();
// }
// }
huffman.TallyDist(strstart - 1 - prevMatch, prevLen);
prevLen -= 2;
do
{
strstart++;
lookahead--;
if (lookahead >= MIN_MATCH)
{
InsertString();
}
} while (--prevLen > 0);
strstart ++;
lookahead--;
prevAvailable = false;
matchLen = MIN_MATCH - 1;
}
else
{
if (prevAvailable)
{
huffman.TallyLit(window[strstart-1] & 0xff);
}
prevAvailable = true;
strstart++;
lookahead--;
}
if (huffman.IsFull())
{
int len = strstart - blockStart;
if (prevAvailable)
{
len--;
}
bool lastBlock = (finish && lookahead == 0 && !prevAvailable);
huffman.FlushBlock(window, blockStart, len, lastBlock);
blockStart += len;
return !lastBlock;
}
}
return true;
}
public bool Deflate(bool flush, bool finish)
{
bool progress;
do
{
FillWindow();
bool canFlush = flush && inputOff == inputEnd;
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("window: ["+blockStart+","+strstart+","
// +lookahead+"], "+comprFunc+","+canFlush);
// }
switch (comprFunc)
{
case DEFLATE_STORED:
progress = DeflateStored(canFlush, finish);
break;
case DEFLATE_FAST:
progress = DeflateFast(canFlush, finish);
break;
case DEFLATE_SLOW:
progress = DeflateSlow(canFlush, finish);
break;
default:
throw new InvalidOperationException("unknown comprFunc");
}
} while (pending.IsFlushed && progress); /* repeat while we have no pending output and progress was made */
return progress;
}
public void SetInput(byte[] buf, int off, int len)
{
if (inputOff < inputEnd)
{
throw new InvalidOperationException("Old input was not completely processed");
}
int end = off + len;
/* We want to throw an ArrayIndexOutOfBoundsException early. The
* check is very tricky: it also handles integer wrap around.
*/
if (0 > off || off > end || end > buf.Length)
{
throw new ArgumentOutOfRangeException();
}
inputBuf = buf;
inputOff = off;
inputEnd = end;
}
public bool NeedsInput()
{
return inputEnd == inputOff;
}
}
}
#endif // CONFIG_COMPRESSION
| |
using System;
using System.Collections.Generic;
using System.Text;
using CalciumImagingProcessor;
using RRLab.PhysiologyWorkbench.Data;
using System.ComponentModel;
using RRLab.PhysiologyDataConnectivity;
using MySql.Data.MySqlClient;
using MathWorks.MATLAB.NET.Arrays;
using RRLab.Utilities;
namespace RRLab.PhysiologyDataWorkshop.Experiments.CalciumImaging
{
public class CalciumImagingExperiment : Experiment, IDisposable
{
#region Data
public event EventHandler SteadyStateCalciumDataSetChanged;
private SteadyStateCalciumDataSet _SteadyStateCalciumDataSet;
public SteadyStateCalciumDataSet SteadyStateCalciumDataSet
{
get { return _SteadyStateCalciumDataSet; }
set {
_SteadyStateCalciumDataSet = value;
OnSteadyStateCalciumDataSetChanged(EventArgs.Empty);
}
}
protected virtual void OnSteadyStateCalciumDataSetChanged(EventArgs e)
{
if(SteadyStateCalciumDataSetChanged != null)
try
{
SteadyStateCalciumDataSetChanged(this, e);
}
catch (Exception x)
{
System.Diagnostics.Debug.Fail("CalciumImagingExperiment: Error during SteadyStateCalciumDataSetChanged event.", x.Message);
}
NotifyPropertyChanged("SteadyStateCalciumDataSet");
}
#endregion
#region State Management
public event EventHandler CurrentSteadyStateCalciumExperimentChanged;
private SteadyStateCalciumDataSet.SteadyStateCalciumExperimentsRow _CurrentSteadyStateCalciumExperiment;
[Bindable(true)]
public SteadyStateCalciumDataSet.SteadyStateCalciumExperimentsRow CurrentSteadyStateCalciumExperiment
{
get { return _CurrentSteadyStateCalciumExperiment; }
set {
_CurrentSteadyStateCalciumExperiment = value;
OnCurrentSteadyStateCalciumExperimentChanged(EventArgs.Empty);
}
}
protected virtual void OnCurrentSteadyStateCalciumExperimentChanged(EventArgs e)
{
if(CurrentSteadyStateCalciumExperimentChanged != null)
try
{
CurrentSteadyStateCalciumExperimentChanged(this, e);
}
catch (Exception x)
{
System.Diagnostics.Debug.Fail("CalciumImagingExperiment: Error during CurrentSteadyStateCalciumExperimentChanged event.", x.Message);
}
NotifyPropertyChanged("CurrentSteadyStateCalciumExperimentChanged");
}
#endregion
#region GUI State Management
private string _HistogramColumn;
[Bindable(true)]
public string HistogramColumn
{
get { return _HistogramColumn; }
set
{
_HistogramColumn = value;
NotifyPropertyChanged("HistogramColumn");
}
}
private string _HistogramFilter;
[Bindable(true)]
public string HistogramFilter
{
get { return _HistogramFilter; }
set
{
_HistogramFilter = value;
NotifyPropertyChanged("HistogramFilter");
}
}
private string _ScatterXColumn;
[Bindable(true)]
public string ScatterXColumn
{
get { return _ScatterXColumn; }
set
{
_ScatterXColumn = value;
NotifyPropertyChanged("ScatterXColumn");
}
}
private string _ScatterYColumn;
[Bindable(true)]
public string ScatterYColumn
{
get { return _ScatterYColumn; }
set
{
_ScatterYColumn = value;
NotifyPropertyChanged("ScatterYColumn");
}
}
private string _ScatterFilter;
[Bindable(true)]
public string ScatterFilter
{
get { return _ScatterFilter; }
set
{
_ScatterFilter = value;
NotifyPropertyChanged("ScatterFilter");
}
}
#endregion
#region Other Properties
private CalciumImagingProcessor.CalciumImagingProcessor _CalciumImagingProcessor;
public CalciumImagingProcessor.CalciumImagingProcessor CalciumImagingProcessor
{
get { return _CalciumImagingProcessor;}
set { _CalciumImagingProcessor = value;}
}
#endregion
#region Constructors
public CalciumImagingExperiment() : base()
{
}
#endregion
#region Overridden ExperimentRow Properties and Methods
public override string Name
{
get
{
return "Calcium Imaging";
}
}
protected CalciumImagingPanelControl _ExperimentPanel;
public override System.Windows.Forms.Control GetExperimentPanelControl()
{
if (_ExperimentPanel == null) _ExperimentPanel = new CalciumImagingPanelControl(this);
return _ExperimentPanel;
}
protected override void OnProgramChanged(EventArgs e)
{
base.OnProgramChanged(e);
try
{
Program.UpdatedDatabase -= new EventHandler(OnPhysiologyDatabaseUpdated);
}
catch { ; }
Program.UpdatedDatabase += new EventHandler(OnPhysiologyDatabaseUpdated);
}
#endregion
#region Actions
protected override void ConfigureCellActions()
{
CellActions.Add("Create new calcium imaging experiment using this cell", new Action<RRLab.PhysiologyWorkbench.Data.PhysiologyDataSet.CellsRow>(CreateNewCalciumImagingExperiment));
CellActions.Add("Delete associated calcium imaging experiment", new Action<RRLab.PhysiologyWorkbench.Data.PhysiologyDataSet.CellsRow>(DeleteCalciumImagingExperiment));
base.ConfigureCellActions();
}
public override bool IsCellActionEnabled(string actionName, PhysiologyDataSet.CellsRow cell)
{
if (SteadyStateCalciumDataSet == null) return false;
switch (actionName)
{
case "Create new calcium imaging experiment using this cell":
return SteadyStateCalciumDataSet.SteadyStateCalciumExperiments.FindByCellID(cell.CellID) == null;
case "Delete associated calcium imaging experiment":
return SteadyStateCalciumDataSet.SteadyStateCalciumExperiments.FindByCellID(cell.CellID) != null;
default:
return true;
}
}
public virtual void CreateNewCalciumImagingExperiment(PhysiologyDataSet.CellsRow cell)
{
CurrentSteadyStateCalciumExperiment = SteadyStateCalciumDataSet.SteadyStateCalciumExperiments.NewSteadyStateCalciumExperimentsRow();
CurrentSteadyStateCalciumExperiment.CellID = cell.CellID;
AddNewCalciumExperimentDialog dialog = new AddNewCalciumExperimentDialog(this, CurrentSteadyStateCalciumExperiment);
dialog.Show();
}
public virtual void DeleteCalciumImagingExperiment(PhysiologyDataSet.CellsRow cell)
{
SteadyStateCalciumDataSet.SteadyStateCalciumExperimentsRow row = SteadyStateCalciumDataSet.SteadyStateCalciumExperiments.FindByCellID(cell.CellID);
if (row != null)
{
row.Delete();
if (CurrentSteadyStateCalciumExperiment == row) CurrentSteadyStateCalciumExperiment = null;
}
else
{
System.Windows.Forms.MessageBox.Show(String.Format("Cell {0} is not currently used in an experiment.", cell.CellID));
}
}
protected override void ConfigureRecordingActions()
{
RecordingActions.Add("Set current recording as the calcium signal", new Action<PhysiologyDataSet.RecordingsRow>(SetCalciumSignalRecording));
RecordingActions.Add("Set current recording as the high signal", new Action<PhysiologyDataSet.RecordingsRow>(SetHighSignalRecording));
RecordingActions.Add("Set current recording as the low signal", new Action<PhysiologyDataSet.RecordingsRow>(SetLowSignalRecording));
base.ConfigureRecordingActions();
}
public override bool IsRecordingActionEnabled(string actionName, PhysiologyDataSet.RecordingsRow recording)
{
if (SteadyStateCalciumDataSet == null) return false;
if (CurrentSteadyStateCalciumExperiment == null) return false;
else return true;
}
public virtual void SetCalciumSignalRecording(PhysiologyDataSet.RecordingsRow recording)
{
if (CurrentSteadyStateCalciumExperiment == null)
CreateNewCalciumImagingExperiment(recording.CellsRow);
CurrentSteadyStateCalciumExperiment.SignalRecordingID = recording.RecordingID;
}
public virtual void SetHighSignalRecording(PhysiologyDataSet.RecordingsRow recording)
{
if (CurrentSteadyStateCalciumExperiment == null)
CreateNewCalciumImagingExperiment(recording.CellsRow);
CurrentSteadyStateCalciumExperiment.HighRecordingID = recording.RecordingID;
}
public virtual void SetLowSignalRecording(PhysiologyDataSet.RecordingsRow recording)
{
if (CurrentSteadyStateCalciumExperiment == null)
CreateNewCalciumImagingExperiment(recording.CellsRow);
CurrentSteadyStateCalciumExperiment.LowRecordingID = recording.RecordingID;
}
#endregion
#region IDisposable Members
~CalciumImagingExperiment()
{
Dispose();
}
public virtual void Dispose()
{
try
{
if (CalciumImagingProcessor != null)
{
CalciumImagingProcessor.Dispose();
}
if (_ExperimentPanel != null)
{
_ExperimentPanel.Dispose();
}
}
catch (Exception x)
{
System.Diagnostics.Debug.Fail("CalciumImagingExperiment: Error while disposing.", x.Message);
}
finally
{
CalciumImagingProcessor = null;
_ExperimentPanel = null;
}
}
#endregion
#region Database Operations
private LogInDialog _LogInDialog = new LogInDialog();
public LogInDialog LogInDialog
{
get { return _LogInDialog; }
set { _LogInDialog = value; }
}
SortedList<SteadyStateCalciumDataSet.SteadyStateCalciumExperimentsRow, PhysiologyDataSet.RecordingsRow> _ProcessedCalciumRowsToSync = new SortedList<SteadyStateCalciumDataSet.SteadyStateCalciumExperimentsRow, PhysiologyDataSet.RecordingsRow>();
public virtual void AddExperiment(SteadyStateCalciumDataSet.SteadyStateCalciumExperimentsRow experiment)
{
try
{
if (!experiment.IsProcessedSignalRecordingIDNull())
{
PhysiologyDataSet.RecordingsRow processedCalcium = PhysiologyDataSet.Recordings.FindByRecordingID(experiment.ProcessedSignalRecordingID);
_ProcessedCalciumRowsToSync.Add(experiment, processedCalcium);
}
if (experiment.RowState == System.Data.DataRowState.Detached)
SteadyStateCalciumDataSet.SteadyStateCalciumExperiments.AddSteadyStateCalciumExperimentsRow(experiment);
Program.UpdateDatabase();
// UpdateDataToDatabase() gets called when Program.UpdateDatabase() asynchronously completes. This ensures that the rows are in the right state.
}
catch (Exception x)
{
System.Windows.Forms.MessageBox.Show(x.Message, "Error adding experiment.");
}
}
protected virtual void OnPhysiologyDatabaseUpdated(object sender, EventArgs e)
{
SyncProcessedCalciumRows();
UpdateDataToDatabase();
}
protected virtual void SyncProcessedCalciumRows()
{
foreach (KeyValuePair<SteadyStateCalciumDataSet.SteadyStateCalciumExperimentsRow, PhysiologyDataSet.RecordingsRow> kv in _ProcessedCalciumRowsToSync)
kv.Key.ProcessedSignalRecordingID = kv.Value.RecordingID;
_ProcessedCalciumRowsToSync.Clear();
}
protected string FillExperimentTableSelectCommandText =
@"SELECT s.CellID, s.Analyzed, rs.Recorded, u.Name Experimenter, g.Genotype,
s.CalciumConcentration, s.DarkAdapted, s.SignalRecordingID, s.HighRecordingID,
s.LowRecordingID, s.ProcessedSignalRecordingID, s.SignalPeakFluorescence,
s.SignalAverageFluorescence, s.SignalFluorescenceError, s.HighAverageFluorescence,
s.HighFluorescenceError, s.LowAverageFluorescence, s.LowFluorescenceError, s.SteadyStateCalcium,
s.SteadyStateCalciumError, s.InitialCalcium, s.InitialCalciumError, s.PeakCalcium,
s.PeakCalciumError, s.TimeToPeak, s.TimeToSteadyState, s.Comments, c.PipetteResistance, c.SealResistance,
c.CellCapacitance, c.MembraneResistance, c.SeriesResistance, c.MembranePotential, rs.HoldingPotential,
rs.PipetteSolution, rs.BathSolution, rh.BathSolution AS HighBathSolution, rl.BathSolution AS LowBathSolution,
c.RoughAppearanceRating, c.LengthAppearanceRating, c.ShapeAppearanceRating, c.BreakInTime,
timediff(c.BreakInTime, rs.Recorded) AS TimeSinceBreakIn,
timediff(rs.Recorded, rh.Recorded) AS HighMeasurementDelay,
timediff(rl.Recorded, rh.Recorded) AS LowMeasurementDelay
FROM expt_sscalcium s, cells c, recordings rs, recordings rh, recordings rl, users u, genotypes g
WHERE c.CellID = s.CellID AND rs.RecordingID = s.SignalRecordingID AND
rh.RecordingID = s.HighRecordingID AND rl.RecordingID = s.LowRecordingID AND
u.UserID = c.UserID AND g.FlyStockID = c.FlyStockID";
public virtual void LoadDataFromDatabase()
{
if (SteadyStateCalciumDataSet == null)
SteadyStateCalciumDataSet = new SteadyStateCalciumDataSet();
if (LogInDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (MySqlConnection connection = new MySqlConnection(LogInDialog.ConnectionString))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(FillExperimentTableSelectCommandText, connection))
{
adapter.Fill(SteadyStateCalciumDataSet.SteadyStateCalciumExperiments);
}
}
}
OnSteadyStateCalciumDataSetChanged(EventArgs.Empty);
}
public virtual void UpdateDataToDatabase()
{
if (SteadyStateCalciumDataSet == null)
SteadyStateCalciumDataSet = new SteadyStateCalciumDataSet();
if (LogInDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (MySqlConnection connection = new MySqlConnection(LogInDialog.ConnectionString))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(FillExperimentTableSelectCommandText, connection))
{
using (MySqlCommand insertCommand = new MySqlCommand(
@"INSERT INTO expt_sscalcium (CellID, Analyzed, CalciumConcentration, DarkAdapted, SignalRecordingID," +
"HighRecordingID, LowRecordingID, ProcessedSignalRecordingID, SignalPeakFluorescence," +
"SignalAverageFluorescence, SignalFluorescenceError, HighAverageFluorescence," +
"HighFluorescenceError, LowAverageFluorescence, LowFluorescenceError, SteadyStateCalcium," +
"SteadyStateCalciumError, InitialCalcium, InitialCalciumError, PeakCalcium," +
"PeakCalciumError, TimeToPeak, TimeToSteadyState, Comments, SignalInitialFluorescence)" +
"VALUES (?p1,?p2,?p3,?p4,?p5,?p6,?p7,?p8,?p9,?p10,?p11,?p12,?p13,?p14,?p15,?p16,?p17,?p18,?p19,?p20,?p21,?p22,?p23,?p24,?p25);",
connection),
updateCommand = new MySqlCommand(
@"UPDATE expt_sscalcium SET CellID = ?p1, Analyzed = ?p2, CalciumConcentration = ?p3, DarkAdapted = ?p4,
SignalRecordingID = ?p5, HighRecordingID = ?p6, LowRecordingID = ?p7, ProcessedSignalRecordingID = ?p8,
SignalPeakFluorescence = ?p9, SignalAverageFluorescence = ?p10,
SignalFluorescenceError = ?p11, HighAverageFluorescence = ?p12, HighFluorescenceError = ?p13,
LowAverageFluorescence = ?p14, LowFluorescenceError = ?p15, SteadyStateCalcium = ?p16,
SteadyStateCalciumError = ?p17, InitialCalcium = ?p18, InitialCalciumError = ?p19, PeakCalcium = ?p20,
PeakCalciumError = ?p21, TimeToPeak = ?p22, TimeToSteadyState = ?p23, Comments = ?p24, SignalInitialFluorescence = ?p25
WHERE CellID = ?p26",
connection),
deleteCommand = new MySqlCommand(
@"DELETE FROM expt_sscalcium WHERE CellID = ?p1", connection))
{
insertCommand.Parameters.Add("?p1", MySqlDbType.Int32, 0, "CellID");
insertCommand.Parameters.Add("?p2", MySqlDbType.Datetime, 0, "Analyzed");
insertCommand.Parameters.Add("?p3", MySqlDbType.Float, 0, "CalciumConcentration");
insertCommand.Parameters.Add("?p4", MySqlDbType.Bit, 0, "DarkAdapted");
insertCommand.Parameters.Add("?p5", MySqlDbType.Int64, 0, "SignalRecordingID");
insertCommand.Parameters.Add("?p6", MySqlDbType.Int64, 0, "HighRecordingID");
insertCommand.Parameters.Add("?p7", MySqlDbType.Int64, 0, "LowRecordingID");
insertCommand.Parameters.Add("?p8", MySqlDbType.Int64, 0, "ProcessedSignalRecordingID");
insertCommand.Parameters.Add("?p9", MySqlDbType.Double, 0, "SignalPeakFluorescence");
insertCommand.Parameters.Add("?p10", MySqlDbType.Double, 0, "SignalAverageFluorescence");
insertCommand.Parameters.Add("?p11", MySqlDbType.Double, 0, "SignalFluorescenceError");
insertCommand.Parameters.Add("?p12", MySqlDbType.Double, 0, "HighAverageFluorescence");
insertCommand.Parameters.Add("?p13", MySqlDbType.Double, 0, "HighFluorescenceError");
insertCommand.Parameters.Add("?p14", MySqlDbType.Double, 0, "LowAverageFluorescence");
insertCommand.Parameters.Add("?p15", MySqlDbType.Double, 0, "LowFluorescenceError");
insertCommand.Parameters.Add("?p16", MySqlDbType.Double, 0, "SteadyStateCalcium");
insertCommand.Parameters.Add("?p17", MySqlDbType.Double, 0, "SteadyStateCalciumError");
insertCommand.Parameters.Add("?p18", MySqlDbType.Double, 0, "InitialCalcium");
insertCommand.Parameters.Add("?p19", MySqlDbType.Double, 0, "InitialCalciumError");
insertCommand.Parameters.Add("?p20", MySqlDbType.Double, 0, "PeakCalcium");
insertCommand.Parameters.Add("?p21", MySqlDbType.Double, 0, "PeakCalciumError");
insertCommand.Parameters.Add("?p22", MySqlDbType.Float, 0, "TimeToPeak");
insertCommand.Parameters.Add("?p23", MySqlDbType.Float, 0, "TimeToSteadyState");
insertCommand.Parameters.Add("?p24", MySqlDbType.String, 0, "Comments");
insertCommand.Parameters.Add("?p25", MySqlDbType.Double, 0, "SignalInitialFluorescence");
updateCommand.Parameters.Add("?p1", MySqlDbType.Int32, 0, "CellID");
updateCommand.Parameters.Add("?p2", MySqlDbType.Datetime, 0, "Analyzed");
updateCommand.Parameters.Add("?p3", MySqlDbType.Float, 0, "CalciumConcentration");
updateCommand.Parameters.Add("?p4", MySqlDbType.Bit, 0, "DarkAdapted");
updateCommand.Parameters.Add("?p5", MySqlDbType.Int64, 0, "SignalRecordingID");
updateCommand.Parameters.Add("?p6", MySqlDbType.Int64, 0, "HighRecordingID");
updateCommand.Parameters.Add("?p7", MySqlDbType.Int64, 0, "LowRecordingID");
updateCommand.Parameters.Add("?p8", MySqlDbType.Int64, 0, "ProcessedSignalRecordingID");
updateCommand.Parameters.Add("?p9", MySqlDbType.Double, 0, "SignalPeakFluorescence");
updateCommand.Parameters.Add("?p10", MySqlDbType.Double, 0, "SignalAverageFluorescence");
updateCommand.Parameters.Add("?p11", MySqlDbType.Double, 0, "SignalFluorescenceError");
updateCommand.Parameters.Add("?p12", MySqlDbType.Double, 0, "HighAverageFluorescence");
updateCommand.Parameters.Add("?p13", MySqlDbType.Double, 0, "HighFluorescenceError");
updateCommand.Parameters.Add("?p14", MySqlDbType.Double, 0, "LowAverageFluorescence");
updateCommand.Parameters.Add("?p15", MySqlDbType.Double, 0, "LowFluorescenceError");
updateCommand.Parameters.Add("?p16", MySqlDbType.Double, 0, "SteadyStateCalcium");
updateCommand.Parameters.Add("?p17", MySqlDbType.Double, 0, "SteadyStateCalciumError");
updateCommand.Parameters.Add("?p18", MySqlDbType.Double, 0, "InitialCalcium");
updateCommand.Parameters.Add("?p19", MySqlDbType.Double, 0, "InitialCalciumError");
updateCommand.Parameters.Add("?p20", MySqlDbType.Double, 0, "PeakCalcium");
updateCommand.Parameters.Add("?p21", MySqlDbType.Double, 0, "PeakCalciumError");
updateCommand.Parameters.Add("?p22", MySqlDbType.Float, 0, "TimeToPeak");
updateCommand.Parameters.Add("?p23", MySqlDbType.Float, 0, "TimeToSteadyState");
updateCommand.Parameters.Add("?p24", MySqlDbType.String, 0, "Comments");
updateCommand.Parameters.Add("?p25", MySqlDbType.Double, 0, "SignalInitialFluorescence");
updateCommand.Parameters.Add("?p26", MySqlDbType.Int32, 0, "CellID");
updateCommand.Parameters["?p26"].SourceVersion = System.Data.DataRowVersion.Original;
deleteCommand.Parameters.Add("?p1", MySqlDbType.Int32, 0, "CellID");
adapter.DeleteCommand = deleteCommand;
adapter.InsertCommand = insertCommand;
adapter.UpdateCommand = updateCommand;
adapter.Update(SteadyStateCalciumDataSet.SteadyStateCalciumExperiments);
adapter.Fill(SteadyStateCalciumDataSet.SteadyStateCalciumExperiments);
}
}
}
}
}
#endregion
#region Data Processing
private string _FluorescenceDataName = "Photodiode 1";
public string FluorescenceDataName
{
get { return _FluorescenceDataName; }
set { _FluorescenceDataName = value; }
}
public virtual void AnalyzeExperiment(SteadyStateCalciumDataSet.SteadyStateCalciumExperimentsRow experiment, float steadyStateTime, int nPeaks)
{
if (CalciumImagingProcessor == null) CalciumImagingProcessor = new CalciumImagingProcessor.CalciumImagingProcessor();
try {
PhysiologyDataSet.RecordingsRow signalRecording = PhysiologyDataSet.Recordings.FindByRecordingID(experiment.SignalRecordingID);
Program.LoadRecordingAndSubdataFromDatabase(signalRecording);
PhysiologyDataSet.RecordingsRow highRecording = PhysiologyDataSet.Recordings.FindByRecordingID(experiment.HighRecordingID);
Program.LoadRecordingAndSubdataFromDatabase(highRecording);
PhysiologyDataSet.RecordingsRow lowRecording = PhysiologyDataSet.Recordings.FindByRecordingID(experiment.LowRecordingID);
Program.LoadRecordingAndSubdataFromDatabase(lowRecording);
TimeResolvedData signal, high, low;
signal = signalRecording.GetData(FluorescenceDataName);
high = highRecording.GetData(FluorescenceDataName);
low = lowRecording.GetData(FluorescenceDataName);
string equipmentSettingsName = FluorescenceDataName + "-Gain";
if (signalRecording.DoesEquipmentSettingExist(equipmentSettingsName) && highRecording.DoesEquipmentSettingExist(equipmentSettingsName) && lowRecording.DoesEquipmentSettingExist(equipmentSettingsName))
{
try
{
double signalGain = Double.Parse(signalRecording.GetEquipmentSetting(equipmentSettingsName));
double highGain = Double.Parse(highRecording.GetEquipmentSetting(equipmentSettingsName));
double lowGain = Double.Parse(lowRecording.GetEquipmentSetting(equipmentSettingsName));
if (signalGain != highGain || signalGain != lowGain)
{
for(int i=0; i < high.DataPoints.Length; i++)
high[i] = new TimeResolvedDataPoint(high[i].Time, high[i].Data * signalGain / highGain);
for(int i=0; i < low.DataPoints.Length; i++)
low[i] = new TimeResolvedDataPoint(low[i].Time, low[i].Data * signalGain / lowGain);
}
}
catch (Exception x)
{
System.Windows.Forms.MessageBox.Show("Error while analyzing calcium data. Could not adjust fluorescence values for differences in gain.");
}
}
experiment.Analyzed = DateTime.Now;
MWStructArray output = (MWStructArray)CalciumImagingProcessor.ProcessCalciumData((MWNumericArray)signal.Time, (MWNumericArray)signal.Values, (MWNumericArray)high.Time, (MWNumericArray)high.Values, (MWNumericArray)low.Time, (MWNumericArray)low.Values, (MWNumericArray)steadyStateTime, nPeaks);
experiment.SignalInitialFluorescence = ((MWNumericArray)output.GetField("Vinit")).ToScalarDouble();
experiment.SignalAverageFluorescence = ((MWNumericArray)output.GetField("ssV")).ToScalarDouble();
experiment.SignalFluorescenceError = ((MWNumericArray)output.GetField("ssV_std")).ToScalarDouble();
experiment.SignalPeakFluorescence = ((MWNumericArray)output.GetField("peakV")).ToScalarDouble();
experiment.HighAverageFluorescence = ((MWNumericArray)output.GetField("Vmax")).ToScalarDouble();
experiment.HighFluorescenceError = ((MWNumericArray)output.GetField("Vmax_std")).ToScalarDouble();
experiment.LowAverageFluorescence = ((MWNumericArray)output.GetField("Vmin")).ToScalarDouble();
experiment.LowFluorescenceError = ((MWNumericArray)output.GetField("Vmin_std")).ToScalarDouble();
MWNumericArray ssCa = ((MWNumericArray)output.GetField("ssCa"));
if(!ssCa.IsComplex)
experiment.SteadyStateCalcium = ssCa.ToScalarDouble();
MWNumericArray ssCaError = ((MWNumericArray)output.GetField("ssCa_err"));
if(!ssCaError.IsComplex)
experiment.SteadyStateCalciumError = ssCaError.ToScalarDouble();
MWNumericArray iCa = ((MWNumericArray)output.GetField("iCa"));
if(!iCa.IsComplex)
experiment.InitialCalcium = iCa.ToScalarDouble();
MWNumericArray iCaError = ((MWNumericArray)output.GetField("iCa_err"));
if(!iCaError.IsComplex)
experiment.InitialCalciumError = iCaError.ToScalarDouble();
MWNumericArray peakCa = ((MWNumericArray)output.GetField("peakCa"));
if(!peakCa.IsComplex)
experiment.PeakCalcium = peakCa.ToScalarDouble();
MWNumericArray peakCaError = ((MWNumericArray)output.GetField("peakCa_err"));
if(!peakCaError.IsComplex)
experiment.PeakCalciumError = peakCaError.ToScalarDouble();
experiment.TimeToPeak = Convert.ToSingle(((MWNumericArray)output.GetField("TimeToPeak")).ToScalarDouble());
experiment.TimeToSteadyState = Convert.ToSingle(((MWNumericArray)output.GetField("TimeToSteadyState")).ToScalarDouble());
// Create processed recording
MWStructArray caSignal = (MWStructArray) output["CalculatedCa"];
MWNumericArray caTime = (MWNumericArray) caSignal["t"];
MWNumericArray caValues = (MWNumericArray)caSignal["y"];
MWNumericArray caLowError = (MWNumericArray)caSignal["y_lowerr"];
MWNumericArray caHighError = (MWNumericArray)caSignal["y_higherr"];
List<float> time = new List<float>(caTime.NumberOfElements);
List<double> values = new List<double>(caTime.NumberOfElements);
List<double> lowErr = new List<double>(caTime.NumberOfElements);
List<double> highErr = new List<double>(caTime.NumberOfElements);
for (int i = 1; i <= caTime.NumberOfElements; i++)
{
try
{
float time_i = Convert.ToSingle(caTime[i].ToScalarDouble());
double value_i = caValues[i].ToScalarDouble();
double lowErr_i = caLowError[i].ToScalarDouble();
double highErr_i = caHighError[i].ToScalarDouble();
time.Add(time_i);
values.Add(value_i);
lowErr.Add(lowErr_i);
highErr.Add(highErr_i);
}
catch
{
continue; // Ignore errors
}
}
PhysiologyDataSet.RecordingsRow processedSignalRecording;
if (experiment.IsProcessedSignalRecordingIDNull())
processedSignalRecording = PhysiologyDataSet.Recordings.NewRecordingsRow();
else
{
processedSignalRecording = PhysiologyDataSet.Recordings.FindByRecordingID(experiment.ProcessedSignalRecordingID);
ProgressDialog callback = new ProgressDialog("Loading Processed Calcium Recording...");
Program.DatabaseConnector.LoadRecordingSubdataFromDatabase(PhysiologyDataSet, processedSignalRecording.RecordingID, callback);
ICollection<string> dataNames = processedSignalRecording.GetDataNames();
if (dataNames.Contains("Calculated Calcium"))
processedSignalRecording.ClearData("Calculated Calcium");
if (dataNames.Contains("Low Estimated Calcium Error"))
processedSignalRecording.ClearData("Low Estimated Calcium Error");
if (dataNames.Contains("High Estimated Calcium Error"))
processedSignalRecording.ClearData("High Estimated Calcium Error");
}
processedSignalRecording.CellID = experiment.CellID;
processedSignalRecording.BathSolution = signalRecording.BathSolution;
if(!signalRecording.IsPipetteSolutionNull()) processedSignalRecording.PipetteSolution = signalRecording.PipetteSolution;
processedSignalRecording.Recorded = DateTime.Now;
processedSignalRecording.Description = String.Format(
"Processed calcium data based on signal recording {0}, high recording {1}, and low recording {2}. Generated at {3}.",
experiment.SignalRecordingID, experiment.HighRecordingID, experiment.LowRecordingID, processedSignalRecording.Recorded);
if(!signalRecording.IsHoldingPotentialNull()) processedSignalRecording.HoldingPotential = signalRecording.HoldingPotential;
processedSignalRecording.Title = "Processed Calcium Signal";
processedSignalRecording.EndEdit();
if(processedSignalRecording.RowState == System.Data.DataRowState.Detached)
PhysiologyDataSet.Recordings.AddRecordingsRow(processedSignalRecording);
processedSignalRecording.AddData("Calculated Calcium", "uM", time.ToArray(), values.ToArray());
processedSignalRecording.AddData("Low Estimated Calcium Error", "uM", time.ToArray(), lowErr.ToArray());
processedSignalRecording.AddData("High Estimated Calcium Error", "uM", time.ToArray(), highErr.ToArray());
processedSignalRecording.SetMetaData("SignalRecordingID", experiment.SignalRecordingID.ToString());
processedSignalRecording.SetMetaData("HighRecordingID", experiment.HighRecordingID.ToString());
processedSignalRecording.SetMetaData("LowRecordingID", experiment.LowRecordingID.ToString());
PhysiologyDataSet.Recordings_Data.EndLoadData();
}
catch(Exception e)
{
System.Diagnostics.Debug.Fail("Error analyzing experiment.", e.Message);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
namespace System.Management.Automation
{
/// <summary>
/// The metadata associated with a parameter.
/// </summary>
internal class CompiledCommandParameter
{
#region ctor
/// <summary>
/// Constructs an instance of the CompiledCommandAttribute using the specified
/// runtime-defined parameter.
/// </summary>
/// <param name="runtimeDefinedParameter">
/// A runtime defined parameter that contains the definition of the parameter and its metadata.
/// </param>
/// <param name="processingDynamicParameters">
/// True if dynamic parameters are being processed, or false otherwise.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="runtimeDefinedParameter"/> is null.
/// </exception>
/// <exception cref="MetadataException">
/// If the parameter has more than one <see cref="ParameterAttribute">ParameterAttribute</see>
/// that defines the same parameter-set name.
/// </exception>
internal CompiledCommandParameter(RuntimeDefinedParameter runtimeDefinedParameter, bool processingDynamicParameters)
{
if (runtimeDefinedParameter == null)
{
throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameter");
}
this.Name = runtimeDefinedParameter.Name;
this.Type = runtimeDefinedParameter.ParameterType;
this.IsDynamic = processingDynamicParameters;
this.CollectionTypeInformation = new ParameterCollectionTypeInformation(runtimeDefinedParameter.ParameterType);
this.CompiledAttributes = new Collection<Attribute>();
this.ParameterSetData = new Dictionary<string, ParameterSetSpecificMetadata>(StringComparer.OrdinalIgnoreCase);
Collection<ValidateArgumentsAttribute> validationAttributes = null;
Collection<ArgumentTransformationAttribute> argTransformationAttributes = null;
string[] aliases = null;
// First, process attributes that aren't type conversions
foreach (Attribute attribute in runtimeDefinedParameter.Attributes)
{
if (processingDynamicParameters)
{
// When processing dynamic parameters, the attribute list may contain experimental attributes
// and disabled parameter attributes. We should ignore those attributes.
// When processing non-dynamic parameters, the experimental attributes and disabled parameter
// attributes have already been filtered out when constructing the RuntimeDefinedParameter.
if (attribute is ExperimentalAttribute || attribute is ParameterAttribute param && param.ToHide)
{
continue;
}
}
if (!(attribute is ArgumentTypeConverterAttribute))
{
ProcessAttribute(runtimeDefinedParameter.Name, attribute, ref validationAttributes, ref argTransformationAttributes, ref aliases);
}
}
// If this is a PSCredential type and they haven't added any argument transformation attributes,
// add one for credential transformation
if ((this.Type == typeof(PSCredential)) && argTransformationAttributes == null)
{
ProcessAttribute(runtimeDefinedParameter.Name, new CredentialAttribute(), ref validationAttributes, ref argTransformationAttributes, ref aliases);
}
// Now process type converters
foreach (var attribute in runtimeDefinedParameter.Attributes.OfType<ArgumentTypeConverterAttribute>())
{
ProcessAttribute(runtimeDefinedParameter.Name, attribute, ref validationAttributes, ref argTransformationAttributes, ref aliases);
}
this.ValidationAttributes = validationAttributes == null
? Utils.EmptyArray<ValidateArgumentsAttribute>()
: validationAttributes.ToArray();
this.ArgumentTransformationAttributes = argTransformationAttributes == null
? Utils.EmptyArray<ArgumentTransformationAttribute>()
: argTransformationAttributes.ToArray();
this.Aliases = aliases == null
? Utils.EmptyArray<string>()
: aliases.ToArray();
}
/// <summary>
/// Constructs an instance of the CompiledCommandAttribute using the reflection information retrieved
/// from the enclosing bindable object type.
/// </summary>
/// <param name="member">
/// The member information for the parameter
/// </param>
/// <param name="processingDynamicParameters">
/// True if dynamic parameters are being processed, or false otherwise.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="member"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If <paramref name="member"/> is not a field or a property.
/// </exception>
/// <exception cref="MetadataException">
/// If the member has more than one <see cref="ParameterAttribute">ParameterAttribute</see>
/// that defines the same parameter-set name.
/// </exception>
internal CompiledCommandParameter(MemberInfo member, bool processingDynamicParameters)
{
if (member == null)
{
throw PSTraceSource.NewArgumentNullException("member");
}
this.Name = member.Name;
this.DeclaringType = member.DeclaringType;
this.IsDynamic = processingDynamicParameters;
var propertyInfo = member as PropertyInfo;
if (propertyInfo != null)
{
this.Type = propertyInfo.PropertyType;
}
else
{
var fieldInfo = member as FieldInfo;
if (fieldInfo != null)
{
this.Type = fieldInfo.FieldType;
}
else
{
ArgumentException e =
PSTraceSource.NewArgumentException(
"member",
DiscoveryExceptions.CompiledCommandParameterMemberMustBeFieldOrProperty);
throw e;
}
}
this.CollectionTypeInformation = new ParameterCollectionTypeInformation(this.Type);
this.CompiledAttributes = new Collection<Attribute>();
this.ParameterSetData = new Dictionary<string, ParameterSetSpecificMetadata>(StringComparer.OrdinalIgnoreCase);
// We do not want to get the inherited custom attributes, only the attributes exposed
// directly on the member
var memberAttributes = member.GetCustomAttributes(false);
Collection<ValidateArgumentsAttribute> validationAttributes = null;
Collection<ArgumentTransformationAttribute> argTransformationAttributes = null;
string[] aliases = null;
foreach (Attribute attr in memberAttributes)
{
switch (attr)
{
case ExperimentalAttribute _:
case ParameterAttribute param when param.ToHide:
break;
default:
ProcessAttribute(member.Name, attr, ref validationAttributes, ref argTransformationAttributes, ref aliases);
break;
}
}
this.ValidationAttributes = validationAttributes == null
? Utils.EmptyArray<ValidateArgumentsAttribute>()
: validationAttributes.ToArray();
this.ArgumentTransformationAttributes = argTransformationAttributes == null
? Utils.EmptyArray<ArgumentTransformationAttribute>()
: argTransformationAttributes.ToArray();
this.Aliases = aliases ?? Utils.EmptyArray<string>();
}
#endregion ctor
/// <summary>
/// Gets the name of the parameter.
/// </summary>
internal string Name { get; private set; }
/// <summary>
/// The PSTypeName from a PSTypeNameAttribute.
/// </summary>
internal string PSTypeName { get; private set; }
/// <summary>
/// Gets the Type information of the attribute.
/// </summary>
internal Type Type { get; private set; }
/// <summary>
/// Gets the Type information of the attribute.
/// </summary>
internal Type DeclaringType { get; private set; }
/// <summary>
/// Gets whether the parameter is a dynamic parameter or not.
/// </summary>
internal bool IsDynamic { get; private set; }
/// <summary>
/// Gets the parameter collection type information.
/// </summary>
internal ParameterCollectionTypeInformation CollectionTypeInformation { get; private set; }
/// <summary>
/// A collection of the attributes found on the member. The attributes have been compiled into
/// a format that easier to digest by the metadata processor.
/// </summary>
internal Collection<Attribute> CompiledAttributes { get; private set; }
/// <summary>
/// Gets the collection of data generation attributes on this parameter.
/// </summary>
internal ArgumentTransformationAttribute[] ArgumentTransformationAttributes { get; private set; }
/// <summary>
/// Gets the collection of data validation attributes on this parameter.
/// </summary>
internal ValidateArgumentsAttribute[] ValidationAttributes { get; private set; }
/// <summary>
/// Get and private set the obsolete attribute on this parameter.
/// </summary>
internal ObsoleteAttribute ObsoleteAttribute { get; private set; }
/// <summary>
/// If true, null can be bound to the parameter even if the parameter is mandatory.
/// </summary>
internal bool AllowsNullArgument { get; private set; }
/// <summary>
/// If true, null cannot be bound to the parameter (ValidateNotNull
/// and/or ValidateNotNullOrEmpty has been specified).
/// </summary>
internal bool CannotBeNull { get; private set; }
/// <summary>
/// If true, an empty string can be bound to the string parameter
/// even if the parameter is mandatory.
/// </summary>
internal bool AllowsEmptyStringArgument { get; private set; }
/// <summary>
/// If true, an empty collection can be bound to the collection/array parameter
/// even if the parameter is mandatory.
/// </summary>
internal bool AllowsEmptyCollectionArgument { get; private set; }
/// <summary>
/// Gets or sets the value that tells whether this parameter
/// is for the "all" parameter set.
/// </summary>
internal bool IsInAllSets { get; set; }
/// <summary>
/// Returns true if this parameter is ValueFromPipeline or ValueFromPipelineByPropertyName
/// in one or more (but not necessarily all) parameter sets.
/// </summary>
internal bool IsPipelineParameterInSomeParameterSet { get; private set; }
/// <summary>
/// Returns true if this parameter is Mandatory in one or more (but not necessarily all) parameter sets.
/// </summary>
internal bool IsMandatoryInSomeParameterSet { get; private set; }
/// <summary>
/// Gets or sets the parameter set flags that map the parameter sets
/// for this parameter to the parameter set names.
/// </summary>
/// <remarks>
/// This is a bit-field that maps the parameter sets in this parameter
/// to the parameter sets for the rest of the command.
/// </remarks>
internal uint ParameterSetFlags { get; set; }
/// <summary>
/// A delegate that can set the property.
/// </summary>
internal Action<object, object> Setter { get; set; }
/// <summary>
/// A dictionary of the parameter sets and the parameter set specific data for this parameter.
/// </summary>
internal Dictionary<string, ParameterSetSpecificMetadata> ParameterSetData { get; private set; }
/// <summary>
/// The alias names for this parameter.
/// </summary>
internal string[] Aliases { get; private set; }
/// <summary>
/// Determines if this parameter takes pipeline input for any of the specified
/// parameter set flags.
/// </summary>
/// <param name="validParameterSetFlags">
/// The flags for the parameter sets to check to see if the parameter takes
/// pipeline input.
/// </param>
/// <returns>
/// True if the parameter takes pipeline input in any of the specified parameter
/// sets, or false otherwise.
/// </returns>
internal bool DoesParameterSetTakePipelineInput(uint validParameterSetFlags)
{
if (!IsPipelineParameterInSomeParameterSet)
{
return false;
}
// Loop through each parameter set the parameter is in to see if that parameter set is
// still valid. If so, and the parameter takes pipeline input in that parameter set,
// then return true
foreach (ParameterSetSpecificMetadata parameterSetData in ParameterSetData.Values)
{
if ((parameterSetData.IsInAllSets ||
(parameterSetData.ParameterSetFlag & validParameterSetFlags) != 0) &&
(parameterSetData.ValueFromPipeline ||
parameterSetData.ValueFromPipelineByPropertyName))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets the parameter set data for this parameter for the specified parameter set.
/// </summary>
/// <param name="parameterSetFlag">
/// The parameter set to get the parameter set data for.
/// </param>
/// <returns>
/// The parameter set specified data for the specified parameter set.
/// </returns>
internal ParameterSetSpecificMetadata GetParameterSetData(uint parameterSetFlag)
{
ParameterSetSpecificMetadata result = null;
foreach (ParameterSetSpecificMetadata setData in ParameterSetData.Values)
{
// If the parameter is in all sets, then remember the data, but
// try to find a more specific match
if (setData.IsInAllSets)
{
result = setData;
}
else
{
if ((setData.ParameterSetFlag & parameterSetFlag) != 0)
{
result = setData;
break;
}
}
}
return result;
}
/// <summary>
/// Gets the parameter set data for this parameter for the specified parameter sets.
/// </summary>
/// <param name="parameterSetFlags">
/// The parameter sets to get the parameter set data for.
/// </param>
/// <returns>
/// A collection for all parameter set specified data for the parameter sets specified by
/// the <paramref name="parameterSetFlags"/>.
/// </returns>
internal IEnumerable<ParameterSetSpecificMetadata> GetMatchingParameterSetData(uint parameterSetFlags)
{
foreach (ParameterSetSpecificMetadata setData in ParameterSetData.Values)
{
// If the parameter is in all sets, then remember the data, but
// try to find a more specific match
if (setData.IsInAllSets)
{
yield return setData;
}
else
{
if ((setData.ParameterSetFlag & parameterSetFlags) != 0)
{
yield return setData;
}
}
}
}
#region helper methods
/// <summary>
/// Processes the Attribute metadata to generate a CompiledCommandAttribute.
/// </summary>
/// <exception cref="MetadataException">
/// If the attribute is a parameter attribute and another parameter attribute
/// has been processed with the same parameter-set name.
/// </exception>
private void ProcessAttribute(
string memberName,
Attribute attribute,
ref Collection<ValidateArgumentsAttribute> validationAttributes,
ref Collection<ArgumentTransformationAttribute> argTransformationAttributes,
ref string[] aliases)
{
if (attribute == null)
return;
CompiledAttributes.Add(attribute);
// Now process the attribute based on it's type
if (attribute is ParameterAttribute paramAttr)
{
ProcessParameterAttribute(memberName, paramAttr);
return;
}
ValidateArgumentsAttribute validateAttr = attribute as ValidateArgumentsAttribute;
if (validateAttr != null)
{
if (validationAttributes == null)
validationAttributes = new Collection<ValidateArgumentsAttribute>();
validationAttributes.Add(validateAttr);
if ((attribute is ValidateNotNullAttribute) || (attribute is ValidateNotNullOrEmptyAttribute))
{
this.CannotBeNull = true;
}
return;
}
AliasAttribute aliasAttr = attribute as AliasAttribute;
if (aliasAttr != null)
{
if (aliases == null)
{
aliases = aliasAttr.aliasNames;
}
else
{
var prevAliasNames = aliases;
var newAliasNames = aliasAttr.aliasNames;
aliases = new string[prevAliasNames.Length + newAliasNames.Length];
Array.Copy(prevAliasNames, aliases, prevAliasNames.Length);
Array.Copy(newAliasNames, 0, aliases, prevAliasNames.Length, newAliasNames.Length);
}
return;
}
ArgumentTransformationAttribute argumentAttr = attribute as ArgumentTransformationAttribute;
if (argumentAttr != null)
{
if (argTransformationAttributes == null)
argTransformationAttributes = new Collection<ArgumentTransformationAttribute>();
argTransformationAttributes.Add(argumentAttr);
return;
}
AllowNullAttribute allowNullAttribute = attribute as AllowNullAttribute;
if (allowNullAttribute != null)
{
this.AllowsNullArgument = true;
return;
}
AllowEmptyStringAttribute allowEmptyStringAttribute = attribute as AllowEmptyStringAttribute;
if (allowEmptyStringAttribute != null)
{
this.AllowsEmptyStringArgument = true;
return;
}
AllowEmptyCollectionAttribute allowEmptyCollectionAttribute = attribute as AllowEmptyCollectionAttribute;
if (allowEmptyCollectionAttribute != null)
{
this.AllowsEmptyCollectionArgument = true;
return;
}
ObsoleteAttribute obsoleteAttr = attribute as ObsoleteAttribute;
if (obsoleteAttr != null)
{
ObsoleteAttribute = obsoleteAttr;
return;
}
PSTypeNameAttribute psTypeNameAttribute = attribute as PSTypeNameAttribute;
if (psTypeNameAttribute != null)
{
this.PSTypeName = psTypeNameAttribute.PSTypeName;
}
}
/// <summary>
/// Extracts the data from the ParameterAttribute and creates the member data as necessary.
/// </summary>
/// <param name="parameterName">
/// The name of the parameter.
/// </param>
/// <param name="parameter">
/// The instance of the ParameterAttribute to extract the data from.
/// </param>
/// <exception cref="MetadataException">
/// If a parameter set name has already been declared on this parameter.
/// </exception>
private void ProcessParameterAttribute(
string parameterName,
ParameterAttribute parameter)
{
// If the parameter set name already exists on this parameter and the set name is the default parameter
// set name, it is an error.
if (ParameterSetData.ContainsKey(parameter.ParameterSetName))
{
MetadataException e =
new MetadataException(
"ParameterDeclaredInParameterSetMultipleTimes",
null,
DiscoveryExceptions.ParameterDeclaredInParameterSetMultipleTimes,
parameterName,
parameter.ParameterSetName);
throw e;
}
if (parameter.ValueFromPipeline || parameter.ValueFromPipelineByPropertyName)
{
IsPipelineParameterInSomeParameterSet = true;
}
if (parameter.Mandatory)
{
IsMandatoryInSomeParameterSet = true;
}
// Construct an instance of the parameter set specific data
ParameterSetSpecificMetadata parameterSetSpecificData = new ParameterSetSpecificMetadata(parameter);
ParameterSetData.Add(parameter.ParameterSetName, parameterSetSpecificData);
}
public override string ToString()
{
return Name;
}
#endregion helper methods
}
/// <summary>
/// The types of collections that are supported as parameter types.
/// </summary>
internal enum ParameterCollectionType
{
NotCollection,
IList,
Array,
ICollectionGeneric
}
/// <summary>
/// Contains the collection type information for a parameter.
/// </summary>
internal class ParameterCollectionTypeInformation
{
/// <summary>
/// Constructs a parameter collection type information object
/// which exposes the specified Type's collection type in a
/// simple way.
/// </summary>
/// <param name="type">
/// The type to determine the collection information for.
/// </param>
internal ParameterCollectionTypeInformation(Type type)
{
ParameterCollectionType = ParameterCollectionType.NotCollection;
Diagnostics.Assert(type != null, "Caller to verify type argument");
// NTRAID#Windows OS Bugs-1009284-2004/05/11-JeffJon
// What other collection types should be supported?
// Look for array types
// NTRAID#Windows Out of Band Releases-906820-2005/09/07
// According to MSDN, IsSubclassOf returns false if the types are exactly equal.
// Should this include ==?
if (type.IsSubclassOf(typeof(Array)))
{
ParameterCollectionType = ParameterCollectionType.Array;
ElementType = type.GetElementType();
return;
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return;
}
Type[] interfaces = type.GetInterfaces();
if (interfaces.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>))
|| (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>)))
{
return;
}
bool implementsIList = (type.GetInterface(typeof(IList).Name) != null);
// Look for class Collection<T>. Collection<T> implements IList, and also IList
// is more efficient to bind than ICollection<T>. This optimization
// retrieves the element type so that we can coerce the elements.
// Otherwise they must already be the right type.
if (implementsIList && type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Collection<>)))
{
ParameterCollectionType = ParameterCollectionType.IList;
// figure out elementType
Type[] elementTypes = type.GetGenericArguments();
Diagnostics.Assert(
elementTypes.Length == 1,
"Expected 1 generic argument, got " + elementTypes.Length);
ElementType = elementTypes[0];
return;
}
// Look for interface ICollection<T>. Note that Collection<T>
// does not implement ICollection<T>, and also, ICollection<T>
// does not derive from IList. The only way to add elements
// to an ICollection<T> is via reflected calls to Add(T),
// but the advantage over plain IList is that we can typecast the elements.
Type interfaceICollection =
interfaces.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>));
if (interfaceICollection != null)
{
// We only deal with the first type for which ICollection<T> is implemented
ParameterCollectionType = ParameterCollectionType.ICollectionGeneric;
// figure out elementType
Type[] elementTypes = interfaceICollection.GetGenericArguments();
Diagnostics.Assert(
elementTypes.Length == 1,
"Expected 1 generic argument, got " + elementTypes.Length);
ElementType = elementTypes[0];
return;
}
// Look for IList
if (implementsIList)
{
ParameterCollectionType = ParameterCollectionType.IList;
// elementType remains null
return;
}
}
/// <summary>
/// The collection type of the parameter.
/// </summary>
internal ParameterCollectionType ParameterCollectionType { get; private set; }
/// <summary>
/// The type of the elements in the collection.
/// </summary>
internal Type ElementType { get; private set; }
}
}
| |
/**********************************************************************
* Name : Shyam M Guthikonda
* Date : 13. Jan. 06.
* Class : COMP 460
* Asgt : Asgt #1, P. 01
* Desc : - Performs the "Wallpaper Algorithm" as described in 'The New
* Turing Omnibus' by A.K. Dewdney.
* - Built on C# OpenGL Framework v1.7.5.0
* http://www.csharpopenglframework.com/
**********************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using OpenGL;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Collections;
namespace openglFramework
{
public partial class OpenGLControl : UserControl
{
#region memberData_dontPrint
// Background Gradient colors
protected Color backgroundTopColor;
protected Color backgroundBottomColor;
protected float edgeWeight = 2.0f;
protected float wireframeWeight = 1.5f;
// Frustum Settings
private float fieldOfView = 50.0f;
protected float zNearPerspective = 100;
protected float zFarPerspective = 2000;
protected float aspect;
protected float zNearOrtho = 100;
protected float zFarOrtho = 2000;
protected float zModel = -800;
protected float zBackground = -1500;
protected float zZoomAndSelBox = 0;
protected float zUcsIcon = +100;
protected float zLabels = +200;
protected float m_cornerX = 0.0f;
protected float m_cornerY = 0.0f;
protected float m_sideLength = 325.0f;
protected float m_evenR = 0.0f;
protected float m_evenG = 0.0f;
protected float m_evenB = 0.0f;
protected float m_oddR = 1.0f;
protected float m_oddG = 1.0f;
protected float m_oddB = 1.0f;
public enum projectionType
{
Parallel,
Perspective
}
protected projectionType projectionMode = projectionType.Perspective;
// Hide/Show
protected bool showBoundingBox = false;
protected bool showUCSIcon = true;
protected bool showOrigin = false;
protected bool showLabels = true;
protected bool showLegend = true;
protected bool showProgress = true;
// Quadrics: spheres, cones, cylinders, etc...
protected IntPtr quadric;
// Textures
protected uint[] texNames;
// Labels
Label xUcsLabel;
Label yUcsLabel;
Label zUcsLabel;
Label originLabel;
public enum shadingType
{
Wireframe,
Shaded,
ShadedAndEdges
}
protected shadingType renderMode = shadingType.ShadedAndEdges;
public enum backgroundType
{
None,
Gradient,
Bitmap
}
protected backgroundType backgroundMode = backgroundType.Gradient;
public enum shadowType
{
None,
Opaque,
Transparent
}
protected shadowType shadowMode = shadowType.None;
// Scale to obtain a fixed size model of 100 units
protected float scaleTo100;
// frames per second
protected int fps;
protected bool backFaceCulling;
protected float pointSize = 4;
public int Fps
{
get { return fps; }
}
public bool BackFaceCulling
{
get { return backFaceCulling; }
set { backFaceCulling = value; }
}
public float EdgeWeight
{
get { return edgeWeight; }
set { edgeWeight = value; }
}
public float WireframeWeight
{
get { return wireframeWeight; }
set { wireframeWeight = value; }
}
public float PointSize
{
get { return pointSize; }
set { pointSize = value; }
}
[CategoryAttribute("Hide/Show")]
public bool ShowBoundingBox
{
get { return showBoundingBox; }
set
{
showBoundingBox = value;
Invalidate();
}
}
[CategoryAttribute("Hide/Show")]
public bool ShowOrigin
{
get { return showOrigin; }
set
{
showOrigin = value;
Invalidate();
}
}
[CategoryAttribute("Hide/Show")]
public bool ShowLabels
{
get { return showLabels; }
set
{
showLabels = value;
Invalidate();
}
}
[CategoryAttribute("Hide/Show")]
public bool ShowLegend
{
get { return showLegend; }
set { showLegend = value; }
}
[CategoryAttribute("Hide/Show")]
public bool ShowProgress
{
get { return showProgress; }
set
{
showProgress = value;
Invalidate();
}
}
[CategoryAttribute("Hide/Show")]
public bool ShowUCSIcon
{
get { return showUCSIcon; }
set { showUCSIcon = value; }
}
public backgroundType BackgroundMode
{
get { return backgroundMode; }
set
{
backgroundMode = value;
Invalidate();
}
}
[CategoryAttribute("Shadow")]
public shadowType ShadowMode
{
get { return shadowMode; }
set
{
shadowMode = value;
Invalidate();
}
}
#endregion
public float CornerX
{
get { return m_cornerX; }
set { m_cornerX = value;Invalidate(); }
}
public float CornerY
{
get { return m_cornerX; }
set { m_cornerX = value; Invalidate();}
}
public float SideLength
{
get { return m_sideLength; }
set { m_sideLength = value; Invalidate();}
}
public float EvenR
{
get { return m_evenR; }
set { m_evenR = value; Invalidate(); }
}
public float EvenG
{
get { return m_evenG; }
set { m_evenG = value; Invalidate(); }
}
public float EvenB
{
get { return m_evenB; }
set { m_evenB = value; Invalidate(); }
}
public float OddR
{
get { return m_oddR; }
set { m_oddR = value; Invalidate(); }
}
public float OddG
{
get { return m_oddG; }
set { m_oddG = value; Invalidate(); }
}
public float OddB
{
get { return m_oddB; }
set { m_oddB = value; Invalidate(); }
}
public void DrawScene(bool forSelection, bool onlyOnBackBuffer)
{
int StartTickCount = Environment.TickCount;
gl.Enable(gl.DEPTH_TEST);
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
ViewportSetup();
#region 1: Background.
if (backgroundMode != backgroundType.None && forSelection != true)
{
SceneSetup2D((-zBackground) - 10, (-zBackground) + 10);
DrawBackground();
}
#endregion
#region 2: Models.
gl.Clear(gl.DEPTH_BUFFER_BIT);
switch (projectionMode)
{
case projectionType.Parallel:
SceneSetupOrtho3D();
break;
case projectionType.Perspective:
SceneSetupPerispective3D();
break;
}
Draw3D(forSelection);
#endregion
#region 3: Zoom, selection boxes, UCS icon, labels
gl.Clear(gl.DEPTH_BUFFER_BIT);
if (!forSelection)
{
SceneSetup2D((-zLabels) -10, (-zZoomAndSelBox) + 10);
Draw2D();
}
#endregion
gl.Flush();
if (!onlyOnBackBuffer)
renderingContext.SwapBuffers();
// FPS.
int MS = Environment.TickCount - StartTickCount;
if (MS > 0) fps = (int) (1000.0f / MS);
}
protected void DrawOrigin(float radius)
{
gl.Enable(gl.LIGHTING);
gl.Color3ub(255, 255, 255);
gl.Enable(gl.TEXTURE_2D);
gl.BindTexture(gl.TEXTURE_2D, texNames[0]);
glu.Sphere(quadric, radius, 32, 32);
originLabel.UpdatePos(0, 0, 0);
gl.Disable(gl.TEXTURE_2D);
}
protected void DrawEntities()
{
gl.Disable(gl.LIGHTING);
#region Points
gl.PointSize(pointSize);
gl.Begin(gl.POINTS);
/* Wallpaper Algorithm.
*/
int iMax = 100;
int jMax = 100;
for (int i = 0; i < iMax; ++i)
{
for (int j = 0; j < jMax; ++j)
{
float x = m_cornerX + (float)i * m_sideLength / 100.0f;
float y = m_cornerY + (float)j * m_sideLength / 100.0f;
int c = (int)(Math.Pow(x, 2) + Math.Pow(y, 2));
if ( (c % 2) == 0 )
{
// Subtract to center the points.
gl.Color3f( m_evenR, m_evenG, m_evenB );
gl.Vertex3f( i - iMax / 2, 0, j - jMax / 2 );
}
else {
// Subtract to center the points.
gl.Color3f( m_oddR, m_oddG, m_oddB );
gl.Vertex3f(i - iMax / 2, 0, j - jMax / 2);
}
}
}
gl.End();
#endregion
#region Lines
gl.Begin(gl.LINES);
// draw a fake line to avoid troubles if there
// are NOT lines entities. Calling gl.Begin(...)
// gl.End() without something inside causes problems
gl.Color3ub(0xff, 0xff, 0xff); // white to blend with background during selection (it could anyway hide some entitites)
gl.Vertex3f(0, 0, 0);
gl.Vertex3f(0.1f, 0, 0);
gl.End();
#endregion
#region RichLines
gl.Enable(gl.LINE_STIPPLE);
gl.Disable(gl.LINE_STIPPLE);
#endregion
#region Shading
if (renderMode == shadingType.ShadedAndEdges)
{
gl.Enable(gl.POLYGON_OFFSET_FILL);
gl.PolygonOffset(1.0f, 1.0f);
}
if (backFaceCulling)
gl.Enable(gl.CULL_FACE);
gl.Enable(gl.LIGHTING);
#region TriangularFaces
switch (renderMode)
{
case shadingType.Wireframe:
gl.PolygonMode(gl.FRONT_AND_BACK, gl.LINE);
gl.Disable(gl.LIGHTING);
gl.LineWidth(wireframeWeight);
gl.Disable(gl.CULL_FACE);
break;
case shadingType.Shaded:
case shadingType.ShadedAndEdges:
gl.PolygonMode(gl.FRONT_AND_BACK, gl.FILL);
break;
}
gl.Begin(gl.TRIANGLES);
gl.End();
#endregion
gl.Disable(gl.LIGHTING);
#endregion
#region Edges
if (renderMode == shadingType.ShadedAndEdges)
{
gl.Disable(gl.POLYGON_OFFSET_FILL);
gl.PolygonMode(gl.FRONT_AND_BACK, gl.LINE);
gl.LineWidth(edgeWeight);
gl.Begin(gl.TRIANGLES);
gl.End();
}
#endregion
}
protected void DrawUcsIcon()
{
gl.PolygonMode(gl.FRONT_AND_BACK, gl.FILL);
gl.Disable(gl.CULL_FACE);
if (openglVersion >= 1.2f)
gl.Enable(gl.RESCALE_NORMAL);
else
gl.Enable(gl.NORMALIZE);
gl.PushMatrix();
if (hasFocus)
gl.Color3ub(255, 0, 0);
else
gl.Color3ub(0xBF, 0x40, 0x40);
glu.Sphere(quadric, 4, 16, 16);
DrawAxisArrow(xUcsLabel);
gl.PopMatrix();
gl.PushMatrix();
if (hasFocus)
gl.Color3ub(0, 255, 0);
else
gl.Color3ub(0x40, 0xBF, 0x40);
gl.Rotatef(90F, 0.0F, 0.0F, 1.0F);
DrawAxisArrow(yUcsLabel);
gl.PopMatrix();
gl.PushMatrix();
if (hasFocus)
gl.Color3ub(0, 0, 255);
else
gl.Color3ub(0x40, 0x40, 0xBF);
gl.Rotatef(-90F, 0.0F, 1.0F, 0.0F);
DrawAxisArrow(zUcsLabel);
gl.PopMatrix();
if (openglVersion >= 1.2f)
gl.Disable(gl.RESCALE_NORMAL);
else
gl.Disable(gl.NORMALIZE);
}
protected void DrawAxisArrow(Label label)
{
// Cylinder
gl.PushMatrix();
gl.Rotatef(90F, 0F, 1F, 0F);
glu.Cylinder(quadric, 1.75, 1.75, 20, 16, 1);
gl.PopMatrix();
// Cone
gl.PushMatrix();
gl.Translatef(20, 0.0f, 0.0f);
gl.Rotatef(90F, 0F, 1F, 0F);
glu.Cylinder(quadric, 5, 0, 14, 16, 1);
gl.PopMatrix();
// Cone tapping
gl.PushMatrix();
gl.Translatef(20, 0.0f, 0.0f);
gl.Rotatef(-90F, 0F, 1F, 0F);
glu.Disk(quadric, 1.75, 5, 16, 1);
gl.PopMatrix();
// Label
label.UpdatePos(40, 0, 0);
}
#region Overridables
protected virtual void DrawBackground()
{
gl.MatrixMode(gl.MODELVIEW);
gl.LoadIdentity();
gl.Disable(gl.LIGHTING);
gl.PolygonMode(gl.FRONT, gl.FILL);
gl.Begin(gl.POLYGON);
gl.Color3ub(backgroundBottomColor.R, backgroundBottomColor.G, backgroundBottomColor.B);
gl.Vertex3f(0.0f, 0.0f, zBackground);
gl.Vertex3f(this.Width, 0.0f, zBackground);
gl.Color3ub(backgroundTopColor.R, backgroundTopColor.G, backgroundTopColor.B);
gl.Vertex3f(this.Width, this.Height, zBackground);
gl.Vertex3f(0.0f, this.Height, zBackground);
gl.End();
}
protected virtual void Draw2D()
{
gl.MatrixMode(gl.MODELVIEW);
gl.LoadIdentity();
// An optimum compromise that allows all primitives to be specified
// at integer positions, while still ensuring predictable rasterization,
// is to translate x and y by 0.375
gl.Translatef(0.375f, 0.375f, 0.0f);
gl.Disable(gl.LIGHTING);
gl.LineWidth(1.0f);
if (action == actionType.ZoomWindow)
DrawZoomWindowBox();
if (action == actionType.SelectByBox)
DrawSelectionBox();
// DrawBoundingRect();
gl.Enable(gl.LIGHTING);
if (showUCSIcon)
{
gl.PushMatrix();
// axis icon position
gl.Translatef(50.0f, 50.0f, zUcsIcon);
// axis icon rotation
gl.Rotatef(MU.radToDeg(rotAngle), rotAxis.x, rotAxis.y, rotAxis.z); // multiply into matrix
// swaps axis Y with Z
gl.Rotatef(-90.0f, 1.0f, 0.0f, 0.0f);
DrawUcsIcon();
gl.PopMatrix();
gl.Disable(gl.LIGHTING);
gl.PushMatrix();
gl.Color3ub(63, 63, 63);
if (hasFocus)
{
xUcsLabel.Draw(zLabels);
yUcsLabel.Draw(zLabels);
zUcsLabel.Draw(zLabels);
}
}
if (showLabels)
{
gl.Disable(gl.LIGHTING);
originLabel.Draw(0, 20);
gl.Color3ub(255, 255, 255);
foreach (Label l in labels)
l.Draw(zLabels);
}
if (showLegend)
DrawLegend();
if (showProgress)
DrawProgressBar();
gl.Color3ub(180, 180, 180);
if (stencilBits == 0)
DrawText(Width-366, Height-50, "Stencil buffer not available. Transparent shadow will not be rendered.");
gl.PopMatrix();
}
protected virtual void Draw3D(bool forSelection)
{
gl.MatrixMode(gl.MODELVIEW);
gl.LoadIdentity();
// Move out Z axis so we can see everything (needed only for Perspective view)
gl.Translatef(0, 0, zModel);
if (projectionMode == projectionType.Perspective && // we see it only in perspective mode
shadowMode != shadowType.None &&
forSelection != true)
DrawShadow();
gl.Rotatef(MU.radToDeg(rotAngle), rotAxis.x, rotAxis.y, rotAxis.z); // multiply into matrix
// this command swaps the Y and Z axis
gl.Rotatef(-90.0f, 1.0f, 0.0f, 0.0f);
CenterTheModel();
if (showOrigin)
DrawOrigin(10);
// give to the model a fixed size: 100 units
gl.Scalef(scaleTo100, scaleTo100, scaleTo100);
foreach (LeaderLabel l in labels)
l.UpdatePos();
if (forSelection) {
gl.Disable(gl.LIGHTING);
gl.PolygonMode(gl.FRONT_AND_BACK, gl.FILL);
DrawSelectableEntities();
}
else {
DrawEntities();
}
}
protected virtual void DrawShadow()
{
}
protected virtual void DrawLegend()
{
}
protected virtual void DrawProgressBar()
{
}
protected virtual void DrawSelectableEntities()
{
}
#endregion
protected void CenterTheModel()
{
gl.Translatef(-(globalMin[0] + xSize / 2) * scaleTo100,
-(globalMin[1] + ySize / 2) * scaleTo100,
-(globalMin[2] + zSize / 2) * scaleTo100);
}
public void UpdateModelSize()
{
globalMin[0] = float.MaxValue;
globalMin[1] = float.MaxValue;
globalMin[2] = float.MaxValue;
globalMax[0] = float.MinValue;
globalMax[1] = float.MinValue;
globalMax[2] = float.MinValue;
foreach (Entity e in entities)
e.BoundingBox(ref globalMin[0], ref globalMin[1], ref globalMin[2], ref globalMax[0], ref globalMax[1], ref globalMax[2]);
xSize = globalMax[0] - globalMin[0];
ySize = globalMax[1] - globalMin[1];
zSize = globalMax[2] - globalMin[2];
float modelSize = (float)Math.Sqrt(xSize * xSize + ySize * ySize + zSize * zSize);
// originally was 100 but with the True Zooming TM everything has changed
// Now the model size is 900 units of diameter and never changes
scaleTo100 = 900 / modelSize;
Console.WriteLine(" ");
Console.WriteLine("Model dimensions");
Console.WriteLine("-------------------------------------------------------------");
Console.WriteLine("Model min : {0,15}, {1,15}, {2,15}", globalMin[0], globalMin[1], globalMin[2]);
Console.WriteLine("Model max : {0,15}, {1,15}, {2,15}", globalMax[0], globalMax[1], globalMax[2]);
Console.WriteLine("Model size: {0,15}, {1,15}, {2,15}", xSize, ySize, zSize);
UpdateNormals();
}
protected void DrawBox(int firstX, int firstY, int secondX, int secondY, int zOffset)
{
// gl.Begin(gl.POLYGON);
gl.Vertex3i( firstX, firstY, (int) zZoomAndSelBox + zOffset);
gl.Vertex3i(secondX, firstY, (int) zZoomAndSelBox + zOffset);
gl.Vertex3i(secondX, secondY, (int) zZoomAndSelBox + zOffset);
gl.Vertex3i( firstX, secondY, (int) zZoomAndSelBox + zOffset);
// gl.End();
}
protected void DrawText(int x, int y, string text)
{
gl.ListBase(1000); // normal
gl.RasterPos2f(x, y);
gl.CallLists(text.Length, gl.UNSIGNED_BYTE, text);
}
protected void DrawBoldText(int x, int y, string text)
{
gl.ListBase(2000); // bold
gl.RasterPos2f(x, y);
gl.CallLists(text.Length, gl.UNSIGNED_BYTE, text);
}
protected void DrawWelcomeText(int x, int y, string text)
{
gl.ListBase(3000); // welcome
gl.Color3ub(0xff, 0xff, 0xff);
gl.RasterPos2f(x, y);
gl.CallLists(text.Length, gl.UNSIGNED_BYTE, text);
gl.Color3ub(0, 0, 0);
gl.RasterPos2f(x + 1, y + 1);
gl.CallLists(text.Length, gl.UNSIGNED_BYTE, text);
gl.RasterPos2f(x + 1, y - 1);
gl.CallLists(text.Length, gl.UNSIGNED_BYTE, text);
gl.RasterPos2f(x - 1, y - 1);
gl.CallLists(text.Length, gl.UNSIGNED_BYTE, text);
gl.RasterPos2f(x - 1, y + 1);
gl.CallLists(text.Length, gl.UNSIGNED_BYTE, text);
}
}
}
| |
/*
* 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.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Statistics;
using OpenSim.Region.Framework.Scenes;
using OpenMetaverse;
using TokenBucket = OpenSim.Region.ClientStack.LindenUDP.TokenBucket;
namespace OpenSim.Region.ClientStack.LindenUDP
{
/// <summary>
/// A shim around LLUDPServer that implements the IClientNetworkServer interface
/// </summary>
public sealed class LLUDPServerShim : IClientNetworkServer
{
LLUDPServer m_udpServer;
public LLUDPServerShim()
{
}
public void Initialise(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
{
m_udpServer = new LLUDPServer(listenIP, ref port, proxyPortOffsetParm, allow_alternate_port, configSource, circuitManager);
}
public void NetworkStop()
{
m_udpServer.Stop();
}
public void AddScene(IScene scene)
{
m_udpServer.AddScene(scene);
}
public bool HandlesRegion(Location x)
{
return m_udpServer.HandlesRegion(x);
}
public void Start()
{
m_udpServer.Start();
}
public void Stop()
{
m_udpServer.Stop();
}
}
/// <summary>
/// The LLUDP server for a region. This handles incoming and outgoing
/// packets for all UDP connections to the region
/// </summary>
public class LLUDPServer : OpenSimUDPBase
{
/// <summary>Maximum transmission unit, or UDP packet size, for the LLUDP protocol</summary>
public const int MTU = 1400;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>The measured resolution of Environment.TickCount</summary>
public readonly float TickCountResolution;
/// <summary>Number of prim updates to put on the queue each time the
/// OnQueueEmpty event is triggered for updates</summary>
public readonly int PrimUpdatesPerCallback;
/// <summary>Number of texture packets to put on the queue each time the
/// OnQueueEmpty event is triggered for textures</summary>
public readonly int TextureSendLimit;
/// <summary>Handlers for incoming packets</summary>
//PacketEventDictionary packetEvents = new PacketEventDictionary();
/// <summary>Incoming packets that are awaiting handling</summary>
private OpenMetaverse.BlockingQueue<IncomingPacket> packetInbox = new OpenMetaverse.BlockingQueue<IncomingPacket>();
/// <summary></summary>
//private UDPClientCollection m_clients = new UDPClientCollection();
/// <summary>Bandwidth throttle for this UDP server</summary>
protected TokenBucket m_throttle;
/// <summary>Bandwidth throttle rates for this UDP server</summary>
protected ThrottleRates m_throttleRates;
/// <summary>Manages authentication for agent circuits</summary>
private AgentCircuitManager m_circuitManager;
/// <summary>Reference to the scene this UDP server is attached to</summary>
protected Scene m_scene;
/// <summary>The X/Y coordinates of the scene this UDP server is attached to</summary>
private Location m_location;
/// <summary>The size of the receive buffer for the UDP socket. This value
/// is passed up to the operating system and used in the system networking
/// stack. Use zero to leave this value as the default</summary>
private int m_recvBufferSize;
/// <summary>Flag to process packets asynchronously or synchronously</summary>
private bool m_asyncPacketHandling;
/// <summary>Tracks whether or not a packet was sent each round so we know
/// whether or not to sleep</summary>
private bool m_packetSent;
/// <summary>Environment.TickCount of the last time that packet stats were reported to the scene</summary>
private int m_elapsedMSSinceLastStatReport = 0;
/// <summary>Environment.TickCount of the last time the outgoing packet handler executed</summary>
private int m_tickLastOutgoingPacketHandler;
/// <summary>Keeps track of the number of elapsed milliseconds since the last time the outgoing packet handler looped</summary>
private int m_elapsedMSOutgoingPacketHandler;
/// <summary>Keeps track of the number of 100 millisecond periods elapsed in the outgoing packet handler executed</summary>
private int m_elapsed100MSOutgoingPacketHandler;
/// <summary>Keeps track of the number of 500 millisecond periods elapsed in the outgoing packet handler executed</summary>
private int m_elapsed500MSOutgoingPacketHandler;
/// <summary>Flag to signal when clients should check for resends</summary>
private bool m_resendUnacked;
/// <summary>Flag to signal when clients should send ACKs</summary>
private bool m_sendAcks;
/// <summary>Flag to signal when clients should send pings</summary>
private bool m_sendPing;
private int m_defaultRTO = 0;
private int m_maxRTO = 0;
public Socket Server { get { return null; } }
public LLUDPServer(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
: base(listenIP, (int)port)
{
#region Environment.TickCount Measurement
// Measure the resolution of Environment.TickCount
TickCountResolution = 0f;
for (int i = 0; i < 5; i++)
{
int start = Environment.TickCount;
int now = start;
while (now == start)
now = Environment.TickCount;
TickCountResolution += (float)(now - start) * 0.2f;
}
m_log.Info("[LLUDPSERVER]: Average Environment.TickCount resolution: " + TickCountResolution + "ms");
TickCountResolution = (float)Math.Ceiling(TickCountResolution);
#endregion Environment.TickCount Measurement
m_circuitManager = circuitManager;
int sceneThrottleBps = 0;
IConfig config = configSource.Configs["ClientStack.LindenUDP"];
if (config != null)
{
m_asyncPacketHandling = config.GetBoolean("async_packet_handling", false);
m_recvBufferSize = config.GetInt("client_socket_rcvbuf_size", 0);
sceneThrottleBps = config.GetInt("scene_throttle_max_bps", 0);
PrimUpdatesPerCallback = config.GetInt("PrimUpdatesPerCallback", 100);
TextureSendLimit = config.GetInt("TextureSendLimit", 20);
m_defaultRTO = config.GetInt("DefaultRTO", 0);
m_maxRTO = config.GetInt("MaxRTO", 0);
}
else
{
PrimUpdatesPerCallback = 100;
TextureSendLimit = 20;
}
#region BinaryStats
config = configSource.Configs["Statistics.Binary"];
m_shouldCollectStats = false;
if (config != null)
{
if (config.Contains("enabled") && config.GetBoolean("enabled"))
{
if (config.Contains("collect_packet_headers"))
m_shouldCollectStats = config.GetBoolean("collect_packet_headers");
if (config.Contains("packet_headers_period_seconds"))
{
binStatsMaxFilesize = TimeSpan.FromSeconds(config.GetInt("region_stats_period_seconds"));
}
if (config.Contains("stats_dir"))
{
binStatsDir = config.GetString("stats_dir");
}
}
else
{
m_shouldCollectStats = false;
}
}
#endregion BinaryStats
m_throttle = new TokenBucket(null, sceneThrottleBps, sceneThrottleBps);
m_throttleRates = new ThrottleRates(configSource);
}
public void Start()
{
if (m_scene == null)
throw new InvalidOperationException("[LLUDPSERVER]: Cannot LLUDPServer.Start() without an IScene reference");
m_log.Info("[LLUDPSERVER]: Starting the LLUDP server in " + (m_asyncPacketHandling ? "asynchronous" : "synchronous") + " mode");
base.Start(m_recvBufferSize, m_asyncPacketHandling);
// Start the packet processing threads
Watchdog.StartThread(IncomingPacketHandler, "Incoming Packets (" + m_scene.RegionInfo.RegionName + ")", ThreadPriority.Normal, false);
Watchdog.StartThread(OutgoingPacketHandler, "Outgoing Packets (" + m_scene.RegionInfo.RegionName + ")", ThreadPriority.Normal, false);
m_elapsedMSSinceLastStatReport = Environment.TickCount;
}
public new void Stop()
{
m_log.Info("[LLUDPSERVER]: Shutting down the LLUDP server for " + m_scene.RegionInfo.RegionName);
base.Stop();
}
public void AddScene(IScene scene)
{
if (m_scene != null)
{
m_log.Error("[LLUDPSERVER]: AddScene() called on an LLUDPServer that already has a scene");
return;
}
if (!(scene is Scene))
{
m_log.Error("[LLUDPSERVER]: AddScene() called with an unrecognized scene type " + scene.GetType());
return;
}
m_scene = (Scene)scene;
m_location = new Location(m_scene.RegionInfo.RegionHandle);
}
public bool HandlesRegion(Location x)
{
return x == m_location;
}
public void BroadcastPacket(Packet packet, ThrottleOutPacketType category, bool sendToPausedAgents, bool allowSplitting)
{
// CoarseLocationUpdate and AvatarGroupsReply packets cannot be split in an automated way
if ((packet.Type == PacketType.CoarseLocationUpdate || packet.Type == PacketType.AvatarGroupsReply) && allowSplitting)
allowSplitting = false;
if (allowSplitting && packet.HasVariableBlocks)
{
byte[][] datas = packet.ToBytesMultiple();
int packetCount = datas.Length;
if (packetCount < 1)
m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
for (int i = 0; i < packetCount; i++)
{
byte[] data = datas[i];
m_scene.ForEachClient(
delegate(IClientAPI client)
{
if (client is LLClientView)
SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category);
}
);
}
}
else
{
byte[] data = packet.ToBytes();
m_scene.ForEachClient(
delegate(IClientAPI client)
{
if (client is LLClientView)
SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category);
}
);
}
}
public void SendPacket(LLUDPClient udpClient, Packet packet, ThrottleOutPacketType category, bool allowSplitting)
{
// CoarseLocationUpdate packets cannot be split in an automated way
if (packet.Type == PacketType.CoarseLocationUpdate && allowSplitting)
allowSplitting = false;
if (allowSplitting && packet.HasVariableBlocks)
{
byte[][] datas = packet.ToBytesMultiple();
int packetCount = datas.Length;
if (packetCount < 1)
m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
for (int i = 0; i < packetCount; i++)
{
byte[] data = datas[i];
SendPacketData(udpClient, data, packet.Type, category);
}
}
else
{
byte[] data = packet.ToBytes();
SendPacketData(udpClient, data, packet.Type, category);
}
}
public void SendPacketData(LLUDPClient udpClient, byte[] data, PacketType type, ThrottleOutPacketType category)
{
int dataLength = data.Length;
bool doZerocode = (data[0] & Helpers.MSG_ZEROCODED) != 0;
bool doCopy = true;
// Frequency analysis of outgoing packet sizes shows a large clump of packets at each end of the spectrum.
// The vast majority of packets are less than 200 bytes, although due to asset transfers and packet splitting
// there are a decent number of packets in the 1000-1140 byte range. We allocate one of two sizes of data here
// to accomodate for both common scenarios and provide ample room for ACK appending in both
int bufferSize = (dataLength > 180) ? LLUDPServer.MTU : 200;
UDPPacketBuffer buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
// Zerocode if needed
if (doZerocode)
{
try
{
dataLength = Helpers.ZeroEncode(data, dataLength, buffer.Data);
doCopy = false;
}
catch (IndexOutOfRangeException)
{
// The packet grew larger than the bufferSize while zerocoding.
// Remove the MSG_ZEROCODED flag and send the unencoded data
// instead
m_log.Debug("[LLUDPSERVER]: Packet exceeded buffer size during zerocoding for " + type + ". DataLength=" + dataLength +
" and BufferLength=" + buffer.Data.Length + ". Removing MSG_ZEROCODED flag");
data[0] = (byte)(data[0] & ~Helpers.MSG_ZEROCODED);
}
}
// If the packet data wasn't already copied during zerocoding, copy it now
if (doCopy)
{
if (dataLength <= buffer.Data.Length)
{
Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
}
else
{
bufferSize = dataLength;
buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
// m_log.Error("[LLUDPSERVER]: Packet exceeded buffer size! This could be an indication of packet assembly not obeying the MTU. Type=" +
// type + ", DataLength=" + dataLength + ", BufferLength=" + buffer.Data.Length + ". Dropping packet");
Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
}
}
buffer.DataLength = dataLength;
#region Queue or Send
OutgoingPacket outgoingPacket = new OutgoingPacket(udpClient, buffer, category);
if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket))
SendPacketFinal(outgoingPacket);
#endregion Queue or Send
}
public void SendAcks(LLUDPClient udpClient)
{
uint ack;
if (udpClient.PendingAcks.Dequeue(out ack))
{
List<PacketAckPacket.PacketsBlock> blocks = new List<PacketAckPacket.PacketsBlock>();
PacketAckPacket.PacketsBlock block = new PacketAckPacket.PacketsBlock();
block.ID = ack;
blocks.Add(block);
while (udpClient.PendingAcks.Dequeue(out ack))
{
block = new PacketAckPacket.PacketsBlock();
block.ID = ack;
blocks.Add(block);
}
PacketAckPacket packet = new PacketAckPacket();
packet.Header.Reliable = false;
packet.Packets = blocks.ToArray();
SendPacket(udpClient, packet, ThrottleOutPacketType.Unknown, true);
}
}
public void SendPing(LLUDPClient udpClient)
{
StartPingCheckPacket pc = (StartPingCheckPacket)PacketPool.Instance.GetPacket(PacketType.StartPingCheck);
pc.Header.Reliable = false;
pc.PingID.PingID = (byte)udpClient.CurrentPingSequence++;
// We *could* get OldestUnacked, but it would hurt performance and not provide any benefit
pc.PingID.OldestUnacked = 0;
SendPacket(udpClient, pc, ThrottleOutPacketType.Unknown, false);
}
public void CompletePing(LLUDPClient udpClient, byte pingID)
{
CompletePingCheckPacket completePing = new CompletePingCheckPacket();
completePing.PingID.PingID = pingID;
SendPacket(udpClient, completePing, ThrottleOutPacketType.Unknown, false);
}
public void ResendUnacked(LLUDPClient udpClient)
{
if (!udpClient.IsConnected)
return;
// Disconnect an agent if no packets are received for some time
//FIXME: Make 60 an .ini setting
if ((Environment.TickCount & Int32.MaxValue) - udpClient.TickLastPacketReceived > 1000 * 60)
{
m_log.Warn("[LLUDPSERVER]: Ack timeout, disconnecting " + udpClient.AgentID);
RemoveClient(udpClient);
return;
}
// Get a list of all of the packets that have been sitting unacked longer than udpClient.RTO
List<OutgoingPacket> expiredPackets = udpClient.NeedAcks.GetExpiredPackets(udpClient.RTO);
if (expiredPackets != null)
{
//m_log.Debug("[LLUDPSERVER]: Resending " + expiredPackets.Count + " packets to " + udpClient.AgentID + ", RTO=" + udpClient.RTO);
// Exponential backoff of the retransmission timeout
udpClient.BackoffRTO();
// Resend packets
for (int i = 0; i < expiredPackets.Count; i++)
{
OutgoingPacket outgoingPacket = expiredPackets[i];
//m_log.DebugFormat("[LLUDPSERVER]: Resending packet #{0} (attempt {1}), {2}ms have passed",
// outgoingPacket.SequenceNumber, outgoingPacket.ResendCount, Environment.TickCount - outgoingPacket.TickCount);
// Set the resent flag
outgoingPacket.Buffer.Data[0] = (byte)(outgoingPacket.Buffer.Data[0] | Helpers.MSG_RESENT);
outgoingPacket.Category = ThrottleOutPacketType.Resend;
// Bump up the resend count on this packet
Interlocked.Increment(ref outgoingPacket.ResendCount);
//Interlocked.Increment(ref Stats.ResentPackets);
// Requeue or resend the packet
if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket))
SendPacketFinal(outgoingPacket);
}
}
}
public void Flush(LLUDPClient udpClient)
{
// FIXME: Implement?
}
internal void SendPacketFinal(OutgoingPacket outgoingPacket)
{
UDPPacketBuffer buffer = outgoingPacket.Buffer;
byte flags = buffer.Data[0];
bool isResend = (flags & Helpers.MSG_RESENT) != 0;
bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
bool isZerocoded = (flags & Helpers.MSG_ZEROCODED) != 0;
LLUDPClient udpClient = outgoingPacket.Client;
if (!udpClient.IsConnected)
return;
#region ACK Appending
int dataLength = buffer.DataLength;
// NOTE: I'm seeing problems with some viewers when ACKs are appended to zerocoded packets so I've disabled that here
if (!isZerocoded)
{
// Keep appending ACKs until there is no room left in the buffer or there are
// no more ACKs to append
uint ackCount = 0;
uint ack;
while (dataLength + 5 < buffer.Data.Length && udpClient.PendingAcks.Dequeue(out ack))
{
Utils.UIntToBytesBig(ack, buffer.Data, dataLength);
dataLength += 4;
++ackCount;
}
if (ackCount > 0)
{
// Set the last byte of the packet equal to the number of appended ACKs
buffer.Data[dataLength++] = (byte)ackCount;
// Set the appended ACKs flag on this packet
buffer.Data[0] = (byte)(buffer.Data[0] | Helpers.MSG_APPENDED_ACKS);
}
}
buffer.DataLength = dataLength;
#endregion ACK Appending
#region Sequence Number Assignment
if (!isResend)
{
// Not a resend, assign a new sequence number
uint sequenceNumber = (uint)Interlocked.Increment(ref udpClient.CurrentSequence);
Utils.UIntToBytesBig(sequenceNumber, buffer.Data, 1);
outgoingPacket.SequenceNumber = sequenceNumber;
if (isReliable)
{
// Add this packet to the list of ACK responses we are waiting on from the server
udpClient.NeedAcks.Add(outgoingPacket);
}
}
#endregion Sequence Number Assignment
// Stats tracking
Interlocked.Increment(ref udpClient.PacketsSent);
if (isReliable)
Interlocked.Add(ref udpClient.UnackedBytes, outgoingPacket.Buffer.DataLength);
// Put the UDP payload on the wire
AsyncBeginSend(buffer);
// Keep track of when this packet was sent out (right now)
outgoingPacket.TickCount = Environment.TickCount & Int32.MaxValue;
}
protected override void PacketReceived(UDPPacketBuffer buffer)
{
// Debugging/Profiling
//try { Thread.CurrentThread.Name = "PacketReceived (" + m_scene.RegionInfo.RegionName + ")"; }
//catch (Exception) { }
LLUDPClient udpClient = null;
Packet packet = null;
int packetEnd = buffer.DataLength - 1;
IPEndPoint address = (IPEndPoint)buffer.RemoteEndPoint;
#region Decoding
try
{
packet = Packet.BuildPacket(buffer.Data, ref packetEnd,
// Only allocate a buffer for zerodecoding if the packet is zerocoded
((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0) ? new byte[4096] : null);
}
catch (MalformedDataException)
{
}
// Fail-safe check
if (packet == null)
{
m_log.ErrorFormat("[LLUDPSERVER]: Malformed data, cannot parse {0} byte packet from {1}:",
buffer.DataLength, buffer.RemoteEndPoint);
m_log.Error(Utils.BytesToHexString(buffer.Data, buffer.DataLength, null));
return;
}
#endregion Decoding
#region Packet to Client Mapping
// UseCircuitCode handling
if (packet.Type == PacketType.UseCircuitCode)
{
m_log.Debug("[LLUDPSERVER]: Handling UseCircuitCode packet from " + buffer.RemoteEndPoint);
object[] array = new object[] { buffer, packet };
if (m_asyncPacketHandling)
Util.FireAndForget(HandleUseCircuitCode, array);
else
HandleUseCircuitCode(array);
return;
}
// Determine which agent this packet came from
IClientAPI client;
if (!m_scene.TryGetClient(address, out client) || !(client is LLClientView))
{
//m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type + " packet from an unrecognized source: " + address + " in " + m_scene.RegionInfo.RegionName);
return;
}
udpClient = ((LLClientView)client).UDPClient;
if (!udpClient.IsConnected)
return;
#endregion Packet to Client Mapping
// Stats tracking
Interlocked.Increment(ref udpClient.PacketsReceived);
int now = Environment.TickCount & Int32.MaxValue;
udpClient.TickLastPacketReceived = now;
#region ACK Receiving
// Handle appended ACKs
if (packet.Header.AppendedAcks && packet.Header.AckList != null)
{
for (int i = 0; i < packet.Header.AckList.Length; i++)
udpClient.NeedAcks.Remove(packet.Header.AckList[i], now, packet.Header.Resent);
}
// Handle PacketAck packets
if (packet.Type == PacketType.PacketAck)
{
PacketAckPacket ackPacket = (PacketAckPacket)packet;
for (int i = 0; i < ackPacket.Packets.Length; i++)
udpClient.NeedAcks.Remove(ackPacket.Packets[i].ID, now, packet.Header.Resent);
// We don't need to do anything else with PacketAck packets
return;
}
#endregion ACK Receiving
#region ACK Sending
if (packet.Header.Reliable)
{
udpClient.PendingAcks.Enqueue(packet.Header.Sequence);
// This is a somewhat odd sequence of steps to pull the client.BytesSinceLastACK value out,
// add the current received bytes to it, test if 2*MTU bytes have been sent, if so remove
// 2*MTU bytes from the value and send ACKs, and finally add the local value back to
// client.BytesSinceLastACK. Lockless thread safety
int bytesSinceLastACK = Interlocked.Exchange(ref udpClient.BytesSinceLastACK, 0);
bytesSinceLastACK += buffer.DataLength;
if (bytesSinceLastACK > LLUDPServer.MTU * 2)
{
bytesSinceLastACK -= LLUDPServer.MTU * 2;
SendAcks(udpClient);
}
Interlocked.Add(ref udpClient.BytesSinceLastACK, bytesSinceLastACK);
}
#endregion ACK Sending
#region Incoming Packet Accounting
// Check the archive of received reliable packet IDs to see whether we already received this packet
if (packet.Header.Reliable && !udpClient.PacketArchive.TryEnqueue(packet.Header.Sequence))
{
if (packet.Header.Resent)
m_log.Debug("[LLUDPSERVER]: Received a resend of already processed packet #" + packet.Header.Sequence + ", type: " + packet.Type);
else
m_log.Warn("[LLUDPSERVER]: Received a duplicate (not marked as resend) of packet #" + packet.Header.Sequence + ", type: " + packet.Type);
// Avoid firing a callback twice for the same packet
return;
}
#endregion Incoming Packet Accounting
#region BinaryStats
LogPacketHeader(true, udpClient.CircuitCode, 0, packet.Type, (ushort)packet.Length);
#endregion BinaryStats
#region Ping Check Handling
if (packet.Type == PacketType.StartPingCheck)
{
// We don't need to do anything else with ping checks
StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
CompletePing(udpClient, startPing.PingID.PingID);
if ((Environment.TickCount - m_elapsedMSSinceLastStatReport) >= 3000)
{
udpClient.SendPacketStats();
m_elapsedMSSinceLastStatReport = Environment.TickCount;
}
return;
}
else if (packet.Type == PacketType.CompletePingCheck)
{
// We don't currently track client ping times
return;
}
#endregion Ping Check Handling
// Inbox insertion
packetInbox.Enqueue(new IncomingPacket(udpClient, packet));
}
#region BinaryStats
public class PacketLogger
{
public DateTime StartTime;
public string Path = null;
public System.IO.BinaryWriter Log = null;
}
public static PacketLogger PacketLog;
protected static bool m_shouldCollectStats = false;
// Number of seconds to log for
static TimeSpan binStatsMaxFilesize = TimeSpan.FromSeconds(300);
static object binStatsLogLock = new object();
static string binStatsDir = "";
public static void LogPacketHeader(bool incoming, uint circuit, byte flags, PacketType packetType, ushort size)
{
if (!m_shouldCollectStats) return;
// Binary logging format is TTTTTTTTCCCCFPPPSS, T=Time, C=Circuit, F=Flags, P=PacketType, S=size
// Put the incoming bit into the least significant bit of the flags byte
if (incoming)
flags |= 0x01;
else
flags &= 0xFE;
// Put the flags byte into the most significant bits of the type integer
uint type = (uint)packetType;
type |= (uint)flags << 24;
// m_log.Debug("1 LogPacketHeader(): Outside lock");
lock (binStatsLogLock)
{
DateTime now = DateTime.Now;
// m_log.Debug("2 LogPacketHeader(): Inside lock. now is " + now.Ticks);
try
{
if (PacketLog == null || (now > PacketLog.StartTime + binStatsMaxFilesize))
{
if (PacketLog != null && PacketLog.Log != null)
{
PacketLog.Log.Close();
}
// First log file or time has expired, start writing to a new log file
PacketLog = new PacketLogger();
PacketLog.StartTime = now;
PacketLog.Path = (binStatsDir.Length > 0 ? binStatsDir + System.IO.Path.DirectorySeparatorChar.ToString() : "")
+ String.Format("packets-{0}.log", now.ToString("yyyyMMddHHmmss"));
PacketLog.Log = new BinaryWriter(File.Open(PacketLog.Path, FileMode.Append, FileAccess.Write));
}
// Serialize the data
byte[] output = new byte[18];
Buffer.BlockCopy(BitConverter.GetBytes(now.Ticks), 0, output, 0, 8);
Buffer.BlockCopy(BitConverter.GetBytes(circuit), 0, output, 8, 4);
Buffer.BlockCopy(BitConverter.GetBytes(type), 0, output, 12, 4);
Buffer.BlockCopy(BitConverter.GetBytes(size), 0, output, 16, 2);
// Write the serialized data to disk
if (PacketLog != null && PacketLog.Log != null)
PacketLog.Log.Write(output);
}
catch (Exception ex)
{
m_log.Error("Packet statistics gathering failed: " + ex.Message, ex);
if (PacketLog.Log != null)
{
PacketLog.Log.Close();
}
PacketLog = null;
}
}
}
#endregion BinaryStats
private void HandleUseCircuitCode(object o)
{
object[] array = (object[])o;
UDPPacketBuffer buffer = (UDPPacketBuffer)array[0];
UseCircuitCodePacket packet = (UseCircuitCodePacket)array[1];
IPEndPoint remoteEndPoint = (IPEndPoint)buffer.RemoteEndPoint;
// Begin the process of adding the client to the simulator
AddNewClient((UseCircuitCodePacket)packet, remoteEndPoint);
// Acknowledge the UseCircuitCode packet
SendAckImmediate(remoteEndPoint, packet.Header.Sequence);
}
private void SendAckImmediate(IPEndPoint remoteEndpoint, uint sequenceNumber)
{
PacketAckPacket ack = new PacketAckPacket();
ack.Header.Reliable = false;
ack.Packets = new PacketAckPacket.PacketsBlock[1];
ack.Packets[0] = new PacketAckPacket.PacketsBlock();
ack.Packets[0].ID = sequenceNumber;
byte[] packetData = ack.ToBytes();
int length = packetData.Length;
UDPPacketBuffer buffer = new UDPPacketBuffer(remoteEndpoint, length);
buffer.DataLength = length;
Buffer.BlockCopy(packetData, 0, buffer.Data, 0, length);
AsyncBeginSend(buffer);
}
private bool IsClientAuthorized(UseCircuitCodePacket useCircuitCode, out AuthenticateResponse sessionInfo)
{
UUID agentID = useCircuitCode.CircuitCode.ID;
UUID sessionID = useCircuitCode.CircuitCode.SessionID;
uint circuitCode = useCircuitCode.CircuitCode.Code;
sessionInfo = m_circuitManager.AuthenticateSession(sessionID, agentID, circuitCode);
return sessionInfo.Authorised;
}
private void AddNewClient(UseCircuitCodePacket useCircuitCode, IPEndPoint remoteEndPoint)
{
UUID agentID = useCircuitCode.CircuitCode.ID;
UUID sessionID = useCircuitCode.CircuitCode.SessionID;
uint circuitCode = useCircuitCode.CircuitCode.Code;
if (m_scene.RegionStatus != RegionStatus.SlaveScene)
{
AuthenticateResponse sessionInfo;
if (IsClientAuthorized(useCircuitCode, out sessionInfo))
{
AddClient(circuitCode, agentID, sessionID, remoteEndPoint, sessionInfo);
}
else
{
// Don't create circuits for unauthorized clients
m_log.WarnFormat(
"[LLUDPSERVER]: Connection request for client {0} connecting with unnotified circuit code {1} from {2}",
useCircuitCode.CircuitCode.ID, useCircuitCode.CircuitCode.Code, remoteEndPoint);
}
}
else
{
// Slave regions don't accept new clients
m_log.Debug("[LLUDPSERVER]: Slave region " + m_scene.RegionInfo.RegionName + " ignoring UseCircuitCode packet");
}
}
protected virtual void AddClient(uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AuthenticateResponse sessionInfo)
{
// Create the LLUDPClient
LLUDPClient udpClient = new LLUDPClient(this, m_throttleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
IClientAPI existingClient;
if (!m_scene.TryGetClient(agentID, out existingClient))
{
// Create the LLClientView
LLClientView client = new LLClientView(remoteEndPoint, m_scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode);
client.OnLogout += LogoutHandler;
// Start the IClientAPI
client.Start();
}
else
{
m_log.WarnFormat("[LLUDPSERVER]: Ignoring a repeated UseCircuitCode from {0} at {1} for circuit {2}",
udpClient.AgentID, remoteEndPoint, circuitCode);
}
}
private void RemoveClient(LLUDPClient udpClient)
{
// Remove this client from the scene
IClientAPI client;
if (m_scene.TryGetClient(udpClient.AgentID, out client))
{
client.IsLoggingOut = true;
client.Close();
}
}
private void IncomingPacketHandler()
{
// Set this culture for the thread that incoming packets are received
// on to en-US to avoid number parsing issues
Culture.SetCurrentCulture();
while (base.IsRunning)
{
try
{
IncomingPacket incomingPacket = null;
// HACK: This is a test to try and rate limit packet handling on Mono.
// If it works, a more elegant solution can be devised
if (Util.FireAndForgetCount() < 2)
{
//m_log.Debug("[LLUDPSERVER]: Incoming packet handler is sleeping");
Thread.Sleep(30);
}
if (packetInbox.Dequeue(100, ref incomingPacket))
ProcessInPacket(incomingPacket);//, incomingPacket); Util.FireAndForget(ProcessInPacket, incomingPacket);
}
catch (Exception ex)
{
m_log.Error("[LLUDPSERVER]: Error in the incoming packet handler loop: " + ex.Message, ex);
}
Watchdog.UpdateThread();
}
if (packetInbox.Count > 0)
m_log.Warn("[LLUDPSERVER]: IncomingPacketHandler is shutting down, dropping " + packetInbox.Count + " packets");
packetInbox.Clear();
Watchdog.RemoveThread();
}
private void OutgoingPacketHandler()
{
// Set this culture for the thread that outgoing packets are sent
// on to en-US to avoid number parsing issues
Culture.SetCurrentCulture();
// Typecast the function to an Action<IClientAPI> once here to avoid allocating a new
// Action generic every round
Action<IClientAPI> clientPacketHandler = ClientOutgoingPacketHandler;
while (base.IsRunning)
{
try
{
m_packetSent = false;
#region Update Timers
m_resendUnacked = false;
m_sendAcks = false;
m_sendPing = false;
// Update elapsed time
int thisTick = Environment.TickCount & Int32.MaxValue;
if (m_tickLastOutgoingPacketHandler > thisTick)
m_elapsedMSOutgoingPacketHandler += ((Int32.MaxValue - m_tickLastOutgoingPacketHandler) + thisTick);
else
m_elapsedMSOutgoingPacketHandler += (thisTick - m_tickLastOutgoingPacketHandler);
m_tickLastOutgoingPacketHandler = thisTick;
// Check for pending outgoing resends every 100ms
if (m_elapsedMSOutgoingPacketHandler >= 100)
{
m_resendUnacked = true;
m_elapsedMSOutgoingPacketHandler = 0;
m_elapsed100MSOutgoingPacketHandler += 1;
}
// Check for pending outgoing ACKs every 500ms
if (m_elapsed100MSOutgoingPacketHandler >= 5)
{
m_sendAcks = true;
m_elapsed100MSOutgoingPacketHandler = 0;
m_elapsed500MSOutgoingPacketHandler += 1;
}
// Send pings to clients every 5000ms
if (m_elapsed500MSOutgoingPacketHandler >= 10)
{
m_sendPing = true;
m_elapsed500MSOutgoingPacketHandler = 0;
}
#endregion Update Timers
// Handle outgoing packets, resends, acknowledgements, and pings for each
// client. m_packetSent will be set to true if a packet is sent
m_scene.ForEachClient(clientPacketHandler);
// If nothing was sent, sleep for the minimum amount of time before a
// token bucket could get more tokens
if (!m_packetSent)
Thread.Sleep((int)TickCountResolution);
Watchdog.UpdateThread();
}
catch (Exception ex)
{
m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler loop threw an exception: " + ex.Message, ex);
}
}
Watchdog.RemoveThread();
}
private void ClientOutgoingPacketHandler(IClientAPI client)
{
try
{
if (client is LLClientView)
{
LLUDPClient udpClient = ((LLClientView)client).UDPClient;
if (udpClient.IsConnected)
{
if (m_resendUnacked)
ResendUnacked(udpClient);
if (m_sendAcks)
SendAcks(udpClient);
if (m_sendPing)
SendPing(udpClient);
// Dequeue any outgoing packets that are within the throttle limits
if (udpClient.DequeueOutgoing())
m_packetSent = true;
}
}
}
catch (Exception ex)
{
m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler iteration for " + client.Name +
" threw an exception: " + ex.Message, ex);
}
}
private void ProcessInPacket(object state)
{
IncomingPacket incomingPacket = (IncomingPacket)state;
Packet packet = incomingPacket.Packet;
LLUDPClient udpClient = incomingPacket.Client;
IClientAPI client;
// Sanity check
if (packet == null || udpClient == null)
{
m_log.WarnFormat("[LLUDPSERVER]: Processing a packet with incomplete state. Packet=\"{0}\", UDPClient=\"{1}\"",
packet, udpClient);
}
// Make sure this client is still alive
if (m_scene.TryGetClient(udpClient.AgentID, out client))
{
try
{
// Process this packet
client.ProcessInPacket(packet);
}
catch (ThreadAbortException)
{
// If something is trying to abort the packet processing thread, take that as a hint that it's time to shut down
m_log.Info("[LLUDPSERVER]: Caught a thread abort, shutting down the LLUDP server");
Stop();
}
catch (Exception e)
{
// Don't let a failure in an individual client thread crash the whole sim.
m_log.ErrorFormat("[LLUDPSERVER]: Client packet handler for {0} for packet {1} threw an exception", udpClient.AgentID, packet.Type);
m_log.Error(e.Message, e);
}
}
else
{
m_log.DebugFormat("[LLUDPSERVER]: Dropping incoming {0} packet for dead client {1}", packet.Type, udpClient.AgentID);
}
}
protected void LogoutHandler(IClientAPI client)
{
client.SendLogoutPacket();
if (client.IsActive)
RemoveClient(((LLClientView)client).UDPClient);
}
}
}
| |
// 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 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
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 Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ExpressRouteCircuitAuthorizationsOperations operations.
/// </summary>
internal partial class ExpressRouteCircuitAuthorizationsOperations : IServiceOperations<NetworkManagementClient>, IExpressRouteCircuitAuthorizationsOperations
{
/// <summary>
/// Initializes a new instance of the ExpressRouteCircuitAuthorizationsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ExpressRouteCircuitAuthorizationsOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// The delete authorization operation deletes the specified authorization
/// from the specified ExpressRouteCircuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(
resourceGroupName, circuitName, authorizationName, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// The delete authorization operation deletes the specified authorization
/// from the specified ExpressRouteCircuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", Uri.EscapeDataString(circuitName));
_url = _url.Replace("{authorizationName}", Uri.EscapeDataString(authorizationName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
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;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// 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 != 202 && (int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The GET authorization operation retrieves the specified authorization from
/// the specified ExpressRouteCircuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", Uri.EscapeDataString(circuitName));
_url = _url.Replace("{authorizationName}", Uri.EscapeDataString(authorizationName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
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;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitAuthorization>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, this.Client.DeserializationSettings);
}
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>
/// The Put Authorization operation creates/updates an authorization in
/// thespecified ExpressRouteCircuits
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create/update ExpressRouteCircuitAuthorization
/// operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ExpressRouteCircuitAuthorization> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(
resourceGroupName, circuitName, authorizationName, authorizationParameters, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// The Put Authorization operation creates/updates an authorization in
/// thespecified ExpressRouteCircuits
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create/update ExpressRouteCircuitAuthorization
/// operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (authorizationParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationParameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("authorizationParameters", authorizationParameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", Uri.EscapeDataString(circuitName));
_url = _url.Replace("{authorizationName}", Uri.EscapeDataString(authorizationName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
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;
if(authorizationParameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(authorizationParameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// 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 != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitAuthorization>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, this.Client.DeserializationSettings);
}
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>
/// The List authorization operation retrieves all the authorizations in an
/// ExpressRouteCircuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the curcuit.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", Uri.EscapeDataString(circuitName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
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;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitAuthorization>>(_responseContent, this.Client.DeserializationSettings);
}
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>
/// The List authorization operation retrieves all the authorizations in an
/// ExpressRouteCircuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
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;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitAuthorization>>(_responseContent, this.Client.DeserializationSettings);
}
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;
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. 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.
*******************************************************************************/
//
// Novell.Directory.Ldap.Rfc2251.RfcLdapMessage.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using System.IO;
using Novell.Directory.Ldap.Asn1;
namespace Novell.Directory.Ldap.Rfc2251
{
/// <summary> Represents an Ldap Message.
///
/// <pre>
/// LdapMessage ::= SEQUENCE {
/// messageID MessageID,
/// protocolOp CHOICE {
/// bindRequest BindRequest,
/// bindResponse BindResponse,
/// unbindRequest UnbindRequest,
/// searchRequest SearchRequest,
/// searchResEntry SearchResultEntry,
/// searchResDone SearchResultDone,
/// searchResRef SearchResultReference,
/// modifyRequest ModifyRequest,
/// modifyResponse ModifyResponse,
/// addRequest AddRequest,
/// addResponse AddResponse,
/// delRequest DelRequest,
/// delResponse DelResponse,
/// modDNRequest ModifyDNRequest,
/// modDNResponse ModifyDNResponse,
/// compareRequest CompareRequest,
/// compareResponse CompareResponse,
/// abandonRequest AbandonRequest,
/// extendedReq ExtendedRequest,
/// extendedResp ExtendedResponse },
/// controls [0] Controls OPTIONAL }
/// </pre>
///
///
/// Note: The creation of a MessageID should be hidden within the creation of
/// an RfcLdapMessage. The MessageID needs to be in sequence, and has an
/// upper and lower limit. There is never a case when a user should be
/// able to specify the MessageID for an RfcLdapMessage. The MessageID()
/// constructor should be package protected. (So the MessageID value
/// isn't arbitrarily run up.)
/// </summary>
public class RfcLdapMessage : Asn1Sequence
{
/// <summary> Returns this RfcLdapMessage's messageID as an int.</summary>
virtual public int MessageID
{
get
{
return ((Asn1Integer)get_Renamed(0)).intValue();
}
}
/// <summary> Returns this RfcLdapMessage's message type</summary>
virtual public int Type
{
get
{
return get_Renamed(1).getIdentifier().Tag;
}
}
/// <summary> Returns the response associated with this RfcLdapMessage.
/// Can be one of RfcLdapResult, RfcBindResponse, RfcExtendedResponse
/// all which extend RfcResponse. It can also be
/// RfcSearchResultEntry, or RfcSearchResultReference
/// </summary>
virtual public Asn1Object Response
{
get
{
return get_Renamed(1);
}
}
/// <summary> Returns the optional Controls for this RfcLdapMessage.</summary>
virtual public RfcControls Controls
{
get
{
if (size() > 2)
return (RfcControls)get_Renamed(2);
return null;
}
}
/// <summary> Returns the dn of the request, may be null</summary>
virtual public string RequestDN
{
get
{
return ((RfcRequest)op).getRequestDN();
}
}
/// <summary> returns the original request in this message
///
/// </summary>
/// <returns> the original msg request for this response
/// </returns>
/// <summary> sets the original request in this message
///
/// </summary>
/// <param name="msg">the original request for this response
/// </param>
virtual public LdapMessage RequestingMessage
{
get
{
return requestMessage;
}
set
{
requestMessage = value;
}
}
private Asn1Object op;
private RfcControls controls;
private LdapMessage requestMessage = null;
/// <summary> Create an RfcLdapMessage by copying the content array
///
/// </summary>
/// <param name="origContent">the array list to copy
/// </param>
/* package */
internal RfcLdapMessage(Asn1Object[] origContent, RfcRequest origRequest, string dn, string filter, bool reference) : base(origContent, origContent.Length)
{
set_Renamed(0, new RfcMessageID()); // MessageID has static counter
RfcRequest req = (RfcRequest)origContent[1];
RfcRequest newreq = req.dupRequest(dn, filter, reference);
op = (Asn1Object)newreq;
set_Renamed(1, (Asn1Object)newreq);
}
/// <summary> Create an RfcLdapMessage using the specified Ldap Request.</summary>
public RfcLdapMessage(RfcRequest op) : this(op, null)
{
}
/// <summary> Create an RfcLdapMessage request from input parameters.</summary>
public RfcLdapMessage(RfcRequest op, RfcControls controls) : base(3)
{
this.op = (Asn1Object)op;
this.controls = controls;
add(new RfcMessageID()); // MessageID has static counter
add((Asn1Object)op);
if (controls != null)
{
add(controls);
}
}
/// <summary> Create an RfcLdapMessage using the specified Ldap Response.</summary>
public RfcLdapMessage(Asn1Sequence op) : this(op, null)
{
}
/// <summary> Create an RfcLdapMessage response from input parameters.</summary>
public RfcLdapMessage(Asn1Sequence op, RfcControls controls) : base(3)
{
this.op = op;
this.controls = controls;
add(new RfcMessageID()); // MessageID has static counter
add(op);
if (controls != null)
{
add(controls);
}
}
/// <summary> Will decode an RfcLdapMessage directly from an InputStream.</summary>
[CLSCompliantAttribute(false)]
public RfcLdapMessage(Asn1Decoder dec, Stream in_Renamed, int len) : base(dec, in_Renamed, len)
{
sbyte[] content;
MemoryStream bais;
// Decode implicitly tagged protocol operation from an Asn1Tagged type
// to its appropriate application type.
Asn1Tagged protocolOp = (Asn1Tagged)get_Renamed(1);
Asn1Identifier protocolOpId = protocolOp.getIdentifier();
content = ((Asn1OctetString)protocolOp.taggedValue()).byteValue();
bais = new MemoryStream(SupportClass.ToByteArray(content));
switch (protocolOpId.Tag)
{
case LdapMessage.SEARCH_RESPONSE:
set_Renamed(1, new RfcSearchResultEntry(dec, bais, content.Length));
break;
case LdapMessage.SEARCH_RESULT:
set_Renamed(1, new RfcSearchResultDone(dec, bais, content.Length));
break;
case LdapMessage.SEARCH_RESULT_REFERENCE:
set_Renamed(1, new RfcSearchResultReference(dec, bais, content.Length));
break;
case LdapMessage.ADD_RESPONSE:
set_Renamed(1, new RfcAddResponse(dec, bais, content.Length));
break;
case LdapMessage.BIND_RESPONSE:
set_Renamed(1, new RfcBindResponse(dec, bais, content.Length));
break;
case LdapMessage.COMPARE_RESPONSE:
set_Renamed(1, new RfcCompareResponse(dec, bais, content.Length));
break;
case LdapMessage.DEL_RESPONSE:
set_Renamed(1, new RfcDelResponse(dec, bais, content.Length));
break;
case LdapMessage.EXTENDED_RESPONSE:
set_Renamed(1, new RfcExtendedResponse(dec, bais, content.Length));
break;
case LdapMessage.INTERMEDIATE_RESPONSE:
set_Renamed(1, new RfcIntermediateResponse(dec, bais, content.Length));
break;
case LdapMessage.MODIFY_RESPONSE:
set_Renamed(1, new RfcModifyResponse(dec, bais, content.Length));
break;
case LdapMessage.MODIFY_RDN_RESPONSE:
set_Renamed(1, new RfcModifyDNResponse(dec, bais, content.Length));
break;
default:
throw new Exception("RfcLdapMessage: Invalid tag: " + protocolOpId.Tag);
}
// decode optional implicitly tagged controls from Asn1Tagged type to
// to RFC 2251 types.
if (size() > 2)
{
Asn1Tagged controls = (Asn1Tagged)get_Renamed(2);
// Asn1Identifier controlsId = protocolOp.getIdentifier();
// we could check to make sure we have controls here....
content = ((Asn1OctetString)controls.taggedValue()).byteValue();
bais = new MemoryStream(SupportClass.ToByteArray(content));
set_Renamed(2, new RfcControls(dec, bais, content.Length));
}
}
//*************************************************************************
// Accessors
//*************************************************************************
/// <summary> Returns the request associated with this RfcLdapMessage.
/// Throws a class cast exception if the RfcLdapMessage is not a request.
/// </summary>
public RfcRequest getRequest()
{
return (RfcRequest)get_Renamed(1);
}
public virtual bool isRequest()
{
return get_Renamed(1) is RfcRequest;
}
/// <summary> Duplicate this message, replacing base dn, filter, and scope if supplied
///
/// </summary>
/// <param name="dn">the base dn
///
/// </param>
/// <param name="filter">the filter
///
/// </param>
/// <param name="reference">true if a search reference
///
/// </param>
/// <returns> the object representing the new message
/// </returns>
public object dupMessage(string dn, string filter, bool reference)
{
if ((op == null))
{
throw new LdapException("DUP_ERROR", LdapException.LOCAL_ERROR, (string)null);
}
RfcLdapMessage newMsg = new RfcLdapMessage(toArray(), (RfcRequest)get_Renamed(1), dn, filter, reference);
return newMsg;
}
}
}
| |
using System;
using System.Linq;
using SFML.Graphics;
using SFML.Window;
namespace NetGore.Graphics.GUI
{
/// <summary>
/// A standard static button control.
/// </summary>
public class Button : TextControl
{
/// <summary>
/// The name of this <see cref="Control"/> for when looking up the skin information.
/// </summary>
const string _controlSkinName = "Button";
Vector2 _textPos = Vector2.Zero;
Vector2 _textSize = Vector2.Zero;
/// <summary>
/// Initializes a new instance of the <see cref="Button"/> class.
/// </summary>
/// <param name="parent">Parent <see cref="Control"/> of this <see cref="Control"/>.</param>
/// <param name="position">Position of the Control reletive to its parent.</param>
/// <param name="clientSize">The size of the <see cref="Control"/>'s client area.</param>
/// <exception cref="NullReferenceException"><paramref name="parent"/> is null.</exception>
public Button(Control parent, Vector2 position, Vector2 clientSize) : base(parent, position, clientSize)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Button"/> class.
/// </summary>
/// <param name="guiManager">The GUI manager this <see cref="Control"/> will be managed by.</param>
/// <param name="position">Position of the Control reletive to its parent.</param>
/// <param name="clientSize">The size of the <see cref="Control"/>'s client area.</param>
/// <exception cref="ArgumentNullException"><paramref name="guiManager"/> is null.</exception>
public Button(IGUIManager guiManager, Vector2 position, Vector2 clientSize) : base(guiManager, position, clientSize)
{
}
/// <summary>
/// Gets or sets the ControlBorder used for when the button is in a normal state.
/// </summary>
public ControlBorder BorderNormal { get; set; }
/// <summary>
/// Gets or sets the ControlBorder used for when the mouse is over the control.
/// </summary>
public ControlBorder BorderOver { get; set; }
/// <summary>
/// Gets or sets the ControlBorder used for when the control is pressed.
/// </summary>
public ControlBorder BorderPressed { get; set; }
/// <summary>
/// Draw the Button.
/// </summary>
/// <param name="spriteBatch"><see cref="ISpriteBatch"/> to draw to.</param>
protected override void DrawControl(ISpriteBatch spriteBatch)
{
base.DrawControl(spriteBatch);
// Draw the text
DrawText(spriteBatch, _textPos);
}
/// <summary>
/// When overridden in the derived class, loads the skinning information for the <see cref="Control"/>
/// from the given <paramref name="skinManager"/>.
/// </summary>
/// <param name="skinManager">The <see cref="ISkinManager"/> to load the skinning information from.</param>
public override void LoadSkin(ISkinManager skinManager)
{
BorderNormal = skinManager.GetBorder(_controlSkinName);
BorderOver = skinManager.GetBorder(_controlSkinName, "MouseOver");
BorderPressed = skinManager.GetBorder(_controlSkinName, "Pressed");
Border = BorderNormal;
}
/// <summary>
/// Handles when the <see cref="TextControl.Font"/> has changed.
/// This is called immediately before <see cref="TextControl.FontChanged"/>.
/// Override this method instead of using an event hook on <see cref="TextControl.FontChanged"/> when possible.
/// </summary>
protected override void OnFontChanged()
{
base.OnFontChanged();
UpdateTextSize();
}
/// <summary>
/// Handles when a mouse button has been pressed down on this <see cref="Control"/>.
/// This is called immediately before <see cref="Control.OnMouseDown"/>.
/// Override this method instead of using an event hook on <see cref="Control.MouseDown"/> when possible.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
if (GUIManager.UnderCursor != this)
Border = BorderNormal;
else
{
if (e.Button == Mouse.Button.Left)
Border = BorderPressed;
else
Border = BorderOver;
}
}
/// <summary>
/// Handles when the mouse has entered the area of the <see cref="Control"/>.
/// This is called immediately before <see cref="Control.OnMouseEnter"/>.
/// Override this method instead of using an event hook on <see cref="Control.MouseEnter"/> when possible.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseEnter(MouseMoveEventArgs e)
{
base.OnMouseEnter(e);
if (GUIManager.UnderCursor == this)
Border = BorderOver;
else
Border = BorderNormal;
}
/// <summary>
/// Handles when the mouse has left the area of the <see cref="Control"/>.
/// This is called immediately before <see cref="Control.OnMouseLeave"/>.
/// Override this method instead of using an event hook on <see cref="Control.MouseLeave"/> when possible.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseLeave(MouseMoveEventArgs e)
{
base.OnMouseLeave(e);
Border = BorderNormal;
}
/// <summary>
/// Handles when the mouse has moved over the <see cref="Control"/>.
/// This is called immediately before <see cref="Control.MouseMoved"/>.
/// Override this method instead of using an event hook on <see cref="Control.MouseMoved"/> when possible.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseMoved(MouseMoveEventArgs e)
{
base.OnMouseMoved(e);
if (GUIManager.UnderCursor != this)
Border = BorderNormal;
else
{
if (GUIManager.IsMouseButtonDown(Mouse.Button.Left))
Border = BorderPressed;
else
Border = BorderOver;
}
}
/// <summary>
/// Handles when a mouse button has been raised on the <see cref="Control"/>.
/// This is called immediately before <see cref="Control.OnMouseUp"/>.
/// Override this method instead of using an event hook on <see cref="Control.MouseUp"/> when possible.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
if (GUIManager.UnderCursor == this)
Border = BorderOver;
else
Border = BorderNormal;
}
/// <summary>
/// Handles when the <see cref="Control.Size"/> of this <see cref="Control"/> has changed.
/// This is called immediately before <see cref="Control.Resized"/>.
/// Override this method instead of using an event hook on <see cref="Control.Resized"/> when possible.
/// </summary>
protected override void OnResized()
{
base.OnResized();
UpdateTextPosition();
}
/// <summary>
/// Handles when the <see cref="TextControl.Text"/> has changed.
/// This is called immediately before <see cref="TextControl.TextChanged"/>.
/// Override this method instead of using an event hook on <see cref="TextControl.TextChanged"/> when possible.
/// </summary>
protected override void OnTextChanged()
{
base.OnTextChanged();
UpdateTextSize();
}
/// <summary>
/// Sets the default values for the <see cref="Control"/>. This should always begin with a call to the
/// base class's method to ensure that changes to settings are hierchical.
/// </summary>
protected override void SetDefaultValues()
{
base.SetDefaultValues();
CanDrag = false;
CanFocus = false;
Border = BorderNormal;
}
/// <summary>
/// Updates teh position of the button's text.
/// </summary>
void UpdateTextPosition()
{
// Center the text on the control
_textPos = ((Size / 2f) - (_textSize / 2f)).Round();
}
/// <summary>
/// Updates the size and position of the button's text.
/// </summary>
void UpdateTextSize()
{
if (string.IsNullOrEmpty(Text))
return;
// Get the size of the text
_textSize = Font.MeasureString(Text);
UpdateTextPosition();
}
}
}
| |
/* Copyright (c) 2006 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.Collections;
using System.Text;
using System.Xml;
using System.Net;
using Google.GData.Client;
using Google.GData.Extensions;
namespace Google.GData.Spreadsheets
{
/// <summary>
/// Feed API customization class for defining a Cells feed.
/// </summary>
public class CellFeed : AbstractFeed
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="uriBase">The uri for this cells feed.</param>
/// <param name="iService">The Spreadsheets service.</param>
public CellFeed(Uri uriBase, IService iService) : base(uriBase, iService)
{
this.AddExtension(new ColCountElement());
this.AddExtension(new RowCountElement());
}
/// <summary>
/// The number of rows in this cell feed, as a RowCountElement
/// </summary>
public RowCountElement RowCount
{
get
{
return FindExtension(GDataSpreadsheetsNameTable.XmlRowCountElement,
GDataSpreadsheetsNameTable.NSGSpreadsheets) as RowCountElement;
}
}
/// <summary>
/// The number of columns in this cell feed, as a ColCountElement
/// </summary>
public ColCountElement ColCount
{
get
{
return FindExtension(GDataSpreadsheetsNameTable.XmlColCountElement,
GDataSpreadsheetsNameTable.NSGSpreadsheets) as ColCountElement;
}
}
/// <summary>checks if this is a namespace
/// decl that we already added</summary>
/// <param name="node">XmlNode to check</param>
/// <returns>true if this node should be skipped </returns>
protected override bool SkipNode(XmlNode node)
{
if (base.SkipNode(node))
{
return true;
}
return node.NodeType == XmlNodeType.Attribute &&
node.Name.StartsWith("xmlns") &&
(String.Compare(node.Value, GDataSpreadsheetsNameTable.NSGSpreadsheets) == 0);
}
/// <summary>
/// creates our cellfeed type entry
/// </summary>
/// <returns>AtomEntry</returns>
public override AtomEntry CreateFeedEntry()
{
return new CellEntry();
}
/// <summary>
/// returns an update URI for a given row/column combination
/// in general that URI is based on the feeds POST feed plus the
/// cell address in RnCn notation:
/// https://spreadsheets.google.com/feeds/cells/key/worksheetId/private/full/cell
/// </summary>
/// <param name="row"></param>
/// <param name="column"></param>
/// <returns>string</returns>
[CLSCompliant(false)]
public string CellUri(uint row, uint column)
{
string target = this.Post;
if (!target.EndsWith("/"))
{
target += "/";
}
target += "R" + row.ToString() + "C" + column.ToString();
return target;
}
/// <summary>
/// returns the given CellEntry object. Note that the getter will go to the server
/// to get CellEntries that are NOT yet on the client
/// </summary>
/// <returns>CellEntry</returns>
[CLSCompliant(false)]
public CellEntry this[uint row, uint column]
{
get
{
// let's find the cell
foreach (CellEntry entry in this.Entries )
{
CellEntry.CellElement cell = entry.Cell;
if (cell.Row == row && cell.Column == column)
{
return entry;
}
}
// if we are here, we need to get the entry from the service
string url = CellUri(row, column);
CellQuery query = new CellQuery(url);
CellFeed feed = this.Service.Query(query) as CellFeed;
CellEntry newEntry = feed.Entries[0] as CellEntry;
this.Entries.Add(newEntry);
// we don't want this one to show up in the batch feed on it's own
newEntry.Dirty = false;
return newEntry;
}
}
/// <summary>
/// deletes a cell by using row and column addressing
/// </summary>
/// <param name="row"></param>
/// <param name="column"></param>
[CLSCompliant(false)]
public void Delete(uint row, uint column)
{
// now we need to create a new guy
string url = CellUri(row, column);
this.Service.Delete(new Uri(url));
}
//////////////////////////////////////////////////////////////////////
/// <summary>uses GData batch to batchupdate the cell feed. If the returned
/// batch result set contained an error, it will throw a GDataRequestBatchException</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public override void Publish()
{
if (this.Batch == null)
{
throw new InvalidOperationException("This feed has no batch URI");
}
AtomFeed batchFeed = CreateBatchFeed(GDataBatchOperationType.update);
if (batchFeed != null)
{
AtomFeed resultFeed = this.Service.Batch(batchFeed, new Uri(this.Batch));
foreach (AtomEntry resultEntry in resultFeed.Entries )
{
GDataBatchEntryData data = resultEntry.BatchData;
if (data.Status.Code != (int) HttpStatusCode.OK)
{
throw new GDataBatchRequestException(resultFeed);
}
}
// if we get here, everything is fine. So update the edit URIs in the original feed,
// because those might have changed.
foreach (AtomEntry resultEntry in resultFeed.Entries )
{
AtomEntry originalEntry = this.Entries.FindById(resultEntry.Id);
if (originalEntry == null)
{
throw new GDataBatchRequestException(resultFeed);
}
if (originalEntry != null)
{
originalEntry.EditUri = resultEntry.EditUri;
}
}
}
this.Dirty = false;
}
/////////////////////////////////////////////////////////////////////////////
}
}
| |
// 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.
// ----------------------------------------------------------------------------------
// Interop library code
//
// COM Marshalling helpers used by MCG
//
// NOTE:
// These source code are being published to InternalAPIs and consumed by RH builds
// Use PublishInteropAPI.bat to keep the InternalAPI copies in sync
// ----------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;
using System.Runtime;
using System.Diagnostics.Contracts;
using Internal.NativeFormat;
using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices
{
internal static unsafe class McgComHelpers
{
/// <summary>
/// Returns runtime class name for a specific object
/// </summary>
internal static string GetRuntimeClassName(Object obj)
{
#if ENABLE_WINRT
System.IntPtr pWinRTItf = default(IntPtr);
try
{
pWinRTItf = McgMarshal.ObjectToIInspectable(obj);
if (pWinRTItf == default(IntPtr))
return String.Empty;
else
return GetRuntimeClassName(pWinRTItf);
}
finally
{
if (pWinRTItf != default(IntPtr)) McgMarshal.ComRelease(pWinRTItf);
}
#else
return string.Empty;
#endif
}
/// <summary>
/// Returns runtime class name for a specific WinRT interface
/// </summary>
internal static string GetRuntimeClassName(IntPtr pWinRTItf)
{
#if ENABLE_WINRT
void* unsafe_hstring = null;
try
{
int hr = CalliIntrinsics.StdCall__int(
((__com_IInspectable*)(void*)pWinRTItf)->pVtable->pfnGetRuntimeClassName,
pWinRTItf, &unsafe_hstring);
// Don't throw if the call fails
if (hr < 0)
return String.Empty;
return McgMarshal.HStringToString(new IntPtr(unsafe_hstring));
}
finally
{
if (unsafe_hstring != null)
McgMarshal.FreeHString(new IntPtr(unsafe_hstring));
}
#else
throw new PlatformNotSupportedException("GetRuntimeClassName(IntPtr)");
#endif
}
/// <summary>
/// Given a IStream*, seek to its beginning
/// </summary>
internal static unsafe bool SeekStreamToBeginning(IntPtr pStream)
{
Interop.COM.__IStream* pStreamNativePtr = (Interop.COM.__IStream*)(void*)pStream;
UInt64 newPosition;
int hr = CalliIntrinsics.StdCall<int>(
pStreamNativePtr->vtbl->pfnSeek,
pStreamNativePtr,
0UL,
(uint)Interop.COM.STREAM_SEEK.STREAM_SEEK_SET,
&newPosition);
return (hr >= 0);
}
/// <summary>
/// Given a IStream*, change its size
/// </summary>
internal static unsafe bool SetStreamSize(IntPtr pStream, ulong lSize)
{
Interop.COM.__IStream* pStreamNativePtr = (Interop.COM.__IStream*)(void*)pStream;
UInt64 newPosition;
int hr = CalliIntrinsics.StdCall<int>(
pStreamNativePtr->vtbl->pfnSetSize,
pStreamNativePtr,
lSize,
(uint)Interop.COM.STREAM_SEEK.STREAM_SEEK_SET,
&newPosition);
return (hr >= 0);
}
/// <summary>
/// Release a IStream that has marshalled data in it
/// </summary>
internal static void SafeReleaseStream(IntPtr pStream)
{
#if ENABLE_WINRT
if (pStream != default(IntPtr))
{
// Release marshalled data and ignore any error
ExternalInterop.CoReleaseMarshalData(pStream);
McgMarshal.ComRelease(pStream);
}
#else
throw new PlatformNotSupportedException("SafeReleaseStream");
#endif
}
/// <summary>
/// Returns whether the IUnknown* is a free-threaded COM object
/// </summary>
/// <param name="pUnknown"></param>
internal static unsafe bool IsFreeThreaded(IntPtr pUnknown)
{
//
// Does it support IAgileObject?
//
IntPtr pAgileObject = McgMarshal.ComQueryInterfaceNoThrow(pUnknown, ref Interop.COM.IID_IAgileObject);
if (pAgileObject != default(IntPtr))
{
// Anything that implements IAgileObject is considered to be free-threaded
// NOTE: This doesn't necessarily mean that the object is free-threaded - it only means
// we BELIEVE it is free-threaded
McgMarshal.ComRelease_StdCall(pAgileObject);
return true;
}
IntPtr pMarshal = McgMarshal.ComQueryInterfaceNoThrow(pUnknown, ref Interop.COM.IID_IMarshal);
if (pMarshal == default(IntPtr))
return false;
try
{
//
// Check the un-marshaler
//
Interop.COM.__IMarshal* pIMarshalNativePtr = (Interop.COM.__IMarshal*)(void*)pMarshal;
fixed (Guid* pGuid = &Interop.COM.IID_IUnknown)
{
Guid clsid;
int hr = CalliIntrinsics.StdCall__int(
pIMarshalNativePtr->vtbl->pfnGetUnmarshalClass,
new IntPtr(pIMarshalNativePtr),
pGuid,
default(IntPtr),
(uint)Interop.COM.MSHCTX.MSHCTX_INPROC,
default(IntPtr),
(uint)Interop.COM.MSHLFLAGS.MSHLFLAGS_NORMAL,
&clsid);
if (hr >= 0 && InteropExtensions.GuidEquals(ref clsid, ref Interop.COM.CLSID_InProcFreeMarshaler))
{
// The un-marshaller is indeed the unmarshaler for the FTM so this object
// is free threaded.
return true;
}
}
return false;
}
finally
{
McgMarshal.ComRelease_StdCall(pMarshal);
}
}
/// <summary>
/// Get from cache if available, else allocate from heap
/// </summary>
#if !RHTESTCL
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
#endif
internal static void* CachedAlloc(int size, ref IntPtr cache)
{
// Read cache, clear it
void* pBlock = (void*)Interlocked.Exchange(ref cache, default(IntPtr));
if (pBlock == null)
{
pBlock =(void*) ExternalInterop.MemAlloc(new UIntPtr((uint)size));
}
return pBlock;
}
/// <summary>
/// Return to cache if empty, else free to heap
/// </summary>
#if !RHTESTCL
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
#endif
internal static void CachedFree(void* block, ref IntPtr cache)
{
if ((void*)Interlocked.CompareExchange(ref cache, new IntPtr(block), default(IntPtr)) != null)
{
ExternalInterop.MemFree((IntPtr)block);
}
}
/// <summary>
/// Return true if the object is a RCW. False otherwise
/// </summary>
internal static bool IsComObject(object obj)
{
return (obj is __ComObject);
}
/// <summary>
/// Unwrap if this is a managed wrapper
/// Typically used in data binding
/// For example, you don't want to data bind against a KeyValuePairImpl<K, V> - you want the real
/// KeyValuePair<K, V>
/// </summary>
/// <param name="target">The object you want to unwrap</param>
/// <returns>The original object or the unwrapped object</returns>
internal static object UnboxManagedWrapperIfBoxed(object target)
{
//
// If the target is boxed by managed code:
// 1. BoxedValue
// 2. BoxedKeyValuePair
// 3. StandardCustomPropertyProviderProxy/EnumerableCustomPropertyProviderProxy/ListCustomPropertyProviderProxy
//
// we should use its value for data binding
//
if (InteropExtensions.AreTypesAssignable(target.GetTypeHandle(), typeof(IManagedWrapper).TypeHandle))
{
target = ((IManagedWrapper)target).GetTarget();
Debug.Assert(!(target is IManagedWrapper));
}
return target;
}
[Flags]
internal enum CreateComObjectFlags
{
None = 0,
IsWinRTObject,
/// <summary>
/// Don't attempt to find out the actual type (whether it is IInspectable nor IProvideClassInfo)
/// of the incoming interface and do not attempt to unbox them using WinRT rules
/// </summary>
SkipTypeResolutionAndUnboxing
}
/// <summary>
/// Returns the existing RCW or create a new RCW from the COM interface pointer
/// NOTE: Don't use this overload if you already have the identity IUnknown
/// </summary>
/// <param name="expectedContext">
/// The current context of this thread. If it is passed and is not Default, we'll check whether the
/// returned RCW from cache matches this expected context. If it is not a match (from a different
/// context, and is not free threaded), we'll go ahead ignoring the cached entry, and create a new
/// RCW instead - which will always end up in the current context
/// We'll skip the check if current == ContextCookie.Default.
/// </param>
internal static object ComInterfaceToComObject(
IntPtr pComItf,
RuntimeTypeHandle interfaceType,
RuntimeTypeHandle classTypeInSigature,
ContextCookie expectedContext,
CreateComObjectFlags flags
)
{
Debug.Assert(expectedContext.IsDefault || expectedContext.IsCurrent);
//
// Get identity IUnknown for lookup
//
IntPtr pComIdentityIUnknown = McgMarshal.ComQueryInterfaceNoThrow(pComItf, ref Interop.COM.IID_IUnknown);
if (pComIdentityIUnknown == default(IntPtr))
throw new InvalidCastException();
try
{
object obj = ComInterfaceToComObjectInternal(
pComItf,
pComIdentityIUnknown,
interfaceType,
classTypeInSigature,
expectedContext,
flags
);
return obj;
}
finally
{
McgMarshal.ComRelease(pComIdentityIUnknown);
}
}
/// <summary>
/// Returns the existing RCW or create a new RCW from the COM interface pointer
/// NOTE: This does unboxing unless CreateComObjectFlags.SkipTypeResolutionAndUnboxing is specified
/// </summary>
/// <param name="expectedContext">
/// The current context of this thread. If it is passed and is not Default, we'll check whether the
/// returned RCW from cache matches this expected context. If it is not a match (from a different
/// context, and is not free threaded), we'll go ahead ignoring the cached entry, and create a new
/// RCW instead - which will always end up in the current context
/// We'll skip the check if current == ContextCookie.Default.
/// </param>
internal static object ComInterfaceToComObjectInternal(
IntPtr pComItf,
IntPtr pComIdentityIUnknown,
RuntimeTypeHandle interfaceType,
RuntimeTypeHandle classTypeInSignature,
ContextCookie expectedContext,
CreateComObjectFlags flags
)
{
string className;
object obj = ComInterfaceToComObjectInternal_NoCache(
pComItf,
pComIdentityIUnknown,
interfaceType,
classTypeInSignature,
expectedContext,
flags,
out className
);
//
// The assumption here is that if the classInfoInSignature is null and interfaceTypeInfo
// is either IUnknow and IInspectable we need to try unboxing.
//
bool doUnboxingCheck =
(flags & CreateComObjectFlags.SkipTypeResolutionAndUnboxing) == 0 &&
obj != null &&
classTypeInSignature.IsNull() &&
(interfaceType.Equals(InternalTypes.IUnknown) ||
interfaceType.IsIInspectable());
if (doUnboxingCheck)
{
//
// Try unboxing
// Even though this might just be a IUnknown * from the signature, we still attempt to unbox
// if it implements IInspectable
//
// @TODO - We might need to optimize this by pre-checking the names to see if they
// potentially represents a boxed type, but for now let's keep it simple and I also don't
// want to replicate the knowledge here
// @TODO2- We probably should skip the creating the COM object in the first place.
//
// NOTE: the RCW here could be a cached one (for a brief time if GC doesn't kick in. as there
// is nothing to hold the RCW alive for IReference<T> RCWs), so this could save us a RCW
// creation cost potentially. Desktop CLR doesn't do this. But we also paying for unnecessary
// cache management cost, and it is difficult to say which way is better without proper
// measuring
//
object unboxedObj = McgMarshal.UnboxIfBoxed(obj, className);
if (unboxedObj != null)
return unboxedObj;
}
//
// In order for variance to work, we save the incoming interface pointer as specified in the
// signature into the cache, so that we know this RCW does support this interface and variance
// can take advantage of that later
// NOTE: In some cases, native might pass a WinRT object as a 'compatible' interface, for example,
// pass IVector<IFoo> as IVector<Object> because they are 'compatible', but QI for IVector<object>
// won't succeed. In this case, we'll just believe it implements IVector<Object> as in the
// signature while the underlying interface pointer is actually IVector<IFoo>
//
__ComObject comObject = obj as __ComObject;
if (comObject != null)
{
McgMarshal.ComAddRef(pComItf);
try
{
comObject.InsertIntoCache(interfaceType, ContextCookie.Current, ref pComItf, true);
}
finally
{
//
// Only release when a exception is thrown or we didn't 'swallow' the ref count by
// inserting it into the cache
//
McgMarshal.ComSafeRelease(pComItf);
}
}
return obj;
}
/// <summary>
/// Returns the existing RCW or create a new RCW from the COM interface pointer
/// NOTE: This does not do any unboxing at all.
/// </summary>
/// <param name="expectedContext">
/// The current context of this thread. If it is passed and is not Default, we'll check whether the
/// returned RCW from cache matches this expected context. If it is not a match (from a different
/// context, and is not free threaded), we'll go ahead ignoring the cached entry, and create a new
/// RCW instead - which will always end up in the current context
/// We'll skip the check if current == ContextCookie.Default.
/// </param>
private static object ComInterfaceToComObjectInternal_NoCache(
IntPtr pComItf,
IntPtr pComIdentityIUnknown,
RuntimeTypeHandle interfaceType,
RuntimeTypeHandle classTypeInSignature,
ContextCookie expectedContext,
CreateComObjectFlags flags,
out string className
)
{
className = null;
//
// Lookup RCW in global RCW cache based on the identity IUnknown
//
__ComObject comObject = ComObjectCache.Lookup(pComIdentityIUnknown);
if (comObject != null)
{
bool useThisComObject = true;
if (!expectedContext.IsDefault)
{
//
// Make sure the returned RCW matches the context we specify (if any)
//
if (!comObject.IsFreeThreaded &&
!comObject.ContextCookie.Equals(expectedContext))
{
//
// This is a mismatch.
// We only care about context for WinRT factory RCWs (which is the only place we are
// passing in the context right now).
// When we get back a WinRT factory RCW created in a different context. This means the
// factory is a singleton, and the returned IActivationFactory could be either one of
// the following:
// 1) A raw pointer, and it acts like a free threaded object
// 2) A proxy that is used across different contexts. It might maintain a list of contexts
// that it is marshaled to, and will fail to be called if it is not marshaled to this
// context yet.
//
// In this case, it is unsafe to use this RCW in this context and we should proceed
// to create a duplicated one instead. It might make sense to have a context-sensitive
// RCW cache but I don't think this case will be common enough to justify it
//
// @TODO: Check for DCOM proxy as well
useThisComObject = false;
}
}
if (useThisComObject)
{
//
// We found one - AddRef and return
//
comObject.AddRef();
return comObject;
}
}
string winrtClassName = null;
bool isSealed = false;
if (!classTypeInSignature.IsNull())
{
isSealed = classTypeInSignature.IsSealed();
}
//
// Only look at runtime class name if the class type in signature is not sealed
// NOTE: In the case of System.Uri, we are not pass the class type, only the interface
//
if (!isSealed &&
(flags & CreateComObjectFlags.SkipTypeResolutionAndUnboxing) == 0)
{
IntPtr pInspectable;
bool needRelease = false;
if (interfaceType.IsSupportIInspectable())
{
//
// Use the interface pointer as IInspectable as we know it is indeed a WinRT interface that
// derives from IInspectable
//
pInspectable = pComItf;
}
else if ((flags & CreateComObjectFlags.IsWinRTObject) != 0)
{
//
// Otherwise, if someone tells us that this is a WinRT object, but we don't have a
// IInspectable interface at hand, we'll QI for it
//
pInspectable = McgMarshal.ComQueryInterfaceNoThrow(pComItf, ref Interop.COM.IID_IInspectable);
needRelease = true;
}
else
{
pInspectable = default(IntPtr);
}
try
{
if (pInspectable != default(IntPtr))
{
className = McgComHelpers.GetRuntimeClassName(pInspectable);
winrtClassName = className;
}
}
finally
{
if (needRelease && pInspectable != default(IntPtr))
{
McgMarshal.ComRelease(pInspectable);
pInspectable = default(IntPtr);
}
}
}
//
// 1. Prefer using the class returned from GetRuntimeClassName
// 2. Otherwise use the class (if there) in the signature
// 3. Out of options - create __ComObject
//
RuntimeTypeHandle classTypeToCreateRCW = default(RuntimeTypeHandle);
RuntimeTypeHandle interfaceTypeFromName = default(RuntimeTypeHandle);
if (!String.IsNullOrEmpty(className))
{
if (!McgModuleManager.TryGetClassTypeFromName(className, out classTypeToCreateRCW))
{
//
// If we can't find the class name in our map, try interface as well
// Such as IVector<Int32>
// This apparently won't work if we haven't seen the interface type in MCG
//
McgModuleManager.TryGetInterfaceTypeFromName(className, out interfaceTypeFromName);
}
}
if (classTypeToCreateRCW.IsNull())
classTypeToCreateRCW = classTypeInSignature;
// Use identity IUnknown to create the new RCW
// @TODO: Transfer the ownership of ref count to the RCW
if (classTypeToCreateRCW.IsNull())
{
//
// Create a weakly typed RCW because we have no information about this particular RCW
// @TODO - what if this RCW is not seen by MCG but actually exists in WinMD and therefore we
// are missing GCPressure and ComMarshallingType information for this object?
//
comObject = new __ComObject(pComIdentityIUnknown, default(RuntimeTypeHandle));
}
else
{
//
// Create a strongly typed RCW based on RuntimeTypeHandle
//
comObject = CreateComObjectInternal(classTypeToCreateRCW, pComIdentityIUnknown); // Use identity IUnknown to create the new RCW
}
#if DEBUG
//
// Remember the runtime class name for debugging purpose
// This way you can tell what the class name is, even when we failed to create a strongly typed
// RCW for it
//
comObject.m_runtimeClassName = className;
#endif
//
// Make sure we QI for that interface
//
if (!interfaceType.IsNull())
{
comObject.QueryInterface_NoAddRef_Internal(interfaceType, /* cacheOnly= */ false, /* throwOnQueryInterfaceFailure= */ false);
}
return comObject;
}
internal static __ComGenericInterfaceDispatcher CreateGenericComDispatcher(RuntimeTypeHandle genericDispatcherDef, RuntimeTypeHandle[] genericArguments, __ComObject comThisPointer)
{
#if !RHTESTCL && !CORECLR && !CORERT
Debug.Assert(genericDispatcherDef.IsGenericTypeDefinition());
Debug.Assert(genericArguments != null && genericArguments.Length > 0);
RuntimeTypeHandle instantiatedDispatcherType;
if (!Internal.Runtime.TypeLoader.TypeLoaderEnvironment.Instance.TryGetConstructedGenericTypeForComponents(genericDispatcherDef, genericArguments, out instantiatedDispatcherType))
return null; // ERROR
__ComGenericInterfaceDispatcher dispatcher = (__ComGenericInterfaceDispatcher)InteropExtensions.RuntimeNewObject(instantiatedDispatcherType);
dispatcher.m_comObject = comThisPointer;
return dispatcher;
#else
return null;
#endif
}
private static __ComObject CreateComObjectInternal(RuntimeTypeHandle classType, IntPtr pComItf)
{
Debug.Assert(!classType.IsNull());
if (classType.Equals(McgModule.s_DependencyReductionTypeRemovedTypeHandle))
{
// We should filter out the strongly typed RCW in TryGetClassInfoFromName step
#if !RHTESTCL
Environment.FailFast(McgTypeHelpers.GetDiagnosticMessageForMissingType(classType));
#else
Environment.FailFast("We should never see strongly typed RCW discarded here");
#endif
}
//Note that this doesn't run the constructor in RH but probably do in your reflection based implementation.
//If this were a real RCW, you would actually 'new' the RCW which is wrong. Fortunately in CoreCLR we don't have
//this scenario so we are OK, but we should figure out a way to fix this by having a runtime API.
object newClass = InteropExtensions.RuntimeNewObject(classType);
Debug.Assert(newClass is __ComObject);
__ComObject newObj = InteropExtensions.UncheckedCast<__ComObject>(newClass);
IntPtr pfnCtor = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfAttachingCtor>(__ComObject.AttachingCtor);
CalliIntrinsics.Call<int>(pfnCtor, newObj, pComItf, classType);
return newObj;
}
/// <summary>
/// Converts a COM interface pointer to a managed object
/// This either gets back a existing CCW, or a existing RCW, or create a new RCW
/// </summary>
internal static object ComInterfaceToObjectInternal(
IntPtr pComItf,
RuntimeTypeHandle interfaceType,
RuntimeTypeHandle classTypeInSignature,
CreateComObjectFlags flags)
{
bool needUnboxing = (flags & CreateComObjectFlags.SkipTypeResolutionAndUnboxing) == 0;
object ret = ComInterfaceToObjectInternal_NoManagedUnboxing(pComItf, interfaceType, classTypeInSignature, flags);
if (ret != null && needUnboxing)
{
return UnboxManagedWrapperIfBoxed(ret);
}
return ret;
}
static object ComInterfaceToObjectInternal_NoManagedUnboxing(
IntPtr pComItf,
RuntimeTypeHandle interfaceType,
RuntimeTypeHandle classTypeInSignature,
CreateComObjectFlags flags)
{
if (pComItf == default(IntPtr))
return null;
//
// Is this a CCW?
//
ComCallableObject ccw;
if (ComCallableObject.TryGetCCW(pComItf, out ccw))
{
return ccw.TargetObject;
}
//
// This pointer is not a CCW, but we need to do one additional check here for aggregation
// In case the COM pointer is a interface implementation from native, but the outer object is a
// managed object
//
IntPtr pComIdentityIUnknown = McgMarshal.ComQueryInterfaceNoThrow(pComItf, ref Interop.COM.IID_IUnknown);
if (pComIdentityIUnknown == default(IntPtr))
throw new InvalidCastException();
try
{
//
// Check whether the identity COM pointer to see if it is a aggregating CCW
//
if (ComCallableObject.TryGetCCW(pComIdentityIUnknown, out ccw))
{
return ccw.TargetObject;
}
//
// Nope, not a CCW - let's go down our RCW creation code path
//
return ComInterfaceToComObjectInternal(
pComItf,
pComIdentityIUnknown,
interfaceType,
classTypeInSignature,
ContextCookie.Default,
flags
);
}
finally
{
McgMarshal.ComRelease(pComIdentityIUnknown);
}
}
internal static unsafe IntPtr ObjectToComInterfaceInternal(Object obj, RuntimeTypeHandle typeHnd)
{
if (obj == null)
return default(IntPtr);
#if ENABLE_WINRT
//
// Try boxing if this is a WinRT object
//
if (typeHnd.Equals(InternalTypes.IInspectable))
{
object unboxed = McgMarshal.BoxIfBoxable(obj);
//
// Marshal ReferenceImpl<T> to WinRT as IInspectable
//
if (unboxed != null)
{
obj = unboxed;
}
else
{
//
// Anything that can be casted to object[] will be boxed as object[]
//
object[] objArray = obj as object[];
if (objArray != null)
{
unboxed = McgMarshal.BoxIfBoxable(obj, typeof(object[]).TypeHandle);
if (unboxed != null)
obj = unboxed;
}
}
}
#endif //ENABLE_WINRT
//
// If this is a RCW, and the RCW is not a base class (managed class deriving from RCW class),
// QI on the RCW
//
__ComObject comObject = obj as __ComObject;
if (comObject != null && !comObject.ExtendsComObject)
{
IntPtr pComPtr = comObject.QueryInterface_NoAddRef_Internal(typeHnd, /* cacheOnly= */ false, /* throwOnQueryInterfaceFailure= */ false);
if (pComPtr == default(IntPtr))
return default(IntPtr);
McgMarshal.ComAddRef(pComPtr);
GC.KeepAlive(comObject); // make sure we don't collect the object before adding a refcount.
return pComPtr;
}
//
// Otherwise, go down the CCW code path
//
return ManagedObjectToComInterface(obj, typeHnd);
}
internal static unsafe IntPtr ManagedObjectToComInterface(Object obj, RuntimeTypeHandle interfaceType)
{
Guid iid = interfaceType.GetInterfaceGuid();
return ManagedObjectToComInterfaceInternal(obj, ref iid, interfaceType);
}
internal static unsafe IntPtr ManagedObjectToComInterface(Object obj, ref Guid iid)
{
return ManagedObjectToComInterfaceInternal(obj, ref iid, default(RuntimeTypeHandle));
}
private static unsafe IntPtr ManagedObjectToComInterfaceInternal(Object obj, ref Guid iid, RuntimeTypeHandle interfaceType)
{
if (obj == null)
{
return default(IntPtr);
}
//
// Look up ComCallableObject from the cache
// If couldn't find one, create a new one
//
ComCallableObject ccw = null;
try
{
//
// Either return existing one or create a new one
// In either case, the returned CCW is addref-ed to avoid race condition
//
IntPtr dummy;
ccw = CCWLookupMap.GetOrCreateCCW(obj, interfaceType, out dummy);
Debug.Assert(ccw != null);
return ccw.GetComInterfaceForIID(ref iid, interfaceType);
}
finally
{
//
// Free the extra ref count added by GetOrCreateCCW (to protect the CCW from being collected)
//
if (ccw != null)
ccw.Release();
}
}
}
}
| |
// Author:
// Allis Tauri <allista@gmail.com>
//
// Copyright (c) 2015 Allis Tauri
//
// This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License.
// To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/4.0/
// or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace AT_Utils
{
public class ConfigNodeObject : IConfigNode
{
public const string NODE_NAME = "NODE";
static readonly string cnode_name = typeof(IConfigNode).Name;
string node_name = null;
public string NodeName
{
get
{
if(node_name == null)
{
var T = GetType();
var name_field = T.GetField("NODE_NAME", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
node_name = name_field != null ? name_field.GetValue(null) as string : T.Name;
}
return node_name;
}
}
protected bool not_persistant(FieldInfo fi) =>
fi.GetCustomAttributes(typeof(Persistent), true).Length == 0;
T get_or_create<T>(FieldInfo fi) where T : class =>
(fi.GetValue(this) ?? Activator.CreateInstance(fi.FieldType)) as T;
FieldInfo[] get_fields() =>
GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
virtual public void Load(ConfigNode node)
{
try
{
ConfigNode.LoadObjectFromConfig(this, node);
}
catch(Exception e)
{
Utils.Log("Exception while loading {}\n{}\n{}\n{}",
this, e.Message, e.StackTrace, node);
}
foreach(var fi in get_fields())
{
if(not_persistant(fi)) continue;
var n = node.GetNode(fi.Name);
//restore types saved as nodes
if(n != null)
{
//restore IConfigNodes
if(fi.FieldType.GetInterface(cnode_name) != null)
{
var f = get_or_create<IConfigNode>(fi);
if(f != null)
{
f.Load(n);
fi.SetValue(this, f);
}
}
//restore ConfigNodes
else if(typeof(ConfigNode).IsAssignableFrom(fi.FieldType))
fi.SetValue(this, n.CreateCopy());
//restore Orbit
else if(fi.FieldType == typeof(Orbit))
{
var obt = new OrbitSnapshot(n);
fi.SetValue(this, obt.Load());
}
continue;
}
//restore types saved as values
var v = node.GetValue(fi.Name);
if(v != null)
{
if(fi.FieldType == typeof(Guid))
fi.SetValue(this, new Guid(v));
else if(fi.FieldType == typeof(Vector3d))
fi.SetValue(this, KSPUtil.ParseVector3d(v));
}
}
}
virtual public void LoadFrom(ConfigNode parent, string node_name = null)
{
var node = parent.GetNode(node_name ?? NodeName);
if(node != null) Load(node);
}
ConfigNode get_field_node(FieldInfo fi, ConfigNode parent)
{
var n = parent.GetNode(fi.Name);
if(n == null) n = parent.AddNode(fi.Name);
else n.ClearData();
return n;
}
virtual public void Save(ConfigNode node)
{
try
{
ConfigNode.CreateConfigFromObject(this, node);
}
catch(Exception e)
{
Utils.Log("Exception while saving {}\n{}\n{}\n{}",
GetType().Name, e.Message, e.StackTrace, node);
}
foreach(var fi in get_fields())
{
if(not_persistant(fi)) continue;
//save all IConfigNode
if(fi.FieldType.GetInterface(cnode_name) != null)
{
var f = fi.GetValue(this) as IConfigNode;
if(f != null) f.Save(get_field_node(fi, node));
}
//save ConfigNode
else if(typeof(ConfigNode).IsAssignableFrom(fi.FieldType))
{
var f = fi.GetValue(this) as ConfigNode;
if(f != null) get_field_node(fi, node).AddData(f);
}
//save some often used types
else if(fi.FieldType == typeof(Guid))
node.AddValue(fi.Name, ((Guid)fi.GetValue(this)).ToString("N"));
else if(fi.FieldType == typeof(Vector3d))
node.AddValue(fi.Name, KSPUtil.WriteVector((Vector3d)fi.GetValue(this)));
else if(fi.FieldType == typeof(Orbit))
{
var f = fi.GetValue(this) as Orbit;
if(f != null)
{
var obt = new OrbitSnapshot(f);
obt.Save(get_field_node(fi, node));
}
}
}
}
virtual public void SaveInto(ConfigNode parent, string node_name = null)
{ Save(parent.AddNode(node_name ?? NodeName)); }
virtual public void Copy(ConfigNodeObject other)
{
var node = new ConfigNode();
other.Save(node);
Load(node);
}
virtual public CNO Clone<CNO>()
where CNO : ConfigNodeObject, new()
{
var node = new ConfigNode(NODE_NAME);
Save(node);
return FromConfig<CNO>(node);
}
public static CNO FromConfig<CNO>(ConfigNode node)
where CNO : ConfigNodeObject, new()
{
var cno = new CNO();
cno.Load(node);
return cno;
}
public override string ToString()
{
var n = new ConfigNode(GetType().Name);
Save(n);
return n.ToString();
}
#region Binary Serializer
static MemoryStream memoryStream = new MemoryStream();
static BinaryFormatter binaryFormatter = new BinaryFormatter();
public static string Serialize(object obj)
{
memoryStream.Seek(0, SeekOrigin.Begin);
binaryFormatter.Serialize(memoryStream, obj);
return Convert.ToBase64String(memoryStream.ToArray());
}
public static T Deserialize<T>(string data)
{
var bytes = Convert.FromBase64String(data);
memoryStream.SetLength(0);
memoryStream.Write(bytes, 0, bytes.Length);
return (T)binaryFormatter.Deserialize(memoryStream);
}
#endregion
ConfigNode extract_path(ConfigNode node, List<string> path)
{
var new_node = new ConfigNode(node.name) { id = node.id };
if(path.Count > 1)
{
foreach(var subnode in node.GetNodes(path[0]))
new_node.AddNode(extract_path(subnode, path.GetRange(1, path.Count - 1)));
}
else
{
var leaf_spec = path[0].Split(new[] { ':' }, 2);
var leaf_node = leaf_spec[0];
var leaf_value = leaf_spec.Length > 1 ? leaf_spec[1] : null;
if(string.IsNullOrEmpty(leaf_node))
{
if(string.IsNullOrEmpty(leaf_value))
node.CopyTo(new_node);
else
foreach(var val in node.GetValues(leaf_value))
new_node.AddValue(leaf_value, val);
}
else
{
foreach(var subnode in node.GetNodes(leaf_node))
{
if(string.IsNullOrEmpty(leaf_value))
new_node.AddNode(subnode.CreateCopy());
else
{
var new_subnode = new ConfigNode(subnode.name) { id = subnode.id };
foreach(var val in subnode.GetValues(leaf_value))
new_subnode.AddValue(leaf_value, val);
new_node.AddNode(new_subnode);
}
}
}
}
return new_node;
}
void merge_nodes(ConfigNode base_node, ConfigNode node)
{
int idx = 0;
var value_indexes = new Dictionary<string, int>();
foreach(ConfigNode.Value value in node.values)
{
if(!value_indexes.TryGetValue(value.name, out idx))
idx = 0;
base_node.SetValue(value.name, value.value, idx, true);
value_indexes[value.name] = idx + 1;
}
var node_indexes = new Dictionary<string, int>();
foreach(ConfigNode subnode in node.nodes)
{
if(!node_indexes.TryGetValue(subnode.name, out idx))
idx = 0;
var base_subnode = base_node.GetNode(subnode.name, idx);
if(base_subnode != null)
merge_nodes(base_subnode, subnode);
else
base_node.AddNode(subnode);
value_indexes[subnode.name] = idx + 1;
}
}
public void SavePartial(ConfigNode node, params string[] paths)
{
var full_node = new ConfigNode(node.name);
Save(full_node);
for(int i = 0, pathsLength = paths.Length; i < pathsLength; i++)
{
var partial = extract_path(full_node, paths[i].Split('/').ToList());
merge_nodes(node, partial);
}
}
}
public class TypedConfigNodeObject : ConfigNodeObject
{
public override void Save(ConfigNode node)
{
var type = GetType();
node.AddValue("type", string.Format("{0}, {1}", type.FullName, type.Assembly.GetName().Name));
base.Save(node);
}
public override void Load(ConfigNode node)
{
base.Load(node);
foreach(var fi in GetType().GetFields())
{
if(not_persistant(fi)) continue;
if(fi.FieldType.IsSubclassOf(typeof(TypedConfigNodeObject)))
{
var n = node.GetNode(fi.Name);
fi.SetValue(this, n == null ? null : FromConfig(n));
}
}
}
public static TypedConfigNodeObject FromConfig(ConfigNode node)
{
TypedConfigNodeObject obj = null;
var typename = node.GetValue("type");
if(typename == null) return obj;
var type = Type.GetType(typename);
if(type == null)
{
Utils.Log("Unable to create {}: Type not found.", typename);
return obj;
}
try
{
obj = Activator.CreateInstance(type) as TypedConfigNodeObject;
obj.Load(node);
}
catch(Exception ex) { Utils.Log("Unable to create {}: {}\n{}", typename, ex.Message, ex.StackTrace); }
return obj;
}
}
public class PersistentList<T> : List<T>, IConfigNode where T : IConfigNode, new()
{
public PersistentList() { }
public PersistentList(IEnumerable<T> content) : base(content) { }
public virtual void Save(ConfigNode node)
{
for(int i = 0, count = Count; i < count; i++)
this[i].Save(node.AddNode("Item"));
}
public virtual void Load(ConfigNode node)
{
Clear();
var nodes = node.GetNodes();
for(int i = 0, len = nodes.Length; i < len; i++)
{
var item = new T();
item.Load(nodes[i]);
Add(item);
}
}
}
public class PersistentDictS<T> : Dictionary<string, T>, IConfigNode where T : IConfigNode, new()
{
public PersistentDictS() { }
public PersistentDictS(IDictionary<string, T> data) : base(data) { }
public void Save(ConfigNode node)
{
foreach(var item in this)
item.Value.Save(node.AddNode(item.Key));
}
public void Load(ConfigNode node)
{
Clear();
var nodes = node.GetNodes();
for(int i = 0, len = nodes.Length; i < len; i++)
{
var n = nodes[i];
var item = new T();
item.Load(n);
Add(n.name, item);
}
}
}
public class PersistentQueue<T> : Queue<T>, IConfigNode where T : IConfigNode, new()
{
public PersistentQueue() { }
public PersistentQueue(IEnumerable<T> content) : base(content) { }
public void Save(ConfigNode node)
{
foreach(var item in this)
item.Save(node.AddNode("Item"));
}
public void Load(ConfigNode node)
{
Clear();
var nodes = node.GetNodes();
for(int i = 0, len = nodes.Length; i < len; i++)
{
var item = new T();
item.Load(nodes[i]);
Enqueue(item);
}
}
}
public class PersistentBaseList<T> : ConfigNodeObject where T : TypedConfigNodeObject, new()
{
readonly public List<T> List = new List<T>();
public int Count { get { return List.Count; } }
public T this[int i]
{
get { return List[i]; }
set { List[i] = value; }
}
public void Add(T it) { List.Add(it); }
public bool Remove(T it) { return List.Remove(it); }
public void Clear() { List.Clear(); }
public int IndexOf(T it) { return List.IndexOf(it); }
public override void Save(ConfigNode node)
{
base.Save(node);
for(int i = 0, count = List.Count; i < count; i++)
List[i].Save(node.AddNode(i.ToString()));
}
public override void Load(ConfigNode node)
{
base.Load(node);
foreach(var n in node.GetNodes())
{
var it = TypedConfigNodeObject.FromConfig(n) as T;
if(it != null) List.Add(it);
}
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* 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.
*
* 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 HOLDER 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.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XenAdmin.Actions;
using XenAPI;
using XenAdmin.Actions.HostActions;
using XenAdmin.Controls.DataGridViewEx;
using XenAdmin.Core;
namespace XenAdmin.Dialogs.VMDialogs
{
public partial class SelectVMsToSuspendDialog : XenDialogBase
{
private Host Server;
private readonly VMsWhichCanBeMigratedAction VmsToMigrateAction;
private long PoolMemoryFree = 0;
public SelectVMsToSuspendDialog(Host server)
{
InitializeComponent();
Server = server;
AvailableLabel.Font = Program.DefaultFontBold;
RequiredLabel.Font = Program.DefaultFontBold;
AvailableLabel.Text = PoolMemoryAvailableExcludingHost(Server);
VmsToMigrateAction = new VMsWhichCanBeMigratedAction(Server.Connection, Server);
VmsToMigrateAction.Completed += action_Completed;
VmsToMigrateAction.RunAsync();
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
var shortName = Server.Name();
if (shortName.Length > 25)
shortName = Server.Name().Ellipsise(25);
Text = string.Format(Messages.SELECT_VMS_TO_SUSPEND_DLOG_TITLE, shortName);
}
private string PoolMemoryAvailableExcludingHost(Host Server)
{
PoolMemoryFree = 0;
foreach (Host host in Server.Connection.Cache.Hosts)
{
if (host.Equals(Server))
continue;
PoolMemoryFree += host.memory_free_calc();
}
return Util.MemorySizeStringSuitableUnits(PoolMemoryFree, true);
}
private void UpdateRequiredMemory()
{
long required = 0;
foreach (VmGridRow row in VmsGridView.Rows)
{
if (row.Action != ActionCellAction.Migrate)
continue;
required += (long)row.Vm.memory_dynamic_max;
}
RequiredLabel.ForeColor = required > PoolMemoryFree ? Color.Red : ForeColor;
RequiredLabel.Text = Util.MemorySizeStringSuitableUnits(required, true);
OKButton.Enabled = required == 0 ? true : required < PoolMemoryFree;
}
void action_Completed(ActionBase sender)
{
Program.Invoke(Program.MainWindow, PopulateGridView);
}
private void PopulateGridView()
{
foreach (VM vm in VmsToMigrateAction.MigratableVms)
{
VmsGridView.Rows.Add(new VmGridRow(vm));
}
UpdateRequiredMemory();
}
public List<VM> SelectedVMsToSuspend
{
get
{
List<VM> vms = new List<VM>();
foreach (VmGridRow row in VmsGridView.Rows)
{
if (row.Action != ActionCellAction.Suspend)
continue;
vms.Add(row.Vm);
}
return vms;
}
}
public List<VM> SelectedVMsToShutdown
{
get
{
List<VM> vms = new List<VM>();
foreach (VmGridRow row in VmsGridView.Rows)
{
if (row.Action != ActionCellAction.Shutdown)
continue;
vms.Add(row.Vm);
}
return vms;
}
}
private void VmsGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
UpdateRequiredMemory();
}
private void VmsGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (VmsGridView.IsCurrentCellDirty)
{
VmsGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
}
public class VmGridRow : DataGridViewRow
{
public VM Vm;
private DataGridViewExImageCell ImageCell = new DataGridViewExImageCell();
private DataGridViewTextBoxCell NameCell = new DataGridViewTextBoxCell();
private DataGridViewTextBoxCell MemoryCell = new DataGridViewTextBoxCell();
private DataGridViewComboBoxCell ActionCell = new DataGridViewComboBoxCell();
public VmGridRow(VM vm)
{
Vm = vm;
Cells.Add(ImageCell);
Cells.Add(NameCell);
Cells.Add(MemoryCell);
Cells.Add(ActionCell);
UpdateDetails();
}
public ActionCellAction Action
{
get
{
return ((ActionCellItem)ActionCell.Value).Action;
}
}
private void UpdateDetails()
{
ImageCell.Value = Images.GetImage16For(Images.GetIconFor(Vm));
NameCell.Value = Vm.Name();
MemoryCell.Value = Util.MemorySizeStringSuitableUnits(Vm.memory_dynamic_max, true);
ActionCell.ValueType = typeof(ActionCellItem);
ActionCell.ValueMember = "ActionCell";
ActionCell.DisplayMember = "Text";
ActionCell.Items.Clear();
ActionCell.Items.Add(ActionCellItem.MigrateAction);
ActionCell.Items.Add(ActionCellItem.SuspendAction);
ActionCell.Items.Add(ActionCellItem.ShutdownAction);
ActionCell.Value = ActionCell.Items[0];
}
}
public class ActionCellItem
{
public static ActionCellItem MigrateAction = new ActionCellItem(ActionCellAction.Migrate);
public static ActionCellItem SuspendAction = new ActionCellItem(ActionCellAction.Suspend);
public static ActionCellItem ShutdownAction = new ActionCellItem(ActionCellAction.Shutdown);
public readonly ActionCellAction Action;
public ActionCellItem(ActionCellAction action)
{
Action = action;
}
public ActionCellItem ActionCell
{
get
{
return this;
}
}
public string Text
{
get
{
switch (Action)
{
case ActionCellAction.Migrate:
return Messages.MIGRATE;
case ActionCellAction.Suspend:
return Messages.SUSPEND;
case ActionCellAction.Shutdown:
return Messages.SHUTDOWN;
}
return Action.ToString();
}
}
}
public enum ActionCellAction { Migrate, Suspend, Shutdown }
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Portal.Access;
namespace Microsoft.Xrm.Portal.Core
{
public static class OrganizationServiceContextExtensions
{
public static IEnumerable<Entity> GetSubjects(this OrganizationServiceContext context)
{
if (context == null) throw new ArgumentNullException("context");
return context.CreateQuery("subject").ToList();
}
public static Entity GetArticle(this OrganizationServiceContext context, Guid articleId)
{
if (context == null) throw new ArgumentNullException("context");
var findArticle =
from c in context.CreateQuery("kbarticle")
where c.GetAttributeValue<Guid>("kbarticleid") == articleId
select c;
return findArticle.FirstOrDefault();
}
public static Entity GetCase(this OrganizationServiceContext context, Guid caseId)
{
if (context == null) throw new ArgumentNullException("context");
var findCase =
from c in context.CreateQuery("incident")
where c.GetAttributeValue<Guid>("incidentid") == caseId
select c;
return findCase.FirstOrDefault();
}
public static IEnumerable<Entity> GetCasesByCustomer(this OrganizationServiceContext context, Guid? customerId)
{
if (context == null) throw new ArgumentNullException("context");
var result = new List<Entity>();
var findCases =
from c in context.CreateQuery("incident")
where c.GetAttributeValue<Guid?>("customerid") == customerId
select c;
result.AddRange(findCases);
var findAccounts =
from a in context.CreateQuery("account")
where a.GetAttributeValue<Guid?>("accountid") == customerId
select a;
var account = findAccounts.FirstOrDefault();
if (account == null) return result;
var contacts = account.GetRelatedEntities(context, "contact_customer_accounts");
foreach (var contact in contacts)
{
result.AddRange(context.GetCasesByCustomer(contact.GetAttributeValue<Guid?>("contactid")));
}
return result;
}
public static IEnumerable<Entity> GetCasesForCurrentUser(this OrganizationServiceContext context, Entity contact, int scope)
{
if (context == null) throw new ArgumentNullException("context");
var emptyResult = new List<Entity>();
if (contact == null) return emptyResult;
var access = context.GetCaseAccessByContact(contact);
if (access == null || !access.GetAttributeValue<bool?>("adx_read").GetValueOrDefault()) return emptyResult;
var parentCustomer = contact.GetAttributeValue<Guid?>("parentcustomerid");
return ((access.GetAttributeValue<int?>("adx_scope") == scope) && (parentCustomer != null))
? GetCasesByCustomer(context, parentCustomer)
: GetCasesByCustomer(context, contact.GetAttributeValue<Guid?>("contactid"));
}
/// <summary>
/// Add a Note to an entity.
/// </summary>
/// <param name="context">The service context</param>
/// <param name="entity">The entity to which a note will be attached.</param>
/// <param name="noteTitle"></param>
/// <param name="noteText">The text of the note.</param>
/// <returns>True if successful; otherwise, false.</returns>
/// <remarks>
/// <para>The provided <paramref name="entity"/> must already be persisted to the CRM for this operation to succeed.</para>
/// <para>It it not necessary to SaveChanges after this operation--this operation fully persists this note to CRM.</para>
/// </remarks>
public static bool AddNoteAndSave(this OrganizationServiceContext context, Entity entity, string noteTitle, string noteText)
{
if (context == null) throw new ArgumentNullException("context");
return context.AddNoteAndSave(entity, noteTitle, noteText, null, null, null);
}
/// <summary>
/// Add a note to an entity.
/// </summary>
/// <param name="context">The service context</param>
/// <param name="entity">The entity to which a note will be attached.</param>
/// <param name="noteTitle"></param>
/// <param name="noteText">The text of the note.</param>
/// <param name="fileName">The name of the file to attach to this note.</param>
/// <param name="contentType">The MIME type of the file to attach to this note.</param>
/// <param name="fileContent">The raw byte data of the file to attach to this note.</param>
/// <returns>True if successful; otherwise, false.</returns>
/// <remarks>
/// <para>The provided <paramref name="entity"/> must already be persisted to the CRM for this operation to succeed.</para>
/// <para>It it not necessary to SaveChanges after this operation--this operation fully persists this note to CRM.</para>
/// </remarks>
public static bool AddNoteAndSave(this OrganizationServiceContext context, Entity entity, string noteTitle, string noteText, string fileName, string contentType, byte[] fileContent)
{
if (context == null) throw new ArgumentNullException("context");
if (entity == null) throw new ArgumentNullException("entity");
var entityName = entity.LogicalName;
var note = new Entity("annotation");
note.SetAttributeValue("subject", noteTitle);
note.SetAttributeValue("notetext", noteText);
note.SetAttributeValue("isdocument", false);
note.SetAttributeValue("objectid", entity.ToEntityReference());
note.SetAttributeValue("objecttypecode", entityName);
if (fileContent != null && fileContent.Length > 0 && !string.IsNullOrEmpty(fileName) && !string.IsNullOrEmpty(contentType))
{
note.SetAttributeValue("documentbody", Convert.ToBase64String(fileContent));
note.SetAttributeValue("filename", EnsureValidFileName(fileName));
note.SetAttributeValue("mimetype", contentType);
}
context.AddObject(note);
context.SaveChanges();
return true;
}
/// <summary>
/// Add a note to an entity.
/// </summary>
/// <param name="context">The service context</param>
/// <param name="entity">The entity to which a note will be attached.</param>
/// <param name="noteTitle"></param>
/// <param name="noteText">The text of the note.</param>
/// <param name="file">The file to attach with this note.</param>
/// <returns>True if successful; otherwise, false.</returns>
/// <remarks>
/// <para>The provided <paramref name="entity"/> must already be persisted to the CRM for this operation to succeed.</para>
/// <para>It it not necessary to SaveChanges after this operation--this operation fully persists this note to CRM.</para>
/// </remarks>
public static bool AddNoteAndSave(this OrganizationServiceContext context, Entity entity, string noteTitle, string noteText, HttpPostedFile file)
{
if (context == null) throw new ArgumentNullException("context");
if (file == null || file.ContentLength <= 0)
{
return context.AddNoteAndSave(entity, noteTitle, noteText, null, null, null);
}
var fileContent = new byte[file.ContentLength];
file.InputStream.Read(fileContent, 0, fileContent.Length);
return context.AddNoteAndSave(entity, noteTitle, noteText, file.FileName, file.ContentType, fileContent);
}
private static string EnsureValidFileName(string fileName)
{
return fileName.IndexOf("\\") >= 0 ? fileName.Substring(fileName.LastIndexOf("\\") + 1) : fileName;
}
public static Entity GetContactByFullNameAndEmailAddress(this OrganizationServiceContext context, string firstName, string lastName, string emailAddress)
{
var findContact =
from c in context.CreateQuery("contact")
where c.GetAttributeValue<string>("firstname") == firstName
&& c.GetAttributeValue<string>("lastname") == lastName
&& c.GetAttributeValue<string>("emailaddress1") == emailAddress
select c as Entity;
return findContact.FirstOrDefault();
}
public static Entity GetContactByUsername(this OrganizationServiceContext context, string username)
{
var findContact =
from c in context.CreateQuery("contact")
where c.GetAttributeValue<string>("adx_username") == username
select c;
return findContact.FirstOrDefault();
}
public static Entity GetContactByInvitationCode(this OrganizationServiceContext context, string invitationCode)
{
var now = DateTime.Now.Floor(RoundTo.Minute);
var findContact =
from c in context.CreateQuery("contact")
where c.GetAttributeValue<string>("adx_invitationcode") == invitationCode // MSBug #119992: No need for better string compare, since query provider won't interpret it anyway.
&& (c.GetAttributeValue<DateTime?>("adx_invitationcodeexpirydate") == null || c.GetAttributeValue<DateTime?>("adx_invitationcodeexpirydate") < now)
select c;
return findContact.FirstOrDefault();
}
public static IEnumerable<Entity> GetProductsBySubject(this OrganizationServiceContext context, Entity subject)
{
subject.AssertEntityName("subject");
var subjectID = subject.GetAttributeValue<Guid>("subjectid");
return context.GetProductsBySubject(subjectID);
}
public static IEnumerable<Entity> GetProductsBySubject(this OrganizationServiceContext context, Guid subjectID)
{
var findProducts =
from p in context.CreateQuery("product")
where p.GetAttributeValue<Guid?>("subjectid") == subjectID
select p;
return findProducts.ToList();
}
public static Money GetProductPriceByPriceListName(this OrganizationServiceContext context, Entity product, string priceListName)
{
product.AssertEntityName("product");
return context.GetProductPriceByPriceListName(product.GetAttributeValue<Guid>("productid"), priceListName);
}
public static Money GetProductPriceByPriceListName(this OrganizationServiceContext context, Guid productID, string priceListName)
{
var priceListItem = context.GetPriceListItemByPriceListName(productID, priceListName);
return priceListItem != null ? priceListItem.GetAttributeValue<Money>("amount") : null;
}
public static Entity GetPriceListItemByPriceListName(this OrganizationServiceContext context, Entity product, string priceListName)
{
product.AssertEntityName("product");
return context.GetPriceListItemByPriceListName(product.GetAttributeValue<Guid>("productid"), priceListName);
}
public static Entity GetPriceListItemByPriceListName(this OrganizationServiceContext context, Guid productID, string priceListName)
{
// Get price lists of the given name that are applicable to the current date/time
// MSBug #119992: No need for better string compare on price level name, since query provider won't interpret it anyway.
var webPriceLists =
from pl in context.CreateQuery("pricelevel").ToList()
where pl.GetAttributeValue<string>("name") == priceListName && pl.IsApplicableTo(DateTime.UtcNow)
select pl;
// Get the product price levels in our applicable price lists for our desired product
var priceListItems =
from ppl in context.CreateQuery("productpricelevel").ToList()
join pl in webPriceLists on ppl.GetAttributeValue<Guid?>("pricelevelid") equals pl.GetAttributeValue<Guid>("pricelevelid")
where ppl.GetAttributeValue<Guid?>("productid") == productID
select ppl;
return priceListItems.FirstOrDefault();
}
/// <summary>
/// Change the state of a case.
/// </summary>
/// <param name="context">The service context</param>
/// <param name="incident">The Case to change.</param>
/// <param name="state">The state to change to.</param>
/// <param name="resolutionSubject"></param>
/// <returns>The updated Case.</returns>
/// <remarks>
/// <para>The provided <paramref name="incident"/> must already be persisted to the CRM for this operation to succeed.</para>
/// <para>It it not necessary to SaveChanges after this operation--this operation fully persists the state change to CRM.</para>
/// </remarks>
public static Entity SetCaseStatusAndSave(this OrganizationServiceContext context, Entity incident, string state, string resolutionSubject)
{
incident.AssertEntityName("incident");
return SetCaseStatusAndSave(incident, state, resolutionSubject, context);
}
private static Entity SetCaseStatusAndSave(Entity incident, string state, string resolutionSubject, OrganizationServiceContext service)
{
var id = incident.Id;
if (string.Compare(state, "Active", StringComparison.InvariantCultureIgnoreCase) == 0)
{
service.SetState(0, -1, incident);
}
else if (string.Compare(state, "Resolved", StringComparison.InvariantCultureIgnoreCase) == 0)
{
var resolution = new Entity("incidentresolution");
resolution.SetAttributeValue("incidentid", incident.ToEntityReference());
resolution.SetAttributeValue("statuscode", new OptionSetValue(-1));
resolution.SetAttributeValue("subject", resolutionSubject);
service.CloseIncident(resolution, -1);
}
else // Canceled
{
service.SetState(2, -1, incident);
}
return service.CreateQuery("incident").First(i => i.GetAttributeValue<Guid?>("incidentid") == id);
}
/// <summary>
/// Change the state of an opportunity.
/// </summary>
/// <param name="context">The service context</param>
/// <param name="opportunity">The Opportunity to change.</param>
/// <param name="state">The state to change to.</param>
/// <param name="actualRevenue">The actual revenue of the opportunity.</param>
/// <returns>The updated Opportunity.</returns>
/// <remarks>
/// <para>The provided <paramref name="opportunity"/> must already be persisted to the CRM for this operation to succeed.</para>
/// <para>It it not necessary to SaveChanges after this operation--this operation fully persists the state change to CRM.</para>
/// </remarks>
public static void SetOpportunityStatusAndSave(this OrganizationServiceContext context, Entity opportunity, string state, decimal actualRevenue)
{
opportunity.AssertEntityName("opportunity");
if (string.Compare(state, "Open", StringComparison.InvariantCultureIgnoreCase) == 0)
{
context.SetState(0, -1, opportunity);
}
else if (string.Compare(state, "Won", StringComparison.InvariantCultureIgnoreCase) == 0)
{
var opportunityCloseId = Guid.NewGuid();
var closeOpportunity = new Entity("opportunityclose");
closeOpportunity.SetAttributeValue("opportunityid", opportunity.ToEntityReference());
closeOpportunity.SetAttributeValue("statuscode", new OptionSetValue(-1));
closeOpportunity.SetAttributeValue("actualrevenue", actualRevenue);
closeOpportunity.SetAttributeValue("subject", opportunity.GetAttributeValue("name"));
closeOpportunity.SetAttributeValue("actualend", DateTime.UtcNow.Floor(RoundTo.Day));
closeOpportunity.SetAttributeValue("activityid", opportunityCloseId);
context.WinOpportunity(closeOpportunity, -1);
}
else // Lost
{
var opportunityCloseId = Guid.NewGuid();
var closeOpportunity = new Entity("opportunityclose");
closeOpportunity.SetAttributeValue("opportunityid", opportunity.ToEntityReference());
closeOpportunity.SetAttributeValue("statuscode", new OptionSetValue(-1));
closeOpportunity.SetAttributeValue("actualrevenue", actualRevenue);
closeOpportunity.SetAttributeValue("subject", opportunity.GetAttributeValue("name"));
closeOpportunity.SetAttributeValue("actualend", DateTime.UtcNow.Floor(RoundTo.Day));
closeOpportunity.SetAttributeValue("activityid", opportunityCloseId);
context.LoseOpportunity(closeOpportunity, -1);
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Party.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using Microsoft.Xna.Framework.Content;
using RolePlayingGameData;
#endregion
namespace RolePlaying
{
/// <summary>
/// The group of players, under control of the user.
/// </summary>
public class Party
{
#region Party Members
private ContentManager content;
private ContentManager StaticContent;
/// <summary>
/// The ordered list of players in the party.
/// </summary>
/// <remarks>The first entry is the leader.</remarks>
private List<Player> players = new List<Player>();
/// <summary>
/// The ordered list of players in the party.
/// </summary>
/// <remarks>The first entry is the leader.</remarks>
[ContentSerializerIgnore]
public List<Player> Players
{
get { return players; }
set { players = value; }
}
/// <summary>
/// Add a new player to the party.
/// </summary>
/// <param name="player">The new player.</param>
/// <remarks>Instead of using the lists directly, this fixes all data.</remarks>
public void JoinParty(Player player)
{
// check the parameter
if (player == null)
{
throw new ArgumentNullException("player");
}
if (players.Contains(player))
{
throw new ArgumentException("The player was already in the party.");
}
Player staticInstance = StaticContent.Load<Player>(player.AssetName);
staticInstance.CharacterLevel = player.CharacterLevel;
staticInstance.Experience = player.Experience;
staticInstance.EquippedEquipment.Clear();
foreach (Equipment equipment in player.EquippedEquipment)
{
staticInstance.Equip(StaticContent.Load<Equipment>(equipment.AssetName));
}
staticInstance.StatisticsModifiers = player.StatisticsModifiers;
// add the new player to the list
players.Add(staticInstance);
// add the initial gold
partyGold += staticInstance.Gold;
// only as NPCs are players allowed to have their own gold
staticInstance.Gold = 0;
// add the player's inventory items
foreach (ContentEntry<Gear> contentEntry in staticInstance.Inventory)
{
AddToInventory(contentEntry.Content, contentEntry.Count);
}
// only as NPCs are players allowed to have their own non-equipped gear
staticInstance.Inventory.Clear();
}
/// <summary>
/// Gives the experience amount specified to all party members.
/// </summary>
public void GiveExperience(int experience)
{
// check the parameters
if (experience < 0)
{
throw new ArgumentOutOfRangeException("experience");
}
else if (experience == 0)
{
return;
}
List<Player> leveledUpPlayers = null;
foreach (Player player in players)
{
int oldLevel = player.CharacterLevel;
player.Experience += experience;
if (player.CharacterLevel > oldLevel)
{
if (leveledUpPlayers == null)
{
leveledUpPlayers = new List<Player>();
}
leveledUpPlayers.Add(player);
}
}
if ((leveledUpPlayers != null) && (leveledUpPlayers.Count > 0))
{
Session.ScreenManager.AddScreen(new LevelUpScreen(leveledUpPlayers));
}
}
#endregion
#region Inventory
/// <summary>
/// The items held by the party.
/// </summary>
private List<ContentEntry<Gear>> inventory = new List<ContentEntry<Gear>>();
/// <summary>
/// The items held by the party.
/// </summary>
[ContentSerializerIgnore]
public ReadOnlyCollection<ContentEntry<Gear>> Inventory
{
get { return inventory.AsReadOnly(); }
}
/// <summary>
/// Add the given gear, in the given quantity, to the party's inventory.
/// </summary>
public void AddToInventory(Gear gear, int count)
{
// check the parameters
if ((gear == null) || (count <= 0))
{
return;
}
var staticInstnace = StaticContent.Load<Gear>(gear.AssetName);
// search for an existing entry
ContentEntry<Gear> existingEntry = inventory.Find(
delegate(ContentEntry<Gear> entry)
{
return (entry.Content == gear);
});
// increment the existing entry, if any
if (existingEntry != null)
{
existingEntry.Count += count;
return;
}
// no existing entry - create a new entry
ContentEntry<Gear> newEntry = new ContentEntry<Gear>();
newEntry.Content = staticInstnace;
newEntry.Count = count;
newEntry.ContentName = gear.AssetName;
if (newEntry.ContentName.StartsWith(@"Gear\"))
{
newEntry.ContentName = newEntry.ContentName.Substring(5);
}
inventory.Add(newEntry);
}
/// <summary>
/// Remove the given quantity of the given gear from the party's inventory.
/// </summary>
/// <returns>True if the quantity specified could be removed.</returns>
public bool RemoveFromInventory(Gear gear, int count)
{
// check the parameters
if (gear == null)
{
throw new ArgumentNullException("gear");
}
if (count <= 0)
{
throw new ArgumentOutOfRangeException("count");
}
// search for an existing entry
ContentEntry<Gear> existingEntry = inventory.Find(
delegate(ContentEntry<Gear> entry)
{
return (entry.Content == gear);
});
// no existing entry, so this is moot
if (existingEntry == null)
{
return false;
}
// decrement the existing entry
existingEntry.Count -= count;
bool fullRemoval = (existingEntry.Count >= 0);
// if the entry is empty, then remove it
if (existingEntry.Count <= 0)
{
inventory.Remove(existingEntry);
}
return fullRemoval;
}
/// <summary>
/// The gold held by the party.
/// </summary>
private int partyGold;
/// <summary>
/// The gold held by the party.
/// </summary>
[ContentSerializer(Optional = true)]
public int PartyGold
{
get { return partyGold; }
set { partyGold = value; }
}
#endregion
#region Quest Data
/// <summary>
/// The name and kill-count of monsters killed in the active quest.
/// </summary>
/// <remarks>
/// Used to determine if the requirements for the active quest have been met.
/// </remarks>
private Dictionary<string, int> monsterKills = new Dictionary<string, int>();
/// <summary>
/// The name and kill-count of monsters killed in the active quest.
/// </summary>
/// <remarks>
/// Used to determine if the requirements for the active quest have been met.
/// </remarks>
public Dictionary<string, int> MonsterKills
{
get { return monsterKills; }
}
/// <summary>
/// Add a new monster-kill to the party's records.
/// </summary>
public void AddMonsterKill(Monster monster)
{
if (monsterKills.ContainsKey(monster.AssetName))
{
monsterKills[monster.AssetName]++;
}
else
{
monsterKills.Add(monster.AssetName, 1);
}
}
#endregion
#region Initialization
/// <summary>
/// Creates a new Party object from the game-start description.
/// </summary>
public Party(GameStartDescription gameStartDescription,
ContentManager contentManager,ContentManager staticContent)
{
// check the parameters
if (gameStartDescription == null)
{
throw new ArgumentNullException("gameStartDescription");
}
if (contentManager == null)
{
throw new ArgumentNullException("contentManager");
}
content = contentManager;
StaticContent = staticContent;
// load the players
foreach (string contentName in gameStartDescription.PlayerContentNames)
{
contentManager.Load<Player>(Path.Combine(@"Characters\Players", contentName));
JoinParty(StaticContent.Load<Player>(
Path.Combine(@"Characters\Players", contentName)).Clone() as Player);
}
}
/// <summary>
/// Create a new Party object from serialized party data.
/// </summary>
public Party(PartySaveData partyData, ContentManager contentManager,ContentManager staticContent)
{
// check the parameters
if (partyData == null)
{
throw new ArgumentNullException("partyData");
}
if (contentManager == null)
{
throw new ArgumentNullException("contentManager");
}
content = contentManager;
StaticContent = staticContent;
// load the players
foreach (PlayerSaveData playerData in partyData.players)
{
Player player =
contentManager.Load<Player>(playerData.assetName).Clone() as Player;
player.CharacterLevel = playerData.characterLevel;
player.Experience = playerData.experience;
player.EquippedEquipment.Clear();
foreach (string equipmentAssetName in playerData.equipmentAssetNames)
{
player.Equip(contentManager.Load<Equipment>(equipmentAssetName));
}
player.StatisticsModifiers = playerData.statisticsModifiers;
JoinParty(player);
}
// load the party inventory
inventory.Clear();
inventory.AddRange(partyData.inventory);
foreach (ContentEntry<Gear> entry in inventory)
{
entry.Content = contentManager.Load<Gear>(
Path.Combine(@"Gear", entry.ContentName));
}
// set the party gold
partyGold = partyData.partyGold;
// load the monster kills
for (int i = 0; i < partyData.monsterKillNames.Count; i++)
{
monsterKills.Add(partyData.monsterKillNames[i],
partyData.monsterKillCounts[i]);
}
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System;
public class control : MonoBehaviour
{
public static float AD;
public static float ADD;
public static float AR;
public static float BD;
public static float BDD;
public static float BR;
public static float CD;
public static float CDD;
float control_speed = 4f;
int control_speed2 = 20;
public static float CR;
public float[] curve_points = new float[300];
public GUITexture curve_show;
public Texture2D curve_text;
public static float DD;
public static float DDD;
public static float DR;
private bool enable_curve;
private float g = 9.8f;
public GUISkin gskin;
private float H_SENSOR;
private float H_TARGET = 20f;
private int ic;
float K = 0.1f;
float k_d_h = 0.5f;
float k_d_r = 1f;
float k_i_h = 0.1f;
float k_i_r;
float k_p_h = 0.15f;
float k_p_r = 0.1f;
public Texture2D logo;
private float M = 2f;
float max_power = 70f;
private PID pid = new PID(0f, 0f, 0f);
private PID pid2 = new PID(0f, 0f, 0f);
private PID pid3 = new PID(0f, 0f, 0f);
public static float power = 25f;
public Texture2D Q_text;
public static float stable_power;
private bool start;
private float T;
private float tf_1;
private float tf_2;
private float tf_3;
private float XR_SENSOR;
private float YR_SENSOR;
private float ZR_SENSOR;
void Start()
{
Color[] colors = new Color[0x8ca0];
for (int i = 0; i < colors.Length; i++)
{
colors[i].a = 0.6f;
}
this.curve_text.SetPixels(colors);
this.curve_text.Apply();
}
void stable()
{
this.pid.updata_k(3,0, 0);
//this.pid2.updata_k(this.k_p_r, 0, 0);
//this.pid3.updata_k(this.k_p_r, 0, 0);
float num = this.pid.Update(this.H_TARGET, this.H_SENSOR, Time.deltaTime);
print("error : " + num);
if (power < 20f)
{
power = 20f;
}
if (power > 30f)
{
power = 30f;
}
power = 28.5f + num / 10;
// float num2 = this.pid2.Update(0f, this.XR_SENSOR, Time.deltaTime);
// float num3 = this.pid3.Update(0f, this.ZR_SENSOR, Time.deltaTime);
//AD = -num2 / 30f;
//CD = num2 / 30f;
//BD = num3 / 30f;
//DD = -num3 / 30f;
}
// Update is called once per frame
void OnTriggerEnter(Collider other)
{
}
Vector3 last_position = Vector3.zero;
void Update()
{
if (Input.GetKey(KeyCode.JoystickButton4) || Input.GetKey(KeyCode.Z))
{
BR = this.control_speed2;
DR = -this.control_speed2;
AR = -10f;
CR = 10f;
}
else if (Input.GetKey(KeyCode.JoystickButton5) || Input.GetKey(KeyCode.C))
{
AR = -this.control_speed2;
CR = this.control_speed2;
BR = 10f;
DR = -10f;
}
else
{
AR = 0f;
BR = 0f;
CR = 0f;
DR = 0f;
}
ADD = this.control_speed * -Input.GetAxis("Vertical");
CDD = this.control_speed * Input.GetAxis("Vertical");
BDD = this.control_speed * -Input.GetAxis("Horizontal");
DDD = this.control_speed * Input.GetAxis("Horizontal");
if (((Input.GetAxis("Vertical") <= 0.1f) && (Input.GetAxis("Vertical") >= -0.1f)) && ((Input.GetAxis("Horizontal") <= 0.1f) && (Input.GetAxis("Horizontal") >= -0.1f)))
{
ADD = 0f;
BDD = 0f;
CDD = 0f;
DDD = 0f;
}
if (Input.GetKey(KeyCode.N))
{
this.H_TARGET += Time.deltaTime * 20f;
}
if (Input.GetKey(KeyCode.M))
{
this.H_TARGET -= Time.deltaTime * 20f;
}
this.H_TARGET = (float)Math.Round((double)this.H_TARGET, 2);
if (this.H_TARGET < 0f)
{
this.H_TARGET = 0f;
}
if (this.H_TARGET > 50f)
{
this.H_TARGET = 50f;
}
if (power < 0f)
{
power = 0f;
}
if (power > this.max_power)
{
power = this.max_power;
}
if (Input.GetKeyDown(KeyCode.Joystick1Button6) || Input.GetKeyDown(KeyCode.E))
{
Application.LoadLevel(0);
}
if (Input.GetKeyDown(KeyCode.Joystick1Button2) || Input.GetKeyDown(KeyCode.P))
{
this.start = true;
}
if (this.start)
{
this.stable();
}
}
void OnGUI()
{
GUI.matrix = Matrix4x4.TRS(new Vector3(0f, 0f, 0f), Quaternion.identity, new Vector3(((float)Screen.width) / 1024f, ((float)Screen.height) / 768f, 1f));
GUI.skin = this.gskin;
GUI.Label(new Rect(10f, 10f, 200f, 100f), "Total power :" + power.ToString());
this.H_SENSOR = base.transform.position.y - 13.64f;
this.H_SENSOR = (float)Math.Round((double)this.H_SENSOR, 2);
this.ZR_SENSOR = (float)Math.Round((double)base.transform.rotation.eulerAngles.z, 2);
this.YR_SENSOR = (float)Math.Round((double)base.transform.rotation.eulerAngles.y, 2);
this.XR_SENSOR = (float)Math.Round((double)base.transform.rotation.eulerAngles.x, 2);
if ((this.XR_SENSOR > 180f) && (this.XR_SENSOR <= 360f))
{
this.XR_SENSOR -= 360f;
}
if ((this.ZR_SENSOR > 180f) && (this.ZR_SENSOR <= 360f))
{
this.ZR_SENSOR -= 360f;
}
if ((this.YR_SENSOR > 180f) && (this.YR_SENSOR <= 360f))
{
this.YR_SENSOR -= 360f;
}
GUI.Label(new Rect(10f, 40f, 2000f, 100f), "[" + this.XR_SENSOR.ToString() + " , " + this.YR_SENSOR.ToString() + " , " + this.ZR_SENSOR.ToString() + "]");
GUI.Label(new Rect(10f, 70f, 2000f, 100f), "[" + this.H_SENSOR.ToString() + "][" + this.H_TARGET.ToString() + "]");
GUI.DrawTexture(new Rect(944f, 688f, 80f, 80f), this.logo);
if (this.enable_curve)
{
GUI.DrawTexture(new Rect(0f, 678f, 225f, 90f), this.curve_text);
}
Matrix4x4 matrix = GUI.matrix;
Vector2 pivotPoint = new Vector2(962f, 62f);
GUIUtility.RotateAroundPivot(this.YR_SENSOR, pivotPoint);
GUI.matrix = matrix;
}
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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 SCG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// A utility class with functions for sorting arrays with respect to an IComparer<T>
/// </summary>
public class Sorting
{
Sorting() { }
/// <summary>
/// Sort part of array in place using IntroSort
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">If the <code>start</code>
/// and <code>count</code> arguments does not describe a valid range.</exception>
/// <param name="array">Array to sort</param>
/// <param name="start">Index of first position to sort</param>
/// <param name="count">Number of elements to sort</param>
/// <param name="comparer">IComparer<T> to sort by</param>
public static void IntroSort<T>(T[] array, int start, int count, SCG.IComparer<T> comparer)
{
if (start < 0 || count < 0 || start + count > array.Length)
throw new ArgumentOutOfRangeException();
new Sorter<T>(array, comparer).IntroSort(start, start + count);
}
/// <summary>
/// Sort an array in place using IntroSort and default comparer
/// </summary>
/// <exception cref="NotComparableException">If T is not comparable</exception>
/// <param name="array">Array to sort</param>
public static void IntroSort<T>(T[] array)
{
new Sorter<T>(array, Comparer<T>.Default).IntroSort(0, array.Length);
}
/// <summary>
/// Sort part of array in place using Insertion Sort
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">If the <code>start</code>
/// and <code>count</code> arguments does not describe a valid range.</exception>
/// <param name="array">Array to sort</param>
/// <param name="start">Index of first position to sort</param>
/// <param name="count">Number of elements to sort</param>
/// <param name="comparer">IComparer<T> to sort by</param>
public static void InsertionSort<T>(T[] array, int start, int count, SCG.IComparer<T> comparer)
{
if (start < 0 || count < 0 || start + count > array.Length)
throw new ArgumentOutOfRangeException();
new Sorter<T>(array, comparer).InsertionSort(start, start + count);
}
/// <summary>
/// Sort part of array in place using Heap Sort
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">If the <code>start</code>
/// and <code>count</code> arguments does not describe a valid range.</exception>
/// <param name="array">Array to sort</param>
/// <param name="start">Index of first position to sort</param>
/// <param name="count">Number of elements to sort</param>
/// <param name="comparer">IComparer<T> to sort by</param>
public static void HeapSort<T>(T[] array, int start, int count, SCG.IComparer<T> comparer)
{
if (start < 0 || count < 0 || start + count > array.Length)
throw new ArgumentOutOfRangeException();
new Sorter<T>(array, comparer).HeapSort(start, start + count);
}
class Sorter<T>
{
T[] a;
SCG.IComparer<T> c;
internal Sorter(T[] a, SCG.IComparer<T> c) { this.a = a; this.c = c; }
internal void IntroSort(int f, int b)
{
if (b - f > 31)
{
int depth_limit = (int)Math.Floor(2.5 * Math.Log(b - f, 2));
introSort(f, b, depth_limit);
}
else
InsertionSort(f, b);
}
private void introSort(int f, int b, int depth_limit)
{
const int size_threshold = 14;//24;
if (depth_limit-- == 0)
HeapSort(f, b);
else if (b - f <= size_threshold)
InsertionSort(f, b);
else
{
int p = partition(f, b);
introSort(f, p, depth_limit);
introSort(p, b, depth_limit);
}
}
private int compare(T i1, T i2) { return c.Compare(i1, i2); }
private int partition(int f, int b)
{
int bot = f, mid = (b + f) / 2, top = b - 1;
T abot = a[bot], amid = a[mid], atop = a[top];
if (compare(abot, amid) < 0)
{
if (compare(atop, abot) < 0)//atop<abot<amid
{ a[top] = amid; amid = a[mid] = abot; a[bot] = atop; }
else if (compare(atop, amid) < 0) //abot<=atop<amid
{ a[top] = amid; amid = a[mid] = atop; }
//else abot<amid<=atop
}
else
{
if (compare(amid, atop) > 0) //atop<amid<=abot
{ a[bot] = atop; a[top] = abot; }
else if (compare(abot, atop) > 0) //amid<=atop<abot
{ a[bot] = amid; amid = a[mid] = atop; a[top] = abot; }
else //amid<=abot<=atop
{ a[bot] = amid; amid = a[mid] = abot; }
}
int i = bot, j = top;
while (true)
{
while (compare(a[++i], amid) < 0) ;
while (compare(amid, a[--j]) < 0) ;
if (i < j)
{
T tmp = a[i]; a[i] = a[j]; a[j] = tmp;
}
else
return i;
}
}
internal void InsertionSort(int f, int b)
{
for (int j = f + 1; j < b; j++)
{
T key = a[j], other;
int i = j - 1;
if (c.Compare(other = a[i], key) > 0)
{
a[j] = other;
while (i > f && c.Compare(other = a[i - 1], key) > 0) { a[i--] = other; }
a[i] = key;
}
}
}
internal void HeapSort(int f, int b)
{
for (int i = (b + f) / 2; i >= f; i--) heapify(f, b, i);
for (int i = b - 1; i > f; i--)
{
T tmp = a[f]; a[f] = a[i]; a[i] = tmp;
heapify(f, i, f);
}
}
private void heapify(int f, int b, int i)
{
T pv = a[i], lv, rv, max = pv;
int j = i, maxpt = j;
while (true)
{
int l = 2 * j - f + 1, r = l + 1;
if (l < b && compare(lv = a[l], max) > 0) { maxpt = l; max = lv; }
if (r < b && compare(rv = a[r], max) > 0) { maxpt = r; max = rv; }
if (maxpt == j)
break;
a[j] = max;
max = pv;
j = maxpt;
}
if (j > i)
a[j] = pv;
}
}
}
}
| |
// 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.Net.Sockets;
using System.Runtime.CompilerServices;
namespace System.Net
{
/// <devdoc>
/// <para>
/// Provides an Internet Protocol (IP) address.
/// </para>
/// </devdoc>
public class IPAddress
{
public static readonly IPAddress Any = new IPAddress(0x0000000000000000);
public static readonly IPAddress Loopback = new IPAddress(0x000000000100007F);
public static readonly IPAddress Broadcast = new IPAddress(0x00000000FFFFFFFF);
public static readonly IPAddress None = Broadcast;
internal const long LoopbackMask = 0x00000000000000FF;
public static readonly IPAddress IPv6Any = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0);
public static readonly IPAddress IPv6Loopback = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, 0);
public static readonly IPAddress IPv6None = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0);
/// <summary>
/// For IPv4 addresses, this field stores the Address.
/// For IPv6 addresses, this field stores the ScopeId.
/// Instead of accessing this field directly, use the <see cref="PrivateAddress"/> or <see cref="PrivateScopeId"/> properties.
/// </summary>
private uint _addressOrScopeId;
/// <summary>
/// This field is only used for IPv6 addresses. A null value indicates that this instance is an IPv4 address.
/// </summary>
private readonly ushort[] _numbers;
/// <summary>
/// A lazily initialized cache of the result of calling <see cref="ToString"/>.
/// </summary>
private string _toString;
/// <summary>
/// A lazily initialized cache of the <see cref="GetHashCode"/> value.
/// </summary>
private int _hashCode;
// Maximum length of address literals (potentially including a port number)
// generated by any address-to-string conversion routine. This length can
// be used when declaring buffers used with getnameinfo, WSAAddressToString,
// inet_ntoa, etc. We just provide one define, rather than one per api,
// to avoid confusion.
//
// The totals are derived from the following data:
// 15: IPv4 address
// 45: IPv6 address including embedded IPv4 address
// 11: Scope Id
// 2: Brackets around IPv6 address when port is present
// 6: Port (including colon)
// 1: Terminating null byte
internal const int NumberOfLabels = IPAddressParserStatics.IPv6AddressBytes / 2;
private bool IsIPv4
{
get { return _numbers == null; }
}
private bool IsIPv6
{
get { return _numbers != null; }
}
private uint PrivateAddress
{
get
{
Debug.Assert(IsIPv4);
return _addressOrScopeId;
}
set
{
Debug.Assert(IsIPv4);
_toString = null;
_hashCode = 0;
_addressOrScopeId = value;
}
}
private uint PrivateScopeId
{
get
{
Debug.Assert(IsIPv6);
return _addressOrScopeId;
}
set
{
Debug.Assert(IsIPv6);
_toString = null;
_hashCode = 0;
_addressOrScopeId = value;
}
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Net.IPAddress'/>
/// class with the specified address.
/// </para>
/// </devdoc>
public IPAddress(long newAddress)
{
if (newAddress < 0 || newAddress > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(newAddress));
}
PrivateAddress = (uint)newAddress;
}
/// <devdoc>
/// <para>
/// Constructor for an IPv6 Address with a specified Scope.
/// </para>
/// </devdoc>
public IPAddress(byte[] address, long scopeid) :
this(new ReadOnlySpan<byte>(address ?? ThrowAddressNullException()), scopeid)
{
}
public IPAddress(ReadOnlySpan<byte> address, long scopeid)
{
if (address.Length != IPAddressParserStatics.IPv6AddressBytes)
{
throw new ArgumentException(SR.dns_bad_ip_address, nameof(address));
}
// Consider: Since scope is only valid for link-local and site-local
// addresses we could implement some more robust checking here
if (scopeid < 0 || scopeid > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(scopeid));
}
_numbers = new ushort[NumberOfLabels];
for (int i = 0; i < NumberOfLabels; i++)
{
_numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]);
}
PrivateScopeId = (uint)scopeid;
}
internal unsafe IPAddress(ushort* numbers, int numbersLength, uint scopeid)
{
Debug.Assert(numbers != null);
Debug.Assert(numbersLength == NumberOfLabels);
var arr = new ushort[NumberOfLabels];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = numbers[i];
}
_numbers = arr;
PrivateScopeId = scopeid;
}
private IPAddress(ushort[] numbers, uint scopeid)
{
Debug.Assert(numbers != null);
Debug.Assert(numbers.Length == NumberOfLabels);
_numbers = numbers;
PrivateScopeId = scopeid;
}
/// <devdoc>
/// <para>
/// Constructor for IPv4 and IPv6 Address.
/// </para>
/// </devdoc>
public IPAddress(byte[] address) :
this(new ReadOnlySpan<byte>(address ?? ThrowAddressNullException()))
{
}
public IPAddress(ReadOnlySpan<byte> address)
{
if (address.Length == IPAddressParserStatics.IPv4AddressBytes)
{
PrivateAddress = (uint)((address[3] << 24 | address[2] << 16 | address[1] << 8 | address[0]) & 0x0FFFFFFFF);
}
else if (address.Length == IPAddressParserStatics.IPv6AddressBytes)
{
_numbers = new ushort[NumberOfLabels];
for (int i = 0; i < NumberOfLabels; i++)
{
_numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]);
}
}
else
{
throw new ArgumentException(SR.dns_bad_ip_address, nameof(address));
}
}
// We need this internally since we need to interface with winsock,
// and winsock only understands Int32.
internal IPAddress(int newAddress)
{
PrivateAddress = (uint)newAddress;
}
/// <devdoc>
/// <para>
/// Converts an IP address string to an <see cref='System.Net.IPAddress'/> instance.
/// </para>
/// </devdoc>
public static bool TryParse(string ipString, out IPAddress address)
{
if (ipString == null)
{
address = null;
return false;
}
address = IPAddressParser.Parse(ipString.AsReadOnlySpan(), tryParse: true);
return (address != null);
}
public static bool TryParse(ReadOnlySpan<char> ipSpan, out IPAddress address)
{
address = IPAddressParser.Parse(ipSpan, tryParse: true);
return (address != null);
}
public static IPAddress Parse(string ipString)
{
if (ipString == null)
{
throw new ArgumentNullException(nameof(ipString));
}
return IPAddressParser.Parse(ipString.AsReadOnlySpan(), tryParse: false);
}
public static IPAddress Parse(ReadOnlySpan<char> ipSpan)
{
return IPAddressParser.Parse(ipSpan, tryParse: false);
}
public bool TryWriteBytes(Span<byte> destination, out int bytesWritten)
{
if (IsIPv6)
{
if (destination.Length < IPAddressParserStatics.IPv6AddressBytes)
{
bytesWritten = 0;
return false;
}
WriteIPv6Bytes(destination);
bytesWritten = IPAddressParserStatics.IPv6AddressBytes;
}
else
{
if (destination.Length < IPAddressParserStatics.IPv4AddressBytes)
{
bytesWritten = 0;
return false;
}
WriteIPv4Bytes(destination);
bytesWritten = IPAddressParserStatics.IPv4AddressBytes;
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteIPv6Bytes(Span<byte> destination)
{
Debug.Assert(_numbers != null && _numbers.Length == NumberOfLabels);
int j = 0;
for (int i = 0; i < NumberOfLabels; i++)
{
destination[j++] = (byte)((_numbers[i] >> 8) & 0xFF);
destination[j++] = (byte)((_numbers[i]) & 0xFF);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteIPv4Bytes(Span<byte> destination)
{
uint address = PrivateAddress;
destination[0] = (byte)(address);
destination[1] = (byte)(address >> 8);
destination[2] = (byte)(address >> 16);
destination[3] = (byte)(address >> 24);
}
/// <devdoc>
/// <para>
/// Provides a copy of the IPAddress internals as an array of bytes.
/// </para>
/// </devdoc>
public byte[] GetAddressBytes()
{
if (IsIPv6)
{
Debug.Assert(_numbers != null && _numbers.Length == NumberOfLabels);
byte[] bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
WriteIPv6Bytes(bytes);
return bytes;
}
else
{
byte[] bytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
WriteIPv4Bytes(bytes);
return bytes;
}
}
public AddressFamily AddressFamily
{
get
{
return IsIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6;
}
}
/// <devdoc>
/// <para>
/// IPv6 Scope identifier. This is really a uint32, but that isn't CLS compliant
/// </para>
/// </devdoc>
public long ScopeId
{
get
{
// Not valid for IPv4 addresses
if (IsIPv4)
{
throw new SocketException(SocketError.OperationNotSupported);
}
return PrivateScopeId;
}
set
{
// Not valid for IPv4 addresses
if (IsIPv4)
{
throw new SocketException(SocketError.OperationNotSupported);
}
// Consider: Since scope is only valid for link-local and site-local
// addresses we could implement some more robust checking here
if (value < 0 || value > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
PrivateScopeId = (uint)value;
}
}
/// <devdoc>
/// <para>
/// Converts the Internet address to either standard dotted quad format
/// or standard IPv6 representation.
/// </para>
/// </devdoc>
public override string ToString()
{
if (_toString == null)
{
_toString = IsIPv4 ?
IPAddressParser.IPv4AddressToString(PrivateAddress) :
IPAddressParser.IPv6AddressToString(_numbers, PrivateScopeId);
}
return _toString;
}
public bool TryFormat(Span<char> destination, out int charsWritten)
{
return IsIPv4 ?
IPAddressParser.IPv4AddressToString(PrivateAddress, destination, out charsWritten) :
IPAddressParser.IPv6AddressToString(_numbers, PrivateScopeId, destination, out charsWritten);
}
public static long HostToNetworkOrder(long host)
{
#if BIGENDIAN
return host;
#else
ulong value = (ulong)host;
value = (value << 32) | (value >> 32);
value = (value & 0x0000FFFF0000FFFF) << 16 | (value & 0xFFFF0000FFFF0000) >> 16;
value = (value & 0x00FF00FF00FF00FF) << 8 | (value & 0xFF00FF00FF00FF00) >> 8;
return (long)value;
#endif
}
public static int HostToNetworkOrder(int host)
{
#if BIGENDIAN
return host;
#else
uint value = (uint)host;
value = (value << 16) | (value >> 16);
value = (value & 0x00FF00FF) << 8 | (value & 0xFF00FF00) >> 8;
return (int)value;
#endif
}
public static short HostToNetworkOrder(short host)
{
#if BIGENDIAN
return host;
#else
return unchecked((short)((((int)host & 0xFF) << 8) | (int)((host >> 8) & 0xFF)));
#endif
}
public static long NetworkToHostOrder(long network)
{
return HostToNetworkOrder(network);
}
public static int NetworkToHostOrder(int network)
{
return HostToNetworkOrder(network);
}
public static short NetworkToHostOrder(short network)
{
return HostToNetworkOrder(network);
}
public static bool IsLoopback(IPAddress address)
{
if (address == null)
{
ThrowAddressNullException();
}
if (address.IsIPv6)
{
// Do Equals test for IPv6 addresses
return address.Equals(IPv6Loopback);
}
else
{
return ((address.PrivateAddress & LoopbackMask) == (Loopback.PrivateAddress & LoopbackMask));
}
}
/// <devdoc>
/// <para>
/// Determines if an address is an IPv6 Multicast address
/// </para>
/// </devdoc>
public bool IsIPv6Multicast
{
get
{
return IsIPv6 && ((_numbers[0] & 0xFF00) == 0xFF00);
}
}
/// <devdoc>
/// <para>
/// Determines if an address is an IPv6 Link Local address
/// </para>
/// </devdoc>
public bool IsIPv6LinkLocal
{
get
{
return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFE80);
}
}
/// <devdoc>
/// <para>
/// Determines if an address is an IPv6 Site Local address
/// </para>
/// </devdoc>
public bool IsIPv6SiteLocal
{
get
{
return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFEC0);
}
}
public bool IsIPv6Teredo
{
get
{
return IsIPv6 &&
(_numbers[0] == 0x2001) &&
(_numbers[1] == 0);
}
}
// 0:0:0:0:0:FFFF:x.x.x.x
public bool IsIPv4MappedToIPv6
{
get
{
if (IsIPv4)
{
return false;
}
for (int i = 0; i < 5; i++)
{
if (_numbers[i] != 0)
{
return false;
}
}
return (_numbers[5] == 0xFFFF);
}
}
[Obsolete("This property has been deprecated. It is address family dependent. Please use IPAddress.Equals method to perform comparisons. http://go.microsoft.com/fwlink/?linkid=14202")]
public long Address
{
get
{
//
// IPv6 Changes: Can't do this for IPv6, so throw an exception.
//
//
if (AddressFamily == AddressFamily.InterNetworkV6)
{
throw new SocketException(SocketError.OperationNotSupported);
}
else
{
return PrivateAddress;
}
}
set
{
//
// IPv6 Changes: Can't do this for IPv6 addresses
if (AddressFamily == AddressFamily.InterNetworkV6)
{
throw new SocketException(SocketError.OperationNotSupported);
}
else
{
if (PrivateAddress != value)
{
PrivateAddress = unchecked((uint)value);
}
}
}
}
internal bool Equals(object comparandObj, bool compareScopeId)
{
IPAddress comparand = comparandObj as IPAddress;
if (comparand == null)
{
return false;
}
// Compare families before address representations
if (AddressFamily != comparand.AddressFamily)
{
return false;
}
if (IsIPv6)
{
// For IPv6 addresses, we must compare the full 128-bit representation.
for (int i = 0; i < NumberOfLabels; i++)
{
if (comparand._numbers[i] != _numbers[i])
{
return false;
}
}
// The scope IDs must also match
return comparand.PrivateScopeId == PrivateScopeId || !compareScopeId;
}
else
{
// For IPv4 addresses, compare the integer representation.
return comparand.PrivateAddress == PrivateAddress;
}
}
/// <devdoc>
/// <para>
/// Compares two IP addresses.
/// </para>
/// </devdoc>
public override bool Equals(object comparand)
{
return Equals(comparand, true);
}
public override int GetHashCode()
{
if (_hashCode != 0)
{
return _hashCode;
}
// For IPv6 addresses, we calculate the hashcode by using Marvin
// on a stack-allocated array containing the Address bytes and ScopeId.
int hashCode;
if (IsIPv6)
{
const int addressAndScopeIdLength = IPAddressParserStatics.IPv6AddressBytes + sizeof(uint);
Span<byte> addressAndScopeIdSpan = stackalloc byte[addressAndScopeIdLength];
new ReadOnlySpan<ushort>(_numbers).AsBytes().CopyTo(addressAndScopeIdSpan);
Span<byte> scopeIdSpan = addressAndScopeIdSpan.Slice(IPAddressParserStatics.IPv6AddressBytes);
bool scopeWritten = BitConverter.TryWriteBytes(scopeIdSpan, _addressOrScopeId);
Debug.Assert(scopeWritten);
hashCode = Marvin.ComputeHash32(
ref addressAndScopeIdSpan[0],
addressAndScopeIdLength,
Marvin.DefaultSeed);
}
else
{
// For IPv4 addresses, we use Marvin on the integer representation of the Address.
hashCode = Marvin.ComputeHash32(
ref Unsafe.As<uint, byte>(ref _addressOrScopeId),
sizeof(uint),
Marvin.DefaultSeed);
}
_hashCode = hashCode;
return _hashCode;
}
// For security, we need to be able to take an IPAddress and make a copy that's immutable and not derived.
internal IPAddress Snapshot()
{
return IsIPv4 ?
new IPAddress(PrivateAddress) :
new IPAddress(_numbers, PrivateScopeId);
}
// IPv4 192.168.1.1 maps as ::FFFF:192.168.1.1
public IPAddress MapToIPv6()
{
if (IsIPv6)
{
return this;
}
uint address = PrivateAddress;
ushort[] labels = new ushort[NumberOfLabels];
labels[5] = 0xFFFF;
labels[6] = (ushort)(((address & 0x0000FF00) >> 8) | ((address & 0x000000FF) << 8));
labels[7] = (ushort)(((address & 0xFF000000) >> 24) | ((address & 0x00FF0000) >> 8));
return new IPAddress(labels, 0);
}
// Takes the last 4 bytes of an IPv6 address and converts it to an IPv4 address.
// This does not restrict to address with the ::FFFF: prefix because other types of
// addresses display the tail segments as IPv4 like Terado.
public IPAddress MapToIPv4()
{
if (IsIPv4)
{
return this;
}
// Cast the ushort values to a uint and mask with unsigned literal before bit shifting.
// Otherwise, we can end up getting a negative value for any IPv4 address that ends with
// a byte higher than 127 due to sign extension of the most significant 1 bit.
long address = ((((uint)_numbers[6] & 0x0000FF00u) >> 8) | (((uint)_numbers[6] & 0x000000FFu) << 8)) |
(((((uint)_numbers[7] & 0x0000FF00u) >> 8) | (((uint)_numbers[7] & 0x000000FFu) << 8)) << 16);
return new IPAddress(address);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static byte[] ThrowAddressNullException() => throw new ArgumentNullException("address");
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>AssetGroupSignal</c> resource.</summary>
public sealed partial class AssetGroupSignalName : gax::IResourceName, sys::IEquatable<AssetGroupSignalName>
{
/// <summary>The possible contents of <see cref="AssetGroupSignalName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/assetGroupSignals/{asset_group_id}~{criterion_id}</c>.
/// </summary>
CustomerAssetGroupCriterion = 1,
}
private static gax::PathTemplate s_customerAssetGroupCriterion = new gax::PathTemplate("customers/{customer_id}/assetGroupSignals/{asset_group_id_criterion_id}");
/// <summary>Creates a <see cref="AssetGroupSignalName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AssetGroupSignalName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AssetGroupSignalName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AssetGroupSignalName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AssetGroupSignalName"/> with the pattern
/// <c>customers/{customer_id}/assetGroupSignals/{asset_group_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AssetGroupSignalName"/> constructed from the provided ids.</returns>
public static AssetGroupSignalName FromCustomerAssetGroupCriterion(string customerId, string assetGroupId, string criterionId) =>
new AssetGroupSignalName(ResourceNameType.CustomerAssetGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), assetGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetGroupId, nameof(assetGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AssetGroupSignalName"/> with pattern
/// <c>customers/{customer_id}/assetGroupSignals/{asset_group_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AssetGroupSignalName"/> with pattern
/// <c>customers/{customer_id}/assetGroupSignals/{asset_group_id}~{criterion_id}</c>.
/// </returns>
public static string Format(string customerId, string assetGroupId, string criterionId) =>
FormatCustomerAssetGroupCriterion(customerId, assetGroupId, criterionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AssetGroupSignalName"/> with pattern
/// <c>customers/{customer_id}/assetGroupSignals/{asset_group_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AssetGroupSignalName"/> with pattern
/// <c>customers/{customer_id}/assetGroupSignals/{asset_group_id}~{criterion_id}</c>.
/// </returns>
public static string FormatCustomerAssetGroupCriterion(string customerId, string assetGroupId, string criterionId) =>
s_customerAssetGroupCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(assetGroupId, nameof(assetGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="AssetGroupSignalName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/assetGroupSignals/{asset_group_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="assetGroupSignalName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AssetGroupSignalName"/> if successful.</returns>
public static AssetGroupSignalName Parse(string assetGroupSignalName) => Parse(assetGroupSignalName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AssetGroupSignalName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/assetGroupSignals/{asset_group_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="assetGroupSignalName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AssetGroupSignalName"/> if successful.</returns>
public static AssetGroupSignalName Parse(string assetGroupSignalName, bool allowUnparsed) =>
TryParse(assetGroupSignalName, allowUnparsed, out AssetGroupSignalName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AssetGroupSignalName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/assetGroupSignals/{asset_group_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="assetGroupSignalName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AssetGroupSignalName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string assetGroupSignalName, out AssetGroupSignalName result) =>
TryParse(assetGroupSignalName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AssetGroupSignalName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/assetGroupSignals/{asset_group_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="assetGroupSignalName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AssetGroupSignalName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string assetGroupSignalName, bool allowUnparsed, out AssetGroupSignalName result)
{
gax::GaxPreconditions.CheckNotNull(assetGroupSignalName, nameof(assetGroupSignalName));
gax::TemplatedResourceName resourceName;
if (s_customerAssetGroupCriterion.TryParseName(assetGroupSignalName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerAssetGroupCriterion(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(assetGroupSignalName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private AssetGroupSignalName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string assetGroupId = null, string criterionId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AssetGroupId = assetGroupId;
CriterionId = criterionId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AssetGroupSignalName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/assetGroupSignals/{asset_group_id}~{criterion_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
public AssetGroupSignalName(string customerId, string assetGroupId, string criterionId) : this(ResourceNameType.CustomerAssetGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), assetGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetGroupId, nameof(assetGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AssetGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AssetGroupId { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerAssetGroupCriterion: return s_customerAssetGroupCriterion.Expand(CustomerId, $"{AssetGroupId}~{CriterionId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AssetGroupSignalName);
/// <inheritdoc/>
public bool Equals(AssetGroupSignalName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AssetGroupSignalName a, AssetGroupSignalName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AssetGroupSignalName a, AssetGroupSignalName b) => !(a == b);
}
public partial class AssetGroupSignal
{
/// <summary>
/// <see cref="AssetGroupSignalName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal AssetGroupSignalName ResourceNameAsAssetGroupSignalName
{
get => string.IsNullOrEmpty(ResourceName) ? null : AssetGroupSignalName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AssetGroupName"/>-typed view over the <see cref="AssetGroup"/> resource name property.
/// </summary>
internal AssetGroupName AssetGroupAsAssetGroupName
{
get => string.IsNullOrEmpty(AssetGroup) ? null : AssetGroupName.Parse(AssetGroup, allowUnparsed: true);
set => AssetGroup = value?.ToString() ?? "";
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Util.Automaton
{
/*
* 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>
/// Class to construct DFAs that match a word within some edit distance.
/// <para/>
/// Implements the algorithm described in:
/// Schulz and Mihov: Fast String Correction with Levenshtein Automata
/// <para/>
/// @lucene.experimental
/// </summary>
public class LevenshteinAutomata
{
/// <summary>
/// @lucene.internal </summary>
public const int MAXIMUM_SUPPORTED_DISTANCE = 2;
/* input word */
internal readonly int[] word;
/* the automata alphabet. */
internal readonly int[] alphabet;
/* the maximum symbol in the alphabet (e.g. 255 for UTF-8 or 10FFFF for UTF-32) */
internal readonly int alphaMax;
/* the ranges outside of alphabet */
internal readonly int[] rangeLower;
internal readonly int[] rangeUpper;
internal int numRanges = 0;
internal ParametricDescription[] descriptions;
/// <summary>
/// Create a new <see cref="LevenshteinAutomata"/> for some <paramref name="input"/> string.
/// Optionally count transpositions as a primitive edit.
/// </summary>
public LevenshteinAutomata(string input, bool withTranspositions)
: this(CodePoints(input), Character.MAX_CODE_POINT, withTranspositions)
{
}
/// <summary>
/// Expert: specify a custom maximum possible symbol
/// (alphaMax); default is <see cref="Character.MAX_CODE_POINT"/>.
/// </summary>
public LevenshteinAutomata(int[] word, int alphaMax, bool withTranspositions)
{
this.word = word;
this.alphaMax = alphaMax;
// calculate the alphabet
SortedSet<int> set = new SortedSet<int>();
for (int i = 0; i < word.Length; i++)
{
int v = word[i];
if (v > alphaMax)
{
throw new System.ArgumentException("alphaMax exceeded by symbol " + v + " in word");
}
set.Add(v);
}
alphabet = new int[set.Count];
IEnumerator<int> iterator = set.GetEnumerator();
for (int i = 0; i < alphabet.Length; i++)
{
iterator.MoveNext();
alphabet[i] = iterator.Current;
}
rangeLower = new int[alphabet.Length + 2];
rangeUpper = new int[alphabet.Length + 2];
// calculate the unicode range intervals that exclude the alphabet
// these are the ranges for all unicode characters not in the alphabet
int lower = 0;
for (int i = 0; i < alphabet.Length; i++)
{
int higher = alphabet[i];
if (higher > lower)
{
rangeLower[numRanges] = lower;
rangeUpper[numRanges] = higher - 1;
numRanges++;
}
lower = higher + 1;
}
/* add the final endpoint */
if (lower <= alphaMax)
{
rangeLower[numRanges] = lower;
rangeUpper[numRanges] = alphaMax;
numRanges++;
}
descriptions = new ParametricDescription[] {
null,
withTranspositions ? (ParametricDescription)new Lev1TParametricDescription(word.Length) : new Lev1ParametricDescription(word.Length),
withTranspositions ? (ParametricDescription)new Lev2TParametricDescription(word.Length) : new Lev2ParametricDescription(word.Length)
};
}
private static int[] CodePoints(string input)
{
int length = Character.CodePointCount(input, 0, input.Length);
int[] word = new int[length];
for (int i = 0, j = 0, cp = 0; i < input.Length; i += Character.CharCount(cp))
{
word[j++] = cp = Character.CodePointAt(input, i);
}
return word;
}
/// <summary>
/// Compute a DFA that accepts all strings within an edit distance of <paramref name="n"/>.
/// <para>
/// All automata have the following properties:
/// <list type="bullet">
/// <item><description>They are deterministic (DFA).</description></item>
/// <item><description>There are no transitions to dead states.</description></item>
/// <item><description>They are not minimal (some transitions could be combined).</description></item>
/// </list>
/// </para>
/// </summary>
public virtual Automaton ToAutomaton(int n)
{
if (n == 0)
{
return BasicAutomata.MakeString(word, 0, word.Length);
}
if (n >= descriptions.Length)
{
return null;
}
int range = 2 * n + 1;
ParametricDescription description = descriptions[n];
// the number of states is based on the length of the word and n
State[] states = new State[description.Count];
// create all states, and mark as accept states if appropriate
for (int i = 0; i < states.Length; i++)
{
states[i] = new State();
states[i].number = i;
states[i].Accept = description.IsAccept(i);
}
// create transitions from state to state
for (int k = 0; k < states.Length; k++)
{
int xpos = description.GetPosition(k);
if (xpos < 0)
{
continue;
}
int end = xpos + Math.Min(word.Length - xpos, range);
for (int x = 0; x < alphabet.Length; x++)
{
int ch = alphabet[x];
// get the characteristic vector at this position wrt ch
int cvec = GetVector(ch, xpos, end);
int dest = description.Transition(k, xpos, cvec);
if (dest >= 0)
{
states[k].AddTransition(new Transition(ch, states[dest]));
}
}
// add transitions for all other chars in unicode
// by definition, their characteristic vectors are always 0,
// because they do not exist in the input string.
int dest_ = description.Transition(k, xpos, 0); // by definition
if (dest_ >= 0)
{
for (int r = 0; r < numRanges; r++)
{
states[k].AddTransition(new Transition(rangeLower[r], rangeUpper[r], states[dest_]));
}
}
}
Automaton a = new Automaton(states[0]);
a.IsDeterministic = true;
// we create some useless unconnected states, and its a net-win overall to remove these,
// as well as to combine any adjacent transitions (it makes later algorithms more efficient).
// so, while we could set our numberedStates here, its actually best not to, and instead to
// force a traversal in reduce, pruning the unconnected states while we combine adjacent transitions.
//a.setNumberedStates(states);
a.Reduce();
// we need not trim transitions to dead states, as they are not created.
//a.restoreInvariant();
return a;
}
/// <summary>
/// Get the characteristic vector <c>X(x, V)</c>
/// where V is <c>Substring(pos, end - pos)</c>.
/// </summary>
internal virtual int GetVector(int x, int pos, int end)
{
int vector = 0;
for (int i = pos; i < end; i++)
{
vector <<= 1;
if (word[i] == x)
{
vector |= 1;
}
}
return vector;
}
/// <summary>
/// A <see cref="ParametricDescription"/> describes the structure of a Levenshtein DFA for some degree <c>n</c>.
/// <para/>
/// There are four components of a parametric description, all parameterized on the length
/// of the word <c>w</c>:
/// <list type="number">
/// <item><description>The number of states: <see cref="Count"/></description></item>
/// <item><description>The set of final states: <see cref="IsAccept(int)"/></description></item>
/// <item><description>The transition function: <see cref="Transition(int, int, int)"/></description></item>
/// <item><description>Minimal boundary function: <see cref="GetPosition(int)"/></description></item>
/// </list>
/// </summary>
internal abstract class ParametricDescription
{
protected readonly int m_w;
protected readonly int m_n;
private readonly int[] minErrors;
internal ParametricDescription(int w, int n, int[] minErrors)
{
this.m_w = w;
this.m_n = n;
this.minErrors = minErrors;
}
/// <summary>
/// Return the number of states needed to compute a Levenshtein DFA.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
internal virtual int Count
{
get { return minErrors.Length * (m_w + 1); }
}
/// <summary>
/// Returns <c>true</c> if the <c>state</c> in any Levenshtein DFA is an accept state (final state).
/// </summary>
internal virtual bool IsAccept(int absState)
{
// decode absState -> state, offset
int state = absState / (m_w + 1);
int offset = absState % (m_w + 1);
Debug.Assert(offset >= 0);
return m_w - offset + minErrors[state] <= m_n;
}
/// <summary>
/// Returns the position in the input word for a given <c>state</c>.
/// this is the minimal boundary for the state.
/// </summary>
internal virtual int GetPosition(int absState)
{
return absState % (m_w + 1);
}
/// <summary>
/// Returns the state number for a transition from the given <paramref name="state"/>,
/// assuming <paramref name="position"/> and characteristic vector <paramref name="vector"/>.
/// </summary>
internal abstract int Transition(int state, int position, int vector);
private static readonly long[] MASKS = new long[] {
0x1, 0x3, 0x7, 0xf,
0x1f, 0x3f, 0x7f, 0xff,
0x1ff, 0x3ff, 0x7ff, 0xfff,
0x1fff, 0x3fff, 0x7fff, 0xffff,
0x1ffff, 0x3ffff, 0x7ffff, 0xfffff,
0x1fffff, 0x3fffff, 0x7fffff, 0xffffff,
0x1ffffff, 0x3ffffff, 0x7ffffff, 0xfffffff,
0x1fffffff, 0x3fffffff, 0x7fffffffL, 0xffffffffL,
0x1ffffffffL, 0x3ffffffffL, 0x7ffffffffL, 0xfffffffffL,
0x1fffffffffL, 0x3fffffffffL, 0x7fffffffffL, 0xffffffffffL,
0x1ffffffffffL, 0x3ffffffffffL, 0x7ffffffffffL, 0xfffffffffffL,
0x1fffffffffffL, 0x3fffffffffffL, 0x7fffffffffffL, 0xffffffffffffL,
0x1ffffffffffffL, 0x3ffffffffffffL, 0x7ffffffffffffL, 0xfffffffffffffL,
0x1fffffffffffffL, 0x3fffffffffffffL, 0x7fffffffffffffL, 0xffffffffffffffL,
0x1ffffffffffffffL, 0x3ffffffffffffffL, 0x7ffffffffffffffL, 0xfffffffffffffffL,
0x1fffffffffffffffL, 0x3fffffffffffffffL, 0x7fffffffffffffffL
};
protected internal virtual int Unpack(long[] data, int index, int bitsPerValue)
{
long bitLoc = bitsPerValue * index;
int dataLoc = (int)(bitLoc >> 6);
int bitStart = (int)(bitLoc & 63);
if (bitStart + bitsPerValue <= 64)
{
// not split
return (int)((data[dataLoc] >> bitStart) & MASKS[bitsPerValue - 1]);
}
else
{
// split
int part = 64 - bitStart;
return (int)(((data[dataLoc] >> bitStart) & MASKS[part - 1]) + ((data[1 + dataLoc] & MASKS[bitsPerValue - part - 1]) << part));
}
}
}
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal sealed class SecTrustChainPal : IChainPal
{
private const X509ChainStatusFlags RevocationRelevantFlags =
X509ChainStatusFlags.RevocationStatusUnknown |
X509ChainStatusFlags.Revoked |
X509ChainStatusFlags.OfflineRevocation;
private static readonly SafeCreateHandle s_emptyArray = Interop.CoreFoundation.CFArrayCreate(Array.Empty<IntPtr>(), UIntPtr.Zero);
private Stack<SafeHandle> _extraHandles;
private SafeX509ChainHandle _chainHandle;
public X509ChainElement[] ChainElements { get; private set; }
public X509ChainStatus[] ChainStatus { get; private set; }
private DateTime _verificationTime;
private X509RevocationMode _revocationMode;
internal SecTrustChainPal()
{
_extraHandles = new Stack<SafeHandle>();
}
public SafeX509ChainHandle SafeHandle => null;
internal void OpenTrustHandle(
ICertificatePal leafCert,
X509Certificate2Collection extraStore,
X509RevocationMode revocationMode,
X509Certificate2Collection customTrustStore,
X509ChainTrustMode trustMode)
{
_revocationMode = revocationMode;
SafeCreateHandle policiesArray = PreparePoliciesArray(revocationMode != X509RevocationMode.NoCheck);
SafeCreateHandle certsArray = PrepareCertsArray(leafCert, extraStore, customTrustStore, trustMode);
int osStatus;
SafeX509ChainHandle chain;
int ret = Interop.AppleCrypto.AppleCryptoNative_X509ChainCreate(
certsArray,
policiesArray,
out chain,
out osStatus);
if (ret == 1)
{
if (trustMode == X509ChainTrustMode.CustomRootTrust)
{
SafeCreateHandle customCertsArray = s_emptyArray;
if (customTrustStore != null && customTrustStore.Count > 0)
{
customCertsArray = PrepareCustomCertsArray(customTrustStore);
}
try
{
int error = Interop.AppleCrypto.X509ChainSetTrustAnchorCertificates(chain, customCertsArray);
if (error != 0)
{
throw Interop.AppleCrypto.CreateExceptionForOSStatus(error);
}
}
finally
{
if (customCertsArray != s_emptyArray)
{
customCertsArray.Dispose();
}
}
}
_chainHandle = chain;
return;
}
chain.Dispose();
if (ret == 0)
{
throw Interop.AppleCrypto.CreateExceptionForOSStatus(osStatus);
}
Debug.Fail($"AppleCryptoNative_X509ChainCreate returned unexpected return value {ret}");
throw new CryptographicException();
}
public void Dispose()
{
if (_extraHandles == null)
return;
Stack<SafeHandle> extraHandles = _extraHandles;
_extraHandles = null;
_chainHandle?.Dispose();
while (extraHandles.Count > 0)
{
extraHandles.Pop().Dispose();
}
}
public bool? Verify(X509VerificationFlags flags, out Exception exception)
{
exception = null;
return ChainVerifier.Verify(ChainElements, flags);
}
private SafeCreateHandle PreparePoliciesArray(bool checkRevocation)
{
IntPtr[] policies = new IntPtr[checkRevocation ? 2 : 1];
SafeHandle defaultPolicy = Interop.AppleCrypto.X509ChainCreateDefaultPolicy();
if (defaultPolicy.IsInvalid)
{
defaultPolicy.Dispose();
throw new PlatformNotSupportedException(nameof(X509Chain));
}
_extraHandles.Push(defaultPolicy);
policies[0] = defaultPolicy.DangerousGetHandle();
if (checkRevocation)
{
SafeHandle revPolicy = Interop.AppleCrypto.X509ChainCreateRevocationPolicy();
_extraHandles.Push(revPolicy);
policies[1] = revPolicy.DangerousGetHandle();
}
SafeCreateHandle policiesArray =
Interop.CoreFoundation.CFArrayCreate(policies, (UIntPtr)policies.Length);
_extraHandles.Push(policiesArray);
return policiesArray;
}
private SafeCreateHandle PrepareCertsArray(
ICertificatePal cert,
X509Certificate2Collection extraStore,
X509Certificate2Collection customTrustStore,
X509ChainTrustMode trustMode)
{
List<SafeHandle> safeHandles = new List<SafeHandle> { ((AppleCertificatePal)cert).CertificateHandle };
if (extraStore != null)
{
for (int i = 0; i < extraStore.Count; i++)
{
safeHandles.Add(((AppleCertificatePal)extraStore[i].Pal).CertificateHandle);
}
}
if (trustMode == X509ChainTrustMode.CustomRootTrust && customTrustStore != null)
{
for (int i = 0; i < customTrustStore.Count; i++)
{
// Only adds non self issued certs to the untrusted certs array. Trusted self signed
// certs will be added to the custom certs array.
if (!customTrustStore[i].SubjectName.RawData.ContentsEqual(customTrustStore[i].IssuerName.RawData))
{
safeHandles.Add(((AppleCertificatePal)customTrustStore[i].Pal).CertificateHandle);
}
}
}
return GetCertsArray(safeHandles);
}
private SafeCreateHandle PrepareCustomCertsArray(X509Certificate2Collection customTrustStore)
{
List<SafeHandle> rootCertificates = new List<SafeHandle>();
foreach (X509Certificate2 cert in customTrustStore)
{
if (cert.SubjectName.RawData.ContentsEqual(cert.IssuerName.RawData))
{
rootCertificates.Add(((AppleCertificatePal)cert.Pal).CertificateHandle);
}
}
return GetCertsArray(rootCertificates);
}
private SafeCreateHandle GetCertsArray(IList<SafeHandle> safeHandles)
{
int idx = 0;
try
{
int handlesCount = safeHandles.Count;
IntPtr[] ptrs = new IntPtr[handlesCount];
for (; idx < handlesCount; idx++)
{
SafeHandle handle = safeHandles[idx];
bool addedRef = false;
handle.DangerousAddRef(ref addedRef);
ptrs[idx] = handle.DangerousGetHandle();
}
// Creating the array has the effect of calling CFRetain() on all of the pointers, so the native
// resource is safe even if we DangerousRelease=>ReleaseHandle them.
SafeCreateHandle certsArray = Interop.CoreFoundation.CFArrayCreate(ptrs, (UIntPtr)ptrs.Length);
_extraHandles.Push(certsArray);
return certsArray;
}
finally
{
for (idx--; idx >= 0; idx--)
{
safeHandles[idx].DangerousRelease();
}
}
}
internal void Execute(
DateTime verificationTime,
bool allowNetwork,
OidCollection applicationPolicy,
OidCollection certificatePolicy,
X509RevocationFlag revocationFlag)
{
int osStatus;
// Save the time code for determining which message to load for NotTimeValid.
_verificationTime = verificationTime;
int ret;
using (SafeCFDateHandle cfEvaluationTime = Interop.CoreFoundation.CFDateCreate(verificationTime))
{
ret = Interop.AppleCrypto.AppleCryptoNative_X509ChainEvaluate(
_chainHandle,
cfEvaluationTime,
allowNetwork,
out osStatus);
}
if (ret == 0)
throw Interop.AppleCrypto.CreateExceptionForOSStatus(osStatus);
if (ret != 1)
{
Debug.Fail($"AppleCryptoNative_X509ChainEvaluate returned unknown result {ret}");
throw new CryptographicException();
}
Tuple<X509Certificate2, int>[] elements = ParseResults(_chainHandle, _revocationMode);
Debug.Assert(elements.Length > 0);
if (!IsPolicyMatch(elements, applicationPolicy, certificatePolicy))
{
for (int i = 0; i < elements.Length; i++)
{
Tuple<X509Certificate2, int> currentValue = elements[i];
elements[i] = Tuple.Create(
currentValue.Item1,
currentValue.Item2 | (int)X509ChainStatusFlags.NotValidForUsage);
}
}
FixupRevocationStatus(elements, revocationFlag);
BuildAndSetProperties(elements);
}
private static Tuple<X509Certificate2, int>[] ParseResults(
SafeX509ChainHandle chainHandle,
X509RevocationMode revocationMode)
{
long elementCount = Interop.AppleCrypto.X509ChainGetChainSize(chainHandle);
var elements = new Tuple<X509Certificate2, int>[elementCount];
using (var trustResults = Interop.AppleCrypto.X509ChainGetTrustResults(chainHandle))
{
for (long elementIdx = 0; elementIdx < elementCount; elementIdx++)
{
IntPtr certHandle =
Interop.AppleCrypto.X509ChainGetCertificateAtIndex(chainHandle, elementIdx);
int dwStatus;
int ret = Interop.AppleCrypto.X509ChainGetStatusAtIndex(trustResults, elementIdx, out dwStatus);
// A return value of zero means no errors happened in locating the status (negative) or in
// parsing the status (positive).
if (ret != 0)
{
Debug.Fail($"X509ChainGetStatusAtIndex returned unexpected error {ret}");
throw new CryptographicException();
}
X509Certificate2 cert = new X509Certificate2(certHandle);
FixupStatus(cert, revocationMode, ref dwStatus);
elements[elementIdx] = Tuple.Create(cert, dwStatus);
}
}
return elements;
}
private bool IsPolicyMatch(
Tuple<X509Certificate2, int>[] elements,
OidCollection applicationPolicy,
OidCollection certificatePolicy)
{
if (applicationPolicy?.Count > 0 || certificatePolicy?.Count > 0)
{
List<X509Certificate2> certsToRead = new List<X509Certificate2>();
foreach (var element in elements)
{
certsToRead.Add(element.Item1);
}
CertificatePolicyChain policyChain = new CertificatePolicyChain(certsToRead);
if (certificatePolicy?.Count > 0)
{
if (!policyChain.MatchesCertificatePolicies(certificatePolicy))
{
return false;
}
}
if (applicationPolicy?.Count > 0)
{
if (!policyChain.MatchesApplicationPolicies(applicationPolicy))
{
return false;
}
}
}
return true;
}
private void BuildAndSetProperties(Tuple<X509Certificate2, int>[] elementTuples)
{
X509ChainElement[] elements = new X509ChainElement[elementTuples.Length];
int allStatus = 0;
for (int i = 0; i < elementTuples.Length; i++)
{
Tuple<X509Certificate2, int> tuple = elementTuples[i];
elements[i] = BuildElement(tuple.Item1, tuple.Item2);
allStatus |= tuple.Item2;
}
ChainElements = elements;
X509ChainElement rollupElement = BuildElement(null, allStatus);
ChainStatus = rollupElement.ChainElementStatus;
}
private static void FixupRevocationStatus(
Tuple<X509Certificate2, int>[] elements,
X509RevocationFlag revocationFlag)
{
if (revocationFlag == X509RevocationFlag.ExcludeRoot)
{
// When requested
int idx = elements.Length - 1;
Tuple<X509Certificate2, int> element = elements[idx];
X509ChainStatusFlags statusFlags = (X509ChainStatusFlags)element.Item2;
// Apple will terminate the chain at the first "root" or "trustAsRoot" certificate
// it finds, which it refers to as "anchors". We'll consider a "trustAsRoot" cert
// as a root for the purposes of ExcludeRoot. So as long as the last element doesn't
// have PartialChain consider it the root.
if ((statusFlags & X509ChainStatusFlags.PartialChain) == 0)
{
statusFlags &= ~RevocationRelevantFlags;
elements[idx] = Tuple.Create(element.Item1, (int)statusFlags);
}
}
else if (revocationFlag == X509RevocationFlag.EndCertificateOnly)
{
// In Windows the EndCertificateOnly flag (CERT_CHAIN_REVOCATION_CHECK_END_CERT) will apply
// to a root if that's the only element, so we'll do the same.
// Start at element 1, and move to the end.
for (int i = 1; i < elements.Length; i++)
{
Tuple<X509Certificate2, int> element = elements[i];
X509ChainStatusFlags statusFlags = (X509ChainStatusFlags)element.Item2;
statusFlags &= ~RevocationRelevantFlags;
elements[i] = Tuple.Create(element.Item1, (int)statusFlags);
}
}
}
private static void FixupStatus(
X509Certificate2 cert,
X509RevocationMode revocationMode,
ref int dwStatus)
{
X509ChainStatusFlags flags = (X509ChainStatusFlags)dwStatus;
if ((flags & X509ChainStatusFlags.UntrustedRoot) != 0)
{
X509ChainStatusFlags newFlag = FindUntrustedRootReason(cert);
if (newFlag != X509ChainStatusFlags.UntrustedRoot)
{
flags &= ~X509ChainStatusFlags.UntrustedRoot;
flags |= newFlag;
dwStatus = (int)flags;
}
}
if (revocationMode == X509RevocationMode.NoCheck)
{
// Clear any revocation-related flags if NoCheck was requested, since
// the OS may use cached results opportunistically.
flags &= ~RevocationRelevantFlags;
dwStatus = (int)flags;
}
}
private static X509ChainStatusFlags FindUntrustedRootReason(X509Certificate2 cert)
{
// UntrustedRoot comes back for at least the following reasons:
// 1. The parent cert could not be found (no network, no AIA, etc) (PartialChain)
// 2. The root cert was found, and wasn't trusted (UntrustedRoot)
// 3. The certificate was tampered with, so the parent was declared invalid.
//
// In the #3 case we'd like to call it NotSignatureValid, but since we didn't get
// the parent certificate we can't recompute that, so it'll just get called
// PartialChain.
if (!cert.SubjectName.RawData.ContentsEqual(cert.IssuerName.RawData))
{
return X509ChainStatusFlags.PartialChain;
}
// Okay, so we're looking at a self-signed certificate.
// What are some situations?
// 1. A private / new root certificate was matched which is not trusted (UntrustedRoot)
// 2. A valid root certificate is tampered with (NotSignatureValid)
// 3. A valid certificate is created which has the same subject name as
// an existing root cert (UntrustedRoot)
//
// To a user, case 2 and 3 aren't really distinguishable:
// "What do you mean [my favorite CA] isn't trusted?".
// NotSignatureValid would reveal the tamper, but since whoever was tampering can
// easily re-sign a self-signed cert, it's not worth duplicating the signature
// computation here.
return X509ChainStatusFlags.UntrustedRoot;
}
private X509ChainElement BuildElement(X509Certificate2 cert, int dwStatus)
{
if (dwStatus == 0)
{
return new X509ChainElement(cert, Array.Empty<X509ChainStatus>(), "");
}
List<X509ChainStatus> statuses = new List<X509ChainStatus>();
X509ChainStatusFlags flags = (X509ChainStatusFlags)dwStatus;
foreach (X509ChainErrorMapping mapping in X509ChainErrorMapping.s_chainErrorMappings)
{
if ((mapping.ChainStatusFlag & flags) == mapping.ChainStatusFlag)
{
int osStatus;
string errorString;
// Disambiguate the NotTimeValid code to get the right string.
if (mapping.ChainStatusFlag == X509ChainStatusFlags.NotTimeValid)
{
const int errSecCertificateExpired = -67818;
const int errSecCertificateNotValidYet = -67819;
osStatus = cert != null && cert.NotBefore > _verificationTime ?
errSecCertificateNotValidYet :
errSecCertificateExpired;
errorString = Interop.AppleCrypto.GetSecErrorString(osStatus);
}
else
{
osStatus = mapping.OSStatus;
errorString = mapping.ErrorString;
}
statuses.Add(
new X509ChainStatus
{
Status = mapping.ChainStatusFlag,
StatusInformation = errorString
});
}
}
return new X509ChainElement(cert, statuses.ToArray(), "");
}
private readonly struct X509ChainErrorMapping
{
internal static readonly X509ChainErrorMapping[] s_chainErrorMappings =
{
new X509ChainErrorMapping(X509ChainStatusFlags.NotTimeValid),
new X509ChainErrorMapping(X509ChainStatusFlags.NotTimeNested),
new X509ChainErrorMapping(X509ChainStatusFlags.Revoked),
new X509ChainErrorMapping(X509ChainStatusFlags.NotSignatureValid),
new X509ChainErrorMapping(X509ChainStatusFlags.NotValidForUsage),
new X509ChainErrorMapping(X509ChainStatusFlags.UntrustedRoot),
new X509ChainErrorMapping(X509ChainStatusFlags.RevocationStatusUnknown),
new X509ChainErrorMapping(X509ChainStatusFlags.Cyclic),
new X509ChainErrorMapping(X509ChainStatusFlags.InvalidExtension),
new X509ChainErrorMapping(X509ChainStatusFlags.InvalidPolicyConstraints),
new X509ChainErrorMapping(X509ChainStatusFlags.InvalidBasicConstraints),
new X509ChainErrorMapping(X509ChainStatusFlags.InvalidNameConstraints),
new X509ChainErrorMapping(X509ChainStatusFlags.HasNotSupportedNameConstraint),
new X509ChainErrorMapping(X509ChainStatusFlags.HasNotDefinedNameConstraint),
new X509ChainErrorMapping(X509ChainStatusFlags.HasNotPermittedNameConstraint),
new X509ChainErrorMapping(X509ChainStatusFlags.HasExcludedNameConstraint),
new X509ChainErrorMapping(X509ChainStatusFlags.PartialChain),
new X509ChainErrorMapping(X509ChainStatusFlags.CtlNotTimeValid),
new X509ChainErrorMapping(X509ChainStatusFlags.CtlNotSignatureValid),
new X509ChainErrorMapping(X509ChainStatusFlags.CtlNotValidForUsage),
new X509ChainErrorMapping(X509ChainStatusFlags.OfflineRevocation),
new X509ChainErrorMapping(X509ChainStatusFlags.NoIssuanceChainPolicy),
new X509ChainErrorMapping(X509ChainStatusFlags.ExplicitDistrust),
new X509ChainErrorMapping(X509ChainStatusFlags.HasNotSupportedCriticalExtension),
new X509ChainErrorMapping(X509ChainStatusFlags.HasWeakSignature),
};
internal readonly X509ChainStatusFlags ChainStatusFlag;
internal readonly int OSStatus;
internal readonly string ErrorString;
private X509ChainErrorMapping(X509ChainStatusFlags flag)
{
ChainStatusFlag = flag;
OSStatus = Interop.AppleCrypto.GetOSStatusForChainStatus(flag);
ErrorString = Interop.AppleCrypto.GetSecErrorString(OSStatus);
}
}
}
internal sealed partial class ChainPal
{
public static IChainPal FromHandle(IntPtr chainContext)
{
// This is possible to do on Apple's platform, but is tricky in execution.
// In Windows, CertGetCertificateChain is what allocates the handle, and it does
// * Chain building
// * Revocation checking as directed
// But notably does not apply any policy rules (TLS hostname matching, etc), or
// even inquire as to what policies should be applied.
//
// On Apple, the order is reversed. Creating the SecTrust(Ref) object requires
// the policy to match against, but when the handle is created it might not have
// built the chain. Then a call to SecTrustEvaluate actually does the chain building.
//
// This means that Windows never had to handle the "unevaluated chain" pointer, but
// on Apple we would. And so it means that the .NET API doesn't understand it can be in
// that state.
// * Is that an exception on querying the status or elements?
// * An exception in this call chain (new X509Chain(IntPtr))?
// * Should we build the chain on first data query?
// * Should we build the chain now?
//
// The only thing that is known is that if this method succeeds it does not take ownership
// of the handle. So it should CFRetain the handle and let the PAL object's SafeHandle
// still Dispose/CFRelease.
//
// For now, just PNSE, it didn't work when we used OpenSSL, and we can add this when we
// decide what it should do.
throw new PlatformNotSupportedException();
}
public static bool ReleaseSafeX509ChainHandle(IntPtr handle)
{
Interop.CoreFoundation.CFRelease(handle);
return true;
}
public static IChainPal BuildChain(
bool useMachineContext,
ICertificatePal cert,
X509Certificate2Collection extraStore,
OidCollection applicationPolicy,
OidCollection certificatePolicy,
X509RevocationMode revocationMode,
X509RevocationFlag revocationFlag,
X509Certificate2Collection customTrustStore,
X509ChainTrustMode trustMode,
DateTime verificationTime,
TimeSpan timeout)
{
// If the time was given in Universal, it will stay Universal.
// If the time was given in Local, it will be converted.
// If the time was given in Unspecified, it will be assumed local, and converted.
//
// This matches the "assume Local unless explicitly Universal" implicit contract.
verificationTime = verificationTime.ToUniversalTime();
// The Windows (and other-Unix-PAL) behavior is to allow network until network operations
// have exceeded the specified timeout. For Apple it's either on (and AIA fetching works),
// or off (and AIA fetching doesn't work). And once an SSL policy is used, or revocation is
// being checked, the value is on anyways.
const bool allowNetwork = true;
SecTrustChainPal chainPal = new SecTrustChainPal();
try
{
chainPal.OpenTrustHandle(
cert,
extraStore,
revocationMode,
customTrustStore,
trustMode);
chainPal.Execute(
verificationTime,
allowNetwork,
applicationPolicy,
certificatePolicy,
revocationFlag);
}
catch
{
chainPal.Dispose();
throw;
}
return chainPal;
}
}
}
| |
// Copyright (c) 2011 Daniel A. Schilling
namespace W3CValidators.Markup
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Threading;
using System.Web;
/// <summary>
/// Communicates with a W3C Markup Validator service.
/// </summary>
public class MarkupValidatorClient
{
/// <summary>
/// The location of W3C's free public markup validator service.
/// </summary>
public static readonly Uri PublicValidator = new Uri("http://validator.w3.org/check");
public static Uri ConfiguredValidator
{
get
{
var configSection = (ValidatorConfigSection)ConfigurationManager.GetSection("w3cValidators");
return configSection == null
? PublicValidator
: configSection.MarkupValidatorUri;
}
}
private static readonly object ThrottleLock = new object();
private readonly Uri _validator;
/// <summary>
/// Creates a new MarkupValidatorClient instance pointing at the validator specified in your
/// app.config file, defaulting to W3C's public validator: http://validator.w3.org/check.
/// </summary>
public MarkupValidatorClient()
: this(ConfiguredValidator)
{}
/// <summary>
/// Creates a new MarkupValidatorClient instance pointing at the specified validator. See
/// http://validator.w3.org/docs/install.html for instructions on installing your own copy
/// of the validator.
/// </summary>
/// <param name="validator">the location of the validator service</param>
public MarkupValidatorClient(Uri validator)
{
_validator = validator;
}
/// <summary>
/// Asks the validator service to download and validate the document at specified public
/// uri. This is the "uri" method.
/// </summary>
/// <param name="documentUri">the location of the document to be validated</param>
/// <param name="options">configuration options</param>
/// <returns>a MarkupValidatorResponse object</returns>
public MarkupValidatorResponse CheckByUri(Uri documentUri, MarkupValidatorOptions options)
{
if (options == null)
options = new MarkupValidatorOptions();
var queryStrings = options.ToDictionary();
queryStrings.Add("uri", documentUri.ToString());
var request = WebRequest.Create(AppendQueryString(_validator, queryStrings));
return ThrottledParseResponse(request);
}
/// <summary>
/// Uploads a document to the validator service for validation. This is the
/// "uploaded_file" method.
/// </summary>
/// <param name="documentData">the document to upload</param>
/// <param name="options">configuration options</param>
/// <returns>a MarkupValidatorResponse object</returns>
public MarkupValidatorResponse CheckByUpload(byte[] documentData, MarkupValidatorOptions options)
{
if (options == null)
options = new MarkupValidatorOptions();
var request = this.ConstructPostRequest(
options,
writer => writer.Write("uploaded_file", "document.html", "text/html", documentData));
return ThrottledParseResponse(request);
}
/// <summary>
/// Posts a document to the validator service for validation. This is the "fragment"
/// method.
/// </summary>
/// <param name="documentFragment">the document to upload</param>
/// <param name="options">configuration options</param>
/// <returns>a MarkupValidatorResponse object</returns>
public MarkupValidatorResponse CheckByFragment(string documentFragment, MarkupValidatorOptions options)
{
if (options == null)
options = new MarkupValidatorOptions();
var request = this.ConstructPostRequest(
options,
writer => writer.Write("fragment", documentFragment));
return ThrottledParseResponse(request);
}
private WebRequest ConstructPostRequest(MarkupValidatorOptions options, Action<MultipartFormDataWriter> writePayload)
{
var request = WebRequest.Create(this._validator);
var boundary = Guid.NewGuid().ToString();
request.Method = "POST";
request.ContentType = string.Concat("multipart/form-data; boundary=", boundary);
using (var contents = new MemoryStream())
{
using (var writer = new MultipartFormDataWriter(contents, boundary))
{
foreach (var pair in options.ToDictionary())
{
writer.Write(pair.Key, pair.Value);
}
writePayload(writer);
}
contents.Flush();
request.ContentLength = contents.Length;
using (var requestStream = request.GetRequestStream())
{
contents.WriteTo(requestStream);
}
}
return request;
}
private static Uri AppendQueryString(Uri baseUri, ICollection<KeyValuePair<string, string>> queryStrings)
{
if (queryStrings.Count <= 0)
return baseUri;
var pieces = new string[queryStrings.Count];
var i = 0;
foreach (var pair in queryStrings)
{
pieces[i] = string.Concat(
HttpUtility.UrlEncode(pair.Key),
"=",
HttpUtility.UrlEncode(pair.Value));
i++;
}
var uriString = string.Concat(
baseUri.ToString(),
"?",
string.Join("&", pieces));
return new Uri(uriString);
}
private MarkupValidatorResponse ThrottledParseResponse(WebRequest request)
{
if (!Equals(this._validator, PublicValidator))
return this.ParseResponse(request);
lock (ThrottleLock)
{
Thread.Sleep(1000);
return this.ParseResponse(request);
}
}
private MarkupValidatorResponse ParseResponse(WebRequest request)
{
this.OnSendingRequest();
using (var response = request.GetResponse())
{
this.OnResponseReceived();
using (var stream = response.GetResponseStream())
return new MarkupValidatorResponse(stream);
}
}
/// <summary>
/// Fires just before the client sends its request to the service.
/// </summary>
public event EventHandler SendingRequest;
private void OnSendingRequest()
{
if (this.SendingRequest != null)
this.SendingRequest(this, EventArgs.Empty);
}
/// <summary>
/// Fires just after the response has been recieved from the service.
/// </summary>
public event EventHandler ResponseReceived;
private void OnResponseReceived()
{
if (this.ResponseReceived != null)
this.ResponseReceived(this, EventArgs.Empty);
}
}
}
| |
using System;
using FakeItEasy;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace M.Executables.Executors.NetCore.UnitTests
{
public class NetCoreExecutorTests
{
[Fact]
public void Execute_IsCalledOnVoidExecutable()
{
var executable = A.Fake<IExecutableVoid>();
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
executor.Execute<IExecutableVoid>();
A.CallTo(() => executable.Execute()).MustHaveHappenedOnceExactly();
}
[Fact]
public void Execute_IsCalledOnVoidExecutableWithParameter()
{
var executable = A.Fake<IExecutableVoid<string>>();
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
executor.Execute<IExecutableVoid<string>, string>("parameter hello");
A.CallTo(() => executable.Execute("parameter hello")).MustHaveHappenedOnceExactly();
}
[Fact]
public void Execute_IsCalledOnExecutable()
{
var executable = A.Fake<IExecutable<string>>();
A.CallTo(() => executable.Execute()).Returns("return value hello");
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
var result = executor.Execute<IExecutable<string>, string>();
A.CallTo(() => executable.Execute()).MustHaveHappenedOnceExactly();
Assert.Equal("return value hello", result);
}
[Fact]
public void Execute_IsCalledOnExecutableWithParameter()
{
var executable = A.Fake<IExecutable<string, string>>();
A.CallTo(() => executable.Execute("parameter hello")).Returns("return value hello");
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
var result = executor.Execute<IExecutable<string, string>, string, string>("parameter hello");
A.CallTo(() => executable.Execute("parameter hello")).MustHaveHappenedOnceExactly();
Assert.Equal("return value hello", result);
}
[Fact]
public void Execute_InterceptorsAreCalledInOrder()
{
var executable = A.Fake<IExecutable<string, string>>();
A.CallTo(() => executable.Execute("parameter hello")).Returns("return value hello");
var generalInterceptor1 = A.Fake<IExecutionInterceptor>();
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptor>();
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptor<IExecutable<string, string>, string, string>>();
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
var result = executor.Execute<IExecutable<string, string>, string, string>("parameter hello");
Assert.Equal("return value hello", result);
// interceptors called in ascending OrderIndex order
A.CallTo(() => generalInterceptor1.Before(executable, "parameter hello")).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => specificInterceptor.Before(executable, "parameter hello")).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor2.Before(executable, "parameter hello")).MustHaveHappenedOnceExactly())
// executable called
.Then(A.CallTo(() => executable.Execute("parameter hello")).MustHaveHappenedOnceExactly())
// interceptors called in descending OrderIndex order
.Then(A.CallTo(() => generalInterceptor2.After(executable, "parameter hello", "return value hello", null)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.After(executable, "parameter hello", "return value hello", null)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor1.After(executable, "parameter hello", "return value hello", null)).MustHaveHappenedOnceExactly());
}
[Fact]
public void Execute_ExceptionIsPassedToInterceptors()
{
var executable = A.Fake<IExecutable<string, string>>();
var exception = new InvalidOperationException();
A.CallTo(() => executable.Execute("parameter hello")).Throws(exception);
var generalInterceptor1 = A.Fake<IExecutionInterceptor>();
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptor>();
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptor<IExecutable<string, string>, string, string>>();
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
_ = Assert.Throws(exception.GetType(), () => executor.Execute<IExecutable<string, string>, string, string>("parameter hello"));
// interceptors called in ascending OrderIndex order
_ = A.CallTo(() => generalInterceptor1.Before(executable, "parameter hello")).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => specificInterceptor.Before(executable, "parameter hello")).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor2.Before(executable, "parameter hello")).MustHaveHappenedOnceExactly())
// executable called
.Then(A.CallTo(() => executable.Execute("parameter hello")).MustHaveHappenedOnceExactly())
// interceptors called in descending OrderIndex order
.Then(A.CallTo(() => generalInterceptor2.After(executable, "parameter hello", default(string), exception)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.After(executable, "parameter hello", default(string), exception)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor1.After(executable, "parameter hello", default(string), exception)).MustHaveHappenedOnceExactly());
}
[Fact]
public void Execute_InterceptorsGetIEmptyWhenNoParameterOrReturnValue()
{
var executable = A.Fake<IExecutableVoid>();
var generalInterceptor1 = A.Fake<IExecutionInterceptor>();
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptor>();
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptor<IExecutableVoid, IEmpty, IEmpty>>();
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
executor.Execute<IExecutableVoid>();
// interceptors called in ascending OrderIndex order
_ = A.CallTo(() => generalInterceptor1.Before(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => specificInterceptor.Before(executable, default(IEmpty))).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor2.Before(executable, default(IEmpty))).MustHaveHappenedOnceExactly())
// executable called
.Then(A.CallTo(() => executable.Execute()).MustHaveHappenedOnceExactly())
// interceptors called in descending OrderIndex order
.Then(A.CallTo(() => generalInterceptor2.After(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.After(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor1.After(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
}
[Fact]
public void Execute_InterceptorsImplementIDiscardOtherInteceptors_TheOneWithSmallestOrderIndexIsCalled()
{
var executable = A.Fake<IExecutableVoid>();
var generalInterceptor1 = A.Fake<IExecutionInterceptor>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptor>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptor<IExecutableVoid, IEmpty, IEmpty>>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
executor.Execute<IExecutableVoid>();
_ = A.CallTo(() => generalInterceptor1.Before(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => executable.Execute()).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor1.After(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
A.CallTo(() => specificInterceptor.Before(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.Before(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.After(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
A.CallTo(() => specificInterceptor.After(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
}
[Fact]
public void Execute_InterceptorsImplementIDiscardOtherInteceptorsAndIDiscardNonGenericInterceptors_TheIDiscardNonGenericInterceptorsIsCalled()
{
var executable = A.Fake<IExecutableVoid>();
var generalInterceptor1 = A.Fake<IExecutionInterceptor>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptor>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptor<IExecutableVoid, IEmpty, IEmpty>>(x => x.Implements<IDiscardOtherInterceptors>().Implements<IDiscardNonGenericInterceptors>());
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
executor.Execute<IExecutableVoid>();
_ = A.CallTo(() => specificInterceptor.Before(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => executable.Execute()).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.After(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
A.CallTo(() => generalInterceptor1.Before(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.Before(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor1.After(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.After(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
}
[Fact]
public void Execute_SpecificInterceptorImplementIDiscardOtherInteceptors_TheSpecificInterceptorsIsCalled()
{
var executable = A.Fake<IExecutableVoid>();
var generalInterceptor1 = A.Fake<IExecutionInterceptor>();
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptor>();
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptor<IExecutableVoid, IEmpty, IEmpty>>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
executor.Execute<IExecutableVoid>();
_ = A.CallTo(() => specificInterceptor.Before(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => executable.Execute()).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.After(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
A.CallTo(() => generalInterceptor1.Before(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.Before(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor1.After(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.After(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
}
[Fact]
public void Execute_GeneralInterceptorImplementIDiscardOtherInteceptors_TheGeneralInterceptorsIsCalled()
{
var executable = A.Fake<IExecutableVoid>();
var generalInterceptor1 = A.Fake<IExecutionInterceptor>();
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptor>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptor<IExecutableVoid, IEmpty, IEmpty>>();
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
executor.Execute<IExecutableVoid>();
_ = A.CallTo(() => generalInterceptor2.Before(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => executable.Execute()).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor2.After(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
A.CallTo(() => specificInterceptor.Before(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor1.Before(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor1.After(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
A.CallTo(() => specificInterceptor.After(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
}
[Fact]
public void Execute_SpecificInterceptorImplementsIDiscardNonGenericInterceptors_NonGenericInterceptorsAreNorCalled()
{
var executable = A.Fake<IExecutableVoid>();
var generalInterceptor1 = A.Fake<IExecutionInterceptor>();
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptor>();
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptor<IExecutableVoid, IEmpty, IEmpty>>(x => x.Implements<IDiscardNonGenericInterceptors>());
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
executor.Execute<IExecutableVoid>();
_ = A.CallTo(() => specificInterceptor.Before(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => executable.Execute()).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.After(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
A.CallTo(() => generalInterceptor1.Before(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.Before(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor1.After(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.After(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
}
[Fact]
public void Execute_GeneralInterceptorImplementsIDiscardNonGenericInterceptors_DoesNotAffectGeneralInterceptors()
{
var executable = A.Fake<IExecutableVoid>();
var generalInterceptor1 = A.Fake<IExecutionInterceptor>(x => x.Implements<IDiscardNonGenericInterceptors>());
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptor>(x => x.Implements<IDiscardNonGenericInterceptors>());
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptor<IExecutableVoid, IEmpty, IEmpty>>();
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutor>();
executor.Execute<IExecutableVoid>();
// interceptors called in ascending OrderIndex order
_ = A.CallTo(() => generalInterceptor1.Before(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => specificInterceptor.Before(executable, default(IEmpty))).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor2.Before(executable, default(IEmpty))).MustHaveHappenedOnceExactly())
// executable called
.Then(A.CallTo(() => executable.Execute()).MustHaveHappenedOnceExactly())
// interceptors called in descending OrderIndex order
.Then(A.CallTo(() => generalInterceptor2.After(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.After(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor1.After(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ToolStripButton.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.ComponentModel;
using System.Windows.Forms.Design;
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton"]/*' />
/// <devdoc/>
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip)]
public class ToolStripButton : ToolStripItem {
private CheckState checkState = CheckState.Unchecked;
private bool checkOnClick = false;
private const int StandardButtonWidth = 23;
private static readonly object EventCheckedChanged = new object();
private static readonly object EventCheckStateChanged = new object();
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton.ToolStripButton"]/*' />
/// <devdoc>
/// Summary of ToolStripButton.
/// </devdoc>
public ToolStripButton() {
Initialize();
}
public ToolStripButton(string text):base(text,null,null) {
Initialize();
}
public ToolStripButton(Image image):base(null,image,null) {
Initialize();
}
public ToolStripButton(string text, Image image):base(text,image,null) {
Initialize();
}
public ToolStripButton(string text, Image image, EventHandler onClick):base(text,image,onClick) {
Initialize();
}
public ToolStripButton(string text, Image image, EventHandler onClick, string name):base(text,image,onClick,name) {
Initialize();
}
[DefaultValue(true)]
public new bool AutoToolTip {
get {
return base.AutoToolTip;
}
set {
base.AutoToolTip = value;
}
}
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton.CanSelect"]/*' />
/// <devdoc>
/// Summary of CanSelect.
/// </devdoc>
public override bool CanSelect {
get {
return true;
}
}
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton.CheckOnClick"]/*' />
[
DefaultValue(false),
SRCategory(SR.CatBehavior),
SRDescription(SR.ToolStripButtonCheckOnClickDescr)
]
public bool CheckOnClick {
get {
return checkOnClick;
}
set {
checkOnClick = value;
}
}
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton.Checked"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the item is checked.
/// </para>
/// </devdoc>
[
DefaultValue(false),
SRCategory(SR.CatAppearance),
SRDescription(SR.ToolStripButtonCheckedDescr)
]
public bool Checked {
get {
return checkState != CheckState.Unchecked;
}
set {
if (value != Checked) {
CheckState = value ? CheckState.Checked : CheckState.Unchecked;
InvokePaint();
}
}
}
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton.CheckState"]/*' />
/// <devdoc>
/// <para>Gets
/// or sets a value indicating whether the check box is checked.</para>
/// </devdoc>
[
SRCategory(SR.CatAppearance),
DefaultValue(CheckState.Unchecked),
SRDescription(SR.CheckBoxCheckStateDescr)
]
public CheckState CheckState {
get {
return checkState;
}
set {
//valid values are 0x0 to 0x2
if (!ClientUtils.IsEnumValid(value, (int)value, (int)CheckState.Unchecked, (int)CheckState.Indeterminate))
{
throw new InvalidEnumArgumentException("value", (int)value, typeof(CheckState));
}
if (value != checkState) {
checkState = value;
Invalidate();
OnCheckedChanged(EventArgs.Empty);
OnCheckStateChanged(EventArgs.Empty);
}
}
}
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton.CheckedChanged"]/*' />
/// <devdoc>
/// <para>Occurs when the
/// value of the <see cref='System.Windows.Forms.CheckBox.Checked'/>
/// property changes.</para>
/// </devdoc>
[SRDescription(SR.CheckBoxOnCheckedChangedDescr)]
public event EventHandler CheckedChanged {
add {
Events.AddHandler(EventCheckedChanged, value);
}
remove {
Events.RemoveHandler(EventCheckedChanged, value);
}
}
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton.CheckStateChanged"]/*' />
/// <devdoc>
/// <para>Occurs when the
/// value of the <see cref='System.Windows.Forms.CheckBox.CheckState'/>
/// property changes.</para>
/// </devdoc>
[SRDescription(SR.CheckBoxOnCheckStateChangedDescr)]
public event EventHandler CheckStateChanged {
add {
Events.AddHandler(EventCheckStateChanged, value);
}
remove {
Events.RemoveHandler(EventCheckStateChanged, value);
}
}
protected override bool DefaultAutoToolTip {
get {
return true;
}
}
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton.CreateAccessibilityInstance"]/*' />
/// <devdoc>
/// constructs the new instance of the accessibility object for this ToolStripItem. Subclasses
/// should not call base.CreateAccessibilityObject.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override AccessibleObject CreateAccessibilityInstance() {
return new ToolStripButtonAccessibleObject(this);
}
public override Size GetPreferredSize(Size constrainingSize) {
Size prefSize = base.GetPreferredSize(constrainingSize);
prefSize.Width = Math.Max(prefSize.Width, StandardButtonWidth);
return prefSize;
}
/// <devdoc>
/// Called by all constructors of ToolStripButton.
/// </devdoc>
private void Initialize() {
SupportsSpaceKey = true;
}
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton.OnCheckedChanged"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='System.Windows.Forms.ToolStripMenuItem.CheckedChanged'/>
/// event.</para>
/// </devdoc>
protected virtual void OnCheckedChanged(EventArgs e) {
EventHandler handler = (EventHandler)Events[EventCheckedChanged];
if (handler != null) handler(this,e);
}
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton.OnCheckStateChanged"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='System.Windows.Forms.ToolStripMenuItem.CheckStateChanged'/> event.</para>
/// </devdoc>
protected virtual void OnCheckStateChanged(EventArgs e) {
AccessibilityNotifyClients(AccessibleEvents.StateChange);
EventHandler handler = (EventHandler)Events[EventCheckStateChanged];
if (handler != null) handler(this,e);
}
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton.OnPaint"]/*' />
/// <devdoc>
/// Inheriting classes should override this method to handle this event.
/// </devdoc>
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) {
if (this.Owner != null) {
ToolStripRenderer renderer = this.Renderer;
renderer.DrawButtonBackground(new ToolStripItemRenderEventArgs(e.Graphics, this));
if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image) {
ToolStripItemImageRenderEventArgs rea = new ToolStripItemImageRenderEventArgs(e.Graphics, this, InternalLayout.ImageRectangle);
rea.ShiftOnPress = true;
renderer.DrawItemImage(rea);
}
if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) {
renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(e.Graphics, this, this.Text, InternalLayout.TextRectangle, this.ForeColor, this.Font, InternalLayout.TextFormat));
}
}
}
/// <include file='doc\ToolStripButton.uex' path='docs/doc[@for="ToolStripButton.OnClick"]/*' />
protected override void OnClick(EventArgs e) {
if (checkOnClick) {
this.Checked = !this.Checked;
}
base.OnClick(e);
}
/// <devdoc>
/// An implementation of AccessibleChild for use with ToolStripItems
/// </devdoc>
[System.Runtime.InteropServices.ComVisible(true)]
internal class ToolStripButtonAccessibleObject : ToolStripItemAccessibleObject {
private ToolStripButton ownerItem = null;
public ToolStripButtonAccessibleObject(ToolStripButton ownerItem): base(ownerItem) {
this.ownerItem = ownerItem;
}
public override AccessibleStates State {
get {
if (ownerItem.Enabled && ownerItem.Checked) {
return base.State | AccessibleStates.Checked;
}
return base.State;
}
}
}
}
}
| |
/*
* 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 OpenMetaverse;
namespace OpenSim.Framework
{
/// <summary>
/// Sandbox mode region comms listener. There is one of these per region
/// </summary>
public class RegionCommsListener : IRegionCommsListener
{
public string debugRegionName = String.Empty;
private AcknowledgeAgentCross handlerAcknowledgeAgentCrossed = null; // OnAcknowledgeAgentCrossed;
private AcknowledgePrimCross handlerAcknowledgePrimCrossed = null; // OnAcknowledgePrimCrossed;
private AgentCrossing handlerAvatarCrossingIntoRegion = null; // OnAvatarCrossingIntoRegion;
private ChildAgentUpdate handlerChildAgentUpdate = null; // OnChildAgentUpdate;
private CloseAgentConnection handlerCloseAgentConnection = null; // OnCloseAgentConnection;
private GenericCall2 handlerExpectChildAgent = null; // OnExpectChildAgent;
private ExpectPrimDelegate handlerExpectPrim = null; // OnExpectPrim;
private ExpectUserDelegate handlerExpectUser = null; // OnExpectUser
private UpdateNeighbours handlerNeighboursUpdate = null; // OnNeighboursUpdate;
private PrimCrossing handlerPrimCrossingIntoRegion = null; // OnPrimCrossingIntoRegion;
private RegionUp handlerRegionUp = null; // OnRegionUp;
private LogOffUser handlerLogOffUser = null;
private GetLandData handlerGetLandData = null;
#region IRegionCommsListener Members
public event ExpectUserDelegate OnExpectUser;
public event ExpectPrimDelegate OnExpectPrim;
public event GenericCall2 OnExpectChildAgent;
public event AgentCrossing OnAvatarCrossingIntoRegion;
public event PrimCrossing OnPrimCrossingIntoRegion;
public event UpdateNeighbours OnNeighboursUpdate;
public event AcknowledgeAgentCross OnAcknowledgeAgentCrossed;
public event AcknowledgePrimCross OnAcknowledgePrimCrossed;
public event CloseAgentConnection OnCloseAgentConnection;
public event RegionUp OnRegionUp;
public event ChildAgentUpdate OnChildAgentUpdate;
public event LogOffUser OnLogOffUser;
public event GetLandData OnGetLandData;
#endregion
/// <summary>
///
/// </summary>
/// <param name="agent"></param>
/// <returns></returns>
public virtual bool TriggerExpectUser(AgentCircuitData agent)
{
handlerExpectUser = OnExpectUser;
if (handlerExpectUser != null)
{
handlerExpectUser(agent);
return true;
}
return false;
}
// From User Server
public virtual void TriggerLogOffUser(UUID agentID, UUID RegionSecret, string message)
{
handlerLogOffUser = OnLogOffUser;
if (handlerLogOffUser != null)
{
handlerLogOffUser(agentID, RegionSecret, message);
}
}
public virtual bool TriggerExpectPrim(UUID primID, string objData, int XMLMethod)
{
handlerExpectPrim = OnExpectPrim;
if (handlerExpectPrim != null)
{
handlerExpectPrim(primID, objData, XMLMethod);
return true;
}
return false;
}
public virtual bool TriggerRegionUp(RegionInfo region)
{
handlerRegionUp = OnRegionUp;
if (handlerRegionUp != null)
{
handlerRegionUp(region);
return true;
}
return false;
}
public virtual bool TriggerChildAgentUpdate(ChildAgentDataUpdate cAgentData)
{
handlerChildAgentUpdate = OnChildAgentUpdate;
if (handlerChildAgentUpdate != null)
{
handlerChildAgentUpdate(cAgentData);
return true;
}
return false;
}
public virtual bool TriggerExpectAvatarCrossing(UUID agentID, Vector3 position, bool isFlying)
{
handlerAvatarCrossingIntoRegion = OnAvatarCrossingIntoRegion;
if (handlerAvatarCrossingIntoRegion != null)
{
handlerAvatarCrossingIntoRegion(agentID, position, isFlying);
return true;
}
return false;
}
public virtual bool TriggerExpectPrimCrossing(UUID primID, Vector3 position,
bool isPhysical)
{
handlerPrimCrossingIntoRegion = OnPrimCrossingIntoRegion;
if (handlerPrimCrossingIntoRegion != null)
{
handlerPrimCrossingIntoRegion(primID, position, isPhysical);
return true;
}
return false;
}
public virtual bool TriggerAcknowledgeAgentCrossed(UUID agentID)
{
handlerAcknowledgeAgentCrossed = OnAcknowledgeAgentCrossed;
if (handlerAcknowledgeAgentCrossed != null)
{
handlerAcknowledgeAgentCrossed(agentID);
return true;
}
return false;
}
public virtual bool TriggerAcknowledgePrimCrossed(UUID primID)
{
handlerAcknowledgePrimCrossed = OnAcknowledgePrimCrossed;
if (handlerAcknowledgePrimCrossed != null)
{
handlerAcknowledgePrimCrossed(primID);
return true;
}
return false;
}
public virtual bool TriggerCloseAgentConnection(UUID agentID)
{
handlerCloseAgentConnection = OnCloseAgentConnection;
if (handlerCloseAgentConnection != null)
{
handlerCloseAgentConnection(agentID);
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <remarks>TODO: Doesnt take any args??</remarks>
/// <returns></returns>
public virtual bool TriggerExpectChildAgent()
{
handlerExpectChildAgent = OnExpectChildAgent;
if (handlerExpectChildAgent != null)
{
handlerExpectChildAgent();
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <remarks>Added to avoid a unused compiler warning on OnNeighboursUpdate, TODO: Check me</remarks>
/// <param name="neighbours"></param>
/// <returns></returns>
public virtual bool TriggerOnNeighboursUpdate(List<RegionInfo> neighbours)
{
handlerNeighboursUpdate = OnNeighboursUpdate;
if (handlerNeighboursUpdate != null)
{
handlerNeighboursUpdate(neighbours);
return true;
}
return false;
}
public bool TriggerTellRegionToCloseChildConnection(UUID agentID)
{
handlerCloseAgentConnection = OnCloseAgentConnection;
if (handlerCloseAgentConnection != null)
return handlerCloseAgentConnection(agentID);
return false;
}
public LandData TriggerGetLandData(uint x, uint y)
{
handlerGetLandData = OnGetLandData;
if (handlerGetLandData != null)
return handlerGetLandData(x, y);
return null;
}
}
}
| |
// 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.Runtime;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Text
{
public sealed class EncoderReplacementFallback : EncoderFallback
{
// Our variables
private String _strDefault;
// Construction. Default replacement fallback uses no best fit and ? replacement string
public EncoderReplacementFallback() : this("?")
{
}
public EncoderReplacementFallback(String replacement)
{
// Must not be null
if (replacement == null)
throw new ArgumentNullException(nameof(replacement));
Contract.EndContractBlock();
// Make sure it doesn't have bad surrogate pairs
bool bFoundHigh = false;
for (int i = 0; i < replacement.Length; i++)
{
// Found a surrogate?
if (Char.IsSurrogate(replacement, i))
{
// High or Low?
if (Char.IsHighSurrogate(replacement, i))
{
// if already had a high one, stop
if (bFoundHigh)
break; // break & throw at the bFoundHIgh below
bFoundHigh = true;
}
else
{
// Low, did we have a high?
if (!bFoundHigh)
{
// Didn't have one, make if fail when we stop
bFoundHigh = true;
break;
}
// Clear flag
bFoundHigh = false;
}
}
// If last was high we're in trouble (not surrogate so not low surrogate, so break)
else if (bFoundHigh)
break;
}
if (bFoundHigh)
throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequenceNoIndex, nameof(replacement)));
_strDefault = replacement;
}
public String DefaultString
{
get
{
return _strDefault;
}
}
public override EncoderFallbackBuffer CreateFallbackBuffer()
{
return new EncoderReplacementFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return _strDefault.Length;
}
}
public override bool Equals(Object value)
{
EncoderReplacementFallback that = value as EncoderReplacementFallback;
if (that != null)
{
return (_strDefault == that._strDefault);
}
return (false);
}
public override int GetHashCode()
{
return _strDefault.GetHashCode();
}
}
public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer
{
// Store our default string
private String _strDefault;
private int _fallbackCount = -1;
private int _fallbackIndex = -1;
// Construction
public EncoderReplacementFallbackBuffer(EncoderReplacementFallback fallback)
{
// 2X in case we're a surrogate pair
_strDefault = fallback.DefaultString + fallback.DefaultString;
}
// Fallback Methods
public override bool Fallback(char charUnknown, int index)
{
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
if (_fallbackCount >= 1)
{
// If we're recursive we may still have something in our buffer that makes this a surrogate
if (char.IsHighSurrogate(charUnknown) && _fallbackCount >= 0 &&
char.IsLowSurrogate(_strDefault[_fallbackIndex + 1]))
ThrowLastCharRecursive(Char.ConvertToUtf32(charUnknown, _strDefault[_fallbackIndex + 1]));
// Nope, just one character
ThrowLastCharRecursive(unchecked((int)charUnknown));
}
// Go ahead and get our fallback
// Divide by 2 because we aren't a surrogate pair
_fallbackCount = _strDefault.Length / 2;
_fallbackIndex = -1;
return _fallbackCount != 0;
}
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
{
// Double check input surrogate pair
if (!Char.IsHighSurrogate(charUnknownHigh))
throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF));
if (!Char.IsLowSurrogate(charUnknownLow))
throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF));
Contract.EndContractBlock();
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
if (_fallbackCount >= 1)
ThrowLastCharRecursive(Char.ConvertToUtf32(charUnknownHigh, charUnknownLow));
// Go ahead and get our fallback
_fallbackCount = _strDefault.Length;
_fallbackIndex = -1;
return _fallbackCount != 0;
}
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
_fallbackCount--;
_fallbackIndex++;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (_fallbackCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (_fallbackCount == int.MaxValue)
{
_fallbackCount = -1;
return '\0';
}
// Now make sure its in the expected range
Debug.Assert(_fallbackIndex < _strDefault.Length && _fallbackIndex >= 0,
"Index exceeds buffer range");
return _strDefault[_fallbackIndex];
}
public override bool MovePrevious()
{
// Back up one, only if we just processed the last character (or earlier)
if (_fallbackCount >= -1 && _fallbackIndex >= 0)
{
_fallbackIndex--;
_fallbackCount++;
return true;
}
// Return false 'cause we couldn't do it.
return false;
}
// How many characters left to output?
public override int Remaining
{
get
{
// Our count is 0 for 1 character left.
return (_fallbackCount < 0) ? 0 : _fallbackCount;
}
}
// Clear the buffer
public override unsafe void Reset()
{
_fallbackCount = -1;
_fallbackIndex = 0;
charStart = null;
bFallingBack = false;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace DbgEng
{
[ComImport, Guid("D98ADA1F-29E9-4EF5-A6C0-E53349883212"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDebugDataSpaces4 : IDebugDataSpaces3
{
#pragma warning disable CS0108 // XXX hides inherited member. This is COM default.
#region IDebugDataSpaces
void ReadVirtual(
[In] ulong Offset,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesRead);
void WriteVirtual(
[In] ulong Offset,
[In] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesWritten);
ulong SearchVirtual(
[In] ulong Offset,
[In] ulong Length,
[In] IntPtr Pattern,
[In] uint PatternSize,
[In] uint PatternGranularity);
void ReadVirtualUncached(
[In] ulong Offset,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesRead);
void WriteVirtualUncached(
[In] ulong Offset,
[In] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesWritten);
ulong ReadPointersVirtual(
[In] uint Count,
[In] ulong Offset);
void WritePointersVirtual(
[In] uint Count,
[In] ulong Offset,
[In] ref ulong Ptrs);
void ReadPhysical(
[In] ulong Offset,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesRead);
void WritePhysical(
[In] ulong Offset,
[In] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesWritten);
void ReadControl(
[In] uint Processor,
[In] ulong Offset,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesRead);
void WriteControl(
[In] uint Processor,
[In] ulong Offset,
[In] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesWritten);
void ReadIo(
[In] uint InterfaceType,
[In] uint BusNumber,
[In] uint AddressSpace,
[In] ulong Offset,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesRead);
void WriteIo(
[In] uint InterfaceType,
[In] uint BusNumber,
[In] uint AddressSpace,
[In] ulong Offset,
[In] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesWritten);
ulong ReadMsr(
[In] uint Msr);
void WriteMsr(
[In] uint Msr,
[In] ulong Value);
void ReadBusData(
[In] uint BusDataType,
[In] uint BusNumber,
[In] uint SlotNumber,
[In] uint Offset,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesRead);
void WriteBusData(
[In] uint BusDataType,
[In] uint BusNumber,
[In] uint SlotNumber,
[In] uint Offset,
[In] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesWritten);
void CheckLowMemory();
void ReadDebuggerData(
[In] uint Index,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint DataSize);
void ReadProcessorSystemData(
[In] uint Processor,
[In] uint Index,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint DataSize);
#endregion
#region IDebugDataSpaces2
ulong VirtualToPhysical(
[In] ulong Virtual);
void GetVirtualTranslationPhysicalOffsets(
[In] ulong Virtual,
[Out] out ulong Offsets,
[In] uint OffsetsSize,
[Out] out uint Levels);
void ReadHandleData(
[In] ulong Handle,
[In] uint DataType,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint DataSize);
void FillVirtual(
[In] ulong Start,
[In] uint Size,
[In] IntPtr Pattern,
[In] uint PatternSize,
[Out] out uint Filled);
void FillPhysical(
[In] ulong Start,
[In] uint Size,
[In] IntPtr Pattern,
[In] uint PatternSize,
[Out] out uint Filled);
_MEMORY_BASIC_INFORMATION64 QueryVirtual(
[In] ulong Offset);
#endregion
#region IDebugDataSpaces3
_IMAGE_NT_HEADERS64 ReadImageNtHeaders(
[In] ulong ImageBase);
void ReadTagged(
[In] ref Guid Tag,
[In] uint Offset,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint TotalSize);
ulong StartEnumTagged();
void GetNextTagged(
[In] ulong Handle,
out Guid Tag,
out uint Size);
void EndEnumTagged(
[In] ulong Handle);
#endregion
#pragma warning restore CS0108 // XXX hides inherited member. This is COM default.
void GetOffsetInformation(
[In] uint Space,
[In] uint Which,
[In] ulong Offset,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint InfoSize);
ulong GetNextDifferentlyValidOffsetVirtual(
[In] ulong Offset);
void GetValidRegionVirtual(
[In] ulong Base,
[In] uint Size,
[Out] out ulong ValidBase,
[Out] out uint ValidSize);
ulong SearchVirtual2(
[In] ulong Offset,
[In] ulong Length,
[In] uint Flags,
[In] IntPtr Pattern,
[In] uint PatternSize,
[In] uint PatternGranularity);
void ReadMultiByteStringVirtual(
[In] ulong Offset,
[In] uint MaxBytes,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint StringBytes);
void ReadMultiByteStringVirtualWide(
[In] ulong Offset,
[In] uint MaxBytes,
[In] uint CodePage,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint StringBytes);
void ReadUnicodeStringVirtual(
[In] ulong Offset,
[In] uint MaxBytes,
[In] uint CodePage,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint StringBytes);
void ReadUnicodeStringVirtualWide(
[In] ulong Offset,
[In] uint MaxBytes,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint StringBytes);
void ReadPhysical2(
[In] ulong Offset,
[In] uint Flags,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesRead);
void WritePhysical2(
[In] ulong Offset,
[In] uint Flags,
[In] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesWritten);
}
}
| |
/*
* nMQTT, a .Net MQTT v3 client implementation.
* http://wiki.github.com/markallanson/nmqtt
*
* Copyright (c) 2009 Mark Allanson (mark@markallanson.net) & Contributors
*
* Licensed under the MIT License. You may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/mit-license.php
*/
using System;
using System.IO;
using Nmqtt.Encoding;
using Nmqtt.ExtensionMethods;
namespace Nmqtt
{
/// <summary>
/// Represents the base class for the Variable Header portion of some MQTT Messages.
/// </summary>
internal class MqttVariableHeader
{
private int length;
/// <summary>
/// The length, in bytes, consumed by the variable header.
/// </summary>
public int Length {
get {
// TODO: improve the way that we calculate the variable header length somehow
return length;
}
}
public string ProtocolName { get; set; }
public byte ProtocolVersion { get; set; }
public MqttConnectFlags ConnectFlags { get; set; }
/// <summary>
/// Defines the maximum allowable lag, in seconds, between expected messages.
/// </summary>
/// <remarks>
/// The spec indicates that clients won't be disconnected until KeepAlive + 1/2 KeepAlive time period
/// elapses.
/// </remarks>
public short KeepAlive { get; set; }
public MqttConnectReturnCode ReturnCode { get; set; }
public string TopicName { get; set; }
public short MessageIdentifier { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MqttVariableHeader" /> class.
/// </summary>
public MqttVariableHeader() {
this.ProtocolName = "MQIsdp";
this.ProtocolVersion = 3;
this.ConnectFlags = new MqttConnectFlags();
}
/// <summary>
/// Initializes a new instance of the <see cref="MqttVariableHeader" /> class, populating it with data from a stream.
/// </summary>
/// <param name="headerStream">The stream containing the variable header.</param>
public MqttVariableHeader(Stream headerStream) {
ReadFrom(headerStream);
}
/// <summary>
/// Gets the Read Flags used during message deserialization
/// </summary>
protected virtual ReadWriteFlags ReadFlags {
get { return 0; }
}
/// <summary>
/// Gets the write flags used during message serialization
/// </summary>
protected virtual ReadWriteFlags WriteFlags {
get { return 0; }
}
/// <summary>
/// Writes the variable header to the supplied stream.
/// </summary>
/// <param name="variableHeaderStream">The stream to write the variable header to.</param>
/// <remarks>
/// This base implementation uses the WriteFlags property that can be
/// overridden in subclasses to determine what to read from the variable header.
/// A subclass can override this method to do completely custom read operations
/// if required.
/// </remarks>
public virtual void WriteTo(Stream variableHeaderStream) {
if ((WriteFlags & ReadWriteFlags.ProtocolName) == ReadWriteFlags.ProtocolName) {
WriteProtocolName(variableHeaderStream);
}
if ((WriteFlags & ReadWriteFlags.ProtocolVersion) == ReadWriteFlags.ProtocolVersion) {
WriteProtocolVersion(variableHeaderStream);
}
if ((WriteFlags & ReadWriteFlags.ConnectFlags) == ReadWriteFlags.ConnectFlags) {
WriteConnectFlags(variableHeaderStream);
}
if ((WriteFlags & ReadWriteFlags.KeepAlive) == ReadWriteFlags.KeepAlive) {
WriteKeepAlive(variableHeaderStream);
}
if ((WriteFlags & ReadWriteFlags.ReturnCode) == ReadWriteFlags.ReturnCode) {
WriteReturnCode(variableHeaderStream);
}
if ((WriteFlags & ReadWriteFlags.TopicName) == ReadWriteFlags.TopicName) {
WriteTopicName(variableHeaderStream);
}
if ((WriteFlags & ReadWriteFlags.MessageIdentifier) == ReadWriteFlags.MessageIdentifier) {
WriteMessageIdentifier(variableHeaderStream);
}
}
/// <summary>
/// Creates a variable header from the specified header stream.
/// </summary>
/// <param name="variableHeaderStream">The stream to read the variable header from.</param>
/// <remarks>
/// This base implementation uses the ReadFlags property that can be
/// overridden in subclasses to determine what to read from the variable header.
/// A subclass can override this method to do completely custom read operations
/// if required.
/// </remarks>
public virtual void ReadFrom(Stream variableHeaderStream) {
if ((ReadFlags & ReadWriteFlags.ProtocolName) == ReadWriteFlags.ProtocolName) {
ReadProtocolName(variableHeaderStream);
}
if ((ReadFlags & ReadWriteFlags.ProtocolVersion) == ReadWriteFlags.ProtocolVersion) {
ReadProtocolVersion(variableHeaderStream);
}
if ((ReadFlags & ReadWriteFlags.ConnectFlags) == ReadWriteFlags.ConnectFlags) {
ReadConnectFlags(variableHeaderStream);
}
if ((ReadFlags & ReadWriteFlags.KeepAlive) == ReadWriteFlags.KeepAlive) {
ReadKeepAlive(variableHeaderStream);
}
if ((ReadFlags & ReadWriteFlags.ReturnCode) == ReadWriteFlags.ReturnCode) {
ReadReturnCode(variableHeaderStream);
}
if ((ReadFlags & ReadWriteFlags.TopicName) == ReadWriteFlags.TopicName) {
ReadTopicName(variableHeaderStream);
}
if ((ReadFlags & ReadWriteFlags.MessageIdentifier) == ReadWriteFlags.MessageIdentifier) {
ReadMessageIdentifier(variableHeaderStream);
}
}
/// <summary>
/// Gets the length of the write data when WriteTo will be called.
/// </summary>
/// <returns>The length of data witten by the call to GetWriteLength</returns>
public virtual int GetWriteLength() {
int headerLength = 0;
var enc = new MqttEncoding();
if ((WriteFlags & ReadWriteFlags.ProtocolName) == ReadWriteFlags.ProtocolName) {
headerLength += enc.GetByteCount(ProtocolName);
}
if ((WriteFlags & ReadWriteFlags.ProtocolVersion) == ReadWriteFlags.ProtocolVersion) {
headerLength += sizeof (byte);
}
if ((WriteFlags & ReadWriteFlags.ConnectFlags) == ReadWriteFlags.ConnectFlags) {
headerLength += MqttConnectFlags.GetWriteLength();
}
if ((WriteFlags & ReadWriteFlags.KeepAlive) == ReadWriteFlags.KeepAlive) {
headerLength += sizeof (short);
}
if ((WriteFlags & ReadWriteFlags.ReturnCode) == ReadWriteFlags.ReturnCode) {
headerLength += sizeof (byte);
}
if ((WriteFlags & ReadWriteFlags.TopicName) == ReadWriteFlags.TopicName) {
headerLength += enc.GetByteCount(TopicName.ToString());
}
if ((WriteFlags & ReadWriteFlags.MessageIdentifier) == ReadWriteFlags.MessageIdentifier) {
headerLength += sizeof (short);
}
return headerLength;
}
protected void WriteProtocolName(Stream stream) {
stream.WriteMqttString(ProtocolName);
}
protected void WriteProtocolVersion(Stream stream) {
stream.WriteByte(ProtocolVersion);
}
protected void WriteKeepAlive(Stream stream) {
stream.WriteShort(KeepAlive);
}
protected void WriteReturnCode(Stream stream) {
stream.WriteByte((byte) ReturnCode);
}
protected void WriteTopicName(Stream stream) {
stream.WriteMqttString(TopicName.ToString());
}
protected void WriteMessageIdentifier(Stream stream) {
stream.WriteShort(MessageIdentifier);
}
protected void WriteConnectFlags(Stream stream) {
ConnectFlags.WriteTo(stream);
}
protected void ReadProtocolName(Stream stream) {
ProtocolName = stream.ReadMqttString();
length += ProtocolName.Length + 2; // 2 for length short at front of string
}
protected void ReadProtocolVersion(Stream stream) {
ProtocolVersion = (byte) stream.ReadByte();
length++;
}
protected void ReadKeepAlive(Stream stream) {
KeepAlive = stream.ReadShort();
length += 2;
}
protected void ReadReturnCode(Stream stream) {
ReturnCode = (MqttConnectReturnCode) stream.ReadByte();
length++;
}
protected void ReadTopicName(Stream stream) {
TopicName = stream.ReadMqttString();
length += TopicName.Length + 2; // 2 for length short at front of string.
}
protected void ReadMessageIdentifier(Stream stream) {
MessageIdentifier = stream.ReadShort();
length += 2;
}
protected void ReadConnectFlags(Stream stream) {
ConnectFlags = new MqttConnectFlags(stream);
length += 1;
}
/// <summary>
/// Enumeration used by subclasses to tell the variable header what should be read from the underlying stream.
/// </summary>
[Flags]
protected enum ReadWriteFlags
{
ProtocolName = 1,
ProtocolVersion = 2,
ConnectFlags = 4,
KeepAlive = 8,
ReturnCode = 16,
TopicName = 32,
MessageIdentifier = 64
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Bloom.Api;
using Bloom.Book;
using Bloom.Collection;
using L10NSharp;
using SIL.IO;
using SIL.Reporting;
namespace Bloom
{
/// <summary>
/// This class is a more complex version of LibPalaso's FileLocator class. It handles finding files in collections the user
/// has installed, which we (sometimes) want to do. We decided to just copy some of the implementation of that class,
/// rather than continuing to complicate it with hooks to allow Bloom to customize it.
/// </summary>
public class BloomFileLocator : IChangeableFileLocator
{
private readonly CollectionSettings _collectionSettings;
private readonly XMatterPackFinder _xMatterPackFinder;
private readonly IEnumerable<string> _factorySearchPaths;
private readonly List<string> _bookSpecificSearchPaths;
private readonly IEnumerable<string> _userInstalledSearchPaths;
private readonly IEnumerable<string> _afterXMatterSearchPaths;
public static string BrowserRoot
{
get
{
return Directory.Exists(Path.Combine(FileLocationUtilities.DirectoryOfApplicationOrSolution,"output")) ? "output"+Path.DirectorySeparatorChar+"browser" : "browser";
}
}
public static BloomFileLocator sTheMostRecentBloomFileLocator;
public BloomFileLocator(CollectionSettings collectionSettings, XMatterPackFinder xMatterPackFinder, IEnumerable<string> factorySearchPaths, IEnumerable<string> userInstalledSearchPaths,
IEnumerable<string> afterXMatterSearchPaths = null)
{
if (afterXMatterSearchPaths == null)
{
afterXMatterSearchPaths = new string[] {};
}
_bookSpecificSearchPaths = new List<string>();
_collectionSettings = collectionSettings;
_xMatterPackFinder = xMatterPackFinder;
_factorySearchPaths = factorySearchPaths;
_userInstalledSearchPaths = userInstalledSearchPaths;
_afterXMatterSearchPaths = afterXMatterSearchPaths;
sTheMostRecentBloomFileLocator = this;
}
public void AddPath(string path)
{
_bookSpecificSearchPaths.Add(path);
ClearLocateDirectoryCache();
}
public void RemovePath(string path)
{
_bookSpecificSearchPaths.Remove(path);
ClearLocateDirectoryCache();
}
public string LocateFile(string fileName)
{
foreach (var path in GetSearchPaths(fileName))
{
var fullPath = Path.Combine(path, fileName);
if (File.Exists(fullPath))
return fullPath;
}
return string.Empty;
}
/// <summary>
/// These are used (as of 26 aug 2016) only by LibPalaso's FileLocationUtilities.LocateFile(). Not used by GetFileDistributedWIthApplication().
/// </summary>
/// <returns></returns>
protected IEnumerable<string> GetSearchPaths(string fileName = null)
{
yield return BloomFileLocator.BrowserRoot;
//The versions of the files that come with the program should always win out.
//NB: This should not include any sample books.
foreach (var searchPath in _factorySearchPaths)
{
yield return searchPath;
}
//Note: the order here has major ramifications, as it's quite common to have mutliple copies of the same file around
//in several of our locations.
//For example, if do this:
// return base.GetSearchPaths().Concat(paths);
//Then we will favor the paths known to the base class over those we just compiled in the lines above.
//One particular bug that came out of that was when a custom xmatter (because of a previous bug) snuck into the
//Sample "Vaccinations" book, then *that* copy of the xmatter was always used, becuase it was found first.
// So, first we want to try the factory xmatter paths. These have precedence over factory templates.
foreach (var xMatterInfo in _xMatterPackFinder.Factory)
{
//NB: if we knew what the xmatter pack they wanted, we could limit to that. for now, we just iterate over all of
//them and rely (reasonably) on the names being unique
//this is a bit weird... we include the parent, in case they're looking for the xmatter *folder*, and the folder
//itself, in case they're looking for something inside it
yield return xMatterInfo.PathToFolder;
yield return Path.GetDirectoryName(xMatterInfo.PathToFolder);
}
// On the other hand the remaining factory stuff has precedence over non-factory XMatter.
foreach (var searchPath in _afterXMatterSearchPaths)
{
yield return searchPath;
}
foreach (var xMatterInfo in _xMatterPackFinder.CustomInstalled)
{
//this is a bit weird... we include the parent, in case they're looking for the xmatter *folder*, and the folder
//itself, in case they're looking for something inside it
yield return xMatterInfo.PathToFolder;
yield return Path.GetDirectoryName(xMatterInfo.PathToFolder);
}
//REVIEW: this one is just a big grab bag of all folders we find in their programdata, installed stuff. This could be insufficient.
if (ShouldSearchInstalledCollectionsForFile(fileName))
{
foreach (var searchPath in _userInstalledSearchPaths)
{
yield return searchPath;
}
}
//Book-specific paths (added by AddPath()) are last because we want people to get the latest stylesheet,
//not just the version the had when they made the book.
//This may seem counter-intuitive. One scenario, which has played out many times, is that the
//book has been started, and the customer requests some change to the stylesheet, which we deliver just by having them
//double-click a bloompack.
//Another scenario is that a new version of Bloom comes out that expects/needs the newer stylesheet
foreach (var searchPath in _bookSpecificSearchPaths)
{
yield return searchPath;
}
if (_collectionSettings.FolderPath != null) // typically only in tests, but makes more robust anyway
yield return _collectionSettings.FolderPath;
}
bool ShouldSearchInstalledCollectionsForFile(string fileName)
{
if (fileName == null)
return true; // default if we weren't given the filename
// We definitely don't want to get random versions of these files from some arbitrary installed collection.
// Enhance: we're thinking of switching to some sort of "whitelist" approach, where only particular
// groups of files (e.g., *-template.css) would be looked for in these locations. There is significant
// danger of finding something irrelevant, and also, of hard-to-reproduce bugs that don't happen because
// the developer has different installed collections than the reporter.
return !fileName.Contains("defaultLangStyles.css")
&& !fileName.Contains("customCollectionStyles.css")
&& fileName != "customBookStyles.css";
}
public IFileLocator CloneAndCustomize(IEnumerable<string> addedSearchPaths)
{
var locator= new BloomFileLocator(_collectionSettings, _xMatterPackFinder,_factorySearchPaths, _userInstalledSearchPaths, _afterXMatterSearchPaths);
foreach (var path in _bookSpecificSearchPaths)
{
locator.AddPath(path);
}
foreach (var path in addedSearchPaths)
{
locator.AddPath(path);
}
return locator;
}
public static string GetBrowserFile(bool optional, params string[] parts)
{
parts[0] = Path.Combine(BrowserRoot,parts[0]);
return FileLocationUtilities.GetFileDistributedWithApplication(optional, parts);
}
public static string GetBrowserDirectory(params string[] parts)
{
parts[0] = Path.Combine(BrowserRoot, parts[0]);
return FileLocationUtilities.GetDirectoryDistributedWithApplication(false, parts);
}
public static string GetOptionalBrowserDirectory(params string[] parts)
{
parts[0] = Path.Combine(BrowserRoot, parts[0]);
return FileLocationUtilities.GetDirectoryDistributedWithApplication(true, parts);
}
public static string GetFactoryXMatterDirectory()
{
return BloomFileLocator.GetBrowserDirectory("templates","xMatter");
}
public static string GetProjectSpecificInstalledXMatterDirectory()
{
return BloomFileLocator.GetBrowserDirectory("templates","xMatter","project-specific");
}
public static string GetCustomXMatterDirectory()
{
return BloomFileLocator.GetBrowserDirectory("templates","customXMatter");
}
public static string FactoryTemplateBookDirectory
{
get { return BloomFileLocator.GetBrowserDirectory("templates", "template books"); }
}
public static string SampleShellsDirectory
{
get { return GetBrowserDirectory("templates", "Sample Shells"); }
}
/// <summary>
/// contains both the template books and the sample shells
/// </summary>
public static string FactoryCollectionsDirectory {
get
{
return GetBrowserDirectory("templates");
}
}
public static string GetFactoryBookTemplateDirectory(string bookName)
{
return Path.Combine(FactoryTemplateBookDirectory, bookName);
}
/// <summary>
/// Get the pathname of the directory containing the executing assembly (Bloom.exe).
/// </summary>
public static string GetCodeBaseFolder()
{
var file = Assembly.GetExecutingAssembly().CodeBase.Replace("file://", string.Empty);
if (SIL.PlatformUtilities.Platform.IsWindows)
file = file.TrimStart('/');
return Path.GetDirectoryName(file);
}
/// <summary>
/// Check whether this file was installed with Bloom (and likely to be read-only on Linux or for allUsers install).
/// </summary>
public static bool IsInstalledFileOrDirectory(string filepath)
{
var folder = GetCodeBaseFolder();
var slash = Path.DirectorySeparatorChar;
if (folder.EndsWith($"{slash}output{slash}Debug"))
folder = folder.Replace($"{slash}Debug", string.Empty); // files now copied to output/browser for access
return filepath.Contains(folder);
}
/// <summary>
/// This can be used to find the best localized file when there is only one file with the given name,
/// and the file is part of the files distributed with Bloom (i.e., not something in a downloaded template).
/// </summary>
public static string GetBestLocalizableFileDistributedWithApplication(bool existenceOfEnglishVersionIsOptional, params string[] partsOfEnglishFilePath)
{
// at this time, FileLocator does not have a way for the app to actually tell it where to find things distributed
// with the application...
var englishPath = FileLocationUtilities.GetFileDistributedWithApplication(true, partsOfEnglishFilePath);
// ... so if it doesn't find it, we have to keep looking
if (string.IsNullOrWhiteSpace(englishPath))
{
//this one will throw if we still can't find it and existenceOfEnglishVersionIsOptional is false
englishPath = BloomFileLocator.GetBrowserFile(existenceOfEnglishVersionIsOptional, partsOfEnglishFilePath);
}
if (!RobustFile.Exists(englishPath))
{
return englishPath; // just return whatever the original GetFileDistributedWithApplication gave. "", null, whatever it is.
}
return BloomFileLocator.GetBestLocalizedFile(englishPath);
}
/// <summary>
/// If there is a file sitting next to the english one with the desired language, get that path.
/// Otherwise, returns the English path.
/// </summary>
public static string GetBestLocalizedFile(string pathToEnglishFile)
{
var langId = LocalizationManager.UILanguageId;
var pathInDesiredLanguage = pathToEnglishFile.Replace("-en.", "-" + langId + ".");
if (RobustFile.Exists(pathInDesiredLanguage))
return pathInDesiredLanguage;
if (langId.Contains('-'))
{
// Ignore any country (or script) code to see if we can find a match to the generic language.
langId = langId.Substring(0, langId.IndexOf('-'));
pathInDesiredLanguage = pathToEnglishFile.Replace("-en.", "-" + langId + ".");
if (RobustFile.Exists(pathInDesiredLanguage))
return pathInDesiredLanguage;
}
return pathToEnglishFile; // can't find a localized version, fall back to English
}
/// <summary>
/// Gets a file in the specified branding folder
/// </summary>
/// <param name="brandingNameOrFolderPath"> Normally, the branding is just a name, which we look up in the official branding folder
// but unit tests can instead provide a path to the folder.
/// </param>
/// <param name="fileName"></param>
/// <returns></returns>
public static string GetOptionalBrandingFile(string brandingNameOrFolderPath, string fileName)
{
if(Path.IsPathRooted(brandingNameOrFolderPath)) //if it looks like a path
{
var path = Path.Combine(brandingNameOrFolderPath, fileName);
if(RobustFile.Exists(path))
return path;
return null;
}
if (Path.IsPathRooted(fileName) && RobustFile.Exists(fileName)) // also just for unit tests
return fileName;
return BloomFileLocator.GetBrowserFile(true, "branding", brandingNameOrFolderPath, fileName);
}
public static string GetBrandingFolder(string fullBrandingName)
{
BrandingSettings.ParseBrandingKey(fullBrandingName, out var brandingFolderName, out var flavor);
return BloomFileLocator.GetOptionalBrowserDirectory("branding", brandingFolderName);
}
public string GetBrandingFile(Boolean optional, string fileName)
{
return BloomFileLocator.GetBrowserFile(optional, "branding", _collectionSettings.GetBrandingFolderName(), fileName);
}
//-----------------------------------------------------
// Copied mostly unchanged from libpalaso/FileLocationUtilities. Bloom may not actually need all of these.
//----------------------------------------------------
Dictionary<string, string> _mapDirectoryNameToPath = new Dictionary<string, string>();
private void ClearLocateDirectoryCache()
{
_mapDirectoryNameToPath.Clear();
}
public string LocateDirectory(string directoryName)
{
if (_mapDirectoryNameToPath.TryGetValue(directoryName, out string result))
return result;
// Because GetSearchPaths is not being passed a file name, it won't search
// in the user-installed directories, and the other places is searches shouldn't
// change without restarting Bloom or calling things that clear the cache.
foreach (var path in GetSearchPaths())
{
var fullPath = Path.Combine(path, directoryName);
if (Directory.Exists(fullPath))
{
_mapDirectoryNameToPath[directoryName] = fullPath;
return fullPath;
}
}
_mapDirectoryNameToPath[directoryName] = string.Empty;
return string.Empty;
}
public string LocateDirectory(string directoryName, string descriptionForErrorMessage)
{
var path = LocateDirectory(directoryName);
if (string.IsNullOrEmpty(path) || !Directory.Exists(path))
{
ErrorReport.NotifyUserOfProblem(
"{0} could not find the {1}. It expected to find it in one of these locations: {2}",
UsageReporter.AppNameToUseInDialogs, descriptionForErrorMessage, string.Join(", ", GetSearchPaths())
);
}
return path;
}
public string LocateDirectoryWithThrow(string directoryName)
{
var path = LocateDirectory(directoryName);
if (string.IsNullOrEmpty(path) || !Directory.Exists(path))
{
throw new ApplicationException(String.Format("Could not find {0}. It expected to find it in one of these locations: {1}",
directoryName, string.Join(Environment.NewLine, GetSearchPaths())));
}
return path;
}
public string LocateFile(string fileName, string descriptionForErrorMessage)
{
var path = LocateFile(fileName);
if (string.IsNullOrEmpty(path) || !File.Exists(path))
{
ErrorReport.NotifyUserOfProblem(
"{0} could not find the {1}. It expected to find it in one of these locations: {2}",
UsageReporter.AppNameToUseInDialogs, descriptionForErrorMessage, string.Join(", ", GetSearchPaths(fileName))
);
}
return path;
}
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <returns>null if not found</returns>
public string LocateOptionalFile(string fileName)
{
var path = LocateFile(fileName);
if (string.IsNullOrEmpty(path) || !File.Exists(path))
{
return null;
}
return path;
}
/// <summary>
/// Throws ApplicationException if not found.
/// </summary>
public string LocateFileWithThrow(string fileName)
{
var path = LocateFile(fileName);
if (string.IsNullOrEmpty(path) || !File.Exists(path))
{
throw new ApplicationException("Could not find " + fileName + ". It expected to find it in one of these locations: " + Environment.NewLine + string.Join(Environment.NewLine, GetSearchPaths(fileName)));
}
return path;
}
}
}
| |
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
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.
****************************************************************************/
// root name of xml
using System;
using CocosSharp;
using System.IO;
#if !WINDOWS && !MACOS && !LINUX && !NETFX_CORE
using System.IO.IsolatedStorage;
#endif
#if NETFX_CORE
using Microsoft.Xna.Framework.Storage;
#endif
using System.Collections.Generic;
using System.Text;
using System.Xml;
// Note: Something to use here http://msdn.microsoft.com/en-us/library/hh582102.aspx
namespace CocosSharp
{
public class CCUserDefault
{
static CCUserDefault UserDefault = null;
static string USERDEFAULT_ROOT_NAME = "userDefaultRoot";
static string XML_FILE_NAME = "UserDefault.xml";
#if !WINDOWS && !MACOS && !LINUX && !NETFX_CORE
IsolatedStorageFile myIsolatedStorage;
#elif NETFX_CORE
StorageContainer myIsolatedStorage;
StorageDevice myDevice;
#endif
Dictionary<string, string> values = new Dictionary<string, string>();
#region Properties
public static CCUserDefault SharedUserDefault
{
get {
if (UserDefault == null)
{
UserDefault = new CCUserDefault();
}
return UserDefault;
}
}
#endregion Properties
#if NETFX_CORE
private StorageDevice CheckStorageDevice() {
if(myDevice != null) {
return(myDevice);
}
var result = StorageDevice.BeginShowSelector(null, null);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
myDevice = StorageDevice.EndShowSelector(result);
if(myDevice != null) {
result =
myDevice.BeginOpenContainer(XML_FILE_NAME, null, null);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
myIsolatedStorage = myDevice.EndOpenContainer(result);
// Close the wait handle.
result.AsyncWaitHandle.Dispose();
}
return(myDevice);
}
#endif
#region Constructors
CCUserDefault()
{
#if NETFX_CORE
if(myIsolatedStorage == null) {
CheckStorageDevice();
}
if(myIsolatedStorage != null)
{
// only create xml file once if it doesnt exist
if ((!IsXMLFileExist()))
{
CreateXMLFile();
}
using (Stream s = myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.OpenOrCreate))
{
ParseXMLFile(s);
}
}
#elif WINDOWS || MACOS || LINUX || WINDOWSGL
// only create xml file once if it doesnt exist
if ((!IsXMLFileExist())) {
CreateXMLFile();
}
using (FileStream fileStream = new FileInfo(XML_FILE_NAME).OpenRead()){
ParseXMLFile(fileStream);
}
#else
myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
// only create xml file once if it doesnt exist
if ((!IsXMLFileExist())) {
CreateXMLFile();
}
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.Open, FileAccess.Read)) {
ParseXMLFile(fileStream);
}
#endif
}
#endregion Constructors
public void PurgeSharedUserDefault()
{
UserDefault = null;
}
bool ParseXMLFile(Stream xmlFile)
{
values.Clear();
string key = "";
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(xmlFile)) {
// Parse the file and display each of the nodes.
while (reader.Read()) {
switch (reader.NodeType) {
case XmlNodeType.Element:
key = reader.Name;
break;
case XmlNodeType.Text:
values.Add(key, reader.Value);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
break;
case XmlNodeType.Comment:
break;
case XmlNodeType.EndElement:
break;
}
}
}
return true;
}
string GetValueForKey(string key)
{
string value = null;
if (! values.TryGetValue(key, out value)) {
value = null;
}
return value;
}
void SetValueForKey(string key, string value)
{
values[key] = value;
}
public bool GetBoolForKey(string key, bool defaultValue=false)
{
string value = GetValueForKey(key);
bool ret = defaultValue;
if (value != null)
{
ret = bool.Parse(value);
}
return ret;
}
public int GetIntegerForKey(string key, int defaultValue=0)
{
string value = GetValueForKey(key);
int ret = defaultValue;
if (value != null)
{
ret = CCUtils.CCParseInt(value);
}
return ret;
}
public float GetFloatForKey(string key, float defaultValue)
{
float ret = (float)GetDoubleForKey(key, (double)defaultValue);
return ret;
}
public double GetDoubleForKey(string key, double defaultValue)
{
string value = GetValueForKey(key);
double ret = defaultValue;
if (value != null)
{
ret = double.Parse(value);
}
return ret;
}
public string GetStringForKey(string key, string defaultValue)
{
string value = GetValueForKey(key);
string ret = defaultValue;
if (value != null)
{
ret = value;
}
return ret;
}
public void SetBoolForKey(string key, bool value)
{
// check key
if (key == null) {
return;
}
// save bool value as string
SetStringForKey(key, value.ToString());
}
public void SetIntegerForKey(string key, int value)
{
// check key
if (key == null)
{
return;
}
// convert to string
SetValueForKey(key, value.ToString());
}
public void SetFloatForKey(string key, float value)
{
SetDoubleForKey(key, value);
}
public void SetDoubleForKey(string key, double value)
{
// check key
if (key == null)
{
return;
}
// convert to string
SetValueForKey(key, value.ToString());
}
public void SetStringForKey(string key, string value)
{
// check key
if (key == null)
{
return;
}
// convert to string
SetValueForKey(key, value.ToString());
}
bool IsXMLFileExist()
{
bool bRet = false;
#if NETFX_CORE
// use the StorageContainer to determine if the file exists.
if (myIsolatedStorage.FileExists(XML_FILE_NAME))
{
bRet = true;
}
#elif WINDOWS || LINUX || MACOS || WINDOWSGL
if (new FileInfo(XML_FILE_NAME).Exists)
{
bRet = true;
}
#else
if (myIsolatedStorage.FileExists(XML_FILE_NAME))
{
bRet = true;
}
#endif
return bRet;
}
bool CreateXMLFile()
{
bool bRet = false;
#if NETFX_CORE
using (StreamWriter writeFile = new StreamWriter(myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.Create)))
#elif WINDOWS || LINUX || MACOS || WINDOWSGL
using (StreamWriter writeFile = new StreamWriter(XML_FILE_NAME))
#else
using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(XML_FILE_NAME, FileMode.Create, FileAccess.Write, myIsolatedStorage)))
#endif
{
string someTextData = "<?xml version=\"1.0\" encoding=\"utf-8\"?><userDefaultRoot>";
writeFile.WriteLine(someTextData);
// Do not write anything here. This just creates the temporary xml save file.
writeFile.WriteLine("</userDefaultRoot>");
}
return bRet;
}
public void Flush()
{
#if NETFX_CORE
using (Stream stream = myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.Create))
#elif WINDOWS || LINUX || MACOS || WINDOWSGL
using (StreamWriter stream = new StreamWriter(XML_FILE_NAME))
#else
using (StreamWriter stream = new StreamWriter(new IsolatedStorageFileStream(XML_FILE_NAME, FileMode.Create, FileAccess.Write, myIsolatedStorage)))
#endif
{
//create xml doc
XmlWriterSettings ws = new XmlWriterSettings();
ws.Encoding = Encoding.UTF8;
ws.Indent = true;
using (XmlWriter writer = XmlWriter.Create(stream, ws))
{
writer.WriteStartDocument();
writer.WriteStartElement(USERDEFAULT_ROOT_NAME);
foreach (KeyValuePair<string, string> pair in values)
{
writer.WriteStartElement(pair.Key);
writer.WriteString(pair.Value);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
namespace Fungus.EditorUtils
{
[CustomEditor (typeof(Say))]
public class SayEditor : CommandEditor
{
public static bool showTagHelp;
public Texture2D blackTex;
public static void DrawTagHelpLabel()
{
string tagsText = TextTagParser.GetTagHelp();
if (CustomTag.activeCustomTags.Count > 0)
{
tagsText += "\n\n\t-------- CUSTOM TAGS --------";
List<Transform> activeCustomTagGroup = new List<Transform>();
foreach (CustomTag ct in CustomTag.activeCustomTags)
{
if(ct.transform.parent != null)
{
if (!activeCustomTagGroup.Contains(ct.transform.parent.transform))
{
activeCustomTagGroup.Add(ct.transform.parent.transform);
}
}
else
{
activeCustomTagGroup.Add(ct.transform);
}
}
foreach(Transform parent in activeCustomTagGroup)
{
string tagName = parent.name;
string tagStartSymbol = "";
string tagEndSymbol = "";
CustomTag parentTag = parent.GetComponent<CustomTag>();
if (parentTag != null)
{
tagName = parentTag.name;
tagStartSymbol = parentTag.TagStartSymbol;
tagEndSymbol = parentTag.TagEndSymbol;
}
tagsText += "\n\n\t" + tagStartSymbol + " " + tagName + " " + tagEndSymbol;
foreach(Transform child in parent)
{
tagName = child.name;
tagStartSymbol = "";
tagEndSymbol = "";
CustomTag childTag = child.GetComponent<CustomTag>();
if (childTag != null)
{
tagName = childTag.name;
tagStartSymbol = childTag.TagStartSymbol;
tagEndSymbol = childTag.TagEndSymbol;
}
tagsText += "\n\t " + tagStartSymbol + " " + tagName + " " + tagEndSymbol;
}
}
}
tagsText += "\n";
float pixelHeight = EditorStyles.miniLabel.CalcHeight(new GUIContent(tagsText), EditorGUIUtility.currentViewWidth);
EditorGUILayout.SelectableLabel(tagsText, GUI.skin.GetStyle("HelpBox"), GUILayout.MinHeight(pixelHeight));
}
protected SerializedProperty characterProp;
protected SerializedProperty portraitProp;
protected SerializedProperty storyTextProp;
protected SerializedProperty descriptionProp;
protected SerializedProperty voiceOverClipProp;
protected SerializedProperty showAlwaysProp;
protected SerializedProperty showCountProp;
protected SerializedProperty extendPreviousProp;
protected SerializedProperty fadeWhenDoneProp;
protected SerializedProperty waitForClickProp;
protected SerializedProperty stopVoiceoverProp;
protected SerializedProperty setSayDialogProp;
protected SerializedProperty waitForVOProp;
public override void OnEnable()
{
base.OnEnable();
characterProp = serializedObject.FindProperty("character");
portraitProp = serializedObject.FindProperty("portrait");
storyTextProp = serializedObject.FindProperty("storyText");
descriptionProp = serializedObject.FindProperty("description");
voiceOverClipProp = serializedObject.FindProperty("voiceOverClip");
showAlwaysProp = serializedObject.FindProperty("showAlways");
showCountProp = serializedObject.FindProperty("showCount");
extendPreviousProp = serializedObject.FindProperty("extendPrevious");
fadeWhenDoneProp = serializedObject.FindProperty("fadeWhenDone");
waitForClickProp = serializedObject.FindProperty("waitForClick");
stopVoiceoverProp = serializedObject.FindProperty("stopVoiceover");
setSayDialogProp = serializedObject.FindProperty("setSayDialog");
waitForVOProp = serializedObject.FindProperty("waitForVO");
if (blackTex == null)
{
blackTex = CustomGUI.CreateBlackTexture();
}
}
protected virtual void OnDisable()
{
DestroyImmediate(blackTex);
}
public override void DrawCommandGUI()
{
serializedObject.Update();
bool showPortraits = false;
CommandEditor.ObjectField<Character>(characterProp,
new GUIContent("Character", "Character that is speaking"),
new GUIContent("<None>"),
Character.ActiveCharacters);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(" ");
characterProp.objectReferenceValue = (Character) EditorGUILayout.ObjectField(characterProp.objectReferenceValue, typeof(Character), true);
EditorGUILayout.EndHorizontal();
Say t = target as Say;
// Only show portrait selection if...
if (t._Character != null && // Character is selected
t._Character.Portraits != null && // Character has a portraits field
t._Character.Portraits.Count > 0 ) // Selected Character has at least 1 portrait
{
showPortraits = true;
}
if (showPortraits)
{
CommandEditor.ObjectField<Sprite>(portraitProp,
new GUIContent("Portrait", "Portrait representing speaking character"),
new GUIContent("<None>"),
t._Character.Portraits);
}
else
{
if (!t.ExtendPrevious)
{
t.Portrait = null;
}
}
EditorGUILayout.PropertyField(storyTextProp);
EditorGUILayout.PropertyField(descriptionProp);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(extendPreviousProp);
GUILayout.FlexibleSpace();
if (GUILayout.Button(new GUIContent("Tag Help", "View available tags"), new GUIStyle(EditorStyles.miniButton)))
{
showTagHelp = !showTagHelp;
}
EditorGUILayout.EndHorizontal();
if (showTagHelp)
{
DrawTagHelpLabel();
}
EditorGUILayout.Separator();
EditorGUILayout.PropertyField(voiceOverClipProp,
new GUIContent("Voice Over Clip", "Voice over audio to play when the text is displayed"));
EditorGUILayout.PropertyField(showAlwaysProp);
if (showAlwaysProp.boolValue == false)
{
EditorGUILayout.PropertyField(showCountProp);
}
GUIStyle centeredLabel = new GUIStyle(EditorStyles.label);
centeredLabel.alignment = TextAnchor.MiddleCenter;
GUIStyle leftButton = new GUIStyle(EditorStyles.miniButtonLeft);
leftButton.fontSize = 10;
leftButton.font = EditorStyles.toolbarButton.font;
GUIStyle rightButton = new GUIStyle(EditorStyles.miniButtonRight);
rightButton.fontSize = 10;
rightButton.font = EditorStyles.toolbarButton.font;
EditorGUILayout.PropertyField(fadeWhenDoneProp);
EditorGUILayout.PropertyField(waitForClickProp);
EditorGUILayout.PropertyField(stopVoiceoverProp);
EditorGUILayout.PropertyField(setSayDialogProp);
EditorGUILayout.PropertyField(waitForVOProp);
if (showPortraits && t.Portrait != null)
{
Texture2D characterTexture = t.Portrait.texture;
float aspect = (float)characterTexture.width / (float)characterTexture.height;
Rect previewRect = GUILayoutUtility.GetAspectRect(aspect, GUILayout.Width(100), GUILayout.ExpandWidth(true));
if (characterTexture != null)
{
GUI.DrawTexture(previewRect,characterTexture,ScaleMode.ScaleToFit,true,aspect);
}
}
serializedObject.ApplyModifiedProperties();
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Conn.Params.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Org.Apache.Http.Conn.Params
{
/// <summary>
/// <para>An adaptor for accessing route related parameters in HttpParams. See ConnRoutePNames for parameter name definitions.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para></para><title>Revision:</title><para>658785 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnRouteParams
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnRouteParams", AccessFlags = 33)]
public partial class ConnRouteParams : global::Org.Apache.Http.Conn.Params.IConnRoutePNames
/* scope: __dot42__ */
{
/// <summary>
/// <para>A special value indicating "no host". This relies on a nonsense scheme name to avoid conflicts with actual hosts. Note that this is a <b>valid</b> host. </para>
/// </summary>
/// <java-name>
/// NO_HOST
/// </java-name>
[Dot42.DexImport("NO_HOST", "Lorg/apache/http/HttpHost;", AccessFlags = 25)]
public static readonly global::Org.Apache.Http.HttpHost NO_HOST;
/// <summary>
/// <para>A special value indicating "no route". This is a route with NO_HOST as the target. </para>
/// </summary>
/// <java-name>
/// NO_ROUTE
/// </java-name>
[Dot42.DexImport("NO_ROUTE", "Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 25)]
public static readonly global::Org.Apache.Http.Conn.Routing.HttpRoute NO_ROUTE;
/// <summary>
/// <para>Disabled default constructor. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal ConnRouteParams() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the DEFAULT_PROXY parameter value. NO_HOST will be mapped to <code>null</code>, to allow unsetting in a hierarchy.</para><para></para>
/// </summary>
/// <returns>
/// <para>the default proxy set in the argument parameters, or <code>null</code> if not set </para>
/// </returns>
/// <java-name>
/// getDefaultProxy
/// </java-name>
[Dot42.DexImport("getDefaultProxy", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/HttpHost;", AccessFlags = 9)]
public static global::Org.Apache.Http.HttpHost GetDefaultProxy(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <summary>
/// <para>Sets the DEFAULT_PROXY parameter value.</para><para></para>
/// </summary>
/// <java-name>
/// setDefaultProxy
/// </java-name>
[Dot42.DexImport("setDefaultProxy", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/HttpHost;)V", AccessFlags = 9)]
public static void SetDefaultProxy(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.HttpHost proxy) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the FORCED_ROUTE parameter value. NO_ROUTE will be mapped to <code>null</code>, to allow unsetting in a hierarchy.</para><para></para>
/// </summary>
/// <returns>
/// <para>the forced route set in the argument parameters, or <code>null</code> if not set </para>
/// </returns>
/// <java-name>
/// getForcedRoute
/// </java-name>
[Dot42.DexImport("getForcedRoute", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 9)]
public static global::Org.Apache.Http.Conn.Routing.HttpRoute GetForcedRoute(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Routing.HttpRoute);
}
/// <summary>
/// <para>Sets the FORCED_ROUTE parameter value.</para><para></para>
/// </summary>
/// <java-name>
/// setForcedRoute
/// </java-name>
[Dot42.DexImport("setForcedRoute", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/conn/routing/HttpRoute;)V", AccessFlags = 9)]
public static void SetForcedRoute(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the LOCAL_ADDRESS parameter value. There is no special value that would automatically be mapped to <code>null</code>. You can use the wildcard address (0.0.0.0 for IPv4, :: for IPv6) to override a specific local address in a hierarchy.</para><para></para>
/// </summary>
/// <returns>
/// <para>the local address set in the argument parameters, or <code>null</code> if not set </para>
/// </returns>
/// <java-name>
/// getLocalAddress
/// </java-name>
[Dot42.DexImport("getLocalAddress", "(Lorg/apache/http/params/HttpParams;)Ljava/net/InetAddress;", AccessFlags = 9)]
public static global::Java.Net.InetAddress GetLocalAddress(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Java.Net.InetAddress);
}
/// <summary>
/// <para>Sets the LOCAL_ADDRESS parameter value.</para><para></para>
/// </summary>
/// <java-name>
/// setLocalAddress
/// </java-name>
[Dot42.DexImport("setLocalAddress", "(Lorg/apache/http/params/HttpParams;Ljava/net/InetAddress;)V", AccessFlags = 9)]
public static void SetLocalAddress(global::Org.Apache.Http.Params.IHttpParams @params, global::Java.Net.InetAddress local) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>This interface is intended for looking up maximum number of connections allowed for for a given route. This class can be used by pooling connection managers for a fine-grained control of connections on a per route basis.</para><para><para></para><para></para><title>Revision:</title><para>651813 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnPerRoute
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnPerRoute", AccessFlags = 1537)]
public partial interface IConnPerRoute
/* scope: __dot42__ */
{
/// <java-name>
/// getMaxForRoute
/// </java-name>
[Dot42.DexImport("getMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)I", AccessFlags = 1025)]
int GetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Parameter names for connection managers in HttpConn.</para><para><para></para><title>Revision:</title><para>658781 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnManagerPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnManagerPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IConnManagerPNamesConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Defines the timeout in milliseconds used when retrieving an instance of org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager. </para><para>This parameter expects a value of type Long. </para>
/// </summary>
/// <java-name>
/// TIMEOUT
/// </java-name>
[Dot42.DexImport("TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)]
public const string TIMEOUT = "http.conn-manager.timeout";
/// <summary>
/// <para>Defines the maximum number of connections per route. This limit is interpreted by client connection managers and applies to individual manager instances. </para><para>This parameter expects a value of type ConnPerRoute. </para>
/// </summary>
/// <java-name>
/// MAX_CONNECTIONS_PER_ROUTE
/// </java-name>
[Dot42.DexImport("MAX_CONNECTIONS_PER_ROUTE", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_CONNECTIONS_PER_ROUTE = "http.conn-manager.max-per-route";
/// <summary>
/// <para>Defines the maximum number of connections in total. This limit is interpreted by client connection managers and applies to individual manager instances. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// MAX_TOTAL_CONNECTIONS
/// </java-name>
[Dot42.DexImport("MAX_TOTAL_CONNECTIONS", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_TOTAL_CONNECTIONS = "http.conn-manager.max-total";
}
/// <summary>
/// <para>Parameter names for connection managers in HttpConn.</para><para><para></para><title>Revision:</title><para>658781 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnManagerPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnManagerPNames", AccessFlags = 1537)]
public partial interface IConnManagerPNames
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>Parameter names for connections in HttpConn.</para><para><para></para><title>Revision:</title><para>576068 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnConnectionPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnConnectionPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IConnConnectionPNamesConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Defines the maximum number of ignorable lines before we expect a HTTP response's status line. </para><para>With HTTP/1.1 persistent connections, the problem arises that broken scripts could return a wrong Content-Length (there are more bytes sent than specified). Unfortunately, in some cases, this cannot be detected after the bad response, but only before the next one. So HttpClient must be able to skip those surplus lines this way. </para><para>This parameter expects a value of type Integer. 0 disallows all garbage/empty lines before the status line. Use java.lang.Integer#MAX_VALUE for unlimited (default in lenient mode). </para>
/// </summary>
/// <java-name>
/// MAX_STATUS_LINE_GARBAGE
/// </java-name>
[Dot42.DexImport("MAX_STATUS_LINE_GARBAGE", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_STATUS_LINE_GARBAGE = "http.connection.max-status-line-garbage";
}
/// <summary>
/// <para>Parameter names for connections in HttpConn.</para><para><para></para><title>Revision:</title><para>576068 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnConnectionPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnConnectionPNames", AccessFlags = 1537)]
public partial interface IConnConnectionPNames
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>Allows for setting parameters relating to connections on HttpParams. This class ensures that the values set on the params are type-safe. </para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnConnectionParamBean
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnConnectionParamBean", AccessFlags = 33)]
public partial class ConnConnectionParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public ConnConnectionParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para><para>ConnConnectionPNames::MAX_STATUS_LINE_GARBAGE </para></para>
/// </summary>
/// <java-name>
/// setMaxStatusLineGarbage
/// </java-name>
[Dot42.DexImport("setMaxStatusLineGarbage", "(I)V", AccessFlags = 1)]
public virtual void SetMaxStatusLineGarbage(int maxStatusLineGarbage) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ConnConnectionParamBean() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Allows for setting parameters relating to connection routes on HttpParams. This class ensures that the values set on the params are type-safe. </para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnRouteParamBean
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnRouteParamBean", AccessFlags = 33)]
public partial class ConnRouteParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public ConnRouteParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para><para>ConnRoutePNames::DEFAULT_PROXY </para></para>
/// </summary>
/// <java-name>
/// setDefaultProxy
/// </java-name>
[Dot42.DexImport("setDefaultProxy", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)]
public virtual void SetDefaultProxy(global::Org.Apache.Http.HttpHost defaultProxy) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para><para>ConnRoutePNames::LOCAL_ADDRESS </para></para>
/// </summary>
/// <java-name>
/// setLocalAddress
/// </java-name>
[Dot42.DexImport("setLocalAddress", "(Ljava/net/InetAddress;)V", AccessFlags = 1)]
public virtual void SetLocalAddress(global::Java.Net.InetAddress address) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para><para>ConnRoutePNames::FORCED_ROUTE </para></para>
/// </summary>
/// <java-name>
/// setForcedRoute
/// </java-name>
[Dot42.DexImport("setForcedRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)V", AccessFlags = 1)]
public virtual void SetForcedRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ConnRouteParamBean() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>This class represents a collection of HTTP protocol parameters applicable to client-side connection managers.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke</para><para></para><title>Revision:</title><para>658785 </para></para><para><para>4.0</para><para>ConnManagerPNames </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnManagerParams
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnManagerParams", AccessFlags = 49)]
public sealed partial class ConnManagerParams : global::Org.Apache.Http.Conn.Params.IConnManagerPNames
/* scope: __dot42__ */
{
/// <summary>
/// <para>The default maximum number of connections allowed overall </para>
/// </summary>
/// <java-name>
/// DEFAULT_MAX_TOTAL_CONNECTIONS
/// </java-name>
[Dot42.DexImport("DEFAULT_MAX_TOTAL_CONNECTIONS", "I", AccessFlags = 25)]
public const int DEFAULT_MAX_TOTAL_CONNECTIONS = 20;
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public ConnManagerParams() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the timeout in milliseconds used when retrieving a org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager.</para><para></para>
/// </summary>
/// <returns>
/// <para>timeout in milliseconds. </para>
/// </returns>
/// <java-name>
/// getTimeout
/// </java-name>
[Dot42.DexImport("getTimeout", "(Lorg/apache/http/params/HttpParams;)J", AccessFlags = 9)]
public static long GetTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(long);
}
/// <summary>
/// <para>Sets the timeout in milliseconds used when retrieving a org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager.</para><para></para>
/// </summary>
/// <java-name>
/// setTimeout
/// </java-name>
[Dot42.DexImport("setTimeout", "(Lorg/apache/http/params/HttpParams;J)V", AccessFlags = 9)]
public static void SetTimeout(global::Org.Apache.Http.Params.IHttpParams @params, long timeout) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets lookup interface for maximum number of connections allowed per route.</para><para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para>
/// </summary>
/// <java-name>
/// setMaxConnectionsPerRoute
/// </java-name>
[Dot42.DexImport("setMaxConnectionsPerRoute", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/conn/params/ConnPerRoute;)V", AccessFlags = 9)]
public static void SetMaxConnectionsPerRoute(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.Conn.Params.IConnPerRoute connPerRoute) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns lookup interface for maximum number of connections allowed per route.</para><para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para>
/// </summary>
/// <returns>
/// <para>lookup interface for maximum number of connections allowed per route.</para>
/// </returns>
/// <java-name>
/// getMaxConnectionsPerRoute
/// </java-name>
[Dot42.DexImport("getMaxConnectionsPerRoute", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/conn/params/ConnPerRoute;", AccessFlags = 9)]
public static global::Org.Apache.Http.Conn.Params.IConnPerRoute GetMaxConnectionsPerRoute(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Params.IConnPerRoute);
}
/// <summary>
/// <para>Sets the maximum number of connections allowed.</para><para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para>
/// </summary>
/// <java-name>
/// setMaxTotalConnections
/// </java-name>
[Dot42.DexImport("setMaxTotalConnections", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)]
public static void SetMaxTotalConnections(global::Org.Apache.Http.Params.IHttpParams @params, int maxTotalConnections) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the maximum number of connections allowed.</para><para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para>
/// </summary>
/// <returns>
/// <para>The maximum number of connections allowed.</para>
/// </returns>
/// <java-name>
/// getMaxTotalConnections
/// </java-name>
[Dot42.DexImport("getMaxTotalConnections", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)]
public static int GetMaxTotalConnections(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(int);
}
}
/// <summary>
/// <para>This class maintains a map of HTTP routes to maximum number of connections allowed for those routes. This class can be used by pooling connection managers for a fine-grained control of connections on a per route basis.</para><para><para></para><para></para><title>Revision:</title><para>652947 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnPerRouteBean
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnPerRouteBean", AccessFlags = 49)]
public sealed partial class ConnPerRouteBean : global::Org.Apache.Http.Conn.Params.IConnPerRoute
/* scope: __dot42__ */
{
/// <summary>
/// <para>The default maximum number of connections allowed per host </para>
/// </summary>
/// <java-name>
/// DEFAULT_MAX_CONNECTIONS_PER_ROUTE
/// </java-name>
[Dot42.DexImport("DEFAULT_MAX_CONNECTIONS_PER_ROUTE", "I", AccessFlags = 25)]
public const int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 2;
[Dot42.DexImport("<init>", "(I)V", AccessFlags = 1)]
public ConnPerRouteBean(int defaultMax) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public ConnPerRouteBean() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getDefaultMax
/// </java-name>
[Dot42.DexImport("getDefaultMax", "()I", AccessFlags = 1)]
public int GetDefaultMax() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// setDefaultMaxPerRoute
/// </java-name>
[Dot42.DexImport("setDefaultMaxPerRoute", "(I)V", AccessFlags = 1)]
public void SetDefaultMaxPerRoute(int max) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setMaxForRoute
/// </java-name>
[Dot42.DexImport("setMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;I)V", AccessFlags = 1)]
public void SetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route, int max) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getMaxForRoute
/// </java-name>
[Dot42.DexImport("getMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)I", AccessFlags = 1)]
public int GetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// setMaxForRoutes
/// </java-name>
[Dot42.DexImport("setMaxForRoutes", "(Ljava/util/Map;)V", AccessFlags = 1, Signature = "(Ljava/util/Map<Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Integer;>;)V")]
public void SetMaxForRoutes(global::Java.Util.IMap<global::Org.Apache.Http.Conn.Routing.HttpRoute, int?> map) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getDefaultMax
/// </java-name>
public int DefaultMax
{
[Dot42.DexImport("getDefaultMax", "()I", AccessFlags = 1)]
get{ return GetDefaultMax(); }
}
}
/// <summary>
/// <para>Allows for setting parameters relating to connection managers on HttpParams. This class ensures that the values set on the params are type-safe. </para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnManagerParamBean
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnManagerParamBean", AccessFlags = 33)]
public partial class ConnManagerParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public ConnManagerParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setTimeout
/// </java-name>
[Dot42.DexImport("setTimeout", "(J)V", AccessFlags = 1)]
public virtual void SetTimeout(long timeout) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para>
/// </summary>
/// <java-name>
/// setMaxTotalConnections
/// </java-name>
[Dot42.DexImport("setMaxTotalConnections", "(I)V", AccessFlags = 1)]
public virtual void SetMaxTotalConnections(int maxConnections) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para>
/// </summary>
/// <java-name>
/// setConnectionsPerRoute
/// </java-name>
[Dot42.DexImport("setConnectionsPerRoute", "(Lorg/apache/http/conn/params/ConnPerRouteBean;)V", AccessFlags = 1)]
public virtual void SetConnectionsPerRoute(global::Org.Apache.Http.Conn.Params.ConnPerRouteBean connPerRoute) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ConnManagerParamBean() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Parameter names for routing in HttpConn.</para><para><para></para><title>Revision:</title><para>613656 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnRoutePNames
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnRoutePNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IConnRoutePNamesConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Parameter for the default proxy. The default value will be used by some HttpRoutePlanner implementations, in particular the default implementation. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para>
/// </summary>
/// <java-name>
/// DEFAULT_PROXY
/// </java-name>
[Dot42.DexImport("DEFAULT_PROXY", "Ljava/lang/String;", AccessFlags = 25)]
public const string DEFAULT_PROXY = "http.route.default-proxy";
/// <summary>
/// <para>Parameter for the local address. On machines with multiple network interfaces, this parameter can be used to select the network interface from which the connection originates. It will be interpreted by the standard HttpRoutePlanner implementations, in particular the default implementation. </para><para>This parameter expects a value of type java.net.InetAddress. </para>
/// </summary>
/// <java-name>
/// LOCAL_ADDRESS
/// </java-name>
[Dot42.DexImport("LOCAL_ADDRESS", "Ljava/lang/String;", AccessFlags = 25)]
public const string LOCAL_ADDRESS = "http.route.local-address";
/// <summary>
/// <para>Parameter for an forced route. The forced route will be interpreted by the standard HttpRoutePlanner implementations. Instead of computing a route, the given forced route will be returned, even if it points to the wrong target host. </para><para>This parameter expects a value of type HttpRoute. </para>
/// </summary>
/// <java-name>
/// FORCED_ROUTE
/// </java-name>
[Dot42.DexImport("FORCED_ROUTE", "Ljava/lang/String;", AccessFlags = 25)]
public const string FORCED_ROUTE = "http.route.forced-route";
}
/// <summary>
/// <para>Parameter names for routing in HttpConn.</para><para><para></para><title>Revision:</title><para>613656 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/params/ConnRoutePNames
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/params/ConnRoutePNames", AccessFlags = 1537)]
public partial interface IConnRoutePNames
/* scope: __dot42__ */
{
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the SysObraSocial class.
/// </summary>
[Serializable]
public partial class SysObraSocialCollection : ActiveList<SysObraSocial, SysObraSocialCollection>
{
public SysObraSocialCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SysObraSocialCollection</returns>
public SysObraSocialCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
SysObraSocial o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Sys_ObraSocial table.
/// </summary>
[Serializable]
public partial class SysObraSocial : ActiveRecord<SysObraSocial>, IActiveRecord
{
#region .ctors and Default Settings
public SysObraSocial()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public SysObraSocial(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public SysObraSocial(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public SysObraSocial(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Sys_ObraSocial", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdObraSocial = new TableSchema.TableColumn(schema);
colvarIdObraSocial.ColumnName = "idObraSocial";
colvarIdObraSocial.DataType = DbType.Int32;
colvarIdObraSocial.MaxLength = 0;
colvarIdObraSocial.AutoIncrement = true;
colvarIdObraSocial.IsNullable = false;
colvarIdObraSocial.IsPrimaryKey = true;
colvarIdObraSocial.IsForeignKey = false;
colvarIdObraSocial.IsReadOnly = false;
colvarIdObraSocial.DefaultSetting = @"";
colvarIdObraSocial.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdObraSocial);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 200;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarSigla = new TableSchema.TableColumn(schema);
colvarSigla.ColumnName = "sigla";
colvarSigla.DataType = DbType.String;
colvarSigla.MaxLength = 50;
colvarSigla.AutoIncrement = false;
colvarSigla.IsNullable = false;
colvarSigla.IsPrimaryKey = false;
colvarSigla.IsForeignKey = false;
colvarSigla.IsReadOnly = false;
colvarSigla.DefaultSetting = @"('')";
colvarSigla.ForeignKeyTableName = "";
schema.Columns.Add(colvarSigla);
TableSchema.TableColumn colvarCodigoNacion = new TableSchema.TableColumn(schema);
colvarCodigoNacion.ColumnName = "codigoNacion";
colvarCodigoNacion.DataType = DbType.AnsiString;
colvarCodigoNacion.MaxLength = 200;
colvarCodigoNacion.AutoIncrement = false;
colvarCodigoNacion.IsNullable = false;
colvarCodigoNacion.IsPrimaryKey = false;
colvarCodigoNacion.IsForeignKey = false;
colvarCodigoNacion.IsReadOnly = false;
colvarCodigoNacion.DefaultSetting = @"('')";
colvarCodigoNacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarCodigoNacion);
TableSchema.TableColumn colvarCuenta = new TableSchema.TableColumn(schema);
colvarCuenta.ColumnName = "cuenta";
colvarCuenta.DataType = DbType.AnsiString;
colvarCuenta.MaxLength = 50;
colvarCuenta.AutoIncrement = false;
colvarCuenta.IsNullable = false;
colvarCuenta.IsPrimaryKey = false;
colvarCuenta.IsForeignKey = false;
colvarCuenta.IsReadOnly = false;
colvarCuenta.DefaultSetting = @"('')";
colvarCuenta.ForeignKeyTableName = "";
schema.Columns.Add(colvarCuenta);
TableSchema.TableColumn colvarDomicilio = new TableSchema.TableColumn(schema);
colvarDomicilio.ColumnName = "domicilio";
colvarDomicilio.DataType = DbType.AnsiString;
colvarDomicilio.MaxLength = 500;
colvarDomicilio.AutoIncrement = false;
colvarDomicilio.IsNullable = false;
colvarDomicilio.IsPrimaryKey = false;
colvarDomicilio.IsForeignKey = false;
colvarDomicilio.IsReadOnly = false;
colvarDomicilio.DefaultSetting = @"('')";
colvarDomicilio.ForeignKeyTableName = "";
schema.Columns.Add(colvarDomicilio);
TableSchema.TableColumn colvarIdTipoIva = new TableSchema.TableColumn(schema);
colvarIdTipoIva.ColumnName = "idTipoIva";
colvarIdTipoIva.DataType = DbType.Int32;
colvarIdTipoIva.MaxLength = 0;
colvarIdTipoIva.AutoIncrement = false;
colvarIdTipoIva.IsNullable = false;
colvarIdTipoIva.IsPrimaryKey = false;
colvarIdTipoIva.IsForeignKey = false;
colvarIdTipoIva.IsReadOnly = false;
colvarIdTipoIva.DefaultSetting = @"((0))";
colvarIdTipoIva.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdTipoIva);
TableSchema.TableColumn colvarCuit = new TableSchema.TableColumn(schema);
colvarCuit.ColumnName = "cuit";
colvarCuit.DataType = DbType.AnsiString;
colvarCuit.MaxLength = 50;
colvarCuit.AutoIncrement = false;
colvarCuit.IsNullable = false;
colvarCuit.IsPrimaryKey = false;
colvarCuit.IsForeignKey = false;
colvarCuit.IsReadOnly = false;
colvarCuit.DefaultSetting = @"('')";
colvarCuit.ForeignKeyTableName = "";
schema.Columns.Add(colvarCuit);
TableSchema.TableColumn colvarContacto = new TableSchema.TableColumn(schema);
colvarContacto.ColumnName = "contacto";
colvarContacto.DataType = DbType.AnsiString;
colvarContacto.MaxLength = 500;
colvarContacto.AutoIncrement = false;
colvarContacto.IsNullable = false;
colvarContacto.IsPrimaryKey = false;
colvarContacto.IsForeignKey = false;
colvarContacto.IsReadOnly = false;
colvarContacto.DefaultSetting = @"('')";
colvarContacto.ForeignKeyTableName = "";
schema.Columns.Add(colvarContacto);
TableSchema.TableColumn colvarTelefono = new TableSchema.TableColumn(schema);
colvarTelefono.ColumnName = "telefono";
colvarTelefono.DataType = DbType.AnsiString;
colvarTelefono.MaxLength = 50;
colvarTelefono.AutoIncrement = false;
colvarTelefono.IsNullable = false;
colvarTelefono.IsPrimaryKey = false;
colvarTelefono.IsForeignKey = false;
colvarTelefono.IsReadOnly = false;
colvarTelefono.DefaultSetting = @"('')";
colvarTelefono.ForeignKeyTableName = "";
schema.Columns.Add(colvarTelefono);
TableSchema.TableColumn colvarIdTipoObraSocial = new TableSchema.TableColumn(schema);
colvarIdTipoObraSocial.ColumnName = "idTipoObraSocial";
colvarIdTipoObraSocial.DataType = DbType.Int32;
colvarIdTipoObraSocial.MaxLength = 0;
colvarIdTipoObraSocial.AutoIncrement = false;
colvarIdTipoObraSocial.IsNullable = false;
colvarIdTipoObraSocial.IsPrimaryKey = false;
colvarIdTipoObraSocial.IsForeignKey = true;
colvarIdTipoObraSocial.IsReadOnly = false;
colvarIdTipoObraSocial.DefaultSetting = @"((0))";
colvarIdTipoObraSocial.ForeignKeyTableName = "Sys_TipoObraSocial";
schema.Columns.Add(colvarIdTipoObraSocial);
TableSchema.TableColumn colvarIdObraSocialDepende = new TableSchema.TableColumn(schema);
colvarIdObraSocialDepende.ColumnName = "idObraSocialDepende";
colvarIdObraSocialDepende.DataType = DbType.Int32;
colvarIdObraSocialDepende.MaxLength = 0;
colvarIdObraSocialDepende.AutoIncrement = false;
colvarIdObraSocialDepende.IsNullable = false;
colvarIdObraSocialDepende.IsPrimaryKey = false;
colvarIdObraSocialDepende.IsForeignKey = false;
colvarIdObraSocialDepende.IsReadOnly = false;
colvarIdObraSocialDepende.DefaultSetting = @"((0))";
colvarIdObraSocialDepende.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdObraSocialDepende);
TableSchema.TableColumn colvarFacturaPerCapita = new TableSchema.TableColumn(schema);
colvarFacturaPerCapita.ColumnName = "facturaPerCapita";
colvarFacturaPerCapita.DataType = DbType.Boolean;
colvarFacturaPerCapita.MaxLength = 0;
colvarFacturaPerCapita.AutoIncrement = false;
colvarFacturaPerCapita.IsNullable = false;
colvarFacturaPerCapita.IsPrimaryKey = false;
colvarFacturaPerCapita.IsForeignKey = false;
colvarFacturaPerCapita.IsReadOnly = false;
colvarFacturaPerCapita.DefaultSetting = @"((0))";
colvarFacturaPerCapita.ForeignKeyTableName = "";
schema.Columns.Add(colvarFacturaPerCapita);
TableSchema.TableColumn colvarFacturaCarteraFija = new TableSchema.TableColumn(schema);
colvarFacturaCarteraFija.ColumnName = "facturaCarteraFija";
colvarFacturaCarteraFija.DataType = DbType.Boolean;
colvarFacturaCarteraFija.MaxLength = 0;
colvarFacturaCarteraFija.AutoIncrement = false;
colvarFacturaCarteraFija.IsNullable = false;
colvarFacturaCarteraFija.IsPrimaryKey = false;
colvarFacturaCarteraFija.IsForeignKey = false;
colvarFacturaCarteraFija.IsReadOnly = false;
colvarFacturaCarteraFija.DefaultSetting = @"((0))";
colvarFacturaCarteraFija.ForeignKeyTableName = "";
schema.Columns.Add(colvarFacturaCarteraFija);
TableSchema.TableColumn colvarFacturaAjuste = new TableSchema.TableColumn(schema);
colvarFacturaAjuste.ColumnName = "facturaAjuste";
colvarFacturaAjuste.DataType = DbType.Boolean;
colvarFacturaAjuste.MaxLength = 0;
colvarFacturaAjuste.AutoIncrement = false;
colvarFacturaAjuste.IsNullable = false;
colvarFacturaAjuste.IsPrimaryKey = false;
colvarFacturaAjuste.IsForeignKey = false;
colvarFacturaAjuste.IsReadOnly = false;
colvarFacturaAjuste.DefaultSetting = @"((0))";
colvarFacturaAjuste.ForeignKeyTableName = "";
schema.Columns.Add(colvarFacturaAjuste);
TableSchema.TableColumn colvarFacturaPorcentajeAjuste = new TableSchema.TableColumn(schema);
colvarFacturaPorcentajeAjuste.ColumnName = "facturaPorcentajeAjuste";
colvarFacturaPorcentajeAjuste.DataType = DbType.Decimal;
colvarFacturaPorcentajeAjuste.MaxLength = 0;
colvarFacturaPorcentajeAjuste.AutoIncrement = false;
colvarFacturaPorcentajeAjuste.IsNullable = false;
colvarFacturaPorcentajeAjuste.IsPrimaryKey = false;
colvarFacturaPorcentajeAjuste.IsForeignKey = false;
colvarFacturaPorcentajeAjuste.IsReadOnly = false;
colvarFacturaPorcentajeAjuste.DefaultSetting = @"((0))";
colvarFacturaPorcentajeAjuste.ForeignKeyTableName = "";
schema.Columns.Add(colvarFacturaPorcentajeAjuste);
TableSchema.TableColumn colvarNroOrden = new TableSchema.TableColumn(schema);
colvarNroOrden.ColumnName = "nroOrden";
colvarNroOrden.DataType = DbType.Int32;
colvarNroOrden.MaxLength = 0;
colvarNroOrden.AutoIncrement = false;
colvarNroOrden.IsNullable = false;
colvarNroOrden.IsPrimaryKey = false;
colvarNroOrden.IsForeignKey = false;
colvarNroOrden.IsReadOnly = false;
colvarNroOrden.DefaultSetting = @"((10000))";
colvarNroOrden.ForeignKeyTableName = "";
schema.Columns.Add(colvarNroOrden);
TableSchema.TableColumn colvarPermiteFacturaFueraConvenio = new TableSchema.TableColumn(schema);
colvarPermiteFacturaFueraConvenio.ColumnName = "permiteFacturaFueraConvenio";
colvarPermiteFacturaFueraConvenio.DataType = DbType.Boolean;
colvarPermiteFacturaFueraConvenio.MaxLength = 0;
colvarPermiteFacturaFueraConvenio.AutoIncrement = false;
colvarPermiteFacturaFueraConvenio.IsNullable = false;
colvarPermiteFacturaFueraConvenio.IsPrimaryKey = false;
colvarPermiteFacturaFueraConvenio.IsForeignKey = false;
colvarPermiteFacturaFueraConvenio.IsReadOnly = false;
colvarPermiteFacturaFueraConvenio.DefaultSetting = @"((0))";
colvarPermiteFacturaFueraConvenio.ForeignKeyTableName = "";
schema.Columns.Add(colvarPermiteFacturaFueraConvenio);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Sys_ObraSocial",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdObraSocial")]
[Bindable(true)]
public int IdObraSocial
{
get { return GetColumnValue<int>(Columns.IdObraSocial); }
set { SetColumnValue(Columns.IdObraSocial, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("Sigla")]
[Bindable(true)]
public string Sigla
{
get { return GetColumnValue<string>(Columns.Sigla); }
set { SetColumnValue(Columns.Sigla, value); }
}
[XmlAttribute("CodigoNacion")]
[Bindable(true)]
public string CodigoNacion
{
get { return GetColumnValue<string>(Columns.CodigoNacion); }
set { SetColumnValue(Columns.CodigoNacion, value); }
}
[XmlAttribute("Cuenta")]
[Bindable(true)]
public string Cuenta
{
get { return GetColumnValue<string>(Columns.Cuenta); }
set { SetColumnValue(Columns.Cuenta, value); }
}
[XmlAttribute("Domicilio")]
[Bindable(true)]
public string Domicilio
{
get { return GetColumnValue<string>(Columns.Domicilio); }
set { SetColumnValue(Columns.Domicilio, value); }
}
[XmlAttribute("IdTipoIva")]
[Bindable(true)]
public int IdTipoIva
{
get { return GetColumnValue<int>(Columns.IdTipoIva); }
set { SetColumnValue(Columns.IdTipoIva, value); }
}
[XmlAttribute("Cuit")]
[Bindable(true)]
public string Cuit
{
get { return GetColumnValue<string>(Columns.Cuit); }
set { SetColumnValue(Columns.Cuit, value); }
}
[XmlAttribute("Contacto")]
[Bindable(true)]
public string Contacto
{
get { return GetColumnValue<string>(Columns.Contacto); }
set { SetColumnValue(Columns.Contacto, value); }
}
[XmlAttribute("Telefono")]
[Bindable(true)]
public string Telefono
{
get { return GetColumnValue<string>(Columns.Telefono); }
set { SetColumnValue(Columns.Telefono, value); }
}
[XmlAttribute("IdTipoObraSocial")]
[Bindable(true)]
public int IdTipoObraSocial
{
get { return GetColumnValue<int>(Columns.IdTipoObraSocial); }
set { SetColumnValue(Columns.IdTipoObraSocial, value); }
}
[XmlAttribute("IdObraSocialDepende")]
[Bindable(true)]
public int IdObraSocialDepende
{
get { return GetColumnValue<int>(Columns.IdObraSocialDepende); }
set { SetColumnValue(Columns.IdObraSocialDepende, value); }
}
[XmlAttribute("FacturaPerCapita")]
[Bindable(true)]
public bool FacturaPerCapita
{
get { return GetColumnValue<bool>(Columns.FacturaPerCapita); }
set { SetColumnValue(Columns.FacturaPerCapita, value); }
}
[XmlAttribute("FacturaCarteraFija")]
[Bindable(true)]
public bool FacturaCarteraFija
{
get { return GetColumnValue<bool>(Columns.FacturaCarteraFija); }
set { SetColumnValue(Columns.FacturaCarteraFija, value); }
}
[XmlAttribute("FacturaAjuste")]
[Bindable(true)]
public bool FacturaAjuste
{
get { return GetColumnValue<bool>(Columns.FacturaAjuste); }
set { SetColumnValue(Columns.FacturaAjuste, value); }
}
[XmlAttribute("FacturaPorcentajeAjuste")]
[Bindable(true)]
public decimal FacturaPorcentajeAjuste
{
get { return GetColumnValue<decimal>(Columns.FacturaPorcentajeAjuste); }
set { SetColumnValue(Columns.FacturaPorcentajeAjuste, value); }
}
[XmlAttribute("NroOrden")]
[Bindable(true)]
public int NroOrden
{
get { return GetColumnValue<int>(Columns.NroOrden); }
set { SetColumnValue(Columns.NroOrden, value); }
}
[XmlAttribute("PermiteFacturaFueraConvenio")]
[Bindable(true)]
public bool PermiteFacturaFueraConvenio
{
get { return GetColumnValue<bool>(Columns.PermiteFacturaFueraConvenio); }
set { SetColumnValue(Columns.PermiteFacturaFueraConvenio, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.FacContratoObraSocialCollection colFacContratoObraSocialRecords;
public DalSic.FacContratoObraSocialCollection FacContratoObraSocialRecords
{
get
{
if(colFacContratoObraSocialRecords == null)
{
colFacContratoObraSocialRecords = new DalSic.FacContratoObraSocialCollection().Where(FacContratoObraSocial.Columns.IdObraSocial, IdObraSocial).Load();
colFacContratoObraSocialRecords.ListChanged += new ListChangedEventHandler(colFacContratoObraSocialRecords_ListChanged);
}
return colFacContratoObraSocialRecords;
}
set
{
colFacContratoObraSocialRecords = value;
colFacContratoObraSocialRecords.ListChanged += new ListChangedEventHandler(colFacContratoObraSocialRecords_ListChanged);
}
}
void colFacContratoObraSocialRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colFacContratoObraSocialRecords[e.NewIndex].IdObraSocial = IdObraSocial;
}
}
private DalSic.RemFormularioCollection colRemFormularioRecords;
public DalSic.RemFormularioCollection RemFormularioRecords
{
get
{
if(colRemFormularioRecords == null)
{
colRemFormularioRecords = new DalSic.RemFormularioCollection().Where(RemFormulario.Columns.IdObraSocial, IdObraSocial).Load();
colRemFormularioRecords.ListChanged += new ListChangedEventHandler(colRemFormularioRecords_ListChanged);
}
return colRemFormularioRecords;
}
set
{
colRemFormularioRecords = value;
colRemFormularioRecords.ListChanged += new ListChangedEventHandler(colRemFormularioRecords_ListChanged);
}
}
void colRemFormularioRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colRemFormularioRecords[e.NewIndex].IdObraSocial = IdObraSocial;
}
}
private DalSic.SysRelPacienteObraSocialCollection colSysRelPacienteObraSocialRecords;
public DalSic.SysRelPacienteObraSocialCollection SysRelPacienteObraSocialRecords
{
get
{
if(colSysRelPacienteObraSocialRecords == null)
{
colSysRelPacienteObraSocialRecords = new DalSic.SysRelPacienteObraSocialCollection().Where(SysRelPacienteObraSocial.Columns.IdObraSocial, IdObraSocial).Load();
colSysRelPacienteObraSocialRecords.ListChanged += new ListChangedEventHandler(colSysRelPacienteObraSocialRecords_ListChanged);
}
return colSysRelPacienteObraSocialRecords;
}
set
{
colSysRelPacienteObraSocialRecords = value;
colSysRelPacienteObraSocialRecords.ListChanged += new ListChangedEventHandler(colSysRelPacienteObraSocialRecords_ListChanged);
}
}
void colSysRelPacienteObraSocialRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colSysRelPacienteObraSocialRecords[e.NewIndex].IdObraSocial = IdObraSocial;
}
}
private DalSic.SysPacienteCollection colSysPacienteRecords;
public DalSic.SysPacienteCollection SysPacienteRecords
{
get
{
if(colSysPacienteRecords == null)
{
colSysPacienteRecords = new DalSic.SysPacienteCollection().Where(SysPaciente.Columns.IdObraSocial, IdObraSocial).Load();
colSysPacienteRecords.ListChanged += new ListChangedEventHandler(colSysPacienteRecords_ListChanged);
}
return colSysPacienteRecords;
}
set
{
colSysPacienteRecords = value;
colSysPacienteRecords.ListChanged += new ListChangedEventHandler(colSysPacienteRecords_ListChanged);
}
}
void colSysPacienteRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colSysPacienteRecords[e.NewIndex].IdObraSocial = IdObraSocial;
}
}
private DalSic.ConConsultumCollection colConConsulta;
public DalSic.ConConsultumCollection ConConsulta
{
get
{
if(colConConsulta == null)
{
colConConsulta = new DalSic.ConConsultumCollection().Where(ConConsultum.Columns.IdObraSocial, IdObraSocial).Load();
colConConsulta.ListChanged += new ListChangedEventHandler(colConConsulta_ListChanged);
}
return colConConsulta;
}
set
{
colConConsulta = value;
colConConsulta.ListChanged += new ListChangedEventHandler(colConConsulta_ListChanged);
}
}
void colConConsulta_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colConConsulta[e.NewIndex].IdObraSocial = IdObraSocial;
}
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a SysTipoObraSocial ActiveRecord object related to this SysObraSocial
///
/// </summary>
public DalSic.SysTipoObraSocial SysTipoObraSocial
{
get { return DalSic.SysTipoObraSocial.FetchByID(this.IdTipoObraSocial); }
set { SetColumnValue("idTipoObraSocial", value.IdTipoObraSocial); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre,string varSigla,string varCodigoNacion,string varCuenta,string varDomicilio,int varIdTipoIva,string varCuit,string varContacto,string varTelefono,int varIdTipoObraSocial,int varIdObraSocialDepende,bool varFacturaPerCapita,bool varFacturaCarteraFija,bool varFacturaAjuste,decimal varFacturaPorcentajeAjuste,int varNroOrden,bool varPermiteFacturaFueraConvenio)
{
SysObraSocial item = new SysObraSocial();
item.Nombre = varNombre;
item.Sigla = varSigla;
item.CodigoNacion = varCodigoNacion;
item.Cuenta = varCuenta;
item.Domicilio = varDomicilio;
item.IdTipoIva = varIdTipoIva;
item.Cuit = varCuit;
item.Contacto = varContacto;
item.Telefono = varTelefono;
item.IdTipoObraSocial = varIdTipoObraSocial;
item.IdObraSocialDepende = varIdObraSocialDepende;
item.FacturaPerCapita = varFacturaPerCapita;
item.FacturaCarteraFija = varFacturaCarteraFija;
item.FacturaAjuste = varFacturaAjuste;
item.FacturaPorcentajeAjuste = varFacturaPorcentajeAjuste;
item.NroOrden = varNroOrden;
item.PermiteFacturaFueraConvenio = varPermiteFacturaFueraConvenio;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdObraSocial,string varNombre,string varSigla,string varCodigoNacion,string varCuenta,string varDomicilio,int varIdTipoIva,string varCuit,string varContacto,string varTelefono,int varIdTipoObraSocial,int varIdObraSocialDepende,bool varFacturaPerCapita,bool varFacturaCarteraFija,bool varFacturaAjuste,decimal varFacturaPorcentajeAjuste,int varNroOrden,bool varPermiteFacturaFueraConvenio)
{
SysObraSocial item = new SysObraSocial();
item.IdObraSocial = varIdObraSocial;
item.Nombre = varNombre;
item.Sigla = varSigla;
item.CodigoNacion = varCodigoNacion;
item.Cuenta = varCuenta;
item.Domicilio = varDomicilio;
item.IdTipoIva = varIdTipoIva;
item.Cuit = varCuit;
item.Contacto = varContacto;
item.Telefono = varTelefono;
item.IdTipoObraSocial = varIdTipoObraSocial;
item.IdObraSocialDepende = varIdObraSocialDepende;
item.FacturaPerCapita = varFacturaPerCapita;
item.FacturaCarteraFija = varFacturaCarteraFija;
item.FacturaAjuste = varFacturaAjuste;
item.FacturaPorcentajeAjuste = varFacturaPorcentajeAjuste;
item.NroOrden = varNroOrden;
item.PermiteFacturaFueraConvenio = varPermiteFacturaFueraConvenio;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdObraSocialColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn SiglaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn CodigoNacionColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn CuentaColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn DomicilioColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn IdTipoIvaColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn CuitColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn ContactoColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn TelefonoColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn IdTipoObraSocialColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn IdObraSocialDependeColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn FacturaPerCapitaColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn FacturaCarteraFijaColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn FacturaAjusteColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn FacturaPorcentajeAjusteColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn NroOrdenColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn PermiteFacturaFueraConvenioColumn
{
get { return Schema.Columns[17]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdObraSocial = @"idObraSocial";
public static string Nombre = @"nombre";
public static string Sigla = @"sigla";
public static string CodigoNacion = @"codigoNacion";
public static string Cuenta = @"cuenta";
public static string Domicilio = @"domicilio";
public static string IdTipoIva = @"idTipoIva";
public static string Cuit = @"cuit";
public static string Contacto = @"contacto";
public static string Telefono = @"telefono";
public static string IdTipoObraSocial = @"idTipoObraSocial";
public static string IdObraSocialDepende = @"idObraSocialDepende";
public static string FacturaPerCapita = @"facturaPerCapita";
public static string FacturaCarteraFija = @"facturaCarteraFija";
public static string FacturaAjuste = @"facturaAjuste";
public static string FacturaPorcentajeAjuste = @"facturaPorcentajeAjuste";
public static string NroOrden = @"nroOrden";
public static string PermiteFacturaFueraConvenio = @"permiteFacturaFueraConvenio";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colFacContratoObraSocialRecords != null)
{
foreach (DalSic.FacContratoObraSocial item in colFacContratoObraSocialRecords)
{
if (item.IdObraSocial != IdObraSocial)
{
item.IdObraSocial = IdObraSocial;
}
}
}
if (colRemFormularioRecords != null)
{
foreach (DalSic.RemFormulario item in colRemFormularioRecords)
{
if (item.IdObraSocial != IdObraSocial)
{
item.IdObraSocial = IdObraSocial;
}
}
}
if (colSysRelPacienteObraSocialRecords != null)
{
foreach (DalSic.SysRelPacienteObraSocial item in colSysRelPacienteObraSocialRecords)
{
if (item.IdObraSocial != IdObraSocial)
{
item.IdObraSocial = IdObraSocial;
}
}
}
if (colSysPacienteRecords != null)
{
foreach (DalSic.SysPaciente item in colSysPacienteRecords)
{
if (item.IdObraSocial != IdObraSocial)
{
item.IdObraSocial = IdObraSocial;
}
}
}
if (colConConsulta != null)
{
foreach (DalSic.ConConsultum item in colConConsulta)
{
if (item.IdObraSocial != IdObraSocial)
{
item.IdObraSocial = IdObraSocial;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colFacContratoObraSocialRecords != null)
{
colFacContratoObraSocialRecords.SaveAll();
}
if (colRemFormularioRecords != null)
{
colRemFormularioRecords.SaveAll();
}
if (colSysRelPacienteObraSocialRecords != null)
{
colSysRelPacienteObraSocialRecords.SaveAll();
}
if (colSysPacienteRecords != null)
{
colSysPacienteRecords.SaveAll();
}
if (colConConsulta != null)
{
colConConsulta.SaveAll();
}
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute.Models
{
/// <summary>
/// Objects that provide system or application data.
/// </summary>
public partial class ConfigurationSet
{
private AdditionalUnattendContentSettings _additionalUnattendContent;
/// <summary>
/// Optional. Specifies additional base-64 encoded XML formatted
/// information that can be included in the Unattend.xml file, which
/// is used by Windows Setup.
/// </summary>
public AdditionalUnattendContentSettings AdditionalUnattendContent
{
get { return this._additionalUnattendContent; }
set { this._additionalUnattendContent = value; }
}
private string _adminPassword;
/// <summary>
/// Optional. Specifies the string representing the administrator
/// password to use for the virtual machine. If the VM will be created
/// from a 'Specialized' VM image, the password is not required.
/// </summary>
public string AdminPassword
{
get { return this._adminPassword; }
set { this._adminPassword = value; }
}
private string _adminUserName;
/// <summary>
/// Optional. Specifies the name that is used to rename the default
/// administrator account. If the VM will be created from a
/// 'Specialized' VM image, the user name is not required.
/// </summary>
public string AdminUserName
{
get { return this._adminUserName; }
set { this._adminUserName = value; }
}
private string _computerName;
/// <summary>
/// Optional. Specifies the computer name for the virtual machine. If
/// the computer name is not specified, a name is created based on the
/// name of the role. Computer names must be 1 to 15 characters in
/// length. This element is only used with the
/// WindowsProvisioningConfiguration set.
/// </summary>
public string ComputerName
{
get { return this._computerName; }
set { this._computerName = value; }
}
private string _configurationSetType;
/// <summary>
/// Optional. Specifies the configuration type for the configuration
/// set.
/// </summary>
public string ConfigurationSetType
{
get { return this._configurationSetType; }
set { this._configurationSetType = value; }
}
private string _customData;
/// <summary>
/// Optional. Optional. Provides base64 encoded custom data to be
/// passed to VM.
/// </summary>
public string CustomData
{
get { return this._customData; }
set { this._customData = value; }
}
private bool? _disableSshPasswordAuthentication;
/// <summary>
/// Optional. Specifies whether or not SSH authentication is disabled
/// for the password. This element is only used with the
/// LinuxProvisioningConfiguration set. By default this value is set
/// to true.
/// </summary>
public bool? DisableSshPasswordAuthentication
{
get { return this._disableSshPasswordAuthentication; }
set { this._disableSshPasswordAuthentication = value; }
}
private DomainJoinSettings _domainJoin;
/// <summary>
/// Optional. Contains properties that specify a domain to which the
/// virtual machine will be joined. This element is only used with the
/// WindowsProvisioningConfiguration set.
/// </summary>
public DomainJoinSettings DomainJoin
{
get { return this._domainJoin; }
set { this._domainJoin = value; }
}
private bool? _enableAutomaticUpdates;
/// <summary>
/// Optional. Specifies whether automatic updates are enabled for the
/// virtual machine. This element is only used with the
/// WindowsProvisioningConfiguration set. The default value is false.
/// </summary>
public bool? EnableAutomaticUpdates
{
get { return this._enableAutomaticUpdates; }
set { this._enableAutomaticUpdates = value; }
}
private string _hostName;
/// <summary>
/// Optional. Specifies the host name for the VM. Host names are ASCII
/// character strings 1 to 64 characters in length. This element is
/// only used with the LinuxProvisioningConfiguration set.
/// </summary>
public string HostName
{
get { return this._hostName; }
set { this._hostName = value; }
}
private IList<InputEndpoint> _inputEndpoints;
/// <summary>
/// Optional. Contains a collection of external endpoints for the
/// virtual machine. This element is only used with the
/// NetworkConfigurationSet type.
/// </summary>
public IList<InputEndpoint> InputEndpoints
{
get { return this._inputEndpoints; }
set { this._inputEndpoints = value; }
}
private string _iPForwarding;
/// <summary>
/// Optional. Gets or sets the IP Forwarding status for this role.
/// Optional
/// </summary>
public string IPForwarding
{
get { return this._iPForwarding; }
set { this._iPForwarding = value; }
}
private IList<NetworkInterface> _networkInterfaces;
/// <summary>
/// Optional.
/// </summary>
public IList<NetworkInterface> NetworkInterfaces
{
get { return this._networkInterfaces; }
set { this._networkInterfaces = value; }
}
private string _networkSecurityGroup;
/// <summary>
/// Optional. Gets or sets the Network Security Group associated with
/// this role. Optional
/// </summary>
public string NetworkSecurityGroup
{
get { return this._networkSecurityGroup; }
set { this._networkSecurityGroup = value; }
}
private IList<ConfigurationSet.PublicIP> _publicIPs;
/// <summary>
/// Optional. Optional. A set of public IPs. Currently, only one
/// additional public IP per role is supported in an IaaS deployment.
/// The IP address is in addition to the default VIP for the
/// deployment.
/// </summary>
public IList<ConfigurationSet.PublicIP> PublicIPs
{
get { return this._publicIPs; }
set { this._publicIPs = value; }
}
private bool? _resetPasswordOnFirstLogon;
/// <summary>
/// Optional. Specifies whether password should be reset the first time
/// the administrator logs in.
/// </summary>
public bool? ResetPasswordOnFirstLogon
{
get { return this._resetPasswordOnFirstLogon; }
set { this._resetPasswordOnFirstLogon = value; }
}
private SshSettings _sshSettings;
/// <summary>
/// Optional. Specifies the SSH public keys and key pairs to populate
/// in the image during provisioning. This element is only used with
/// the LinuxProvisioningConfiguration set.
/// </summary>
public SshSettings SshSettings
{
get { return this._sshSettings; }
set { this._sshSettings = value; }
}
private string _staticVirtualNetworkIPAddress;
/// <summary>
/// Optional. Specifies a Customer Address, i.e. an IP address assigned
/// to a VM in a VNet's SubNet. For example: 10.0.0.4.
/// </summary>
public string StaticVirtualNetworkIPAddress
{
get { return this._staticVirtualNetworkIPAddress; }
set { this._staticVirtualNetworkIPAddress = value; }
}
private IList<StoredCertificateSettings> _storedCertificateSettings;
/// <summary>
/// Optional. Contains a list of service certificates with which to
/// provision to the new role. This element is only used with the
/// WindowsProvisioningConfiguration set.
/// </summary>
public IList<StoredCertificateSettings> StoredCertificateSettings
{
get { return this._storedCertificateSettings; }
set { this._storedCertificateSettings = value; }
}
private IList<string> _subnetNames;
/// <summary>
/// Optional. The list of Virtual Network subnet names that the
/// deployment belongs to. This element is only used with the
/// NetworkConfigurationSet type.
/// </summary>
public IList<string> SubnetNames
{
get { return this._subnetNames; }
set { this._subnetNames = value; }
}
private string _timeZone;
/// <summary>
/// Optional. Specifies the time zone for the virtual machine. This
/// element is only used with the WindowsProvisioningConfiguration
/// set. For a complete list of supported time zone entries, you can
/// refer to the values listed in the registry entry
/// HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows
/// NT\\CurrentVersion\\Time Zones on a computer running Windows 7,
/// Windows Server 2008, and Windows Server 2008 R2 or you can use the
/// tzutil command-line tool to list the valid time. The tzutil tool
/// is installed by default on Windows 7, Windows Server 2008, and
/// Windows Server 2008 R2.
/// </summary>
public string TimeZone
{
get { return this._timeZone; }
set { this._timeZone = value; }
}
private string _userName;
/// <summary>
/// Optional. Specifies the name of a user to be created in the sudoer
/// group of the virtual machine. User names are ASCII character
/// strings 1 to 32 characters in length. This element is only used
/// with the LinuxProvisioningConfiguration set.
/// </summary>
public string UserName
{
get { return this._userName; }
set { this._userName = value; }
}
private string _userPassword;
/// <summary>
/// Optional. Specifies the password for user name. Passwords are ASCII
/// character strings 6 to 72 characters in length. This element is
/// only used with the LinuxProvisioningConfiguration set.
/// </summary>
public string UserPassword
{
get { return this._userPassword; }
set { this._userPassword = value; }
}
private WindowsRemoteManagementSettings _windowsRemoteManagement;
/// <summary>
/// Optional. Configures the Windows Remote Management service on the
/// virtual machine, which enables remote Windows PowerShell.
/// </summary>
public WindowsRemoteManagementSettings WindowsRemoteManagement
{
get { return this._windowsRemoteManagement; }
set { this._windowsRemoteManagement = value; }
}
/// <summary>
/// Initializes a new instance of the ConfigurationSet class.
/// </summary>
public ConfigurationSet()
{
this.InputEndpoints = new LazyList<InputEndpoint>();
this.NetworkInterfaces = new LazyList<NetworkInterface>();
this.PublicIPs = new LazyList<ConfigurationSet.PublicIP>();
this.StoredCertificateSettings = new LazyList<StoredCertificateSettings>();
this.SubnetNames = new LazyList<string>();
}
/// <summary>
/// An additional public IP that will be created for the role. The
/// public IP will be an additional IP for the role. The role
/// continues to be addressable via the default deployment VIP.
/// </summary>
public partial class PublicIP
{
private string _domainNameLabel;
/// <summary>
/// Optional. The DNS name of the public IP.
/// </summary>
public string DomainNameLabel
{
get { return this._domainNameLabel; }
set { this._domainNameLabel = value; }
}
private int? _idleTimeoutInMinutes;
/// <summary>
/// Optional. The idle timeout in minutes for this Public IP.
/// </summary>
public int? IdleTimeoutInMinutes
{
get { return this._idleTimeoutInMinutes; }
set { this._idleTimeoutInMinutes = value; }
}
private string _name;
/// <summary>
/// Optional. The name of the public IP.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
/// <summary>
/// Initializes a new instance of the PublicIP class.
/// </summary>
public PublicIP()
{
}
}
}
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// 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 BuildAMation 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 HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
using System.Linq;
namespace Bam.Core
{
/// <summary>
/// Singleton representing the single point of reference for all build functionality.
/// This can be thought about as a layer on top of the DependencyGraph.
/// </summary>
public sealed class Graph :
System.Collections.Generic.IEnumerable<ModuleCollection>
{
private string TheBuildRoot;
static Graph()
{
Instance = new Graph();
Instance.Initialize();
}
/// <summary>
/// Obtain the singleton instance of the Graph.
/// </summary>
/// <value>Singleton instance.</value>
public static Graph Instance { get; private set; }
private void
Initialize()
{
this.ProcessState = new BamState();
this.Modules = new System.Collections.Generic.Dictionary<Environment, System.Collections.Generic.List<Module>>();
this.ReferencedModules = new System.Collections.Generic.Dictionary<Environment, Array<Module>>();
this.TopLevelModules = new System.Collections.Generic.List<Module>();
this.Macros = new MacroList(this.GetType().FullName);
this.BuildEnvironmentInternal = null;
this.CommonModuleType = new PeekableStack<System.Type>();
this.ModuleStack = new PeekableStack<Module>();
this.DependencyGraph = new DependencyGraph();
this.MetaData = null;
this.InternalPackageRepositories = new Array<PackageRepository>();
try
{
var primaryPackageRepoPath = System.IO.Directory.GetParent(
System.IO.Directory.GetParent(
System.IO.Directory.GetParent(
this.ProcessState.ExecutableDirectory
).FullName
).FullName
).FullName;
if (!System.IO.Directory.Exists(primaryPackageRepoPath))
{
throw new Exception(
$"Standard BAM package directory '{primaryPackageRepoPath}' does not exist"
);
}
this.AddPackageRepository(primaryPackageRepoPath);
}
catch (System.ArgumentNullException)
{
// this can happen during unit testing
}
this.ForceDefinitionFileUpdate = CommandLineProcessor.Evaluate(new Options.ForceDefinitionFileUpdate());
this.UpdateBamAssemblyVersions = CommandLineProcessor.Evaluate(new Options.UpdateBamAssemblyVersion());
this.CompileWithDebugSymbols = CommandLineProcessor.Evaluate(new Options.UseDebugSymbols());
}
/// <summary>
/// Add the module to the flat list of all modules in the current build environment.
/// </summary>
/// <param name="module">Module to be added</param>
public void
AddModule(
Module module) => this.Modules[this.BuildEnvironmentInternal].Add(module);
/// <summary>
/// Stack of module types, that are pushed when a new module is created, and popped post-creation.
/// This is so that modules created as dependencies can inspect their module parental hierarchy at construction time.
/// </summary>
/// <value>The stack of module types</value>
public PeekableStack<System.Type> CommonModuleType { get; private set; }
/// <summary>
/// Stack of modules that were created prior to the current module.
/// This is so that modules created as dependencies can inspect their module parental hierarchy at construction time.
/// </summary>
public PeekableStack<Module> ModuleStack { get; private set; }
/// <summary>
/// A referenced module is one that is referenced by it's class type. This is normally in use when specifying
/// a dependency. There can be one and only one copy, in a build environment, of this type of module.
/// A non-referenced module, is one that is never referred to explicitly in user scripts, but are created behind
/// the scenes by packages. There can be many instances of these modules.
/// The graph maintains a list of all referenced modules.
/// This function either finds an existing referenced module in the current build Environment, or will create an
/// instance. Since the current build Environment is inspected, this function cal only be called from within the
/// Init() calling hierarchy of a Module.
/// </summary>
/// <returns>The instance of the referenced module.</returns>
/// <typeparam name="T">The type of module being referenced.</typeparam>
public T
FindReferencedModule<T>() where T : Module, new()
{
if (null == this.BuildEnvironmentInternal)
{
var message = new System.Text.StringBuilder();
message.AppendLine("Unable to find a module either within a patch or after the build has started.");
message.AppendLine("If called within a patch function, please modify the calling code to invoke this call within the module's Init method.");
message.AppendLine("If it must called elsewhere, please use the overloaded version accepting an Environment argument.");
throw new Exception(message.ToString());
}
var referencedModules = this.ReferencedModules[this.BuildEnvironmentInternal];
var matchedModule = referencedModules.FirstOrDefault(item => item.GetType() == typeof(T));
if (null != matchedModule)
{
return matchedModule as T;
}
this.CommonModuleType.Push(typeof(T));
var moduleStackAppended = false;
try
{
var newModule = Module.Create<T>(preInitCallback: module =>
{
if (null != module)
{
this.ModuleStack.Push(module);
moduleStackAppended = true;
referencedModules.Add(module);
}
});
return newModule;
}
catch (UnableToBuildModuleException)
{
// remove the failed to create module from the referenced list
// and also any modules and strings created in its Init function, potentially
// of child module types
var moduleTypeToRemove = this.CommonModuleType.Peek();
TokenizedString.RemoveEncapsulatedStrings(moduleTypeToRemove);
Module.RemoveEncapsulatedModules(moduleTypeToRemove);
referencedModules.Remove(referencedModules.First(item => item.GetType() == typeof(T)));
var moduleEnvList = this.Modules[this.BuildEnvironmentInternal];
moduleEnvList.Remove(moduleEnvList.First(item => item.GetType() == typeof(T)));
throw;
}
finally
{
if (moduleStackAppended)
{
this.ModuleStack.Pop();
}
this.CommonModuleType.Pop();
}
}
/// <summary>
/// Find an existing instance of a referenced module, by its type, in the provided build Environment.
/// If no such instance can be found, an exception is thrown.
/// </summary>
/// <typeparam name="T">Type of the referenced Module sought</typeparam>
/// <param name="env">Environment in which the referenced Module should exist.</param>
/// <returns>Instance of the matched Module type in the Environment's referenced Modules.</returns>
public T
FindReferencedModule<T>(
Environment env) where T : Module, new()
{
if (null == env)
{
throw new Exception("Must provide a valid Environment");
}
var referencedModules = this.ReferencedModules[env];
var matchedModule = referencedModules.FirstOrDefault(item => item.GetType() == typeof(T));
if (null == matchedModule)
{
throw new Exception(
$"Unable to locate a referenced module of type {typeof(T).ToString()} in the provided build environment"
);
}
return matchedModule as T;
}
private readonly System.Collections.Generic.Dictionary<System.Type, System.Func<Module>> compiledFindRefModuleCache = new System.Collections.Generic.Dictionary<System.Type, System.Func<Module>>();
private Module
MakeModuleOfType(
System.Type moduleType)
{
try
{
if (!this.compiledFindRefModuleCache.ContainsKey(moduleType))
{
// find method for the module type requested
// (the caching is based on this being 'expensive' as it's based on reflection)
var findReferencedModuleMethod = typeof(Graph).GetMethod("FindReferencedModule", System.Type.EmptyTypes);
var genericVersionForModuleType = findReferencedModuleMethod.MakeGenericMethod(moduleType);
// now compile it, so that we don't have to repeat the above
var instance = System.Linq.Expressions.Expression.Constant(this);
var call = System.Linq.Expressions.Expression.Call(
instance,
genericVersionForModuleType);
var lambda = System.Linq.Expressions.Expression.Lambda<System.Func<Module>>(call);
var func = lambda.Compile();
// and store it
this.compiledFindRefModuleCache.Add(moduleType, func);
}
var newModule = this.compiledFindRefModuleCache[moduleType]();
Log.DetailProgress(Module.Count.ToString());
return newModule;
}
catch (UnableToBuildModuleException exception)
{
Log.Info(
$"Unable to instantiate module of type {moduleType.ToString()} because {exception.Message} from {exception.ModuleType.ToString()}"
);
return null;
}
catch (System.Reflection.TargetInvocationException ex)
{
var exModuleType = (ex.InnerException is ModuleCreationException) ? (ex.InnerException as ModuleCreationException).ModuleType : moduleType;
var realException = ex.InnerException;
if (null == realException)
{
realException = ex;
}
throw new Exception(realException, $"Failed to create module of type {exModuleType.ToString()}");
}
}
/// <summary>
/// Create an unreferenced module instance of the specified type.
/// </summary>
/// <returns>The module of type.</returns>
/// <param name="moduleType">Module type.</param>
/// <typeparam name="ModuleType">The 1st type parameter.</typeparam>
public ModuleType
MakeModuleOfType<ModuleType>(
System.Type moduleType) where ModuleType : Module => this.MakeModuleOfType(moduleType) as ModuleType;
/// <summary>
/// Create all modules in the top level namespace, which is the namespace of the package in which Bam is invoked.
/// </summary>
/// <param name="assembly">Package assembly</param>
/// <param name="env">Environment to create the modules for.</param>
/// <param name="ns">Namespace of the package in which Bam is invoked.</param>
public void
CreateTopLevelModules(
System.Reflection.Assembly assembly,
Environment env,
string ns)
{
var allTypes = assembly.GetTypes();
var allModuleTypesInPackage = allTypes.Where(type =>
(System.String.Equals(ns, type.Namespace, System.StringComparison.Ordinal) ||
(this.UseTestsNamespace && System.String.Equals(ns + ".tests", type.Namespace, System.StringComparison.Ordinal))) &&
type.IsSubclassOf(typeof(Module))
);
if (!allModuleTypesInPackage.Any())
{
throw new Exception(
$"No modules found in the namespace '{ns}'. Please define some modules in the build scripts to use {ns} as a master package."
);
}
System.Collections.Generic.IEnumerable<System.Type> allTopLevelModuleTypesInPackage;
var commandLineTopLevelModules = CommandLineProcessor.Evaluate(new Options.SetTopLevelModules());
if (null != commandLineTopLevelModules && commandLineTopLevelModules.Any())
{
allTopLevelModuleTypesInPackage = allModuleTypesInPackage.Where(
allItem => commandLineTopLevelModules.First().Any(
cmdModuleName => allItem.Name.Contains(cmdModuleName, System.StringComparison.Ordinal)
)
);
}
else
{
allTopLevelModuleTypesInPackage = allModuleTypesInPackage.Where(type => type.IsSealed);
}
if (!allTopLevelModuleTypesInPackage.Any())
{
ICommandLineArgument tlmOption = new Options.SetTopLevelModules();
var tlmOptionEqualsIndex = tlmOption.LongName.IndexOf('=');
var message = new System.Text.StringBuilder();
message.AppendLine(
$"No top-level modules found in the namespace '{ns}'. Please mark some of the modules below as 'sealed', or use the '{tlmOption.LongName.Substring(0, tlmOptionEqualsIndex)}' command line option, to identify them as top-level, and thus buildable when {ns} is the master package:"
);
foreach (var moduleType in allModuleTypesInPackage)
{
message.AppendLine($"\t{moduleType.ToString()}");
}
throw new Exception(message.ToString());
}
try
{
this.CreateTopLevelModuleFromTypes(allTopLevelModuleTypesInPackage, env);
}
catch (Exception ex)
{
throw new Exception(ex, $"An error occurred creating top-level modules in namespace '{ns}':");
}
}
/// <summary>
/// Create top-level modules from a list of types.
/// </summary>
/// <param name="moduleTypes">List of module types to create.</param>
/// <param name="env">Build environment to create modules for.</param>
public void
CreateTopLevelModuleFromTypes(
System.Collections.Generic.IEnumerable<System.Type> moduleTypes,
Environment env)
{
this.BuildEnvironment = env;
foreach (var moduleType in moduleTypes)
{
MakeModuleOfType(moduleType);
}
this.BuildEnvironment = null;
// scan all modules in the build environment for "top-level" status
// as although they should just be from the list of incoming moduleTypes
// it's possible for new modules to be introduced that depend on them
foreach (var module in this.Modules[env])
{
if (module.TopLevel)
{
this.TopLevelModules.Add(module);
}
}
if (!this.TopLevelModules.Any())
{
var message = new System.Text.StringBuilder();
message.AppendLine("Top-level module types detected, but none could be instantiated:");
foreach (var moduleType in moduleTypes)
{
message.AppendLine($"\t{moduleType.ToString()}");
}
throw new Exception(message.ToString());
}
}
/// <summary>
/// Apply any patches associated with modules.
/// </summary>
public void
ApplySettingsPatches()
{
Log.Detail("Apply settings to modules...");
var scale = 100.0f / Module.Count;
var count = 0;
foreach (var rank in this.DependencyGraph.Reverse())
{
foreach (var module in rank.Value)
{
module.ApplySettingsPatches();
Log.DetailProgress("{0,3}%", (int)(++count * scale));
}
}
}
private System.Collections.Generic.List<Module> TopLevelModules { get; set; }
private System.Collections.Generic.Dictionary<Environment, System.Collections.Generic.List<Module>> Modules { get; set; }
private System.Collections.Generic.Dictionary<Environment, Array<Module>> ReferencedModules { get; set; }
/// <summary>
/// Obtain the build mode.
/// </summary>
/// <value>The mode.</value>
public string Mode { get; set; }
/// <summary>
/// Whether the 'tests' namespace of the master package is to be queried for top-level modules.
/// </summary>
public bool UseTestsNamespace { get; set; }
/// <summary>
/// Obtain global macros.
/// </summary>
/// <value>The macros.</value>
public MacroList Macros { get; set; }
/// <summary>
/// Get or set metadata associated with the Graph. This is used for multi-threaded builds.
/// </summary>
/// <value>The meta data.</value>
public object MetaData { get; set; }
private Environment BuildEnvironmentInternal = null;
/// <summary>
/// Get the current build environment.
/// </summary>
/// <value>The build environment.</value>
public Environment BuildEnvironment
{
get
{
return this.BuildEnvironmentInternal;
}
private set
{
this.BuildEnvironmentInternal = value;
if (null != value)
{
this.Modules.Add(value, new System.Collections.Generic.List<Module>());
this.ReferencedModules.Add(value, new Array<Module>());
}
}
}
/// <summary>
/// Get the actual graph of module dependencies.
/// </summary>
/// <value>The dependency graph.</value>
public DependencyGraph DependencyGraph { get; private set; }
private void ApplyGroupDependenciesToChildren(
Module module,
System.Collections.Generic.IEnumerable<Module> children,
System.Collections.Generic.IEnumerable<Module> dependencies)
{
// find all dependencies that are not children of this module
var nonChildDependents = dependencies.Where(item =>
!(item is IChildModule) || (item as IChildModule).Parent != module);
if (!nonChildDependents.Any())
{
return;
}
foreach (var c in children)
{
c.DependsOn(nonChildDependents);
}
}
private void ApplyGroupRequirementsToChildren(
Module module,
System.Collections.Generic.IEnumerable<Module> children,
System.Collections.Generic.IEnumerable<Module> dependencies)
{
// find all dependencies that are not children of this module
var nonChildDependents = dependencies.Where(item =>
!(item is IChildModule) || (item as IChildModule).Parent != module);
if (!nonChildDependents.Any())
{
return;
}
foreach (var c in children)
{
c.Requires(nonChildDependents);
}
}
private void
SetModuleRank(
System.Collections.Generic.Dictionary<Module, int> map,
Module module,
int rankIndex)
{
if (map.ContainsKey(module))
{
throw new Exception($"Module {module.ToString()} rank initialized more than once");
}
map.Add(module, rankIndex);
}
private void
MoveModuleRankBy(
System.Collections.Generic.Dictionary<Module, int> map,
Module module,
int rankDelta)
{
if (!map.ContainsKey(module))
{
// a dependency hasn't yet been initialized, so don't try to move it
return;
}
map[module] += rankDelta;
foreach (var dep in module.Dependents)
{
MoveModuleRankBy(map, dep, rankDelta);
}
foreach (var dep in module.Requirements)
{
MoveModuleRankBy(map, dep, rankDelta);
}
}
private void
MoveModuleRankTo(
System.Collections.Generic.Dictionary<Module, int> map,
Module module,
int rankIndex)
{
if (!map.ContainsKey(module))
{
throw new Exception($"Module {module.ToString()} has yet to be initialized");
}
var currentRank = map[module];
var rankDelta = rankIndex - currentRank;
MoveModuleRankBy(map, module, rankDelta);
}
private void
ProcessModule(
System.Collections.Generic.Dictionary<Module, int> map,
System.Collections.Generic.Queue<Module> toProcess,
Module module,
int rankIndex)
{
if (module.Tool != null)
{
if (null == module.Settings)
{
module.Requires(module.Tool);
var child = module as IChildModule;
if ((null == child) || (null == child.Parent))
{
// children inherit the settings from their parents
module.UsePublicPatches(module.Tool);
}
try
{
// this handles connecting the module to the settings and vice versa too
var settings = module.MakeSettings();
settings?.SetModuleAndDefaultPropertyValues(module);
}
catch (System.TypeInitializationException ex)
{
throw ex.InnerException;
}
catch (System.Reflection.TargetInvocationException ex)
{
var realException = ex.InnerException;
if (null == realException)
{
realException = ex;
}
throw new Exception(realException, "Settings creation:");
}
}
}
if (!module.Dependents.Any() && !module.Requirements.Any())
{
return;
}
if (module is IModuleGroup)
{
var children = module.Children;
this.ApplyGroupDependenciesToChildren(module, children, module.Dependents);
this.ApplyGroupRequirementsToChildren(module, children, module.Requirements);
}
var nextRankIndex = rankIndex + 1;
foreach (var dep in module.Dependents)
{
if (map.ContainsKey(dep))
{
if (map[dep] < nextRankIndex)
{
MoveModuleRankTo(map, dep, nextRankIndex);
}
}
else
{
SetModuleRank(map, dep, nextRankIndex);
toProcess.Enqueue(dep);
}
}
foreach (var dep in module.Requirements)
{
if (map.ContainsKey(dep))
{
if (map[dep] < nextRankIndex)
{
MoveModuleRankTo(map, dep, nextRankIndex);
}
}
else
{
SetModuleRank(map, dep, nextRankIndex);
toProcess.Enqueue(dep);
}
}
}
/// <summary>
/// Sort all dependencies, invoking Init functions, creating all additional dependencies, placing
/// modules into their correct rank.
/// Settings classes are also created and set to default property values if modules have a Tool associated with them.
/// </summary>
public void
SortDependencies()
{
Log.Detail("Analysing module dependencies...");
var moduleRanks = new System.Collections.Generic.Dictionary<Module, int>();
var modulesToProcess = new System.Collections.Generic.Queue<Module>();
var totalProgress = 3 * Module.Count; // all modules are iterated over three times (twice in here, and once in CompleteModules)
var scale = 100.0f / totalProgress;
// initialize the map with top-level modules
// and populate the to-process list
var progress = 0;
Log.DetailProgress("{0,3}%", (int)(progress * scale));
foreach (var module in this.TopLevelModules)
{
SetModuleRank(moduleRanks, module, 0);
ProcessModule(moduleRanks, modulesToProcess, module, 0);
Log.DetailProgress("{0,3}%", (int)((++progress) * scale));
}
// process all modules by initializing them to a best-guess rank
// but then potentially moving them to a higher rank if they re-appear as dependencies
while (modulesToProcess.Any())
{
var module = modulesToProcess.Dequeue();
ProcessModule(moduleRanks, modulesToProcess, module, moduleRanks[module]);
Log.DetailProgress("{0,3}%", (int)((++progress) * scale));
}
// moduleRanks[*].Value is now sparse - there may be gaps between successive ranks with modules
// this needs to be collapsed so that the rank indices are contiguous (the order is correct, the indices are just wrong)
// assign modules, for each rank index, into collections
var contiguousRankIndex = 0;
var lastRankIndex = 0;
foreach (var nextModule in moduleRanks.OrderBy(item => item.Value))
{
if (lastRankIndex != nextModule.Value)
{
lastRankIndex = nextModule.Value;
contiguousRankIndex++;
}
var rank = this.DependencyGraph[contiguousRankIndex];
rank.Add(nextModule.Key);
Log.DetailProgress("{0,3}%", (int)((++progress) * scale));
}
Module.CompleteModules();
}
private static void
DumpModule(
System.Text.StringBuilder builder,
int depth,
char? prefix,
Module module,
Array<Module> visited)
{
if (prefix.HasValue)
{
builder.Append($"{new string(' ', depth)}{prefix.Value}{module.ToString()}");
}
else
{
builder.Append($"{new string(' ', depth)}{module.ToString()}");
}
if (visited.Contains(module))
{
builder.AppendLine("*");
return;
}
visited.Add(module);
if (module is IInputPath inputPath)
{
builder.AppendLine($" {inputPath.InputPath.ToString()}");
}
foreach (var req in module.Requirements)
{
DumpModule(builder, depth + 1, '-', req, visited);
}
foreach (var dep in module.Dependents)
{
DumpModule(builder, depth + 1, '+', dep, visited);
}
}
private void
DumpModuleHierarchy()
{
Log.Message(this.VerbosityLevel, "Module hierarchy");
var visited = new Array<Module>();
foreach (var module in this.TopLevelModules)
{
var text = new System.Text.StringBuilder();
DumpModule(text, 0, null, module, visited);
Log.Message(this.VerbosityLevel, text.ToString());
}
}
private void
DumpRankHierarchy()
{
Log.Message(this.VerbosityLevel, "Rank hierarchy");
foreach (var rank in this.DependencyGraph)
{
var text = new System.Text.StringBuilder();
text.AppendLine();
text.AppendLine($"Rank {rank.Key}: {rank.Value.Count()} modules");
text.AppendLine(new string('-', 80));
foreach (var m in rank.Value)
{
text.AppendLine(m.ToString());
if (m is IInputPath inputPath)
{
text.AppendLine($"\tInput: {inputPath.InputPath.ToString()}");
}
foreach (var s in m.GeneratedPaths)
{
text.AppendLine($"\t{s.Key} : {s.Value}");
}
}
Log.Message(this.VerbosityLevel, text.ToString());
}
}
/// <summary>
/// Dump a representation of the dependency graph to the console.
/// Initially a representation of module hierarchies
/// depth of dependency is indicated by indentation
/// a direct dependency is a + prefix
/// an indirect dependency is a - prefix
/// Then a representation of rank hierarchies, i.e. the order in which
/// modules will be built.
/// </summary>
public void
Dump()
{
Log.Message(this.VerbosityLevel, new string('*', 80));
Log.Message(this.VerbosityLevel, "{0,50}", "DEPENDENCY GRAPH VIEW");
Log.Message(this.VerbosityLevel, new string('*', 80));
this.DumpModuleHierarchy();
this.DumpRankHierarchy();
Log.Message(this.VerbosityLevel, new string('*', 80));
Log.Message(this.VerbosityLevel, "{0,50}", "END DEPENDENCY GRAPH VIEW");
Log.Message(this.VerbosityLevel, new string('*', 80));
}
private void
InternalValidateGraph(
int parentRankIndex,
System.Collections.Generic.IEnumerable<Module> modules)
{
foreach (var c in modules)
{
var childCollection = c.OwningRank;
if (null == childCollection)
{
throw new Exception("Dependency has no rank");
}
try
{
var childRank = this.DependencyGraph.First(item => item.Value == childCollection);
var childRankIndex = childRank.Key;
if (childRankIndex <= parentRankIndex)
{
throw new Exception(
$"Dependent module {c.ToString()} found at a lower rank {childRankIndex} than the dependee {parentRankIndex}"
);
}
}
catch (System.InvalidOperationException)
{
throw new Exception("Module collection not found in graph");
}
}
}
/// <summary>
/// Perform a validation step to ensure that all modules exist and are in correct ranks.
/// </summary>
public void
Validate()
{
foreach (var rank in this.DependencyGraph)
{
foreach (var m in rank.Value)
{
this.InternalValidateGraph(rank.Key, m.Dependents);
this.InternalValidateGraph(rank.Key, m.Requirements);
}
}
Log.DebugMessage("Used packages:");
foreach (var package in this.PackageDefinitions.Where(item => item.CreatedModules().Any()))
{
Log.DebugMessage($"\t{package.Name}");
foreach (var module in package.CreatedModules())
{
Log.DebugMessage($"\t\t{module.ToString()}");
}
}
Log.DebugMessage("Unused packages:");
foreach (var package in this.PackageDefinitions.Where(item => !item.CreatedModules().Any()))
{
Log.DebugMessage($"\t{package.Name}");
}
}
/// <summary>
/// Wrapper around the enumerator of the DependencyGraph, but only returning the rank module collections.
/// </summary>
/// <returns>The enumerator.</returns>
public System.Collections.Generic.IEnumerator<ModuleCollection>
GetEnumerator()
{
foreach (var rank in this.DependencyGraph)
{
yield return rank.Value;
}
}
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator() => this.GetEnumerator();
/// <summary>
/// Determines whether the specified module is referenced or unreferenced.
/// </summary>
/// <returns><c>true</c> if this instance is referenced; otherwise, <c>false</c>.</returns>
/// <param name="module">Module to check.</param>
public bool
IsReferencedModule(
Module module) => this.ReferencedModules[module.BuildEnvironment].Contains(module);
/// <summary>
/// Returns a enumeration of all the named/referenced/encapsulating modules
/// for the specified Environment.
/// </summary>
/// <returns>The collection of modules</returns>
/// <param name="env">The Environment to query for named modules.</param>
public System.Collections.Generic.IEnumerable<Module>
EncapsulatingModules(
Environment env) => this.ReferencedModules[env];
/// <summary>
/// Obtain the list of build environments defined for this Graph.
/// </summary>
/// <value>The build environments.</value>
public System.Collections.Generic.List<Environment> BuildEnvironments => this.Modules.Keys.ToList();
private System.Collections.Generic.IEnumerable<PackageDefinition> PackageDefinitions { get; set; }
/// <summary>
/// Obtain the master package (the package in which Bam was invoked).
/// </summary>
/// <value>The master package.</value>
public PackageDefinition MasterPackage
{
get
{
if (null == this.PackageDefinitions)
{
throw new Exception("No master package was detected");
}
return this.PackageDefinitions.First();
}
}
/// <summary>
/// Assign the array of package definitions to the Graph.
/// Macros added to the Graph are:
/// 'masterpackagename'
/// Packages with external sources are fetched at this point.
/// </summary>
/// <param name="packages">Array of package definitions.</param>
public void
SetPackageDefinitions(
System.Collections.Generic.IEnumerable<PackageDefinition> packages)
{
this.PackageDefinitions = packages;
this.Macros.AddVerbatim(GraphMacroNames.MasterPackageName, this.MasterPackage.Name);
}
/// <summary>
/// Enumerate the package definitions associated with the Graph.
/// </summary>
/// <value>The packages.</value>
public System.Collections.Generic.IEnumerable<PackageDefinition> Packages
{
get
{
if (null == this.PackageDefinitions)
{
throw new Exception("No packages were defined in the build");
}
foreach (var package in this.PackageDefinitions)
{
yield return package;
}
}
}
/// <summary>
/// Obtain the metadata associated with the chosen build mode.
/// </summary>
/// <value>The build mode meta data.</value>
public IBuildModeMetaData BuildModeMetaData { get; set; }
static internal PackageMetaData
InstantiatePackageMetaData(
System.Type metaDataType)
{
try
{
return System.Activator.CreateInstance(metaDataType) as PackageMetaData;
}
catch (Exception exception)
{
throw exception;
}
catch (System.Reflection.TargetInvocationException exception)
{
throw new Exception(exception, "Failed to create package metadata");
}
}
static internal PackageMetaData
InstantiatePackageMetaData<MetaDataType>() => InstantiatePackageMetaData(typeof(MetaDataType));
/// <summary>
/// For a given package, obtain the metadata and cast it to MetaDataType.
/// </summary>
/// <returns>The meta data.</returns>
/// <param name="packageName">Package name.</param>
/// <typeparam name="MetaDataType">The 1st type parameter.</typeparam>
public MetaDataType
PackageMetaData<MetaDataType>(
string packageName)
where MetaDataType : class
{
var package = Bam.Core.Graph.Instance.Packages.FirstOrDefault(item => item.Name.Equals(packageName, System.StringComparison.Ordinal));
if (null == package)
{
throw new Exception($"Unable to locate package '{packageName}'");
}
if (null == package.MetaData)
{
package.MetaData = InstantiatePackageMetaData<MetaDataType>();
}
return package.MetaData as MetaDataType;
}
/// <summary>
/// Get or set the build root to write all build output to.
/// Macros added to the graph:
/// 'buildroot'
/// </summary>
/// <value>The build root.</value>
public string BuildRoot
{
get
{
return this.TheBuildRoot;
}
set
{
if (null != this.TheBuildRoot)
{
throw new Exception("The build root has already been set");
}
var absoluteBuildRootPath = RelativePathUtilities.ConvertRelativePathToAbsolute(
Graph.Instance.ProcessState.WorkingDirectory,
value
);
this.TheBuildRoot = absoluteBuildRootPath;
this.Macros.AddVerbatim(GraphMacroNames.BuildRoot, absoluteBuildRootPath);
}
}
/// <summary>
/// Get or set the logging verbosity level to use across the build.
/// </summary>
/// <value>The verbosity level.</value>
public EVerboseLevel VerbosityLevel { get; set; }
private Array<PackageRepository> InternalPackageRepositories { get; set; }
/// <summary>
/// Adds a new package repository, if not already added.
/// </summary>
/// <param name="repoPath">Path to the new package repository.</param>
/// <param name="insertedDefinitionFiles">Optional array of PackageDefinitions to insert at the front.</param>
/// <returns>The PackageRepository added (or that was already present).</returns>
public PackageRepository
AddPackageRepository(
string repoPath,
params PackageDefinition[] insertedDefinitionFiles)
{
var repo = this.InternalPackageRepositories.FirstOrDefault(item =>
IOWrapper.PathsAreEqual(item.RootPath, repoPath)
);
if (null != repo)
{
return repo;
}
if (repoPath.EndsWith("packages") || repoPath.EndsWith("tests"))
{
// needs to be added as structured
repoPath = System.IO.Path.GetDirectoryName(repoPath);
// re-test
repo = this.InternalPackageRepositories.FirstOrDefault(item =>
IOWrapper.PathsAreEqual(item.RootPath, repoPath)
);
if (null != repo)
{
return repo;
}
}
repo = new PackageRepository(repoPath, insertedDefinitionFiles);
this.InternalPackageRepositories.Add(repo);
return repo;
}
/// <summary>
/// Enumerates the package repositories known about in the build.
/// </summary>
/// <value>Each package repository path.</value>
public System.Collections.Generic.IEnumerable<PackageRepository> PackageRepositories
{
get
{
foreach (var pkgRepo in this.InternalPackageRepositories)
{
yield return pkgRepo;
}
}
}
/// <summary>
/// Determine whether package definition files are automatically updated after being read.
/// </summary>
/// <value><c>true</c> if force definition file update; otherwise, <c>false</c>.</value>
public bool ForceDefinitionFileUpdate { get; private set; }
/// <summary>
/// Determine whether package definition files read have their BAM assembly versions updated
/// to the current version of BAM running.
/// Requires forced updates to definition files to be enabled.
/// </summary>
/// <value><c>true</c> to update bam assembly versions; otherwise, <c>false</c>.</value>
public bool UpdateBamAssemblyVersions { get; private set; }
/// <summary>
/// Determine whether package assembly compilation occurs with debug symbol information.
/// </summary>
/// <value><c>true</c> if compile with debug symbols; otherwise, <c>false</c>.</value>
public bool CompileWithDebugSymbols { get; set; }
/// <summary>
/// Get or set the path of the package script assembly.
/// </summary>
/// <value>The script assembly pathname.</value>
public string ScriptAssemblyPathname { get; set; }
/// <summary>
/// Get or set the compiled package script assembly.
/// </summary>
/// <value>The script assembly.</value>
public System.Reflection.Assembly ScriptAssembly { get; set; }
/// <summary>
/// Obtain the current state of Bam.
/// </summary>
/// <value>The state of the process.</value>
public BamState ProcessState { get; private set; }
/// <summary>
/// Obtain the named referenced module for a given environment and the type of the module required.
/// An exception will be thrown if the type does not refer to any referenced module in that environment.
/// </summary>
/// <param name="env">Environment in which the referenced module was created.</param>
/// <param name="type">The type of the module requested.</param>
/// <returns>The instance of the referenced module requested.</returns>
public Module
GetReferencedModule(
Environment env,
System.Type type)
{
try
{
return this.ReferencedModules[env].First(item => item.GetType() == type);
}
catch (System.InvalidOperationException)
{
Log.ErrorMessage($"Unable to locate a referenced module of type {type.ToString()}");
throw;
}
}
/// <summary>
/// Obtain the IProductDefinition instance (if it exists) from the package assembly.
/// </summary>
public IProductDefinition ProductDefinition { get; set; }
/// <summary>
/// Obtain the IOverrideModuleConfiguration instance (if it exists) from the package assembly.
/// </summary>
public IOverrideModuleConfiguration OverrideModuleConfiguration { get; set; }
/// <summary>
/// Can the use of BuildAMation skip package source downloads? Default is false.
/// </summary>
public bool SkipPackageSourceDownloads { get; set; } = false;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.