context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// BundleResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Numbers.V2.RegulatoryCompliance { public class BundleResource : Resource { public sealed class StatusEnum : StringEnum { private StatusEnum(string value) : base(value) {} public StatusEnum() {} public static implicit operator StatusEnum(string value) { return new StatusEnum(value); } public static readonly StatusEnum Draft = new StatusEnum("draft"); public static readonly StatusEnum PendingReview = new StatusEnum("pending-review"); public static readonly StatusEnum InReview = new StatusEnum("in-review"); public static readonly StatusEnum TwilioRejected = new StatusEnum("twilio-rejected"); public static readonly StatusEnum TwilioApproved = new StatusEnum("twilio-approved"); public static readonly StatusEnum ProvisionallyApproved = new StatusEnum("provisionally-approved"); } public sealed class EndUserTypeEnum : StringEnum { private EndUserTypeEnum(string value) : base(value) {} public EndUserTypeEnum() {} public static implicit operator EndUserTypeEnum(string value) { return new EndUserTypeEnum(value); } public static readonly EndUserTypeEnum Individual = new EndUserTypeEnum("individual"); public static readonly EndUserTypeEnum Business = new EndUserTypeEnum("business"); } public sealed class SortByEnum : StringEnum { private SortByEnum(string value) : base(value) {} public SortByEnum() {} public static implicit operator SortByEnum(string value) { return new SortByEnum(value); } public static readonly SortByEnum Asc = new SortByEnum("ASC"); public static readonly SortByEnum Desc = new SortByEnum("DESC"); } public sealed class SortDirectionEnum : StringEnum { private SortDirectionEnum(string value) : base(value) {} public SortDirectionEnum() {} public static implicit operator SortDirectionEnum(string value) { return new SortDirectionEnum(value); } public static readonly SortDirectionEnum ValidUntilDate = new SortDirectionEnum("valid_until_date"); public static readonly SortDirectionEnum DateUpdated = new SortDirectionEnum("date_updated"); } private static Request BuildCreateRequest(CreateBundleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Numbers, "/v2/RegulatoryCompliance/Bundles", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Create a new Bundle. /// </summary> /// <param name="options"> Create Bundle parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Bundle </returns> public static BundleResource Create(CreateBundleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Create a new Bundle. /// </summary> /// <param name="options"> Create Bundle parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Bundle </returns> public static async System.Threading.Tasks.Task<BundleResource> CreateAsync(CreateBundleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Create a new Bundle. /// </summary> /// <param name="friendlyName"> The string that you assigned to describe the resource </param> /// <param name="email"> The email address </param> /// <param name="statusCallback"> The URL we call to inform your application of status changes. </param> /// <param name="regulationSid"> The unique string of a regulation. </param> /// <param name="isoCountry"> The ISO country code of the country </param> /// <param name="endUserType"> The type of End User of the Bundle resource </param> /// <param name="numberType"> The type of phone number </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Bundle </returns> public static BundleResource Create(string friendlyName, string email, Uri statusCallback = null, string regulationSid = null, string isoCountry = null, BundleResource.EndUserTypeEnum endUserType = null, string numberType = null, ITwilioRestClient client = null) { var options = new CreateBundleOptions(friendlyName, email){StatusCallback = statusCallback, RegulationSid = regulationSid, IsoCountry = isoCountry, EndUserType = endUserType, NumberType = numberType}; return Create(options, client); } #if !NET35 /// <summary> /// Create a new Bundle. /// </summary> /// <param name="friendlyName"> The string that you assigned to describe the resource </param> /// <param name="email"> The email address </param> /// <param name="statusCallback"> The URL we call to inform your application of status changes. </param> /// <param name="regulationSid"> The unique string of a regulation. </param> /// <param name="isoCountry"> The ISO country code of the country </param> /// <param name="endUserType"> The type of End User of the Bundle resource </param> /// <param name="numberType"> The type of phone number </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Bundle </returns> public static async System.Threading.Tasks.Task<BundleResource> CreateAsync(string friendlyName, string email, Uri statusCallback = null, string regulationSid = null, string isoCountry = null, BundleResource.EndUserTypeEnum endUserType = null, string numberType = null, ITwilioRestClient client = null) { var options = new CreateBundleOptions(friendlyName, email){StatusCallback = statusCallback, RegulationSid = regulationSid, IsoCountry = isoCountry, EndUserType = endUserType, NumberType = numberType}; return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadBundleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Numbers, "/v2/RegulatoryCompliance/Bundles", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all Bundles for an account. /// </summary> /// <param name="options"> Read Bundle parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Bundle </returns> public static ResourceSet<BundleResource> Read(ReadBundleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<BundleResource>.FromJson("results", response.Content); return new ResourceSet<BundleResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Bundles for an account. /// </summary> /// <param name="options"> Read Bundle parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Bundle </returns> public static async System.Threading.Tasks.Task<ResourceSet<BundleResource>> ReadAsync(ReadBundleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<BundleResource>.FromJson("results", response.Content); return new ResourceSet<BundleResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all Bundles for an account. /// </summary> /// <param name="status"> The verification status of the Bundle resource </param> /// <param name="friendlyName"> The string that you assigned to describe the resource </param> /// <param name="regulationSid"> The unique string of a regulation. </param> /// <param name="isoCountry"> The ISO country code of the country </param> /// <param name="numberType"> The type of phone number </param> /// <param name="hasValidUntilDate"> Indicates that the Bundle is a valid Bundle until a specified expiration date. /// </param> /// <param name="sortBy"> Can be `ValidUntilDate` or `DateUpdated`. Defaults to `DateCreated` </param> /// <param name="sortDirection"> Default is `DESC`. Can be `ASC` or `DESC`. </param> /// <param name="validUntilDateBefore"> Date to filter Bundles having their `valid_until_date` before or after the /// specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in /// conjunction as well. </param> /// <param name="validUntilDate"> Date to filter Bundles having their `valid_until_date` before or after the specified /// date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. /// </param> /// <param name="validUntilDateAfter"> Date to filter Bundles having their `valid_until_date` before or after the /// specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in /// conjunction as well. </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Bundle </returns> public static ResourceSet<BundleResource> Read(BundleResource.StatusEnum status = null, string friendlyName = null, string regulationSid = null, string isoCountry = null, string numberType = null, bool? hasValidUntilDate = null, BundleResource.SortByEnum sortBy = null, BundleResource.SortDirectionEnum sortDirection = null, DateTime? validUntilDateBefore = null, DateTime? validUntilDate = null, DateTime? validUntilDateAfter = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadBundleOptions(){Status = status, FriendlyName = friendlyName, RegulationSid = regulationSid, IsoCountry = isoCountry, NumberType = numberType, HasValidUntilDate = hasValidUntilDate, SortBy = sortBy, SortDirection = sortDirection, ValidUntilDateBefore = validUntilDateBefore, ValidUntilDate = validUntilDate, ValidUntilDateAfter = validUntilDateAfter, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Bundles for an account. /// </summary> /// <param name="status"> The verification status of the Bundle resource </param> /// <param name="friendlyName"> The string that you assigned to describe the resource </param> /// <param name="regulationSid"> The unique string of a regulation. </param> /// <param name="isoCountry"> The ISO country code of the country </param> /// <param name="numberType"> The type of phone number </param> /// <param name="hasValidUntilDate"> Indicates that the Bundle is a valid Bundle until a specified expiration date. /// </param> /// <param name="sortBy"> Can be `ValidUntilDate` or `DateUpdated`. Defaults to `DateCreated` </param> /// <param name="sortDirection"> Default is `DESC`. Can be `ASC` or `DESC`. </param> /// <param name="validUntilDateBefore"> Date to filter Bundles having their `valid_until_date` before or after the /// specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in /// conjunction as well. </param> /// <param name="validUntilDate"> Date to filter Bundles having their `valid_until_date` before or after the specified /// date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. /// </param> /// <param name="validUntilDateAfter"> Date to filter Bundles having their `valid_until_date` before or after the /// specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in /// conjunction as well. </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Bundle </returns> public static async System.Threading.Tasks.Task<ResourceSet<BundleResource>> ReadAsync(BundleResource.StatusEnum status = null, string friendlyName = null, string regulationSid = null, string isoCountry = null, string numberType = null, bool? hasValidUntilDate = null, BundleResource.SortByEnum sortBy = null, BundleResource.SortDirectionEnum sortDirection = null, DateTime? validUntilDateBefore = null, DateTime? validUntilDate = null, DateTime? validUntilDateAfter = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadBundleOptions(){Status = status, FriendlyName = friendlyName, RegulationSid = regulationSid, IsoCountry = isoCountry, NumberType = numberType, HasValidUntilDate = hasValidUntilDate, SortBy = sortBy, SortDirection = sortDirection, ValidUntilDateBefore = validUntilDateBefore, ValidUntilDate = validUntilDate, ValidUntilDateAfter = validUntilDateAfter, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<BundleResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<BundleResource>.FromJson("results", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<BundleResource> NextPage(Page<BundleResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Numbers) ); var response = client.Request(request); return Page<BundleResource>.FromJson("results", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<BundleResource> PreviousPage(Page<BundleResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Numbers) ); var response = client.Request(request); return Page<BundleResource>.FromJson("results", response.Content); } private static Request BuildFetchRequest(FetchBundleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Numbers, "/v2/RegulatoryCompliance/Bundles/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch a specific Bundle instance. /// </summary> /// <param name="options"> Fetch Bundle parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Bundle </returns> public static BundleResource Fetch(FetchBundleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch a specific Bundle instance. /// </summary> /// <param name="options"> Fetch Bundle parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Bundle </returns> public static async System.Threading.Tasks.Task<BundleResource> FetchAsync(FetchBundleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch a specific Bundle instance. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Bundle </returns> public static BundleResource Fetch(string pathSid, ITwilioRestClient client = null) { var options = new FetchBundleOptions(pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch a specific Bundle instance. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Bundle </returns> public static async System.Threading.Tasks.Task<BundleResource> FetchAsync(string pathSid, ITwilioRestClient client = null) { var options = new FetchBundleOptions(pathSid); return await FetchAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateBundleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Numbers, "/v2/RegulatoryCompliance/Bundles/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Updates a Bundle in an account. /// </summary> /// <param name="options"> Update Bundle parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Bundle </returns> public static BundleResource Update(UpdateBundleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Updates a Bundle in an account. /// </summary> /// <param name="options"> Update Bundle parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Bundle </returns> public static async System.Threading.Tasks.Task<BundleResource> UpdateAsync(UpdateBundleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Updates a Bundle in an account. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource. </param> /// <param name="status"> The verification status of the Bundle resource </param> /// <param name="statusCallback"> The URL we call to inform your application of status changes. </param> /// <param name="friendlyName"> The string that you assigned to describe the resource </param> /// <param name="email"> The email address </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Bundle </returns> public static BundleResource Update(string pathSid, BundleResource.StatusEnum status = null, Uri statusCallback = null, string friendlyName = null, string email = null, ITwilioRestClient client = null) { var options = new UpdateBundleOptions(pathSid){Status = status, StatusCallback = statusCallback, FriendlyName = friendlyName, Email = email}; return Update(options, client); } #if !NET35 /// <summary> /// Updates a Bundle in an account. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource. </param> /// <param name="status"> The verification status of the Bundle resource </param> /// <param name="statusCallback"> The URL we call to inform your application of status changes. </param> /// <param name="friendlyName"> The string that you assigned to describe the resource </param> /// <param name="email"> The email address </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Bundle </returns> public static async System.Threading.Tasks.Task<BundleResource> UpdateAsync(string pathSid, BundleResource.StatusEnum status = null, Uri statusCallback = null, string friendlyName = null, string email = null, ITwilioRestClient client = null) { var options = new UpdateBundleOptions(pathSid){Status = status, StatusCallback = statusCallback, FriendlyName = friendlyName, Email = email}; return await UpdateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteBundleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Numbers, "/v2/RegulatoryCompliance/Bundles/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a specific Bundle. /// </summary> /// <param name="options"> Delete Bundle parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Bundle </returns> public static bool Delete(DeleteBundleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a specific Bundle. /// </summary> /// <param name="options"> Delete Bundle parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Bundle </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteBundleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a specific Bundle. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Bundle </returns> public static bool Delete(string pathSid, ITwilioRestClient client = null) { var options = new DeleteBundleOptions(pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// Delete a specific Bundle. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Bundle </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null) { var options = new DeleteBundleOptions(pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a BundleResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> BundleResource object represented by the provided JSON </returns> public static BundleResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<BundleResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource. /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The unique string of a regulation. /// </summary> [JsonProperty("regulation_sid")] public string RegulationSid { get; private set; } /// <summary> /// The string that you assigned to describe the resource /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The verification status of the Bundle resource /// </summary> [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public BundleResource.StatusEnum Status { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource will be valid until. /// </summary> [JsonProperty("valid_until")] public DateTime? ValidUntil { get; private set; } /// <summary> /// The email address /// </summary> [JsonProperty("email")] public string Email { get; private set; } /// <summary> /// The URL we call to inform your application of status changes. /// </summary> [JsonProperty("status_callback")] public Uri StatusCallback { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the Bundle resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The URLs of the Assigned Items of the Bundle resource /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } private BundleResource() { } } }
/* Copyright (c) Microsoft Corporation 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 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Research.Peloponnese.NotHttpClient; namespace Microsoft.Research.Dryad.ClusterInterface { /// </summary> /// This is the container class for a process once it has been scheduled /// </summary> internal class Process : IProcess { /// <summary> /// internal state to keep track of what we have told the higher level, /// and debug bad state transitions /// </summary> private enum State { Initializing, Queued, Matched, Created, Started, Exited } /// <summary> /// internal state to keep track of what we have told the higher level, /// and debug bad state transitions /// </summary> private State state; /// <summary> /// this is the handle that the scheduler supplies that is used to refer /// to the process /// </summary> private ISchedulerProcess schedulerProcess; /// <summary> /// task to start when the process is canceled /// </summary> private TaskCompletionSource<bool> cancelTask; /// <summary> /// this is the object passed down by higher levels of the software stack, /// that receives updates as the process is queued, matched, scheduled, run, etc. /// </summary> private IProcessWatcher watcher; /// <summary> /// this is the local directory where the process writes its outputs /// </summary> private string directory; /// <summary> /// this is the computer we are running on, once we get scheduled /// </summary> private IComputer computer; /// <summary> /// this task is started when the owning computer is shutting down /// </summary> private Task computerCancellation; /// <summary> /// statusVersion is the version number associated with the process at the remote /// web server, which is incremented every time the process' state changes, e.g. /// when it starts running or exits /// </summary> private UInt64 statusVersion; /// <summary> /// statusString is the status associated with the process at the remote web /// server, which can be Queued, Running, Canceling or Completed /// </summary> private string statusString; /// <summary> /// the interface to the application's logging /// </summary> private ILogger logger; /// <summary> /// construct a new object to represent the lifecycle of a process being scheduled /// </summary> public Process(ISchedulerProcess p, IProcessWatcher w, string cmd, string cmdLineArgs, ILogger l) { schedulerProcess = p; state = State.Initializing; CommandLine = cmd; CommandLineArguments = cmdLineArgs; watcher = w; cancelTask = new TaskCompletionSource<bool>(); directory = null; statusVersion = 0; statusString = ""; logger = l; } public ISchedulerProcess SchedulerProcess { get { return schedulerProcess; } } /// <summary> /// a unique GUID representing the process for logging purposes /// </summary> public string Id { get { return schedulerProcess.Id; } } /// <summary> /// the string used to start the remote process /// </summary> public string CommandLine { get; private set; } /// <summary> /// arguments provided when starting the remote process /// </summary> public string CommandLineArguments { get; private set; } /// <summary> /// the local directory of the process at the daemon's host computer /// </summary> public string Directory { get { return directory; } } /// <summary> /// set the computer where the process is running /// </summary> private void SetComputer(IComputer remote, Task remoteCancel, string suffix) { // use a lock here because computer can be accessed by other threads trying // to get process keys lock (this) { computer = remote; computerCancellation = remoteCancel; directory = suffix; } } private async Task<string> PostRequest(IComputer computer, string requestString, byte[] payload) { string uri = computer.ProcessServer + requestString; IHttpRequest request = HttpClient.Create(uri); request.Timeout = 30 * 1000; // this should come back quickly. If it really takes a long time, something is wrong request.Method = "POST"; try { using (Stream upload = request.GetRequestStream()) { await upload.WriteAsync(payload, 0, payload.Length); } using (IHttpResponse response = await request.GetResponseAsync()) { // this succeeded but we don't care about the response: null indicates no error return null; } } catch (NotHttpException e) { string error = "Post " + uri + " failed message " + e.Message + " status " + e.Response.StatusCode + ": " + e.Response.StatusDescription; logger.Log(error); return error; } catch (Exception e) { string error = "Post " + uri + " failed message " + e.Message; logger.Log(error); return error; } } private async Task<bool> Schedule(IComputer computer, Task interrupt) { logger.Log("Process " + Id + " scheduling itself as " + directory + " on computer " + computer.Name + " at " + computer.Host); ToMatched(computer, DateTime.Now.ToFileTimeUtc()); StringBuilder payload = new StringBuilder(); payload.AppendLine(CommandLine); payload.AppendLine(CommandLineArguments); Task<string> bail = interrupt.ContinueWith((t) => ""); Task<string> upload = PostRequest(computer, directory + "?op=create", Encoding.UTF8.GetBytes(payload.ToString())); Task<string> completed = await Task.WhenAny(bail, upload); if (completed == bail) { logger.Log("Process " + Id + " abandoned creation due to finishWaiter"); ToExited(ProcessExitState.ScheduleFailed, DateTime.Now.ToFileTimeUtc(), 1, "Service shut down while scheduling"); return false; } if (completed.Result == null) { logger.Log("Process " + Id + " got remote create process success for " + directory); ToCreated(DateTime.Now.ToFileTimeUtc()); return true; } else { logger.Log("Proces " + Id + " got remote create process failure " + completed.Result); ToExited(ProcessExitState.ScheduleFailed, DateTime.Now.ToFileTimeUtc(), 1, completed.Result); return false; } } private bool UpdateProcessStatus(IHttpResponse response) { try { UInt64 newVersion = UInt64.Parse(response.Headers["X-Dryad-ValueVersion"]); string status = response.Headers["X-Dryad-ProcessStatus"]; int exitCode = Int32.Parse(response.Headers["X-Dryad-ProcessExitCode"]); long startTime = Int64.Parse(response.Headers["X-Dryad-ProcessStartTime"]); long endTime = Int64.Parse(response.Headers["X-Dryad-ProcessEndTime"]); statusVersion = newVersion; if (status != statusString) { statusString = status; if (status == "Queued") { // don't bother to record this 'transition' logger.Log("Process " + Id + " got Queued status"); } else if (status == "Running") { logger.Log("Process " + Id + " got Running status"); ToStarted(startTime); } else if (status == "Completed") { logger.Log("Process " + Id + " got Completed status"); ToExited(ProcessExitState.ProcessExited, endTime, exitCode, "Process exit detected normally"); return true; } else { logger.Log("Process " + Id + " got unknown status " + status); } } } catch (Exception e) { logger.Log("Process " + Id + " got exception " + e.ToString() + " parsing status"); // we failed to read the headers correctly, which is odd, but we'll assume the process is now dead ToExited(ProcessExitState.StatusFailed, DateTime.Now.ToFileTimeUtc(), 1, "Failed to read headers " + e.Message); return true; } return false; } private async Task<bool> GetStatus(IComputer computer, Task interrupt) { logger.Log("Process " + Id + " getting status on computer " + computer.Name + " at " + computer.Host); // use a 2 minute heartbeat for now int timeout = 120000; StringBuilder sb = new StringBuilder(directory); sb.AppendFormat("?version={0}", statusVersion); sb.AppendFormat("&timeout={0}", timeout); Task<IHttpResponse> completed; try { IHttpRequest request = HttpClient.Create(computer.ProcessServer + sb.ToString()); request.Timeout = timeout + 30000; Task<IHttpResponse> bail = interrupt.ContinueWith((t) => null as IHttpResponse); completed = await Task.WhenAny(bail, request.GetResponseAsync()); if (completed == bail) { logger.Log("Process " + Id + " abandoned status due to finishWaiter"); ToExited(ProcessExitState.StatusFailed, DateTime.Now.ToFileTimeUtc(), 1, "Service stopped while waiting for status"); return true; } } catch (NotHttpException e) { string error = "Status fetch failed message " + e.Message + " status " + e.Response.StatusCode + ": " + e.Response.StatusDescription; logger.Log("Process " + Id + " got remote process status failure " + error); ToExited(ProcessExitState.StatusFailed, DateTime.Now.ToFileTimeUtc(), 1, error); return true; } catch (Exception e) { string error = "Status fetch failed message " + e.Message; logger.Log("Process " + Id + " got remote process status failure " + error); ToExited(ProcessExitState.StatusFailed, DateTime.Now.ToFileTimeUtc(), 1, error); return true; } using (IHttpResponse response = completed.Result) { try { // read the empty payload to the end to keep the protocol happy using (Stream payloadStream = response.GetResponseStream()) { } } catch (NotHttpException e) { string error = "Status fetch failed message " + e.Message + " status " + e.Response.StatusCode + ": " + e.Response.StatusDescription; logger.Log("Process " + Id + " got remote process status failure " + error); ToExited(ProcessExitState.StatusFailed, DateTime.Now.ToFileTimeUtc(), 1, error); return true; } catch (Exception e) { string error = "Status fetch failed message " + e.Message; logger.Log("Process " + Id + " got remote process status failure " + error); ToExited(ProcessExitState.StatusFailed, DateTime.Now.ToFileTimeUtc(), 1, error); return true; } return UpdateProcessStatus(response); } } public async Task Kill(IComputer computer, Task interrupt) { logger.Log("Process " + Id + " sending remote kill to computer " + computer.Name + " on host " + computer.Host); Task<string> bail = interrupt.ContinueWith((t) => ""); Task<string> upload = PostRequest(computer, directory + "?op=kill", new byte[0]); Task<string> completed = await Task.WhenAny(bail, upload); if (completed == bail) { logger.Log("Process " + Id + " abandoned kill due to finishWaiter"); return; } if (completed.Result == null) { logger.Log("Process " + Id + " got successful response for kill"); } else { // if this failed, there's nothing much more we can do logger.Log("Process " + Id + " got failure response for kill " + completed.Result); } } private Task AsyncCancelTask { get { return cancelTask.Task.ContinueWith((t) => { }); } } public async Task Run(IComputer computer, int processId, Task computerInterrupt, string errorReason) { if (errorReason != null) { ToExited(ProcessExitState.ScheduleFailed, DateTime.Now.ToFileTimeUtc(), 1, errorReason); return; } // get a unique id for this process on this computer, and store the identifying // suffix that we will use to refer to it SetComputer(computer, computerInterrupt, processId.ToString()); logger.Log("Process " + Id + " matched to computer " + computer.Name + " on " + computer.Host); { Task interrupt = Task.WhenAny(computerInterrupt, AsyncCancelTask); bool exited = !(await Schedule(computer, interrupt)); while (!exited) { logger.Log("Process " + Id + " getting status from " + computer.Name + " on " + computer.Host); exited = await GetStatus(computer, interrupt); } } logger.Log("Process " + Id + " ensuring it is killed at " + computer.Name + " on " + computer.Host); // we shouldn't get here until the process has exited unless we got a cancellation, but just for belt // and braces we'll always try to make sure it's really dead at the other end await Kill(computer, computerInterrupt); logger.Log("Process " + Id + " finished running at " + computer.Name + " on " + computer.Host); } public void Cancel() { cancelTask.SetResult(true); } public async Task GetKeyStatus(IProcessKeyStatus status) { logger.Log("Process " + Id + " sending key/value fetch for " + status.GetKey() + ":" + status.GetVersion() + ":" + status.GetTimeout()); IComputer remote; Task computerInterrupt; lock (this) { // use a lock to ensure memory safety since these are set on another thread remote = computer; computerInterrupt = computerCancellation; } Task interrupt = Task.WhenAny(computerInterrupt, AsyncCancelTask); StringBuilder sb = new StringBuilder(directory); sb.AppendFormat("?key={0}", status.GetKey()); sb.AppendFormat("&timeout={0}", status.GetTimeout()); sb.AppendFormat("&version={0}", status.GetVersion()); Task<IHttpResponse> completed; try { IHttpRequest request = HttpClient.Create(remote.ProcessServer + sb.ToString()); request.Timeout = status.GetTimeout() + 30000; Task<IHttpResponse> bail = interrupt.ContinueWith((t) => null as IHttpResponse); completed = await Task.WhenAny(bail, request.GetResponseAsync()); if (completed == bail) { logger.Log("Process " + Id + " abandoned property fetch due to interrupt"); return; } } catch (NotHttpException e) { string error = "Status fetch failed message " + e.Message + " status " + e.Response.StatusCode + ": " + e.Response.StatusDescription; logger.Log("Process " + Id + " got remote property fetch failure from " + remote.Name + " at " + remote.Host + ": " + error); status.OnCompleted(0, null, 1, error); return; } catch (Exception e) { string error = "Status fetch failed message " + e.ToString(); logger.Log("Process " + Id + " got remote property fetch failure from " + remote.Name + " at " + remote.Host + ": " + error); status.OnCompleted(0, null, 1, error); return; } using (IHttpResponse response = completed.Result) { try { using (MemoryStream ms = new MemoryStream()) { Task payload; using (Stream payloadStream = response.GetResponseStream()) { payload = await Task.WhenAny(interrupt, payloadStream.CopyToAsync(ms)); } if (payload == interrupt) { logger.Log("Process " + Id + " abandoned property fetch due to interrupt"); return; } logger.Log("Process " + Id + " completed property fetch"); UInt64 newVersion = UInt64.Parse(response.Headers["X-Dryad-ValueVersion"]); string stateString = response.Headers["X-Dryad-ProcessStatus"]; int exitCode = Int32.Parse(response.Headers["X-Dryad-ProcessExitCode"]); logger.Log("Process " + Id + " property fetch: " + status.GetKey() + ":" + newVersion + ":" + stateString); status.OnCompleted(newVersion, ms.ToArray(), exitCode, null); } } catch (NotHttpException e) { string error = "Status fetch failed message " + e.Message + " status " + e.Response.StatusCode + ": " + e.Response.StatusDescription; logger.Log("Process " + Id + " got remote property fetch failure from " + remote.Name + " at " + remote.Host + ": " + error); status.OnCompleted(0, null, 1, error); } catch (Exception e) { string error = "Header fetch failed message " + e.ToString() + " headers " + response.Headers; logger.Log("Process " + Id + " got remote property fetch failure from " + remote.Name + " at " + remote.Host + ": " + error); status.OnCompleted(0, null, 1, error); } } } public async Task SetCommand(IProcessCommand command) { logger.Log("Process " + Id + " sending property command for " + command.GetKey() + ":" + command.GetShortStatus()); IComputer remote; Task computerInterrupt; lock (this) { // use a lock to ensure memory safety since these are set on another thread remote = computer; computerInterrupt = computerCancellation; } Task interrupt = Task.WhenAny(computerInterrupt, AsyncCancelTask); StringBuilder sb = new StringBuilder(directory); sb.AppendFormat("?op=setstatus"); sb.AppendFormat("&key={0}", command.GetKey()); sb.AppendFormat("&shortstatus={0}", command.GetShortStatus()); sb.AppendFormat("&notifywaiters=true"); Task<string> bail = interrupt.ContinueWith((t) => ""); Task<string> upload = PostRequest(remote, sb.ToString(), command.GetPayload()); Task<string> completed = await Task.WhenAny(bail, upload); if (completed == bail) { logger.Log("Process " + Id + " abandoned property command due to interrupt"); return; } if (completed.Result == null) { logger.Log("Process " + Id + " send property command succeeded"); command.OnCompleted(null); } else { // if this failed, there's nothing much more we can do logger.Log("Process " + Id + " got command send failure " + completed.Result); command.OnCompleted(completed.Result); } } public void ToQueued() { lock (this) { Debug.Assert(state == State.Initializing); state = State.Queued; } watcher.OnQueued(); } private void ToMatched(IComputer computer, long timestamp) { lock (this) { Debug.Assert(state == State.Queued); state = State.Matched; } watcher.OnMatched(computer, timestamp); } private void ToCreated(long timestamp) { lock (this) { Debug.Assert(state == State.Matched); state = State.Created; } watcher.OnCreated(timestamp); } private void ToStarted(long timestamp) { lock (this) { Debug.Assert(state == State.Created); state = State.Started; } watcher.OnStarted(timestamp); } private void ToExited(ProcessExitState exitState, long timestamp, int exitCode, string errorText) { lock (this) { if (state == State.Exited) { // duplicate exit; ignore it return; } // this can be reached from any preceding state state = State.Exited; } watcher.OnExited(exitState, timestamp, exitCode, errorText); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Orleans.CodeGeneration; using Orleans.GrainDirectory; namespace Orleans.Runtime { /// <summary> /// Internal data structure that holds a grain interfaces to grain classes map. /// </summary> [Serializable] internal class GrainInterfaceMap { private readonly Dictionary<string, GrainInterfaceData> typeToInterfaceData; private readonly Dictionary<int, GrainInterfaceData> table; private readonly HashSet<int> unordered; private readonly Dictionary<int, GrainClassData> implementationIndex; private readonly Dictionary<int, PlacementStrategy> placementStrategiesIndex; private readonly Dictionary<int, MultiClusterRegistrationStrategy> registrationStrategiesIndex; [NonSerialized] // Client shouldn't need this private readonly Dictionary<string, string> primaryImplementations; private readonly bool localTestMode; private readonly HashSet<string> loadedGrainAsemblies; private readonly PlacementStrategy defaultPlacementStrategy; internal IEnumerable<GrainClassData> SupportedGrainClassData { get { return implementationIndex.Values; } } internal IEnumerable<GrainInterfaceData> SupportedInterfaces { get { return table.Values; } } public GrainInterfaceMap(bool localTestMode, PlacementStrategy defaultPlacementStrategy) { table = new Dictionary<int, GrainInterfaceData>(); typeToInterfaceData = new Dictionary<string, GrainInterfaceData>(); primaryImplementations = new Dictionary<string, string>(); implementationIndex = new Dictionary<int, GrainClassData>(); placementStrategiesIndex = new Dictionary<int, PlacementStrategy>(); registrationStrategiesIndex = new Dictionary<int, MultiClusterRegistrationStrategy>(); unordered = new HashSet<int>(); this.localTestMode = localTestMode; this.defaultPlacementStrategy = defaultPlacementStrategy; if(localTestMode) // if we are running in test mode, we'll build a list of loaded grain assemblies to help with troubleshooting deployment issue loadedGrainAsemblies = new HashSet<string>(); } internal void AddMap(GrainInterfaceMap map) { foreach (var kvp in map.typeToInterfaceData) { if (!typeToInterfaceData.ContainsKey(kvp.Key)) { typeToInterfaceData.Add(kvp.Key, kvp.Value); } } foreach (var kvp in map.table) { if (!table.ContainsKey(kvp.Key)) { table.Add(kvp.Key, kvp.Value); } } foreach (var grainClassTypeCode in map.unordered) { unordered.Add(grainClassTypeCode); } foreach (var kvp in map.implementationIndex) { if (!implementationIndex.ContainsKey(kvp.Key)) { implementationIndex.Add(kvp.Key, kvp.Value); } } foreach (var kvp in map.placementStrategiesIndex) { if (!placementStrategiesIndex.ContainsKey(kvp.Key)) { placementStrategiesIndex.Add(kvp.Key, kvp.Value); } } foreach (var kvp in map.registrationStrategiesIndex) { if (!registrationStrategiesIndex.ContainsKey(kvp.Key)) { registrationStrategiesIndex.Add(kvp.Key, kvp.Value); } } } internal void AddEntry(Type iface, Type grain, PlacementStrategy placement, MultiClusterRegistrationStrategy registrationStrategy, bool primaryImplementation) { lock (this) { var grainTypeInfo = grain.GetTypeInfo(); var grainName = TypeUtils.GetFullName(grainTypeInfo); var isGenericGrainClass = grainTypeInfo.ContainsGenericParameters; var grainTypeCode = GrainInterfaceUtils.GetGrainClassTypeCode(grain); var grainInterfaceData = GetOrAddGrainInterfaceData(iface, isGenericGrainClass); var implementation = new GrainClassData(grainTypeCode, grainName, isGenericGrainClass); if (!implementationIndex.ContainsKey(grainTypeCode)) implementationIndex.Add(grainTypeCode, implementation); if (!placementStrategiesIndex.ContainsKey(grainTypeCode)) placementStrategiesIndex.Add(grainTypeCode, placement); if (!registrationStrategiesIndex.ContainsKey(grainTypeCode)) registrationStrategiesIndex.Add(grainTypeCode, registrationStrategy); grainInterfaceData.AddImplementation(implementation, primaryImplementation); if (primaryImplementation) { primaryImplementations[grainInterfaceData.GrainInterface] = grainName; } else { if (!primaryImplementations.ContainsKey(grainInterfaceData.GrainInterface)) primaryImplementations.Add(grainInterfaceData.GrainInterface, grainName); } if (localTestMode) { var assembly = grainTypeInfo.Assembly.CodeBase; if (!loadedGrainAsemblies.Contains(assembly)) loadedGrainAsemblies.Add(assembly); } } } private GrainInterfaceData GetOrAddGrainInterfaceData(Type iface, bool isGenericGrainClass) { var interfaceId = GrainInterfaceUtils.GetGrainInterfaceId(iface); var version = GrainInterfaceUtils.GetGrainInterfaceVersion(iface); // If already exist GrainInterfaceData grainInterfaceData; if (table.TryGetValue(interfaceId, out grainInterfaceData)) return grainInterfaceData; // If not create new entry var interfaceName = TypeUtils.GetRawClassName(TypeUtils.GetFullName(iface)); grainInterfaceData = new GrainInterfaceData(interfaceId, version, iface, interfaceName); table[interfaceId] = grainInterfaceData; // Add entry to mapping iface string -> data var interfaceTypeKey = GetTypeKey(iface, isGenericGrainClass); typeToInterfaceData[interfaceTypeKey] = grainInterfaceData; // If we are adding a concrete implementation of a generic interface // add also the latter to the map: GrainReference and InvokeMethodRequest // always use the id of the generic one if (iface.IsConstructedGenericType) GetOrAddGrainInterfaceData(iface.GetGenericTypeDefinition(), true); return grainInterfaceData; } internal Dictionary<string, string> GetPrimaryImplementations() { lock (this) { return new Dictionary<string, string>(primaryImplementations); } } internal bool TryGetPrimaryImplementation(string grainInterface, out string grainClass) { lock (this) { return primaryImplementations.TryGetValue(grainInterface, out grainClass); } } internal bool TryGetServiceInterface(int interfaceId, out Type iface) { lock (this) { iface = null; if (!table.ContainsKey(interfaceId)) return false; var interfaceData = table[interfaceId]; iface = interfaceData.Interface; return true; } } internal ushort GetInterfaceVersion(int ifaceId) { return table[ifaceId].InterfaceVersion; } internal bool TryGetTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy registrationStrategy, string genericArguments = null) { lock (this) { grainClass = null; placement = this.defaultPlacementStrategy; registrationStrategy = null; if (!implementationIndex.ContainsKey(typeCode)) return false; var implementation = implementationIndex[typeCode]; grainClass = implementation.GetClassName(genericArguments); placement = placementStrategiesIndex[typeCode]; registrationStrategy = registrationStrategiesIndex[typeCode]; return true; } } internal static string GetTypeKey(Type interfaceType, bool isGenericGrainClass) { var typeInfo = interfaceType.GetTypeInfo(); if (isGenericGrainClass && typeInfo.IsGenericType) { return typeInfo.GetGenericTypeDefinition().AssemblyQualifiedName; } else { return TypeUtils.GetTemplatedName( TypeUtils.GetFullName(interfaceType), interfaceType, interfaceType.GetGenericArguments(), t => false); } } public void AddToUnorderedList(Type grainClass) { var grainClassTypeCode = GrainInterfaceUtils.GetGrainClassTypeCode(grainClass); if (!unordered.Contains(grainClassTypeCode)) unordered.Add(grainClassTypeCode); } public bool IsUnordered(int grainTypeCode) { return unordered.Contains(grainTypeCode); } public IGrainTypeResolver GetGrainTypeResolver() { return new GrainTypeResolver( this.typeToInterfaceData, this.table, this.loadedGrainAsemblies, this.unordered ); } } }
using System; using System.Drawing; using System.Globalization; using System.Reflection; using System.Xml; namespace ICSharpCode.TextEditor.Document { public class HighlightColor { private Color color; private Color backgroundcolor = Color.WhiteSmoke; private bool bold; private bool italic; private bool hasForeground; private bool hasBackground; public bool HasForeground { get { return this.hasForeground; } } public bool HasBackground { get { return this.hasBackground; } } public bool Bold { get { return this.bold; } } public bool Italic { get { return this.italic; } } public Color BackgroundColor { get { return this.backgroundcolor; } } public Color Color { get { return this.color; } } public Font GetFont(FontContainer fontContainer) { if(this.Bold) { if(!this.Italic) { return fontContainer.BoldFont; } return fontContainer.BoldItalicFont; } else { if(!this.Italic) { return fontContainer.RegularFont; } return fontContainer.ItalicFont; } } private Color ParseColorString(string colorName) { string[] array = colorName.Split(new char[] { '*' }); PropertyInfo property = typeof(SystemColors).GetProperty(array[0], BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); Color result = (Color)property.GetValue(null, null); if(array.Length == 2) { double num = double.Parse(array[1]) / 100.0; result = Color.FromArgb((int)((double)result.R * num), (int)((double)result.G * num), (int)((double)result.B * num)); } return result; } private Color PaserColorFrom(string text) { if(text[0] == '#') return HighlightColor.ParseColor(text); if(text.Contains(",")) { var s = text.Split(','); if(s.Length == 3) return Color.FromArgb(int.Parse(s[0]), int.Parse(s[1]), int.Parse(s[2])); if(s.Length == 4) return Color.FromArgb(int.Parse(s[0]), int.Parse(s[1]), int.Parse(s[2]), int.Parse(s[3])); throw new ArgumentOutOfRangeException("color"); } if(text.StartsWith("SystemColors.")) return this.ParseColorString(text.Substring("SystemColors.".Length)); return (Color)this.Color.GetType().InvokeMember(text, BindingFlags.GetProperty, null, this.Color, new object[0]); } public HighlightColor(XmlElement el) { if(el.Attributes["bold"] != null) { this.bold = bool.Parse(el.Attributes["bold"].InnerText); } if(el.Attributes["italic"] != null) { this.italic = bool.Parse(el.Attributes["italic"].InnerText); } if(el.Attributes["color"] != null) { string innerText = el.Attributes["color"].InnerText; this.color = this.PaserColorFrom(innerText); this.hasForeground = true; } else { this.color = Color.Transparent; } if(el.Attributes["bgcolor"] != null) { string innerText2 = el.Attributes["bgcolor"].InnerText; this.backgroundcolor = this.PaserColorFrom(innerText2); this.hasBackground = true; } } public HighlightColor(XmlElement el, HighlightColor defaultColor) { if(el.Attributes["bold"] != null) { this.bold = bool.Parse(el.Attributes["bold"].InnerText); } else { this.bold = defaultColor.Bold; } if(el.Attributes["italic"] != null) { this.italic = bool.Parse(el.Attributes["italic"].InnerText); } else { this.italic = defaultColor.Italic; } if(el.Attributes["color"] != null) { string innerText = el.Attributes["color"].InnerText; this.color = this.PaserColorFrom(innerText); this.hasForeground = true; } else { this.color = defaultColor.color; } if(el.Attributes["bgcolor"] != null) { string innerText2 = el.Attributes["bgcolor"].InnerText; this.backgroundcolor = this.PaserColorFrom(innerText2); this.hasBackground = true; return; } this.backgroundcolor = defaultColor.BackgroundColor; } public HighlightColor(Color color, bool bold, bool italic) { this.hasForeground = true; this.color = color; this.bold = bold; this.italic = italic; } public HighlightColor(Color color, Color backgroundcolor, bool bold, bool italic) { this.hasForeground = true; this.hasBackground = true; this.color = color; this.backgroundcolor = backgroundcolor; this.bold = bold; this.italic = italic; } public HighlightColor(string systemColor, string systemBackgroundColor, bool bold, bool italic) { this.hasForeground = true; this.hasBackground = true; this.color = this.ParseColorString(systemColor); this.backgroundcolor = this.ParseColorString(systemBackgroundColor); this.bold = bold; this.italic = italic; } public HighlightColor(string systemColor, bool bold, bool italic) { this.hasForeground = true; this.color = this.ParseColorString(systemColor); this.bold = bold; this.italic = italic; } private static Color ParseColor(string c) { int alpha = 255; int num = 0; if(c.Length > 7) { num = 2; alpha = int.Parse(c.Substring(1, 2), NumberStyles.HexNumber); } int red = int.Parse(c.Substring(1 + num, 2), NumberStyles.HexNumber); int green = int.Parse(c.Substring(3 + num, 2), NumberStyles.HexNumber); int blue = int.Parse(c.Substring(5 + num, 2), NumberStyles.HexNumber); return Color.FromArgb(alpha, red, green, blue); } public override string ToString() { return string.Concat(new object[] { "[HighlightColor: Bold = ", this.Bold, ", Italic = ", this.Italic, ", Color = ", this.Color, ", BackgroundColor = ", this.BackgroundColor, "]" }); } } }
// 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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestCInt64() { var test = new BooleanBinaryOpTest__TestCInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestCInt64 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Int64); private const int Op2ElementCount = VectorSize / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private BooleanBinaryOpTest__DataTable<Int64, Int64> _dataTable; static BooleanBinaryOpTest__TestCInt64() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); } public BooleanBinaryOpTest__TestCInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new BooleanBinaryOpTest__DataTable<Int64, Int64>(_data1, _data2, VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.TestC( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Avx.TestC( Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Avx.TestC( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }); if (method != null) { var result = method.Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() { var method = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }); if (method != null) { var result = method.Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Avx.TestC( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Avx.TestC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx.TestC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx.TestC(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanBinaryOpTest__TestCInt64(); var result = Avx.TestC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Avx.TestC(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int64> left, Vector256<Int64> right, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "") { var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((~left[i] & right[i]) == 0); } if (expectedResult != result) { Succeeded = false; Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.TestC)}<Int64>(Vector256<Int64>, Vector256<Int64>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Agent.Sdk; using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; namespace Microsoft.VisualStudio.Services.Agent.Util { public static class NetFrameworkUtil { private static List<Version> _versions; public static bool Test(Version minVersion, ITraceWriter trace) { ArgUtil.NotNull(minVersion, nameof(minVersion)); InitVersions(trace); trace?.Info($"Testing for min NET Framework version: '{minVersion}'"); return _versions.Any(x => x >= minVersion); } private static void InitVersions(ITraceWriter trace) { // See http://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx for details on how to detect framework versions // Also see http://support.microsoft.com/kb/318785 if (_versions != null) { return; } var versions = new List<Version>(); // Check for install root. string installRoot = GetHklmValue(@"SOFTWARE\Microsoft\.NETFramework", "InstallRoot", trace) as string; if (!string.IsNullOrEmpty(installRoot)) { // Get the version sub key names. string ndpKeyName = @"SOFTWARE\Microsoft\NET Framework Setup\NDP"; string[] versionSubKeyNames = GetHklmSubKeyNames(ndpKeyName, trace) .Where(x => x.StartsWith("v", StringComparison.OrdinalIgnoreCase)) .ToArray(); foreach (string versionSubKeyName in versionSubKeyNames) { string versionKeyName = $@"{ndpKeyName}\{versionSubKeyName}"; // Test for the version value. string version = GetHklmValue(versionKeyName, "Version", trace) as string; if (!string.IsNullOrEmpty(version)) { // Test for the install flag. object install = GetHklmValue(versionKeyName, "Install", trace); if (!(install is int) || (int)install != 1) { continue; } // Test for the install path. string installPath = Path.Combine(installRoot, versionSubKeyName); trace?.Info($"Testing directory: '{installPath}'"); if (!Directory.Exists(installPath)) { continue; } // Parse the version from the sub key name. Version versionObject; if (!Version.TryParse(versionSubKeyName.Substring(1), out versionObject)) // skip over the leading "v". { trace?.Info($"Unable to parse version from sub key name: '{versionSubKeyName}'"); continue; } trace?.Info($"Found version: {versionObject}"); versions.Add(versionObject); continue; } // Test if deprecated. if (string.Equals(GetHklmValue(versionKeyName, string.Empty, trace) as string, "deprecated", StringComparison.OrdinalIgnoreCase)) { continue; } // Get the profile key names. string[] profileKeyNames = GetHklmSubKeyNames(versionKeyName, trace) .Select(x => $@"{versionKeyName}\{x}") .ToArray(); foreach (string profileKeyName in profileKeyNames) { // Test for the version value. version = GetHklmValue(profileKeyName, "Version", trace) as string; if (string.IsNullOrEmpty(version)) { continue; } // Test for the install flag. object install = GetHklmValue(profileKeyName, "Install", trace); if (!(install is int) || (int)install != 1) { continue; } // Test for the install path. string installPath = (GetHklmValue(profileKeyName, "InstallPath", trace) as string ?? string.Empty) .TrimEnd(Path.DirectorySeparatorChar); if (string.IsNullOrEmpty(installPath)) { continue; } // Determine the version string. // // Use a range since customer might install beta/preview .NET Framework. string versionString = null; object releaseObject = GetHklmValue(profileKeyName, "Release", trace); if (releaseObject != null) { trace?.Info("Type is " + releaseObject.GetType().FullName); } if (releaseObject is int) { int release = (int)releaseObject; if (release == 378389) { versionString = "4.5.0"; } else if (release > 378389 && release <= 378758) { versionString = "4.5.1"; } else if (release > 378758 && release <= 379893) { versionString = "4.5.2"; } else if (release > 379893 && release <= 380995) { versionString = "4.5.3"; } else if (release > 380995 && release <= 393297) { versionString = "4.6.0"; } else if (release > 393297 && release <= 394271) { versionString = "4.6.1"; } else if (release > 394271 && release <= 394806) { versionString = "4.6.2"; } else if (release > 394806) { versionString = "4.7.0"; } else { trace?.Info($"Release '{release}' did not fall into an expected range."); } } if (string.IsNullOrEmpty(versionString)) { continue; } trace?.Info($"Interpreted version: {versionString}"); versions.Add(new Version(versionString)); } } } trace?.Info($"Found {versions.Count} versions:"); foreach (Version versionObject in versions) { trace?.Info($" {versionObject}"); } Interlocked.CompareExchange(ref _versions, versions, null); } private static string[] GetHklmSubKeyNames(string keyName, ITraceWriter trace) { RegistryKey key = Registry.LocalMachine.OpenSubKey(keyName); if (key == null) { trace?.Info($"Key name '{keyName}' is null."); return new string[0]; } try { string[] subKeyNames = key.GetSubKeyNames() ?? new string[0]; trace?.Info($"Key name '{keyName}' contains sub keys:"); foreach (string subKeyName in subKeyNames) { trace?.Info($" '{subKeyName}'"); } return subKeyNames; } finally { key.Dispose(); } } private static object GetHklmValue(string keyName, string valueName, ITraceWriter trace) { keyName = $@"HKEY_LOCAL_MACHINE\{keyName}"; object value = Registry.GetValue(keyName, valueName, defaultValue: null); if (object.ReferenceEquals(value, null)) { trace?.Info($"Key name '{keyName}', value name '{valueName}' is null."); return null; } trace?.Info($"Key name '{keyName}', value name '{valueName}': '{value}'"); return value; } } }
// Copyright 2006-2008 Splicer Project - http://www.codeplex.com/splicer/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Globalization; using System.Text; using DirectShowLib; using DirectShowLib.DES; using Splicer.Utilities; namespace Splicer.Timeline { /// <summary> /// This class handles must of the "trickier" parts of the building the underlying DES objects /// for the timeline. /// </summary> public static class TimelineBuilder { /// <summary> /// Number of MilliSeconds in a second. /// </summary> /// <remarks> /// This constant may be useful for calculations /// </remarks> public const long Milliseconds = (1000); // 10 ^ 3 /// <summary> /// Number of NanoSeconds in a second. /// </summary> /// <remarks> /// This constant may be useful for calculations /// </remarks> public const long Nanoseconds = (1000000000); // 10 ^ 9 /// <summary> /// Number of 100NS in a second. /// </summary> /// <remarks> /// To convert from seconds to 100NS /// units (used by most DES function), multiply the seconds by Units. /// </remarks> public const long Units = (Nanoseconds/100); // 10 ^ 7 /// <summary> /// Converts from 100ns Units to seconds /// </summary> /// <param name="units"></param> /// <returns></returns> public static double ToSeconds(long units) { if (units == -1) return -1; return ((double) units/Units); } /// <summary> /// Converts from seconds to 100ns Units /// </summary> /// <param name="seconds"></param> /// <returns></returns> public static long ToUnits(double seconds) { if (seconds == -1) return -1; return (long) (Units*seconds); } /// <summary> /// Inserts a group into a timeline, and assigns it the supplied media type. /// Will free the media type upon completion. /// </summary> /// <param name="timeline"></param> /// <param name="mediaType"></param> /// <returns></returns> internal static IAMTimelineGroup InsertGroup(IAMTimeline timeline, AMMediaType mediaType, string name) { try { int hr = 0; IAMTimelineObj groupObj; // make the root group/composition hr = timeline.CreateEmptyNode(out groupObj, TimelineMajorType.Group); DESError.ThrowExceptionForHR(hr); if (!string.IsNullOrEmpty(name)) { hr = groupObj.SetUserName(name); DESError.ThrowExceptionForHR(hr); } var group = (IAMTimelineGroup) groupObj; // Set the media type we just created hr = group.SetMediaType(mediaType); DESError.ThrowExceptionForHR(hr); // add the group to the timeline hr = timeline.AddGroup(groupObj); DESError.ThrowExceptionForHR(hr); return group; } finally { DsUtils.FreeAMMediaType(mediaType); } } /// <summary> /// Insert an effect into an effectable object /// </summary> /// <param name="timeline"></param> /// <param name="effectable"></param> /// <param name="offset"></param> /// <param name="duration"></param> /// <param name="effectDefinition"></param> /// <param name="priority"></param> /// <returns></returns> internal static IAMTimelineObj InsertEffect(IAMTimeline timeline, IAMTimelineEffectable effectable, string name, int priority, double offset, double duration, EffectDefinition effectDefinition) { int hr = 0; long unitsStart = ToUnits(offset); long unitsEnd = ToUnits(offset + duration); IAMTimelineObj effectsObj; hr = timeline.CreateEmptyNode(out effectsObj, TimelineMajorType.Effect); DESError.ThrowExceptionForHR(hr); hr = effectsObj.SetSubObjectGUID(effectDefinition.EffectId); DESError.ThrowExceptionForHR(hr); if (!string.IsNullOrEmpty(name)) { hr = effectsObj.SetUserName(name); DESError.ThrowExceptionForHR(hr); } hr = effectsObj.SetStartStop(unitsStart, unitsEnd); DESError.ThrowExceptionForHR(hr); var propertySetter = (IPropertySetter) new PropertySetter(); PopulatePropertySetter(propertySetter, effectDefinition.Parameters); hr = effectsObj.SetPropertySetter(propertySetter); DESError.ThrowExceptionForHR(hr); hr = effectable.EffectInsBefore(effectsObj, priority); DESError.ThrowExceptionForHR(hr); return effectsObj; } /// <summary> /// Insert a transition into a transitionable object /// </summary> /// <param name="timeline"></param> /// <param name="transable"></param> /// <param name="offset"></param> /// <param name="duration"></param> /// <param name="transitionDefinition"></param> /// <param name="swapInputs"></param> /// <returns></returns> internal static IAMTimelineObj InsertTransition(IAMTimeline timeline, IAMTimelineTransable transable, string name, double offset, double duration, TransitionDefinition transitionDefinition, bool swapInputs) { int hr = 0; IAMTimelineObj transitionObj; long unitsStart = ToUnits(offset); long unitsEnd = ToUnits(offset + duration); hr = timeline.CreateEmptyNode(out transitionObj, TimelineMajorType.Transition); DESError.ThrowExceptionForHR(hr); name = string.IsNullOrEmpty(name) ? "transition" : name; if (swapInputs) { hr = transitionObj.SetUserName(string.Format(CultureInfo.InvariantCulture, "{0} (swapped inputs)", name)); DESError.ThrowExceptionForHR(hr); } else { hr = transitionObj.SetUserName(name); DESError.ThrowExceptionForHR(hr); } hr = transitionObj.SetSubObjectGUID(transitionDefinition.TransitionId); DESError.ThrowExceptionForHR(hr); hr = transitionObj.SetStartStop(unitsStart, unitsEnd); DESError.ThrowExceptionForHR(hr); var trans1 = transitionObj as IAMTimelineTrans; if (swapInputs) { hr = trans1.SetSwapInputs(true); DESError.ThrowExceptionForHR(hr); } if (transitionDefinition.Parameters.Count > 0) { var setter1 = (IPropertySetter) new PropertySetter(); PopulatePropertySetter(setter1, transitionDefinition.Parameters); hr = transitionObj.SetPropertySetter(setter1); DESError.ThrowExceptionForHR(hr); } hr = transable.TransAdd(transitionObj); DESError.ThrowExceptionForHR(hr); return transitionObj; } /// <summary> /// Populates the supplied property setter with values from the parameter list. /// </summary> /// <param name="setter"></param> /// <param name="parameters"></param> internal static void PopulatePropertySetter(IPropertySetter setter, IEnumerable<Parameter> parameters) { int hr = 0; foreach (Parameter param in parameters) { DexterParam dexterParam; dexterParam.Name = param.Name; dexterParam.dispID = param.DispId; dexterParam.nValues = 1 + param.Intervals.Count; var valueArray = new DexterValue[dexterParam.nValues]; valueArray[0].v = param.Value; valueArray[0].rt = 0; valueArray[0].dwInterp = Dexterf.Interpolate; for (int i = 0, valueIndex = 1; i < param.Intervals.Count; i++, valueIndex++) { Interval interval = param.Intervals[i]; valueArray[valueIndex].v = interval.Value; valueArray[valueIndex].rt = ToUnits(interval.Time); if (interval.Mode == IntervalMode.Interpolate) { valueArray[valueIndex].dwInterp = Dexterf.Interpolate; } else { valueArray[valueIndex].dwInterp = Dexterf.Jump; } } hr = setter.AddProp(dexterParam, valueArray); DESError.ThrowExceptionForHR(hr); } var builder = new StringBuilder(); int printed = 0; hr = setter.PrintXML(builder, 0, out printed, 0); Console.WriteLine(builder.ToString()); } /// <summary> /// Creates a track, and assigns it with a priority to a selected timeline composition. /// </summary> /// <param name="timeline"></param> /// <param name="parent"></param> /// <param name="name"></param> /// <param name="priority"></param> /// <returns></returns> internal static IAMTimelineTrack CreateTrack(IAMTimeline timeline, IAMTimelineComp parent, string name, int priority) { int hr = 0; IAMTimelineObj newTrack; hr = timeline.CreateEmptyNode(out newTrack, TimelineMajorType.Track); DESError.ThrowExceptionForHR(hr); if (!string.IsNullOrEmpty(name)) { hr = newTrack.SetUserName(name); DESError.ThrowExceptionForHR(hr); } hr = parent.VTrackInsBefore(newTrack, priority); DsError.ThrowExceptionForHR(hr); return (IAMTimelineTrack) newTrack; } /// <summary> /// Creates a composition, and assigns it with a priority to a selected composition /// </summary> /// <param name="timeline"></param> /// <param name="parent"></param> /// <param name="name"></param> /// <param name="priority"></param> /// <returns></returns> internal static IAMTimelineComp CreateComposition(IAMTimeline timeline, IAMTimelineComp parent, string name, int priority) { int hr = 0; IAMTimelineObj newComposition; hr = timeline.CreateEmptyNode(out newComposition, TimelineMajorType.Composite); DESError.ThrowExceptionForHR(hr); if (!string.IsNullOrEmpty(name)) { hr = newComposition.SetUserName(name); DESError.ThrowExceptionForHR(hr); } hr = parent.VTrackInsBefore(newComposition, priority); DsError.ThrowExceptionForHR(hr); return (IAMTimelineComp) newComposition; } /// <summary> /// Creates a des composition, wraps it into an IComposition, adds it to a collecton /// and returns the new IComposition wrapper. /// </summary> /// <param name="timeline"></param> /// <param name="desComposition"></param> /// <param name="compositions"></param> /// <param name="name"></param> /// <param name="priority"></param> /// <returns></returns> internal static IComposition AddCompositionToCollection(ICompositionContainer container, IAMTimeline timeline, IAMTimelineComp desComposition, AddOnlyCollection<IComposition> compositions, string name, int priority) { priority = ReorderPriorities(compositions, priority); IComposition composition = new Composition(container, timeline, CreateComposition(timeline, desComposition, name, priority), name, priority); compositions.Add(composition); return composition; } /// <summary> /// Creates a des track, wraps it into an ITrack, adds it to a collection and /// returns the new ITrack wrapper. /// </summary> /// <param name="desTimeline"></param> /// <param name="desComposition"></param> /// <param name="tracks"></param> /// <param name="name"></param> /// <param name="priority"></param> /// <returns></returns> internal static ITrack AddTrackToCollection(ITrackContainer container, IAMTimeline desTimeline, IAMTimelineComp desComposition, AddOnlyCollection<ITrack> tracks, string name, int priority) { priority = ReorderPriorities(tracks, priority); ITrack track = new Track(container, desTimeline, CreateTrack(desTimeline, desComposition, name, priority), name, priority); tracks.Add(track); return track; } /// <summary> /// Creates a des effect, wraps it into an IEffect, adds it to a collection /// and returns the new IEffect wrapper. /// </summary> /// <param name="desTimeline"></param> /// <param name="desEffectable"></param> /// <param name="effects"></param> /// <param name="name"></param> /// <param name="priority"></param> /// <param name="offset"></param> /// <param name="duration"></param> /// <param name="effectDefinition"></param> /// <returns></returns> internal static IEffect AddEffectToCollection(IEffectContainer container, IAMTimeline desTimeline, IAMTimelineEffectable desEffectable, AddOnlyCollection<IEffect> effects, string name, int priority, double offset, double duration, EffectDefinition effectDefinition) { priority = ReorderPriorities(effects, priority); IAMTimelineObj desEffect = InsertEffect(desTimeline, desEffectable, name, priority, offset, duration, effectDefinition); IEffect effect = new Effect(container, desEffect, name, priority, offset, duration, effectDefinition); effects.Add(effect); return effect; } /// <summary> /// Creates a des transition, wraps it into an ITransition, adds it to a collection /// and returns a new ITransition wrapper. /// </summary> /// <param name="desTimeline"></param> /// <param name="transable"></param> /// <param name="transitions"></param> /// <param name="name"></param> /// <param name="offset"></param> /// <param name="duration"></param> /// <param name="transitionDefinition"></param> /// <param name="swapInputs"></param> /// <returns></returns> internal static ITransition AddTransitionToCollection(ITransitionContainer container, IAMTimeline desTimeline, IAMTimelineTransable transable, AddOnlyCollection<ITransition> transitions, string name, double offset, double duration, TransitionDefinition transitionDefinition, bool swapInputs) { CheckForTransitionOveralp(container, offset, duration); IAMTimelineObj desTransition = InsertTransition(desTimeline, transable, name, offset, duration, transitionDefinition, swapInputs); ITransition transition = new Transition(container, desTransition, name, offset, duration, swapInputs, transitionDefinition); transitions.Add(transition); return transition; } private static void CheckForTransitionOveralp(ITransitionContainer container, double offset, double duratinon) { double prospectStart = offset; double prospectEnd = duratinon + offset; for (int i = 0; i < container.Transitions.Count; i++) { ITransition transition = container.Transitions[i]; double start = transition.Offset; double end = transition.Offset + transition.Duration; if ((prospectStart < end) && (prospectEnd > start)) { throw new SplicerException( string.Format(CultureInfo.InvariantCulture, "Propsective transition overlaps with an existing transition at index: {0}", i)); } } } private static int ReorderPriorities<T>(AddOnlyCollection<T> collection, int newPriority) where T : IPriority { if (newPriority < 0) { return collection.Count; } else { foreach (IPriority priority in collection) { if (priority.Priority >= newPriority) { ((IPrioritySetter) priority).SetPriority(priority.Priority + 1); } } return newPriority; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using De.Osthus.Ambeth.Collections; using De.Osthus.Ambeth.Ioc; using De.Osthus.Ambeth.Log; using De.Osthus.Ambeth.Util; using De.Osthus.Ambeth.Ioc.Annotation; using De.Osthus.Ambeth.Merge.Model; namespace De.Osthus.Ambeth.Xml { public class XmlTypeRegistry : IXmlTypeExtendable, IInitializingBean, IXmlTypeRegistry { [LogInstance] public ILogger Log { private get; set; } [Autowired] public ILoggerHistory LoggerHistory { protected get; set; } protected Tuple2KeyHashMap<String, String, Type> xmlTypeToClassMap = new Tuple2KeyHashMap<String, String, Type>(0.5f); protected Dictionary<Type, IList<XmlTypeKey>> classToXmlTypeMap = new Dictionary<Type, IList<XmlTypeKey>>(); protected Dictionary<Type, IList<XmlTypeKey>> weakClassToXmlTypeMap = new Dictionary<Type, IList<XmlTypeKey>>(); protected readonly Lock readLock, writeLock; public XmlTypeRegistry() { ReadWriteLock rwLock = new ReadWriteLock(); readLock = rwLock.ReadLock; writeLock = rwLock.WriteLock; } public virtual void AfterPropertiesSet() { RegisterXmlType(typeof(Boolean?), "BoolN", null); RegisterXmlType(typeof(Boolean), "Bool", null); RegisterXmlType(typeof(Char?), "CharN", null); RegisterXmlType(typeof(Char), "Char", null); RegisterXmlType(typeof(Byte?), "UByteN", null); RegisterXmlType(typeof(Byte), "UByte", null); RegisterXmlType(typeof(SByte?), "ByteN", null); RegisterXmlType(typeof(SByte), "Byte", null); RegisterXmlType(typeof(Int64?), "Int64N", null); RegisterXmlType(typeof(Int64), "Int64", null); RegisterXmlType(typeof(Int32?), "Int32N", null); RegisterXmlType(typeof(Int32), "Int32", null); RegisterXmlType(typeof(Int16?), "Int16N", null); RegisterXmlType(typeof(Int16), "Int16", null); RegisterXmlType(typeof(UInt64?), "UInt64N", null); RegisterXmlType(typeof(UInt64), "UInt64", null); RegisterXmlType(typeof(UInt32?), "UInt32N", null); RegisterXmlType(typeof(UInt32), "UInt32", null); RegisterXmlType(typeof(UInt16?), "UInt16N", null); RegisterXmlType(typeof(UInt16), "UInt16", null); RegisterXmlType(typeof(Single?), "Float32N", null); RegisterXmlType(typeof(Single), "Float32", null); RegisterXmlType(typeof(Double?), "Float64N", null); RegisterXmlType(typeof(Double), "Float64", null); RegisterXmlType(typeof(String), "String", null); RegisterXmlType(typeof(Object), "Object", null); RegisterXmlType(typeof(Type), "Class", null); RegisterXmlType(typeof(IList), "List", null); RegisterXmlType(typeof(IList<>), "ListG", null); RegisterXmlType(typeof(ObservableCollection<>), "ListG", null); RegisterXmlType(typeof(ISet<>), "SetG", null); RegisterXmlType(typeof(DateTime), "Date", null); } public Type GetType(String name, String namespaceString) { ParamChecker.AssertParamNotNull(name, "name"); if (namespaceString == null) { namespaceString = String.Empty; } XmlTypeKey xmlTypeKey = new XmlTypeKey(); xmlTypeKey.Name = name; xmlTypeKey.Namespace = namespaceString; readLock.Lock(); try { Type type = xmlTypeToClassMap.Get(name, namespaceString); if (type == null) { if (Log.DebugEnabled) { LoggerHistory.DebugOnce(Log, this, "XmlTypeNotFound: name=" + name + ", namespace=" + namespaceString); } return null; } return type; } finally { readLock.Unlock(); } } public IXmlTypeKey GetXmlType(Type type) { return GetXmlType(type, true); } public IXmlTypeKey GetXmlType(Type type, bool expectExisting) { ParamChecker.AssertParamNotNull(type, "type"); readLock.Lock(); try { IList<XmlTypeKey> xmlTypeKeys = DictionaryExtension.ValueOrDefault(weakClassToXmlTypeMap, type); if (xmlTypeKeys == null) { xmlTypeKeys = DictionaryExtension.ValueOrDefault(classToXmlTypeMap, type); if (xmlTypeKeys == null) { Type realType = type; if (typeof(IObjRef).IsAssignableFrom(type)) { realType = typeof(IObjRef); } xmlTypeKeys = DictionaryExtension.ValueOrDefault(classToXmlTypeMap, realType); } if (xmlTypeKeys != null) { readLock.Unlock(); writeLock.Lock(); try { if (!weakClassToXmlTypeMap.ContainsKey(type)) { weakClassToXmlTypeMap.Add(type, xmlTypeKeys); } } finally { writeLock.Unlock(); readLock.Lock(); } } } if ((xmlTypeKeys == null || xmlTypeKeys.Count == 0) && expectExisting) { throw new Exception("No xml type found: Type=" + type); } return xmlTypeKeys[0]; } finally { readLock.Unlock(); } } public void RegisterXmlType(Type type, String name, String namespaceString) { ParamChecker.AssertParamNotNull(type, "type"); ParamChecker.AssertParamNotNull(name, "name"); if (namespaceString == null) { namespaceString = String.Empty; } XmlTypeKey xmlTypeKey = new XmlTypeKey(); xmlTypeKey.Name = name; xmlTypeKey.Namespace = namespaceString; writeLock.Lock(); try { Type typeToSet = type; Type existingType = xmlTypeToClassMap.Get(name, namespaceString); if (existingType != null) { if (type.IsAssignableFrom(existingType)) { // Nothing else to to } else if (existingType.IsAssignableFrom(type)) { typeToSet = existingType; } else if (typeof(IList<>).Equals(existingType) && typeof(ObservableCollection<>).Equals(type)) { // Workaround for C# since the two collections are not assignable to eachother. typeToSet = existingType; } else { throw new Exception("Error while registering '" + type.FullName + "': Unassignable type '" + existingType.FullName + "' already registered for: Name='" + name + "' Namespace='" + namespaceString + "'"); } } xmlTypeToClassMap.Put(name, namespaceString, typeToSet); IList<XmlTypeKey> xmlTypeKeys = DictionaryExtension.ValueOrDefault(classToXmlTypeMap, type); if (xmlTypeKeys == null) { xmlTypeKeys = new List<XmlTypeKey>(); classToXmlTypeMap.Add(type, xmlTypeKeys); } xmlTypeKeys.Add(xmlTypeKey); } finally { writeLock.Unlock(); } } public void UnregisterXmlType(Type type, String name, String namespaceString) { ParamChecker.AssertParamNotNull(type, "type"); ParamChecker.AssertParamNotNull(name, "name"); if (namespaceString == null) { namespaceString = String.Empty; } XmlTypeKey xmlTypeKey = new XmlTypeKey(); xmlTypeKey.Name = name; xmlTypeKey.Namespace = namespaceString; writeLock.Lock(); try { xmlTypeToClassMap.Remove(xmlTypeKey.Name, xmlTypeKey.Namespace); IList<XmlTypeKey> xmlTypeKeys = classToXmlTypeMap[type]; xmlTypeKeys.Remove(xmlTypeKey); if (xmlTypeKeys.Count == 0) { classToXmlTypeMap.Remove(type); } } finally { writeLock.Unlock(); } } } }
using Api; using Newtonsoft.Json; using RestSharp; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Client { /// <summary> /// API client is mainly responible for making the HTTP call to the API backend. /// </summary> public class ApiClient { public ApiClient() { Configuration = Configuration.Default; RestClient = new RestClient(PBHeaders.EndPoint); } public ApiClient(Configuration config = null) { if (config == null) Configuration = Configuration.Default; else Configuration = config; RestClient = new RestClient(PBHeaders.EndPoint); } /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default configuration. /// </summary> /// <param name="basePath">The base path.</param> public ApiClient(String basePath = PBHeaders.EndPoint) { if (String.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); RestClient = new RestClient(basePath); Configuration = Configuration.Default; } /// <summary> /// Gets or sets the default API client for making HTTP calls. /// </summary> /// <value>The default API client.</value> public static ApiClient Default = new ApiClient(Configuration.Default); /// <summary> /// Gets or sets the Configuration. /// </summary> /// <value>An instance of the Configuration.</value> public Configuration Configuration { get; set; } /// <summary> /// Gets or sets the RestClient. /// </summary> /// <value>An instance of the RestClient</value> public RestClient RestClient { get; set; } // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody, Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams, String contentType) { var request = new RestRequest(path, method); string usedBy = Configuration != null ? Configuration.UsedBy ?? "" : Configuration.Default.UsedBy ?? ""; request.AddHeader("User-Agent", string.Format("{0}{1}", PBHeaders.UserAgent, usedBy)); // add path parameter, if any foreach (var param in pathParams) request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); // add header parameter, if any foreach (var param in headerParams) request.AddHeader(param.Key, param.Value); // add query parameter, if any foreach (var param in queryParams) request.AddQueryParameter(param.Key, param.Value); // add form parameter, if any foreach (var param in formParams) request.AddParameter(param.Key, param.Value); // add file parameter, if any foreach (var param in fileParams) request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); if (postBody != null) // http body (model or byte[]) parameter { if (postBody.GetType() == typeof(String)) { request.AddParameter("application/json", postBody, ParameterType.RequestBody); } else if (postBody.GetType() == typeof(byte[])) { request.AddParameter(contentType, postBody, ParameterType.RequestBody); } } return request; } /// <summary> /// Makes the HTTP request (Sync). /// </summary> /// <param name="path">URL path.</param> /// <param name="method">HTTP method.</param> /// <param name="queryParams">Query parameters.</param> /// <param name="postBody">HTTP body (POST request).</param> /// <param name="headerParams">Header parameters.</param> /// <param name="formParams">Form parameters.</param> /// <param name="fileParams">File parameters.</param> /// <param name="pathParams">Path parameters.</param> /// <param name="contentType">Content Type of the request</param> /// <returns>Object</returns> public Object CallApi( String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody, Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams, String contentType) { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); var response = RestClient.Execute(request); return (Object)response; } /// <summary> /// Makes the asynchronous HTTP request. /// </summary> /// <param name="path">URL path.</param> /// <param name="method">HTTP method.</param> /// <param name="queryParams">Query parameters.</param> /// <param name="postBody">HTTP body (POST request).</param> /// <param name="headerParams">Header parameters.</param> /// <param name="formParams">Form parameters.</param> /// <param name="fileParams">File parameters.</param> /// <param name="pathParams">Path parameters.</param> /// <param name="contentType">Content type.</param> /// <returns>The Task instance.</returns> public async System.Threading.Tasks.Task<Object> CallApiAsync( String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody, Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams, String contentType) { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); var response = await RestClient.ExecuteTaskAsync(request); return (Object)response; } /// <summary> /// Escape string (url-encoded). /// </summary> /// <param name="str">String to be escaped.</param> /// <returns>Escaped string.</returns> public string EscapeString(string str) { return UrlEncode(str); } /// <summary> /// Create FileParameter based on Stream. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="stream">Input stream.</param> /// <returns>FileParameter.</returns> public FileParameter ParameterToFile(string name, Stream stream) { if (stream is FileStream) return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name)); else return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided"); } /// <summary> /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. /// If parameter is a list, join the list with ",". /// Otherwise just return the string. /// </summary> /// <param name="obj">The parameter (header, path, query, form).</param> /// <returns>Formatted string.</returns> public string ParameterToString(object obj) { if (obj is DateTime) // Return a formatted date string - Can be customized with Configuration.DateTimeFormat // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTime)obj).ToString(Configuration.DateTimeFormat); else if (obj is DateTimeOffset) // Return a formatted date string - Can be customized with Configuration.DateTimeFormat // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTimeOffset)obj).ToString(Configuration.DateTimeFormat); else if (obj is IList) { var flattenedString = new StringBuilder(); foreach (var param in (IList)obj) { if (flattenedString.Length > 0) flattenedString.Append(","); flattenedString.Append(param); } return flattenedString.ToString(); } else return Convert.ToString(obj); } /// <summary> /// Deserialize the JSON string into a proper object. /// </summary> /// <param name="response">The HTTP response.</param> /// <param name="type">Object type.</param> /// <returns>Object representation of the JSON string.</returns> public object Deserialize(IRestResponse response, Type type) { byte[] data = response.RawBytes; string content = response.Content; IList<Parameter> headers = response.Headers; if (type == typeof(Object)) // return an object { return content; } else if (type == typeof(byte[])) // return byte array { return data; } if (type == typeof(Stream)) { if (headers != null) { var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) ? Path.GetTempPath() : Configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); foreach (var header in headers) { var match = regex.Match(header.ToString()); if (match.Success) { string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); File.WriteAllBytes(fileName, data); return new FileStream(fileName, FileMode.Open); } } } var stream = new MemoryStream(data); return stream; } if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { return DateTime.Parse(content, null, System.Globalization.DateTimeStyles.RoundtripKind); } if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type { return ConvertType(content, type); } // at this point, it must be a model (json) try { return JsonConvert.DeserializeObject(content, type); } catch (Exception e) { throw new ApiException(500, e.Message); } } /// <summary> /// Serialize an input (model) into JSON string /// </summary> /// <param name="obj">Object.</param> /// <returns>JSON string.</returns> public String Serialize(object obj) { try { return obj != null ? JsonConvert.SerializeObject(obj) : null; } catch (Exception e) { throw new ApiException(500, e.Message); } } /// <summary> /// Select the Content-Type header's value from the given content-type array: /// if JSON exists in the given array, use it; /// otherwise use the first one defined in 'consumes' /// </summary> /// <param name="contentTypes">The Content-Type array to select from.</param> /// <returns>The Content-Type header to use.</returns> public String SelectHeaderContentType(String[] contentTypes) { if (contentTypes.Length == 0) return null; if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; return contentTypes[0]; // use the first content type specified in 'consumes' } /// <summary> /// Select the Accept header's value from the given accepts array: /// if JSON exists in the given array, use it; /// otherwise use all of them (joining into a string) /// </summary> /// <param name="accepts">The accepts array to select from.</param> /// <returns>The Accept header to use.</returns> public String SelectHeaderAccept(String[] accepts) { if (accepts.Length == 0) return null; if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; return String.Join(",", accepts); } /// <summary> /// Encode string in base64 format. /// </summary> /// <param name="text">String to be encoded.</param> /// <returns>Encoded string.</returns> public static string Base64Encode(string text) { return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); } /// <summary> /// Dynamically cast the object into target type. /// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast /// </summary> /// <param name="source">Object to be casted</param> /// <param name="dest">Target type</param> /// <returns>Casted object</returns> public static dynamic ConvertType(dynamic source, Type dest) { return Convert.ChangeType(source, dest); } /// <summary> /// Convert stream to byte array /// Credit/Ref: http://stackoverflow.com/a/221941/677735 /// </summary> /// <param name="input">Input stream to be converted</param> /// <returns>Byte array</returns> public static byte[] ReadAsBytes(Stream input) { byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } /// <summary> /// URL encode a string /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 /// </summary> /// <param name="input">String to be URL encoded</param> /// <returns>Byte array</returns> public static string UrlEncode(string input) { const int maxLength = 32766; if (input == null) { throw new ArgumentNullException("input"); } if (input.Length <= maxLength) { return Uri.EscapeDataString(input); } StringBuilder sb = new StringBuilder(input.Length * 2); int index = 0; while (index < input.Length) { int length = Math.Min(input.Length - index, maxLength); string subString = input.Substring(index, length); sb.Append(Uri.EscapeDataString(subString)); index += subString.Length; } return sb.ToString(); } /// <summary> /// Sanitize filename by removing the path /// </summary> /// <param name="filename">Filename</param> /// <returns>Filename</returns> public static string SanitizeFilename(string filename) { Match match = Regex.Match(filename, @".*[/\\](.*)$"); if (match.Success) { return match.Groups[1].Value; } else { return filename; } } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.V2.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAgentsClientTest { [xunit::FactAttribute] public void GetAgentRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.GetAgent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.GetAgentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.GetAgentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAgent() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.GetAgent(request.Parent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.GetAgentAsync(request.Parent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.GetAgentAsync(request.Parent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAgentResourceNames1() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.GetAgent(request.ParentAsProjectName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentResourceNames1Async() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.GetAgentAsync(request.ParentAsProjectName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.GetAgentAsync(request.ParentAsProjectName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAgentResourceNames2() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.GetAgent(request.ParentAsLocationName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentResourceNames2Async() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.GetAgentAsync(request.ParentAsLocationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.GetAgentAsync(request.ParentAsLocationName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetAgentRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetAgentRequest request = new SetAgentRequest { Agent = new Agent(), UpdateMask = new wkt::FieldMask(), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.SetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.SetAgent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetAgentRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetAgentRequest request = new SetAgentRequest { Agent = new Agent(), UpdateMask = new wkt::FieldMask(), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.SetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.SetAgentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.SetAgentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetAgent() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetAgentRequest request = new SetAgentRequest { Agent = new Agent(), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.SetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.SetAgent(request.Agent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetAgentAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetAgentRequest request = new SetAgentRequest { Agent = new Agent(), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.SetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.SetAgentAsync(request.Agent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.SetAgentAsync(request.Agent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAgentRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); client.DeleteAgent(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAgentRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); await client.DeleteAgentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAgentAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAgent() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); client.DeleteAgent(request.Parent); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAgentAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); await client.DeleteAgentAsync(request.Parent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAgentAsync(request.Parent, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAgentResourceNames1() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); client.DeleteAgent(request.ParentAsProjectName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAgentResourceNames1Async() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); await client.DeleteAgentAsync(request.ParentAsProjectName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAgentAsync(request.ParentAsProjectName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAgentResourceNames2() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); client.DeleteAgent(request.ParentAsLocationName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAgentResourceNames2Async() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); await client.DeleteAgentAsync(request.ParentAsLocationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAgentAsync(request.ParentAsLocationName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetValidationResultRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetValidationResultRequest request = new GetValidationResultRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), LanguageCode = "language_code2f6c7160", }; ValidationResult expectedResponse = new ValidationResult { ValidationErrors = { new ValidationError(), }, }; mockGrpcClient.Setup(x => x.GetValidationResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); ValidationResult response = client.GetValidationResult(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetValidationResultRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetValidationResultRequest request = new GetValidationResultRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), LanguageCode = "language_code2f6c7160", }; ValidationResult expectedResponse = new ValidationResult { ValidationErrors = { new ValidationError(), }, }; mockGrpcClient.Setup(x => x.GetValidationResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ValidationResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); ValidationResult responseCallSettings = await client.GetValidationResultAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ValidationResult responseCancellationToken = await client.GetValidationResultAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Linq; using GeneticSharp.Domain.Chromosomes; using GeneticSharp.Domain.Crossovers; using GeneticSharp.Domain.Fitnesses; using GeneticSharp.Domain.Mutations; using GeneticSharp.Domain.Populations; using GeneticSharp.Domain.Randomizations; using GeneticSharp.Domain.Reinsertions; using GeneticSharp.Domain.Selections; using GeneticSharp.Domain.Terminations; using GeneticSharp.Infrastructure.Framework.Threading; using HelperSharp; namespace GeneticSharp.Domain { #region Enums /// <summary> /// The possible states for a genetic algorithm. /// </summary> public enum GeneticAlgorithmState { /// <summary> /// The GA has not been started yet. /// </summary> NotStarted, /// <summary> /// The GA has been started and is running. /// </summary> Started, /// <summary> /// The GA has been stopped ans is not running. /// </summary> Stopped, /// <summary> /// The GA has been resumed after a stop or terminantion reach and is running. /// </summary> Resumed, /// <summary> /// The GA has reach the termination condition and is not running. /// </summary> TerminationReached } #endregion /// <summary> /// A genetic algorithm (GA) is a search heuristic that mimics the process of natural selection. /// This heuristic (also sometimes called a metaheuristic) is routinely used to generate useful solutions /// to optimization and search problems. Genetic algorithms belong to the larger class of evolutionary /// algorithms (EA), which generate solutions to optimization problems using techniques inspired by natural evolution, /// such as inheritance, mutation, selection, and crossover. /// /// Genetic algorithms find application in bioinformatics, phylogenetics, computational science, engineering, /// economics, chemistry, manufacturing, mathematics, physics, pharmacometrics, game development and other fields. /// /// <see href="http://http://en.wikipedia.org/wiki/Genetic_algorithm">Wikipedia</see> /// </summary> public sealed class GeneticAlgorithm : IGeneticAlgorithm { #region Fields private bool m_stopRequested; private object m_lock = new object(); private GeneticAlgorithmState m_state; #endregion #region Constants /// <summary> /// The default crossover probability. /// </summary> public const float DefaultCrossoverProbability = 0.75f; /// <summary> /// The default mutation probability. /// </summary> public const float DefaultMutationProbability = 0.1f; #endregion #region Events /// <summary> /// Occurs when generation ran. /// </summary> public event EventHandler GenerationRan; /// <summary> /// Occurs when termination reached. /// </summary> public event EventHandler TerminationReached; /// <summary> /// Occurs when stopped. /// </summary> public event EventHandler Stopped; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="GeneticSharp.Domain.GeneticAlgorithm"/> class. /// </summary> /// <param name="population">The chromosomes population.</param> /// <param name="fitness">The fitness evaluation function.</param> /// <param name="selection">The selection operator.</param> /// <param name="crossover">The crossover operator.</param> /// <param name="mutation">The mutation operator.</param> public GeneticAlgorithm(Population population, IFitness fitness, ISelection selection, ICrossover crossover, IMutation mutation) { ExceptionHelper.ThrowIfNull("Population", population); ExceptionHelper.ThrowIfNull("fitness", fitness); ExceptionHelper.ThrowIfNull("selection", selection); ExceptionHelper.ThrowIfNull("crossover", crossover); ExceptionHelper.ThrowIfNull("mutation", mutation); Population = population; Fitness = fitness; Selection = selection; Crossover = crossover; Mutation = mutation; Reinsertion = new ElitistReinsertion(); Termination = new GenerationNumberTermination(1); CrossoverProbability = DefaultCrossoverProbability; MutationProbability = DefaultMutationProbability; TimeEvolving = TimeSpan.Zero; State = GeneticAlgorithmState.NotStarted; TaskExecutor = new LinearTaskExecutor(); } #endregion #region Properties /// <summary> /// Gets the population. /// </summary> /// <value>The population.</value> public Population Population { get; private set; } /// <summary> /// Gets the fitness function. /// </summary> public IFitness Fitness { get; private set; } /// <summary> /// Gets the selection operator. /// </summary> public ISelection Selection { get; set; } /// <summary> /// Gets the crossover operator. /// </summary> /// <value>The crossover.</value> public ICrossover Crossover { get; set; } /// <summary> /// Gets or sets the crossover probability. /// </summary> public float CrossoverProbability { get; set; } /// <summary> /// Gets the mutation operator. /// </summary> public IMutation Mutation { get; set; } /// <summary> /// Gets or sets the mutation probability. /// </summary> public float MutationProbability { get; set; } /// <summary> /// Gets or sets the reinsertion operator. /// </summary> public IReinsertion Reinsertion { get; set; } /// <summary> /// Gets or sets the termination condition. /// </summary> public ITermination Termination { get; set; } /// <summary> /// Gets the generations number. /// </summary> /// <value>The generations number.</value> public int GenerationsNumber { get { return Population.GenerationsNumber; } } /// <summary> /// Gets the best chromosome. /// </summary> /// <value>The best chromosome.</value> public IChromosome BestChromosome { get { return Population.BestChromosome; } } /// <summary> /// Gets the time evolving. /// </summary> public TimeSpan TimeEvolving { get; private set; } /// <summary> /// Gets the state. /// </summary> public GeneticAlgorithmState State { get { return m_state; } private set { var goToStopped = Stopped != null && m_state != value && value == GeneticAlgorithmState.Stopped; m_state = value; if (goToStopped) { Stopped(this, EventArgs.Empty); } } } /// <summary> /// Gets a value indicating whether this instance is running. /// </summary> /// <value><c>true</c> if this instance is running; otherwise, <c>false</c>.</value> public bool IsRunning { get { return State == GeneticAlgorithmState.Started || State == GeneticAlgorithmState.Resumed; } } /// <summary> /// Gets or sets the task executor which will be used to execute fitness evaluation. /// </summary> public ITaskExecutor TaskExecutor { get; set; } #endregion #region Methods /// <summary> /// Starts the genetic algorithm using population, fitness, selection, crossover, mutation and termination configured. /// </summary> public void Start() { lock (m_lock) { State = GeneticAlgorithmState.Started; var startDateTime = DateTime.Now; Population.CreateInitialGeneration(); TimeEvolving = DateTime.Now - startDateTime; } Resume(); } /// <summary> /// Resumes the last evolution of the genetic algorithm. /// <remarks> /// If genetic algorithm was not explicit Stop (calling Stop method), you will need provide a new extended Termination. /// </remarks> /// </summary> public void Resume() { try { lock (m_lock) { m_stopRequested = false; } if (Population.GenerationsNumber == 0) { throw new InvalidOperationException("Attempt to resume a genetic algorithm which was not yet started."); } else if (Population.GenerationsNumber > 1) { if (Termination.HasReached(this)) { throw new InvalidOperationException("Attempt to resume a genetic algorithm with a termination ({0}) already reached. Please, specify a new termination or extend the current one.".With(Termination)); } State = GeneticAlgorithmState.Resumed; } if (EndCurrentGeneration()) { return; } bool terminationConditionReached = false; DateTime startDateTime; do { if (m_stopRequested) { break; } startDateTime = DateTime.Now; terminationConditionReached = EvolveOneGeneration(); TimeEvolving += DateTime.Now - startDateTime; } while (!terminationConditionReached); } catch { State = GeneticAlgorithmState.Stopped; throw; } } /// <summary> /// Stops the genetic algorithm.. /// </summary> public void Stop() { if (Population.GenerationsNumber == 0) { throw new InvalidOperationException("Attempt to stop a genetic algorithm which was not yet started."); } lock (m_lock) { m_stopRequested = true; } } /// <summary> /// Evolve one generation. /// </summary> /// <returns>True if termination has been reached, otherwise false.</returns> private bool EvolveOneGeneration() { var parents = SelectParents(); var offspring = Cross(parents); Mutate(offspring); var newGenerationChromosomes = Reinsert(offspring, parents); Population.CreateNewGeneration(newGenerationChromosomes); return EndCurrentGeneration(); } /// <summary> /// Ends the current generation. /// </summary> /// <returns><c>true</c>, if current generation was ended, <c>false</c> otherwise.</returns> private bool EndCurrentGeneration() { EvaluateFitness(); Population.EndCurrentGeneration(); if (GenerationRan != null) { GenerationRan(this, EventArgs.Empty); } if (Termination.HasReached(this)) { State = GeneticAlgorithmState.TerminationReached; if (TerminationReached != null) { TerminationReached(this, EventArgs.Empty); } return true; } if (m_stopRequested) { TaskExecutor.Stop(); State = GeneticAlgorithmState.Stopped; } return false; } /// <summary> /// Evaluates the fitness. /// </summary> private void EvaluateFitness() { try { var chromosomesWithoutFitness = Population.CurrentGeneration.Chromosomes.Where(c => !c.Fitness.HasValue).ToList(); for (int i = 0; i < chromosomesWithoutFitness.Count; i++) { var c = chromosomesWithoutFitness[i]; TaskExecutor.Add(() => { RunEvaluateFitness(c); }); } if (!TaskExecutor.Start()) { throw new TimeoutException("The fitness evaluation rech the {0} timeout.".With(TaskExecutor.Timeout)); } foreach (var c in chromosomesWithoutFitness) { if (c.Fitness < 0 || c.Fitness > 1) { throw new FitnessException(Fitness, "The {0}.Evaluate returns a fitness with value {1}. The fitness value should be between 0.0 and 1.0." .With(Fitness.GetType(), c.Fitness)); } } } finally { TaskExecutor.Stop(); TaskExecutor.Clear(); } Population.CurrentGeneration.Chromosomes = Population.CurrentGeneration.Chromosomes.OrderByDescending(c => c.Fitness.Value).ToList(); } /// <summary> /// Runs the evaluate fitness. /// </summary> /// <returns>The evaluate fitness.</returns> /// <param name="state">State.</param> private object RunEvaluateFitness(object state) { var c = state as IChromosome; try { c.Fitness = Fitness.Evaluate(c); } catch (Exception ex) { throw new FitnessException(Fitness, "Error executing Fitness.Evaluate for chromosome: {0}".With(ex.Message), ex); } return c.Fitness; } /// <summary> /// Selects the parents. /// </summary> /// <returns>The parents.</returns> private IList<IChromosome> SelectParents() { return Selection.SelectChromosomes(Population.MinSize, Population.CurrentGeneration); } /// <summary> /// Cross this instance. /// </summary> private IList<IChromosome> Cross(IList<IChromosome> parents) { var offspring = new List<IChromosome>(); for (int i = 0; i < Population.MinSize; i += Crossover.ParentsNumber) { var selectedParents = parents.Skip(i).Take(Crossover.ParentsNumber).ToList(); // If match the probability cross is made, otherwise the offspring is an exact copy of the parents. // Checks if the number of selected parents is equal which the crossover expect, because the in the end of the list we can // have some rest chromosomes. if (selectedParents.Count == Crossover.ParentsNumber && RandomizationProvider.Current.GetDouble() <= CrossoverProbability) { offspring.AddRange(Crossover.Cross(selectedParents)); } } return offspring; } /// <summary> /// Mutate the specified chromosomes. /// </summary> /// <param name="chromosomes">Chromosomes.</param> private void Mutate(IList<IChromosome> chromosomes) { foreach (var c in chromosomes) { Mutation.Mutate(c, MutationProbability); } } /// <summary> /// Reinsert the specified offspring and parents. /// </summary> /// <param name="offspring">offspring.</param> /// <param name="parents">Parents.</param> private IList<IChromosome> Reinsert(IList<IChromosome> offspring, IList<IChromosome> parents) { return Reinsertion.SelectChromosomes(Population, offspring, parents); } #endregion } }
/* * 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 Newtonsoft.Json; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Securities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using QuantConnect.Orders.Fees; using System.Threading; using QuantConnect.Orders; using QuantConnect.Brokerages.Zerodha.Messages; using Tick = QuantConnect.Data.Market.Tick; using System.Net.WebSockets; using System.Text; using Newtonsoft.Json.Linq; using NodaTime; using QuantConnect.Data.Market; using QuantConnect.Configuration; using QuantConnect.Util; using Order = QuantConnect.Orders.Order; using OrderType = QuantConnect.Orders.OrderType; namespace QuantConnect.Brokerages.Zerodha { /// <summary> /// Zerodha Brokerage implementation /// </summary> [BrokerageFactory(typeof(ZerodhaBrokerageFactory))] public partial class ZerodhaBrokerage : Brokerage, IDataQueueHandler { #region Declarations private const int ConnectionTimeout = 30000; /// <summary> /// The websockets client instance /// </summary> protected WebSocketClientWrapper WebSocket; /// <summary> /// standard json parsing settings /// </summary> protected JsonSerializerSettings JsonSettings = new JsonSerializerSettings { FloatParseHandling = FloatParseHandling.Decimal }; /// <summary> /// A list of currently active orders /// </summary> public ConcurrentDictionary<int, Order> CachedOrderIDs = new ConcurrentDictionary<int, Order>(); /// <summary> /// The api secret /// </summary> protected string ApiSecret; /// <summary> /// The api key /// </summary> protected string ApiKey; private readonly ISecurityProvider _securityProvider; private readonly IAlgorithm _algorithm; private readonly ConcurrentDictionary<int, decimal> _fills = new ConcurrentDictionary<int, decimal>(); private readonly DataQueueHandlerSubscriptionManager SubscriptionManager; private ConcurrentDictionary<string, Symbol> _subscriptionsById = new ConcurrentDictionary<string, Symbol>(); private readonly IDataAggregator _aggregator; private readonly ZerodhaSymbolMapper _symbolMapper; private readonly List<string> subscribeInstrumentTokens = new List<string>(); private readonly List<string> unSubscribeInstrumentTokens = new List<string>(); private Kite _kite; private readonly string _apiKey; private readonly string _accessToken; private readonly string _wssUrl = "wss://ws.kite.trade/"; private readonly string _tradingSegment; private readonly BrokerageConcurrentMessageHandler<WebSocketClientWrapper.MessageData> _messageHandler; private readonly string _zerodhaProductType; private DateTime _lastTradeTickTime; private bool _historyDataTypeErrorFlag; #endregion /// <summary> /// Constructor for brokerage /// </summary> /// <param name="aggregator">data aggregator </param> /// <param name="tradingSegment">trading segment</param> /// <param name="zerodhaProductType">zerodha product type - MIS, CNC or NRML </param> /// <param name="apiKey">api key</param> /// <param name="apiSecret">api secret</param> /// <param name="algorithm">the algorithm instance is required to retrieve account type</param> /// <param name="securityProvider">Security provider for fetching holdings</param> public ZerodhaBrokerage(string tradingSegment, string zerodhaProductType, string apiKey, string apiSecret, IAlgorithm algorithm, ISecurityProvider securityProvider, IDataAggregator aggregator) : base("Zerodha") { _tradingSegment = tradingSegment; _zerodhaProductType = zerodhaProductType; _algorithm = algorithm; _aggregator = aggregator; _kite = new Kite(apiKey, apiSecret); _apiKey = apiKey; _accessToken = apiSecret; _securityProvider = securityProvider; _messageHandler = new BrokerageConcurrentMessageHandler<WebSocketClientWrapper.MessageData>(OnMessageImpl); WebSocket = new WebSocketClientWrapper(); _wssUrl += string.Format(CultureInfo.InvariantCulture, "?api_key={0}&access_token={1}", _apiKey, _accessToken); WebSocket.Initialize(_wssUrl); WebSocket.Message += OnMessage; WebSocket.Open += (sender, args) => { Log.Trace($"ZerodhaBrokerage(): WebSocket.Open. Subscribing"); Subscribe(GetSubscribed()); }; WebSocket.Error += OnError; _symbolMapper = new ZerodhaSymbolMapper(_kite); var subscriptionManager = new EventBasedDataQueueHandlerSubscriptionManager(); subscriptionManager.SubscribeImpl += (s, t) => { Subscribe(s); return true; }; subscriptionManager.UnsubscribeImpl += (s, t) => Unsubscribe(s); SubscriptionManager = subscriptionManager; Log.Trace("Start Zerodha Brokerage"); } /// <summary> /// Subscribes to the requested symbols (using an individual streaming channel) /// </summary> /// <param name="symbols">The list of symbols to subscribe</param> public void Subscribe(IEnumerable<Symbol> symbols) { if (symbols.Count() <= 0) { return; } foreach (var symbol in symbols) { var instrumentTokenList = _symbolMapper.GetZerodhaInstrumentTokenList(symbol.ID.Symbol); if (instrumentTokenList.Count == 0) { Log.Error($"ZerodhaBrokerage.Subscribe(): Invalid Zerodha Instrument token for given: {symbol.ID.Symbol}"); continue; } foreach (var instrumentToken in instrumentTokenList) { var tokenStringInvariant = instrumentToken.ToStringInvariant(); if (!subscribeInstrumentTokens.Contains(tokenStringInvariant)) { subscribeInstrumentTokens.Add(tokenStringInvariant); unSubscribeInstrumentTokens.Remove(tokenStringInvariant); _subscriptionsById[tokenStringInvariant] = symbol; } } } //Websocket Data subscription modes. Full mode gives depth of asks and bids along with basic data. var request = "{\"a\":\"subscribe\",\"v\":[" + String.Join(",", subscribeInstrumentTokens.ToArray()) + "]}"; var requestFullMode = "{\"a\":\"mode\",\"v\":[\"full\",[" + String.Join(",", subscribeInstrumentTokens.ToArray()) + "]]}"; WebSocket.Send(request); WebSocket.Send(requestFullMode); } /// <summary> /// Get list of subscribed symbol /// </summary> /// <returns></returns> private IEnumerable<Symbol> GetSubscribed() { return SubscriptionManager.GetSubscribedSymbols() ?? Enumerable.Empty<Symbol>(); } /// <summary> /// Ends current subscriptions /// </summary> private bool Unsubscribe(IEnumerable<Symbol> symbols) { if (WebSocket.IsOpen) { foreach (var symbol in symbols) { var instrumentTokenList = _symbolMapper.GetZerodhaInstrumentTokenList(symbol.ID.Symbol); if (instrumentTokenList.Count == 0) { Log.Error($"ZerodhaBrokerage.Unsubscribe(): Invalid Zerodha Instrument token for given: {symbol.ID.Symbol}"); continue; } foreach (var instrumentToken in instrumentTokenList) { var tokenStringInvariant = instrumentToken.ToStringInvariant(); if (!unSubscribeInstrumentTokens.Contains(tokenStringInvariant)) { unSubscribeInstrumentTokens.Add(tokenStringInvariant); subscribeInstrumentTokens.Remove(tokenStringInvariant); Symbol unSubscribeSymbol; _subscriptionsById.TryRemove(tokenStringInvariant, out unSubscribeSymbol); } } } var request = "{\"a\":\"unsubscribe\",\"v\":[" + String.Join(",", unSubscribeInstrumentTokens.ToArray()) + "]}"; WebSocket.Send(request); return true; } return false; } /// <summary> /// Gets Quote using Zerodha API /// </summary> /// <returns> Quote</returns> public Quote GetQuote(Symbol symbol) { var instrumentTokenList = _symbolMapper.GetZerodhaInstrumentTokenList(symbol.ID.Symbol); if (instrumentTokenList.Count == 0) { throw new ArgumentException($"ZerodhaBrokerage.GetQuote(): Invalid Zerodha Instrument token for given: {symbol.ID.Symbol}"); } var instrument = instrumentTokenList[0]; var instrumentIds = new string[] { instrument.ToStringInvariant() }; var quotes = _kite.GetQuote(instrumentIds); return quotes[instrument.ToStringInvariant()]; } /// <summary> /// Zerodha brokerage order events /// </summary> /// <param name="orderUpdate"></param> private void OnOrderUpdate(Messages.Order orderUpdate) { try { var brokerId = orderUpdate.OrderId; Log.Trace("OnZerodhaOrderEvent(): Broker ID:" + brokerId); var order = CachedOrderIDs .FirstOrDefault(o => o.Value.BrokerId.Contains(brokerId)) .Value; if (order == null) { Log.Error($"ZerodhaBrokerage.OnOrderUpdate(): order not found: BrokerId: {brokerId}"); return; } if (orderUpdate.Status == "CANCELLED") { Order outOrder; CachedOrderIDs.TryRemove(order.Id, out outOrder); decimal ignored; _fills.TryRemove(order.Id, out ignored); } if (orderUpdate.Status == "REJECTED") { Order outOrder; CachedOrderIDs.TryRemove(order.Id, out outOrder); decimal ignored; _fills.TryRemove(order.Id, out ignored); OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero, "Zerodha Order Rejected Event: " + orderUpdate.StatusMessage) { Status = OrderStatus.Canceled }); } if (orderUpdate.FilledQuantity > 0) { var symbol = _symbolMapper.ConvertZerodhaSymbolToLeanSymbol(orderUpdate.InstrumentToken); var fillPrice = orderUpdate.AveragePrice; decimal cumulativeFillQuantity = orderUpdate.FilledQuantity; var direction = orderUpdate.TransactionType == "SELL" ? OrderDirection.Sell : OrderDirection.Buy; var updTime = orderUpdate.OrderTimestamp.GetValueOrDefault(); var security = _securityProvider.GetSecurity(order.Symbol); var orderFee = security.FeeModel.GetOrderFee( new OrderFeeParameters(security, order)); if (direction == OrderDirection.Sell) { cumulativeFillQuantity = -1 * cumulativeFillQuantity; } var status = OrderStatus.Filled; if (cumulativeFillQuantity != order.Quantity) { status = OrderStatus.PartiallyFilled; } decimal totalRegisteredFillQuantity; _fills.TryGetValue(order.Id, out totalRegisteredFillQuantity); //async events received from zerodha: https://kite.trade/forum/discussion/comment/34752/#Comment_34752 if (Math.Abs(cumulativeFillQuantity) <= Math.Abs(totalRegisteredFillQuantity)) { // already filled more quantity return; } _fills[order.Id] = cumulativeFillQuantity; var fillQuantityInThisEvewnt = cumulativeFillQuantity - totalRegisteredFillQuantity; var orderEvent = new OrderEvent ( order.Id, symbol, updTime, status, direction, fillPrice, fillQuantityInThisEvewnt, orderFee, $"Zerodha Order Event {direction}" ); // if the order is closed, we no longer need it in the active order list if (status == OrderStatus.Filled) { Order outOrder; CachedOrderIDs.TryRemove(order.Id, out outOrder); decimal ignored; _fills.TryRemove(order.Id, out ignored); } OnOrderEvent(orderEvent); } } catch (Exception e) { Log.Error(e); throw; } } #region IBrokerage /// <summary> /// Returns the brokerage account's base currency /// </summary> public override string AccountBaseCurrency => Currencies.INR; /// <summary> /// Checks if the websocket connection is connected or in the process of connecting /// </summary> public override bool IsConnected => WebSocket.IsOpen; /// <summary> /// Connects to Zerodha wss /// </summary> public override void Connect() { if (IsConnected) { return; } Log.Trace("ZerodhaBrokerage.Connect(): Connecting..."); var resetEvent = new ManualResetEvent(false); EventHandler triggerEvent = (o, args) => resetEvent.Set(); WebSocket.Open += triggerEvent; WebSocket.Connect(); if (!resetEvent.WaitOne(ConnectionTimeout)) { throw new TimeoutException("Websockets connection timeout."); } WebSocket.Open -= triggerEvent; } /// <summary> /// Closes the websockets connection /// </summary> public override void Disconnect() { //base.Disconnect(); if (WebSocket.IsOpen) { WebSocket.Close(); } } /// <summary> /// Places a new order and assigns a new broker ID to the order /// </summary> /// <param name="order">The order to be placed</param> /// <returns>True if the request for a new order has been placed, false otherwise</returns> public override bool PlaceOrder(Order order) { var submitted = false; _messageHandler.WithLockedStream(() => { uint orderQuantity = Convert.ToUInt32(Math.Abs(order.Quantity)); JObject orderResponse = new JObject();; decimal? triggerPrice = GetOrderTriggerPrice(order); decimal? orderPrice = GetOrderPrice(order); var kiteOrderType = ConvertOrderType(order.Type); var security = _securityProvider.GetSecurity(order.Symbol); var orderFee = security.FeeModel.GetOrderFee( new OrderFeeParameters(security, order)); var orderProperties = order.Properties as IndiaOrderProperties; var zerodhaProductType = _zerodhaProductType; if (orderProperties == null || orderProperties.Exchange == null) { var errorMessage = $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: Please specify a valid order properties with an exchange value"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Order Event") { Status = OrderStatus.Invalid }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, errorMessage)); return; } if (orderProperties.ProductType != null) { zerodhaProductType = orderProperties.ProductType; } else if (string.IsNullOrEmpty(zerodhaProductType)) { throw new ArgumentException("Please set ProductType in config or provide a value in DefaultOrderProperties"); } try { orderResponse = _kite.PlaceOrder(orderProperties.Exchange.ToString(), order.Symbol.ID.Symbol, order.Direction.ToString().ToUpperInvariant(), orderQuantity, orderPrice, zerodhaProductType, kiteOrderType, null, null, triggerPrice); } catch (Exception ex) { var errorMessage = $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: {ex.Message}"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Order Event") { Status = OrderStatus.Invalid }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, errorMessage)); return; } if ((string)orderResponse["status"] == "success") { if (string.IsNullOrEmpty((string)orderResponse["data"]["order_id"])) { var errorMessage = $"Error parsing response from place order: {(string)orderResponse["status_message"]}"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Order Event") { Status = OrderStatus.Invalid, Message = errorMessage }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, (string)orderResponse["status_message"], errorMessage)); return; } var brokerId = (string)orderResponse["data"]["order_id"]; if (CachedOrderIDs.ContainsKey(order.Id)) { CachedOrderIDs[order.Id].BrokerId.Clear(); CachedOrderIDs[order.Id].BrokerId.Add(brokerId); } else { order.BrokerId.Add(brokerId); CachedOrderIDs.TryAdd(order.Id, order); } // Generate submitted event OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Order Event") { Status = OrderStatus.Submitted }); Log.Trace($"Order submitted successfully - OrderId: {order.Id}"); submitted = true; return; } var message = $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: {orderResponse["status_message"]}"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Order Event") { Status = OrderStatus.Invalid }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, message)); return; }); return submitted; } /// <summary> /// Return a relevant price for order depending on order type /// Price must be positive /// </summary> /// <param name="order"></param> /// <returns></returns> private static decimal? GetOrderPrice(Order order) { switch (order.Type) { case OrderType.Limit: return ((LimitOrder)order).LimitPrice; case OrderType.StopLimit: return ((StopLimitOrder)order).LimitPrice; case OrderType.Market: case OrderType.StopMarket: return null; } throw new NotSupportedException($"ZerodhaBrokerage.ConvertOrderType: Unsupported order type: {order.Type}"); } /// <summary> /// Return a relevant price for order depending on order type /// Price must be positive /// </summary> /// <param name="order"></param> /// <returns></returns> private static decimal? GetOrderTriggerPrice(Order order) { switch (order.Type) { case OrderType.StopLimit: return ((StopLimitOrder)order).StopPrice; case OrderType.StopMarket: return ((StopMarketOrder)order).StopPrice; case OrderType.Limit: case OrderType.Market: return null; } throw new NotSupportedException($"ZerodhaBrokerage.ConvertOrderType: Unsupported order type: {order.Type}"); } private static string ConvertOrderType(OrderType orderType) { switch (orderType) { case OrderType.Limit: return "LIMIT"; case OrderType.Market: return "MARKET"; case OrderType.StopMarket: return "SL-M"; case OrderType.StopLimit: return "SL"; default: throw new NotSupportedException($"ZerodhaBrokerage.ConvertOrderType: Unsupported order type: {orderType}"); } } /// <summary> /// Updates the order with the same id /// </summary> /// <param name="order">The new order information</param> /// <returns>True if the request was made for the order to be updated, false otherwise</returns> public override bool UpdateOrder(Order order) { var submitted = false; _messageHandler.WithLockedStream(() => { if (!order.Status.IsOpen()) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "error", "Order is already being processed")); return; } var orderProperties = order.Properties as IndiaOrderProperties; var zerodhaProductType = _zerodhaProductType; if (orderProperties == null || orderProperties.Exchange == null) { var errorMessage = $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: Please specify a valid order properties with an exchange value"; OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, errorMessage)); return; } if (orderProperties.ProductType != null) { zerodhaProductType = orderProperties.ProductType; } else if (string.IsNullOrEmpty(zerodhaProductType)) { throw new ArgumentException("Please set ProductType in config or provide a value in DefaultOrderProperties"); } uint orderQuantity = Convert.ToUInt32(Math.Abs(order.Quantity)); JObject orderResponse = new JObject();; decimal? triggerPrice = GetOrderTriggerPrice(order); decimal? orderPrice = GetOrderPrice(order); var kiteOrderType = ConvertOrderType(order.Type); var orderFee = OrderFee.Zero; try { orderResponse = _kite.ModifyOrder(order.BrokerId[0].ToStringInvariant(), null, orderProperties.Exchange.ToString(), order.Symbol.ID.Symbol, order.Direction.ToString().ToUpperInvariant(), orderQuantity, orderPrice, zerodhaProductType, kiteOrderType, null, null, triggerPrice ); } catch (Exception ex) { OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Update Order Event") { Status = OrderStatus.Invalid }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: {ex.Message}")); return; } if ((string)orderResponse["status"] == "success") { if (string.IsNullOrEmpty((string)orderResponse["data"]["order_id"])) { var errorMessage = $"Error parsing response from modify order: {orderResponse["status_message"]}"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Update Order Event") { Status = OrderStatus.Invalid, Message = errorMessage }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, (string)orderResponse["status"], errorMessage)); submitted = true; return; } var brokerId = (string)orderResponse["data"]["order_id"]; if (CachedOrderIDs.ContainsKey(order.Id)) { CachedOrderIDs[order.Id].BrokerId.Clear(); CachedOrderIDs[order.Id].BrokerId.Add(brokerId); } else { order.BrokerId.Add(brokerId); CachedOrderIDs.TryAdd(order.Id, order); } // Generate submitted event OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Update Order Event") { Status = OrderStatus.UpdateSubmitted }); Log.Trace($"Order modified successfully - OrderId: {order.Id}"); submitted = true; return; } var message = $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: {orderResponse["status_message"]}"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Update Order Event") { Status = OrderStatus.Invalid }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, message)); return; }); return submitted; } /// <summary> /// Cancels the order with the specified ID /// </summary> /// <param name="order">The order to cancel</param> /// <returns>True if the request was submitted for cancellation, false otherwise</returns> public override bool CancelOrder(Order order) { var submitted = false; _messageHandler.WithLockedStream(() => { JObject orderResponse = new JObject(); if (order.Status.IsOpen()) { try { orderResponse = _kite.CancelOrder(order.BrokerId[0].ToStringInvariant()); } catch (Exception) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, (string)orderResponse["status"], $"Error cancelling order: {orderResponse["status_message"]}")); return; } } else { //Verify this OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, 500, $"Error cancelling open order")); return; } if ((string)orderResponse["status"] == "success") { OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero, "Zerodha Order Cancelled Event") { Status = OrderStatus.Canceled }); submitted = true; return; } var errorMessage = $"Error cancelling order: {orderResponse["status_message"]}"; OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, (string)orderResponse["status"], errorMessage)); return; }); return submitted; } /// <summary> /// Gets all orders not yet closed /// </summary> /// <returns></returns> public override List<Order> GetOpenOrders() { var allOrders = _kite.GetOrders(); List<Order> list = new List<Order>(); //Only loop if there are any actual orders inside response if (allOrders.Count > 0) { foreach (var item in allOrders.Where(z => z.Status == "OPEN" || z.Status == "TRIGGER PENDING")) { Order order; if (item.OrderType.ToUpperInvariant() == "MARKET") { order = new MarketOrder { Price = Convert.ToDecimal(item.Price, CultureInfo.InvariantCulture) }; } else if (item.OrderType.ToUpperInvariant() == "LIMIT") { order = new LimitOrder { LimitPrice = Convert.ToDecimal(item.Price, CultureInfo.InvariantCulture) }; } else if (item.OrderType.ToUpperInvariant() == "SL-M") { order = new StopMarketOrder { StopPrice = Convert.ToDecimal(item.Price, CultureInfo.InvariantCulture) }; } else if (item.OrderType.ToUpperInvariant() == "SL") { order = new StopLimitOrder { StopPrice = Convert.ToDecimal(item.TriggerPrice, CultureInfo.InvariantCulture), LimitPrice = Convert.ToDecimal(item.Price, CultureInfo.InvariantCulture) }; } else { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, "UnKnownOrderType", "ZerodhaBrorage.GetOpenOrders: Unsupported order type returned from brokerage: " + item.OrderType)); continue; } var itemTotalQty = item.Quantity; var originalQty = item.Quantity; order.Quantity = item.TransactionType.ToLowerInvariant() == "sell" ? -itemTotalQty : originalQty; order.BrokerId = new List<string> { item.OrderId }; order.Symbol = _symbolMapper.ConvertZerodhaSymbolToLeanSymbol(item.InstrumentToken); order.Time = (DateTime)item.OrderTimestamp; order.Status = ConvertOrderStatus(item); order.Price = item.Price; list.Add(order); } foreach (var item in list) { if (item.Status.IsOpen()) { var cached = CachedOrderIDs.Where(c => c.Value.BrokerId.Contains(item.BrokerId.First())); if (cached.Any()) { CachedOrderIDs[cached.First().Key] = item; } } } } return list; } private OrderStatus ConvertOrderStatus(Messages.Order orderDetails) { var filledQty = Convert.ToInt32(orderDetails.FilledQuantity, CultureInfo.InvariantCulture); var pendingQty = Convert.ToInt32(orderDetails.PendingQuantity, CultureInfo.InvariantCulture); var orderDetail = _kite.GetOrderHistory(orderDetails.OrderId); if (orderDetails.Status.ToLowerInvariant() != "complete" && filledQty == 0) { return OrderStatus.Submitted; } else if (filledQty > 0 && pendingQty > 0) { return OrderStatus.PartiallyFilled; } else if (pendingQty == 0) { return OrderStatus.Filled; } else if (orderDetails.Status.ToUpperInvariant() == "CANCELLED") { return OrderStatus.Canceled; } return OrderStatus.None; } /// <summary> /// Gets all open postions and account holdings /// </summary> /// <returns></returns> public override List<Holding> GetAccountHoldings() { var holdingsList = new List<Holding>(); var zerodhaProductTypeUpper = _zerodhaProductType.ToUpperInvariant(); var productTypeMIS = KiteProductType.MIS.ToString().ToUpperInvariant(); var productTypeNRML = KiteProductType.NRML.ToString().ToUpperInvariant(); var productTypeCNC = KiteProductType.CNC.ToString().ToUpperInvariant(); // get MIS and NRML Positions if (string.IsNullOrEmpty(_zerodhaProductType) || zerodhaProductTypeUpper == productTypeMIS || zerodhaProductTypeUpper == productTypeNRML) { var PositionsResponse = _kite.GetPositions(); if (PositionsResponse.Day.Count != 0) { foreach (var item in PositionsResponse.Day) { Holding holding = new Holding { AveragePrice = item.AveragePrice, Symbol = _symbolMapper.GetLeanSymbol(item.TradingSymbol), MarketPrice = item.LastPrice, Quantity = item.Quantity, UnrealizedPnL = item.Unrealised, CurrencySymbol = Currencies.GetCurrencySymbol(AccountBaseCurrency), MarketValue = item.ClosePrice * item.Quantity }; holdingsList.Add(holding); } } } // get CNC Positions if (string.IsNullOrEmpty(_zerodhaProductType) || zerodhaProductTypeUpper == productTypeCNC ) { var HoldingResponse = _kite.GetHoldings(); if (HoldingResponse != null) { foreach (var item in HoldingResponse) { Holding holding = new Holding { AveragePrice = item.AveragePrice, Symbol = _symbolMapper.GetLeanSymbol(item.TradingSymbol), MarketPrice = item.LastPrice, Quantity = item.Quantity, UnrealizedPnL = item.PNL, CurrencySymbol = Currencies.GetCurrencySymbol(AccountBaseCurrency), MarketValue = item.ClosePrice * item.Quantity }; holdingsList.Add(holding); } } } return holdingsList; } /// <summary> /// Gets the total account cash balance for specified account type /// </summary> /// <returns></returns> public override List<CashAmount> GetCashBalance() { decimal amt = 0m; var list = new List<CashAmount>(); var response = _kite.GetMargins(); if (_tradingSegment == "EQUITY") { amt = Convert.ToDecimal(response.Equity.Available.Cash, CultureInfo.InvariantCulture); } else { amt = Convert.ToDecimal(response.Commodity.Available.Cash, CultureInfo.InvariantCulture); } list.Add(new CashAmount(amt, AccountBaseCurrency)); return list; } /// <summary> /// Gets the history for the requested security /// </summary> /// <param name="request">The historical data request</param> /// <returns>An enumerable of bars covering the span specified in the request</returns> public override IEnumerable<BaseData> GetHistory(HistoryRequest request) { if (request.DataType != typeof(TradeBar) && !_historyDataTypeErrorFlag) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidBarType", $"{request.DataType} type not supported, no history returned")); _historyDataTypeErrorFlag = true; yield break; } if (request.Symbol.SecurityType != SecurityType.Equity && request.Symbol.SecurityType != SecurityType.Future && request.Symbol.SecurityType != SecurityType.Option) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidSecurityType", $"{request.Symbol.SecurityType} security type not supported, no history returned")); yield break; } if (request.Resolution == Resolution.Tick || request.Resolution == Resolution.Second) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidResolution", $"{request.Resolution} resolution not supported, no history returned")); yield break; } if (request.StartTimeUtc >= request.EndTimeUtc) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidDateRange", "The history request start date must precede the end date, no history returned")); yield break; } if (request.Symbol.ID.SecurityType != SecurityType.Equity && request.Symbol.ID.SecurityType != SecurityType.Future && request.Symbol.ID.SecurityType != SecurityType.Option) { throw new ArgumentException("Zerodha does not support this security type: " + request.Symbol.ID.SecurityType); } if (request.StartTimeUtc >= request.EndTimeUtc) { throw new ArgumentException("Invalid date range specified"); } var history = Enumerable.Empty<BaseData>(); var symbol = request.Symbol; var start = request.StartTimeLocal; var end = request.EndTimeLocal; var resolution = request.Resolution; var exchangeTimeZone = request.ExchangeHours.TimeZone; if (Config.GetBool("zerodha-history-subscription")) { switch (resolution) { case Resolution.Minute: history = GetHistoryForPeriod(symbol, start, end, exchangeTimeZone, resolution, "minute"); break; case Resolution.Hour: history = GetHistoryForPeriod(symbol, start, end, exchangeTimeZone, resolution, "60minute"); break; case Resolution.Daily: history = GetHistoryForPeriod(symbol, start, end, exchangeTimeZone, resolution, "day"); break; } } foreach (var baseData in history) { yield return baseData; } } private IEnumerable<BaseData> GetHistoryForPeriod(Symbol symbol, DateTime start, DateTime end, DateTimeZone exchangeTimeZone, Resolution resolution, string zerodhaResolution) { Log.Debug("ZerodhaBrokerage.GetHistoryForPeriod();"); var scripSymbolTokenList = _symbolMapper.GetZerodhaInstrumentTokenList(symbol.Value); if (scripSymbolTokenList.Count == 0) { throw new ArgumentException($"ZerodhaBrokerage.GetQuote(): Invalid Zerodha Instrument token for given: {symbol.Value}"); } var scripSymbol = scripSymbolTokenList[0]; var candles = _kite.GetHistoricalData(scripSymbol.ToStringInvariant(), start, end, zerodhaResolution); if (!candles.Any()) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "NoHistoricalData", $"Exchange returned no data for {symbol} on history request " + $"from {start:s} to {end:s}")); } foreach (var candle in candles) { yield return new TradeBar(candle.TimeStamp.ConvertFromUtc(exchangeTimeZone),symbol,candle.Open,candle.High,candle.Low,candle.Close,candle.Volume,resolution.ToTimeSpan()); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public override void Dispose() { _aggregator.DisposeSafely(); if (WebSocket.IsOpen) { WebSocket.Close(); } } private void OnError(object sender, WebSocketError e) { Log.Error($"ZerodhaBrokerage.OnError(): Message: {e.Message} Exception: {e.Exception}"); } private void OnMessage(object sender, WebSocketMessage webSocketMessage) { _messageHandler.HandleNewMessage(webSocketMessage.Data); } /// <summary> /// Implementation of the OnMessage event /// </summary> /// <param name="e"></param> private void OnMessageImpl(WebSocketClientWrapper.MessageData message) { try { if (message.MessageType == WebSocketMessageType.Binary) { var e = (WebSocketClientWrapper.BinaryMessage)message; if (e.Count > 1) { int offset = 0; ushort count = ReadShort(e.Data, ref offset); //number of packets for (ushort i = 0; i < count; i++) { ushort length = ReadShort(e.Data, ref offset); // length of the packet Messages.Tick tick = new Messages.Tick(); if (length == 8) // ltp tick = ReadLTP(e.Data, ref offset); else if (length == 28) // index quote tick = ReadIndexQuote(e.Data, ref offset); else if (length == 32) // index quote tick = ReadIndexFull(e.Data, ref offset); else if (length == 44) // quote tick = ReadQuote(e.Data, ref offset); else if (length == 184) // full with marketdepth and timestamp tick = ReadFull(e.Data, ref offset); // If the number of bytes got from stream is less that that is required // data is invalid. This will skip that wrong tick if (tick.InstrumentToken != 0 && offset <= e.Count && tick.Mode == Constants.MODE_FULL) { var symbol = _symbolMapper.ConvertZerodhaSymbolToLeanSymbol(tick.InstrumentToken); var bestBidQuote = tick.Bids[0]; var bestAskQuote = tick.Offers[0]; var instrumentTokenValue = tick.InstrumentToken; var time = tick.Timestamp ?? DateTime.UtcNow.ConvertFromUtc(TimeZones.Kolkata); EmitQuoteTick(symbol, instrumentTokenValue, time, bestBidQuote.Price, bestBidQuote.Quantity, bestAskQuote.Price, bestAskQuote.Quantity); if (_lastTradeTickTime != time) { EmitTradeTick(symbol, instrumentTokenValue, time, tick.LastPrice, tick.LastQuantity); _lastTradeTickTime = time; } } } } } else if (message.MessageType == WebSocketMessageType.Text) { var e = (WebSocketClientWrapper.TextMessage)message; JObject messageDict = Utils.JsonDeserialize(e.Message); if ((string)messageDict["type"] == "order") { OnOrderUpdate(new Messages.Order(messageDict["data"])); } else if ((string)messageDict["type"] == "error") { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, $"Zerodha WSS Error. Data: {e.Message} Exception: {messageDict["data"]}")); } } } catch (Exception exception) { if (message.MessageType == WebSocketMessageType.Binary) { var e = (WebSocketClientWrapper.BinaryMessage)message; OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, $"Parsing wss message failed. Data: {e.Data} Exception: {exception}")); throw; } else { var e = (WebSocketClientWrapper.TextMessage)message; OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, $"Parsing wss message failed. Data: {e.Message} Exception: {exception}")); throw; } } } private void EmitTradeTick(Symbol symbol, uint instrumentToken, DateTime time, decimal price, decimal amount) { var exchange = _symbolMapper.GetZerodhaExchangeFromToken(instrumentToken); if (string.IsNullOrEmpty(exchange)) { Log.Error($"ZerodhaBrokerage.EmitTradeTick(): market info is NUll/Empty for: {symbol.ID.Symbol}"); } var tick = new Tick(time, symbol, string.Empty, exchange, Math.Abs(amount), price); _aggregator.Update(tick); } private void EmitQuoteTick(Symbol symbol, uint instrumentToken, DateTime time, decimal bidPrice, decimal bidSize, decimal askPrice, decimal askSize) { if (bidPrice > 0 && askPrice > 0) { var exchange = _symbolMapper.GetZerodhaExchangeFromToken(instrumentToken); if (string.IsNullOrEmpty(exchange)) { Log.Error($"ZerodhaBrokerage.EmitQuoteTick(): market info is NUll/Empty for: {symbol.ID.Symbol}"); } var tick = new Tick(time, symbol, string.Empty, exchange, bidSize, bidPrice, askSize, askPrice); _aggregator.Update(tick); } } /// <summary> /// Reads 2 byte short int from byte stream /// </summary> private ushort ReadShort(byte[] b, ref int offset) { ushort data = (ushort)(b[offset + 1] + (b[offset] << 8)); offset += 2; return data; } /// <summary> /// Reads 4 byte int32 from byte stream /// </summary> private uint ReadInt(byte[] b, ref int offset) { uint data = BitConverter.ToUInt32(new byte[] { b[offset + 3], b[offset + 2], b[offset + 1], b[offset + 0] }, 0); offset += 4; return data; } /// <summary> /// Reads an ltp mode tick from raw binary data /// </summary> private Messages.Tick ReadLTP(byte[] b, ref int offset) { Messages.Tick tick = new Messages.Tick(); tick.Mode = Constants.MODE_LTP; tick.InstrumentToken = ReadInt(b, ref offset); decimal divisor = (tick.InstrumentToken & 0xff) == 3 ? 10000000.0m : 100.0m; tick.Tradable = (tick.InstrumentToken & 0xff) != 9; tick.LastPrice = ReadInt(b, ref offset) / divisor; return tick; } /// <summary> /// Reads a index's quote mode tick from raw binary data /// </summary> private Messages.Tick ReadIndexQuote(byte[] b, ref int offset) { Messages.Tick tick = new Messages.Tick(); tick.Mode = Constants.MODE_QUOTE; tick.InstrumentToken = ReadInt(b, ref offset); decimal divisor = (tick.InstrumentToken & 0xff) == 3 ? 10000000.0m : 100.0m; tick.Tradable = (tick.InstrumentToken & 0xff) != 9; tick.LastPrice = ReadInt(b, ref offset) / divisor; tick.High = ReadInt(b, ref offset) / divisor; tick.Low = ReadInt(b, ref offset) / divisor; tick.Open = ReadInt(b, ref offset) / divisor; tick.Close = ReadInt(b, ref offset) / divisor; tick.Change = ReadInt(b, ref offset) / divisor; return tick; } private Messages.Tick ReadIndexFull(byte[] b, ref int offset) { Messages.Tick tick = new Messages.Tick(); tick.Mode = Constants.MODE_FULL; tick.InstrumentToken = ReadInt(b, ref offset); decimal divisor = (tick.InstrumentToken & 0xff) == 3 ? 10000000.0m : 100.0m; tick.Tradable = (tick.InstrumentToken & 0xff) != 9; tick.LastPrice = ReadInt(b, ref offset) / divisor; tick.High = ReadInt(b, ref offset) / divisor; tick.Low = ReadInt(b, ref offset) / divisor; tick.Open = ReadInt(b, ref offset) / divisor; tick.Close = ReadInt(b, ref offset) / divisor; tick.Change = ReadInt(b, ref offset) / divisor; uint time = ReadInt(b, ref offset); tick.Timestamp = Time.UnixTimeStampToDateTime(time); return tick; } /// <summary> /// Reads a quote mode tick from raw binary data /// </summary> private Messages.Tick ReadQuote(byte[] b, ref int offset) { Messages.Tick tick = new Messages.Tick { Mode = Constants.MODE_QUOTE, InstrumentToken = ReadInt(b, ref offset) }; decimal divisor = (tick.InstrumentToken & 0xff) == 3 ? 10000000.0m : 100.0m; tick.Tradable = (tick.InstrumentToken & 0xff) != 9; tick.LastPrice = ReadInt(b, ref offset) / divisor; tick.LastQuantity = ReadInt(b, ref offset); tick.AveragePrice = ReadInt(b, ref offset) / divisor; tick.Volume = ReadInt(b, ref offset); tick.BuyQuantity = ReadInt(b, ref offset); tick.SellQuantity = ReadInt(b, ref offset); tick.Open = ReadInt(b, ref offset) / divisor; tick.High = ReadInt(b, ref offset) / divisor; tick.Low = ReadInt(b, ref offset) / divisor; tick.Close = ReadInt(b, ref offset) / divisor; return tick; } /// <summary> /// Reads a full mode tick from raw binary data /// </summary> private Messages.Tick ReadFull(byte[] b, ref int offset) { Messages.Tick tick = new Messages.Tick(); tick.Mode = Constants.MODE_FULL; tick.InstrumentToken = ReadInt(b, ref offset); decimal divisor = (tick.InstrumentToken & 0xff) == 3 ? 10000000.0m : 100.0m; tick.Tradable = (tick.InstrumentToken & 0xff) != 9; tick.LastPrice = ReadInt(b, ref offset) / divisor; tick.LastQuantity = ReadInt(b, ref offset); tick.AveragePrice = ReadInt(b, ref offset) / divisor; tick.Volume = ReadInt(b, ref offset); tick.BuyQuantity = ReadInt(b, ref offset); tick.SellQuantity = ReadInt(b, ref offset); tick.Open = ReadInt(b, ref offset) / divisor; tick.High = ReadInt(b, ref offset) / divisor; tick.Low = ReadInt(b, ref offset) / divisor; tick.Close = ReadInt(b, ref offset) / divisor; // KiteConnect 3 fields tick.LastTradeTime = Time.UnixTimeStampToDateTime(ReadInt(b, ref offset)); tick.OI = ReadInt(b, ref offset); tick.OIDayHigh = ReadInt(b, ref offset); tick.OIDayLow = ReadInt(b, ref offset); tick.Timestamp = Time.UnixTimeStampToDateTime(ReadInt(b, ref offset)); tick.Bids = new DepthItem[5]; for (int i = 0; i < 5; i++) { tick.Bids[i].Quantity = ReadInt(b, ref offset); tick.Bids[i].Price = ReadInt(b, ref offset) / divisor; tick.Bids[i].Orders = ReadShort(b, ref offset); offset += 2; } tick.Offers = new DepthItem[5]; for (int i = 0; i < 5; i++) { tick.Offers[i].Quantity = ReadInt(b, ref offset); tick.Offers[i].Price = ReadInt(b, ref offset) / divisor; tick.Offers[i].Orders = ReadShort(b, ref offset); offset += 2; } return tick; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Linq; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class PropertiesTests : XLinqTestCase { public partial class ImplicitConversionsElem : XLinqTestCase { // these tests are duplication of the // valid cases // - direct value // - concat value // - concat of text // - text & CData // - concat from children // - removing, adding and modifying nodes sanity // invalid cases (sanity, pri2) //[Variation(Priority = 0, Desc = "String - direct", Params = new object[] { @"<A>text</A>", @"text" })] //[Variation(Priority = 0, Desc = "String - concat two text nodes", Params = new object[] { @"<A>text1<B/>text2</A>", @"text1text2" })] //[Variation(Priority = 0, Desc = "String - concat text and CData", Params = new object[] { @"<A>text1<B/><![CDATA[text2]]></A>", @"text1text2" })] //[Variation(Priority = 0, Desc = "String - concat from children", Params = new object[] { @"<A><B>text1<D><![CDATA[text2]]></D></B><C>text3</C></A>", @"text1text2text3" })] //[Variation(Priority = 0, Desc = "String - empty", Params = new object[] { @"<A><B><D></D></B><C></C></A>", @"" })] //[Variation(Priority = 0, Desc = "String - empty with CDATA", Params = new object[] { @"<A><B><D><![CDATA[]]></D></B><C></C></A>", @"" })] public void StringConvert() { string xml = Variation.Params[0] as string; string expText = Variation.Params[1] as string; XElement elem = XElement.Parse(xml); TestLog.Compare((string)elem, expText, "text is not as expected"); } //[Variation(Priority = 0, Desc = "bool - direct - true", Params = new object[] { @"<A>true</A>", true })] //[Variation(Priority = 0, Desc = "bool - direct - 1", Params = new object[] { @"<A>1</A>", true })] //[Variation(Priority = 0, Desc = "bool - direct - false", Params = new object[] { @"<A>false</A>", false })] //[Variation(Priority = 0, Desc = "bool - direct - 0 ", Params = new object[] { @"<A>0</A>", false })] //[Variation(Priority = 1, Desc = "bool - concat two text nodes - true", Params = new object[] { @"<A>tr<B/>ue</A>", true })] //[Variation(Priority = 1, Desc = "bool - concat two text nodes - false", Params = new object[] { @"<A>f<B/>alse</A>", false })] //[Variation(Priority = 1, Desc = "bool - concat text and CData - true", Params = new object[] { @"<A>tru<B/><![CDATA[e]]></A>", true })] //[Variation(Priority = 1, Desc = "bool - concat text and CData - false", Params = new object[] { @"<A>fal<B/><![CDATA[se]]></A>", false })] //[Variation(Priority = 1, Desc = "bool - concat from children - true", Params = new object[] { @"<A><B>t<D><![CDATA[ru]]></D></B><C>e</C></A>", true })] //[Variation(Priority = 1, Desc = "bool - concat from children - 1", Params = new object[] { @"<A> <B><D><![CDATA[1]]></D></B><C> </C></A>", true })] //[Variation(Priority = 1, Desc = "bool - concat from children - false", Params = new object[] { @"<A><B>fa<D><![CDATA[l]]></D></B><C>se</C></A>", false })] //[Variation(Priority = 1, Desc = "bool - concat from children - 0", Params = new object[] { @"<A><B> <D><![CDATA[ ]]></D></B><C>0</C></A>", false })] public void BoolConvert() { string xml = Variation.Params[0] as string; bool expBool = (bool)Variation.Params[1]; XElement elem = XElement.Parse(xml); TestLog.Compare((bool)elem, expBool, "bool is not as expected"); } //[Variation(Priority = 2, Desc = "bool - Invalid - empty", Params = new object[] { @"<A></A>" })] //[Variation(Priority = 2, Desc = "bool - Invalid - capital T", Params = new object[] { @"<A>True</A>" })] //[Variation(Priority = 2, Desc = "bool? - Invalid - some other", Params = new object[] { @"<A>2</A>" })] public void BoolConvertInvalid() { string xml = Variation.Params[0] as string; XElement elem = XElement.Parse(xml); try { bool r = (bool)elem; } catch (FormatException) { } } //[Variation(Priority = 0, Desc = "bool? - direct - true", Params = new object[] { @"<A>true</A>", true })] //[Variation(Priority = 0, Desc = "bool? - direct - 1", Params = new object[] { @"<A>1</A>", true })] //[Variation(Priority = 0, Desc = "bool? - direct - false", Params = new object[] { @"<A>false</A>", false })] //[Variation(Priority = 0, Desc = "bool? - direct - 0 ", Params = new object[] { @"<A>0</A>", false })] //[Variation(Priority = 1, Desc = "bool? - concat two text nodes - true", Params = new object[] { @"<A>tr<B/>ue</A>", true })] //[Variation(Priority = 1, Desc = "bool? - concat two text nodes - false", Params = new object[] { @"<A>f<B/>alse</A>", false })] //[Variation(Priority = 1, Desc = "bool? - concat text and CData - true", Params = new object[] { @"<A>tru<B/><![CDATA[e]]></A>", true })] //[Variation(Priority = 1, Desc = "bool? - concat text and CData - false", Params = new object[] { @"<A>fal<B/><![CDATA[se]]></A>", false })] //[Variation(Priority = 1, Desc = "bool? - concat from children - true", Params = new object[] { @"<A><B>t<D><![CDATA[ru]]></D></B><C>e</C></A>", true })] //[Variation(Priority = 1, Desc = "bool? - concat from children - 1", Params = new object[] { @"<A> <B><D><![CDATA[1]]></D></B><C> </C></A>", true })] //[Variation(Priority = 1, Desc = "bool? - concat from children - false", Params = new object[] { @"<A><B>fa<D><![CDATA[l]]></D></B><C>se</C></A>", false })] //[Variation(Priority = 1, Desc = "bool? - concat from children - 0", Params = new object[] { @"<A><B> <D><![CDATA[ ]]></D></B><C>0</C></A>", false })] public void BoolQConvert() { string xml = Variation.Params[0] as string; bool? expBool = (bool?)Variation.Params[1]; XElement elem = XElement.Parse(xml); TestLog.Compare((bool?)elem, expBool, "bool is not as expected"); } //[Variation(Priority = 2, Desc = "bool? - Invalid - empty", Params = new object[] { @"<A a='1'></A>" })] //[Variation(Priority = 2, Desc = "bool? - Invalid - capital T", Params = new object[] { @"<A a='1'>True</A>" })] //[Variation(Priority = 2, Desc = "bool? - Invalid - space inside", Params = new object[] { @"<A a='1'>tr<B/> ue</A>" })] //[Variation(Priority = 2, Desc = "bool? - Invalid - some other", Params = new object[] { @"<A a='1'>2</A>" })] public void BoolQConvertInvalid() { string xml = Variation.Params[0] as string; XElement elem = XElement.Parse(xml); try { bool? r = (bool?)elem; } catch (FormatException) { } } //[Variation(Priority = 2, Desc = "bool? - Null")] public void BoolQConvertNull() { XElement elem = null; bool? r = (bool?)elem; TestLog.Compare(r == null, "result is null"); } //[Variation(Priority = 0, Desc = "int - direct", Params = new object[] { @"<A a='1'>10</A>", 10 })] //[Variation(Priority = 0, Desc = "int - concat two text nodes", Params = new object[] { @"<A a='1'>1<B/>7</A>", 17 })] //[Variation(Priority = 0, Desc = "int - concat text and CData", Params = new object[] { @"<A a='1'>-<B/><![CDATA[21]]></A>", -21 })] //[Variation(Priority = 0, Desc = "int - concat from children", Params = new object[] { @"<A a='1'><B>-<D><![CDATA[12]]></D></B><C>0</C></A>", -120 })] public void IntConvert() { string xml = Variation.Params[0] as string; int exp = (int)Variation.Params[1]; XElement elem = XElement.Parse(xml); TestLog.Compare((int)elem, exp, "int is not as expected"); } //[Variation(Priority = 2, Desc = "int - Invalid - empty", Params = new object[] { @"<A a='1'></A>" })] //[Variation(Priority = 2, Desc = "int - Invalid - space inside", Params = new object[] { @"<A a='1'>2<B/> 1</A>" })] //[Variation(Priority = 2, Desc = "int - Invalid - some other", Params = new object[] { @"<A a='1'>X</A>" })] public void IntConvertInvalid() { string xml = Variation.Params[0] as string; XElement elem = XElement.Parse(xml); try { int r = (int)elem; } catch (FormatException) { } } //[Variation(Priority = 0, Desc = "int? - direct", Params = new object[] { @"<A a='1'>10</A>", 10 })] //[Variation(Priority = 0, Desc = "int? - concat two text nodes", Params = new object[] { @"<A a='1'>1<B/>7</A>", 17 })] //[Variation(Priority = 0, Desc = "int? - concat text and CData", Params = new object[] { @"<A a='1'>-<B/><![CDATA[21]]></A>", -21 })] //[Variation(Priority = 0, Desc = "int? - concat from children", Params = new object[] { @"<A a='1'><B>-<D><![CDATA[12]]></D></B><C>0</C></A>", -120 })] public void IntQConvert() { string xml = Variation.Params[0] as string; int? exp = (int?)Variation.Params[1]; XElement elem = XElement.Parse(xml); TestLog.Compare((int?)elem, exp, "int? is not as expected"); } //[Variation(Priority = 2, Desc = "int? - Invalid - empty", Params = new object[] { @"<A a='1'></A>" })] //[Variation(Priority = 2, Desc = "int? - Invalid - space inside", Params = new object[] { @"<A a='1'>2<B/> 1</A>" })] //[Variation(Priority = 2, Desc = "int? - Invalid - some other", Params = new object[] { @"<A a='1'>X</A>" })] public void IntQConvertInvalid() { string xml = Variation.Params[0] as string; XElement elem = XElement.Parse(xml); try { int? r = (int?)elem; } catch (FormatException) { } } //[Variation(Priority = 2, Desc = "int? - Null")] public void IntQConvertNull() { XElement elem = null; int? r = (int?)elem; TestLog.Compare(r == null, "result is null"); } //[Variation(Priority = 0, Desc = "uint - direct", Params = new object[] { @"<A a='1'>10</A>", 10 })] //[Variation(Priority = 0, Desc = "uint - concat two text nodes", Params = new object[] { @"<A a='1'>1<B/>7</A>", 17 })] //[Variation(Priority = 0, Desc = "uint - concat text and CData", Params = new object[] { @"<A a='1'><B/><![CDATA[21]]></A>", 21 })] //[Variation(Priority = 0, Desc = "uint - concat from children", Params = new object[] { @"<A a='1'><B><D><![CDATA[12]]></D></B><C>0</C></A>", 120 })] public void UIntConvert() { string xml = Variation.Params[0] as string; uint exp = (uint)((int)Variation.Params[1]); XElement elem = XElement.Parse(xml); TestLog.Compare((uint)elem == exp, "uint is not as expected"); } //[Variation(Priority = 2, Desc = "uint - Invalid - empty", Params = new object[] { @"<A a='1'></A>" })] //[Variation(Priority = 2, Desc = "uint - Invalid - space inside", Params = new object[] { @"<A a='1'>2<B/> 1</A>" })] //[Variation(Priority = 2, Desc = "uint - Invalid - negative", Params = new object[] { @"<A a='1'>-<B/>1</A>" })] //[Variation(Priority = 2, Desc = "uint - Invalid - some other", Params = new object[] { @"<A a='1'>X</A>" })] public void UIntConvertInvalid() { string xml = Variation.Params[0] as string; XElement elem = XElement.Parse(xml); try { uint r = (uint)elem; } catch (FormatException) { } } //[Variation(Priority = 0, Desc = "uint? - direct", Params = new object[] { @"<A a='1'>10</A>", 10 })] //[Variation(Priority = 0, Desc = "uint? - concat two text nodes", Params = new object[] { @"<A a='1'>1<B/>7</A>", 17 })] //[Variation(Priority = 0, Desc = "uint? - concat text and CData", Params = new object[] { @"<A a='1'><B/><![CDATA[21]]></A>", 21 })] //[Variation(Priority = 0, Desc = "uint? - concat from children", Params = new object[] { @"<A a='1'><B><D><![CDATA[12]]></D></B><C>0</C></A>", 120 })] public void UIntQConvert() { string xml = Variation.Params[0] as string; uint? exp = (uint?)((int)Variation.Params[1]); XElement elem = XElement.Parse(xml); TestLog.Compare((uint?)elem, exp, "uint? is not as expected"); } //[Variation(Priority = 2, Desc = "uint? - Invalid - empty", Params = new object[] { @"<A a='1'></A>" })] //[Variation(Priority = 2, Desc = "uint? - Invalid - space inside", Params = new object[] { @"<A a='1'>2<B/> 1</A>" })] //[Variation(Priority = 2, Desc = "uint? - Invalid - negative", Params = new object[] { @"<A a='1'>-<B/>1</A>" })] //[Variation(Priority = 2, Desc = "uint? - Invalid - some other", Params = new object[] { @"<A a='1'>X</A>" })] public void UIntQConvertInvalid() { string xml = Variation.Params[0] as string; XElement elem = XElement.Parse(xml); try { uint? r = (uint?)elem; } catch (FormatException) { } } //[Variation(Priority = 2, Desc = "uint? - Null")] public void UIntQConvertNull() { XElement elem = null; uint? r = (uint?)elem; TestLog.Compare(r == null, "result is 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.Collections.Generic; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Algorithms.Tests { public class IncrementalHashTests { // Some arbitrarily chosen OID segments private static readonly byte[] s_hmacKey = { 2, 5, 29, 54, 1, 2, 84, 113, 54, 91, 1, 1, 2, 5, 29, 10, }; private static readonly byte[] s_inputBytes = ByteUtils.RepeatByte(0xA5, 512); public static IEnumerable<object[]> GetHashAlgorithms() { return new[] { new object[] { MD5.Create(), HashAlgorithmName.MD5 }, new object[] { SHA1.Create(), HashAlgorithmName.SHA1 }, new object[] { SHA256.Create(), HashAlgorithmName.SHA256 }, new object[] { SHA384.Create(), HashAlgorithmName.SHA384 }, new object[] { SHA512.Create(), HashAlgorithmName.SHA512 }, }; } public static IEnumerable<object[]> GetHMACs() { return new[] { new object[] { new HMACMD5(), HashAlgorithmName.MD5 }, new object[] { new HMACSHA1(), HashAlgorithmName.SHA1 }, new object[] { new HMACSHA256(), HashAlgorithmName.SHA256 }, new object[] { new HMACSHA384(), HashAlgorithmName.SHA384 }, new object[] { new HMACSHA512(), HashAlgorithmName.SHA512 }, }; } [Theory] [MemberData("GetHashAlgorithms")] public static void VerifyIncrementalHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { VerifyIncrementalResult(referenceAlgorithm, incrementalHash); } } [Theory] [MemberData("GetHMACs")] public static void VerifyIncrementalHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; VerifyIncrementalResult(referenceAlgorithm, incrementalHash); } } private static void VerifyIncrementalResult(HashAlgorithm referenceAlgorithm, IncrementalHash incrementalHash) { byte[] referenceHash = referenceAlgorithm.ComputeHash(s_inputBytes); const int StepA = 13; const int StepB = 7; int position = 0; while (position < s_inputBytes.Length - StepA) { incrementalHash.AppendData(s_inputBytes, position, StepA); position += StepA; } incrementalHash.AppendData(s_inputBytes, position, s_inputBytes.Length - position); byte[] incrementalA = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalA); // Now try again, verifying both immune to step size behaviors, and that GetHashAndReset resets. position = 0; while (position < s_inputBytes.Length - StepB) { incrementalHash.AppendData(s_inputBytes, position, StepA); position += StepA; } incrementalHash.AppendData(s_inputBytes, position, s_inputBytes.Length - position); byte[] incrementalB = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalB); } [Theory] [MemberData("GetHashAlgorithms")] public static void VerifyEmptyHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { for (int i = 0; i < 10; i++) { incrementalHash.AppendData(Array.Empty<byte>()); } byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Theory] [MemberData("GetHMACs")] public static void VerifyEmptyHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; for (int i = 0; i < 10; i++) { incrementalHash.AppendData(Array.Empty<byte>()); } byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Theory] [MemberData("GetHashAlgorithms")] public static void VerifyTrivialHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Theory] [MemberData("GetHMACs")] public static void VerifyTrivialHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Fact] public static void AppendDataAfterHashClose() { using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { byte[] firstHash = hash.GetHashAndReset(); hash.AppendData(Array.Empty<byte>()); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void AppendDataAfterHMACClose() { using (IncrementalHash hash = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, s_hmacKey)) { byte[] firstHash = hash.GetHashAndReset(); hash.AppendData(Array.Empty<byte>()); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void GetHashTwice() { using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { byte[] firstHash = hash.GetHashAndReset(); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void GetHMACTwice() { using (IncrementalHash hash = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, s_hmacKey)) { byte[] firstHash = hash.GetHashAndReset(); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void ModifyAfterHashDispose() { using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { hash.Dispose(); Assert.Throws<ObjectDisposedException>(() => hash.AppendData(Array.Empty<byte>())); Assert.Throws<ObjectDisposedException>(() => hash.GetHashAndReset()); } } [Fact] public static void ModifyAfterHMACDispose() { using (IncrementalHash hash = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, s_hmacKey)) { hash.Dispose(); Assert.Throws<ObjectDisposedException>(() => hash.AppendData(Array.Empty<byte>())); Assert.Throws<ObjectDisposedException>(() => hash.GetHashAndReset()); } } } }
/*=================================\ * PlotterControl\Form_Print.cs * * The Coestaris licenses this file to you under the MIT license. * See the LICENSE file in the project root for more information. * * Created: 27.11.2017 14:04 * Last Edited: 27.11.2017 14:04:46 *=================================*/ using CnC_WFA.Properties; using CNCWFA_API; using Printing; using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.IO.Ports; using System.Linq; using System.Threading; using System.Windows.Forms; namespace CnC_WFA { public partial class Form_Print : Form { ComponentResourceManager resources = new ComponentResourceManager(typeof(Form_Print)); private Vect buffpr, pr; private VectHeader main_header; private SerialPort main_port; private Print print; private Bitmap bmp_, bmp; private Thread prt; private string path, textBox_xsize_laststring, textBox_ysize_laststring, textbox_xoffset_laststring, textbox_yoffset_laststring, textBox_penwidth_laststring; private int state; private bool ignoreload; private char[] num = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ',' }; private float xsize, ysize, xoffest, yoffest, time; private CNCWFA_API.ErrorEventArgs errorarg; private delegate void SetVisibleCallback(bool val); private delegate void Print_TimeChanged_(TimeEventArgs val); private delegate void SetLabelTextFeedBack_(PrintedEventArgs val); private delegate void SetLabelTextFeedBack(string val); public Form_Print(string fn, bool ignr) { ignoreload = ignr; InitializeComponent(); Form_print_Load(null, null); listBox_prlist.Enabled = false; button_preview.Enabled = false; path = fn; button_tab2_back.Enabled = true; loadingCircle1.Visible = true; button_openfolder.Enabled = false; button_refreshlist.Enabled = false; button_removepr.Enabled = false; loadingCircle1.Active = true; new Thread(button_next_tab1_Click_th).Start(); button_next_tab1.Enabled = false; button_exit.Enabled = false; state = 2; button_tab2_back.Text = "??????????"; CheckState(); } public Form_Print() { InitializeComponent(); tabControl1.SelectedIndex = 4; CheckState(); } private void CheckState() { if(state==0) { label_1.Image = ((Image)(resources.GetObject("label_1.Image"))); label_2.Image = ((Image)(resources.GetObject("label_1.Image"))); label_3.Image = ((Image)(resources.GetObject("label_1.Image"))); label_4.Image = ((Image)(resources.GetObject("label_1.Image"))); label_5.Image = ((Image)(resources.GetObject("label_1.Image"))); } else if(state==1) { label_1.Image = Resources.ok; label_2.Image = ((Image)(resources.GetObject("label_1.Image"))); label_3.Image = ((Image)(resources.GetObject("label_1.Image")));label_4.Image = ((Image)(resources.GetObject("label_1.Image")));label_5.Image = ((Image)(resources.GetObject("label_1.Image"))); } else if (state == 2) { label_1.Image = Resources.ok; label_2.Image = Resources.ok; label_3.Image = ((Image)(resources.GetObject("label_1.Image"))); label_4.Image = ((Image)(resources.GetObject("label_1.Image"))); label_5.Image = ((Image)(resources.GetObject("label_1.Image"))); } else if (state == 3) { label_1.Image = Resources.ok; label_2.Image = Resources.ok; label_3.Image = Resources.ok; label_4.Image = ((Image)(resources.GetObject("label_1.Image")));label_5.Image = ((Image)(resources.GetObject("label_1.Image"))); } else if (state == 4) { label_1.Image = Resources.ok; label_2.Image = Resources.ok; label_3.Image = Resources.ok; label_4.Image = Resources.ok; label_5.Image = ((Image)(resources.GetObject("label_1.Image"))); } else { label_1.Image = Resources.ok; label_2.Image = Resources.ok; label_3.Image = Resources.ok; label_4.Image = Resources.ok; label_5.Image = Resources.ok; } } private void Form_print_Load(object sender, EventArgs e) { loadingCircle_tab1.InnerCircleRadius = 25; loadingCircle_tab1.OuterCircleRadius = 26; loadingCircle_tab1.NumberSpoke = 100; loadingCircle_tab1.Top = pictureBox_prpreview.Top + pictureBox_prpreview.Height / 2 - loadingCircle1.Height / 2; loadingCircle_tab1.Left = pictureBox_prpreview.Left + pictureBox_prpreview.Width / 2 - loadingCircle1.Width / 2; loadingCircle1.InnerCircleRadius = 25; loadingCircle1.OuterCircleRadius = 26; loadingCircle1.NumberSpoke = 100; loadingCircle2.InnerCircleRadius = 25; loadingCircle2.OuterCircleRadius = 26; loadingCircle2.NumberSpoke = 100; comboBox_com.Items.Clear(); comboBox_com.Items.AddRange(SerialPort.GetPortNames()); comboBox_com.Text = GlobalOptions.Mainport; comboBox_bdrate.Text = GlobalOptions.Mainbd.ToString(); radioButton_xsize.Checked = true; if (!ignoreload) { listBox_prlist.Items.Clear(); string[] paths = Directory.GetFiles("Data\\Vect\\", "*.prres"); listBox_prlist.Items.AddRange(paths); paths = Directory.GetFiles("Data\\Vect\\", "*.cvf"); listBox_prlist.Items.AddRange(paths); } else { } prt = new Thread(ImgPr); } private void ImgPr_end_set(bool a) { if (InvokeRequired) { SetVisibleCallback d = new SetVisibleCallback(ImgPr_end_set); Invoke(d, new object[] { a }); } else { loadingCircle_tab1.Visible = false; loadingCircle_tab1.Active = false; button_next_tab1.Enabled = true; button_refreshlist.Enabled = true; button_removepr.Enabled = true; button_preview.Enabled = true; } } private void ImgPr() { pictureBox_prpreview.Image = buffpr.ToBitmap(Color.Black,Color.White); ImgPr_end_set(false); } private void listBox_prlist_SelectedIndexChanged(object sender, EventArgs e) { prt.Abort(); if (listBox_prlist.SelectedIndex != -1) { loadingCircle_tab1.Visible = false; loadingCircle_tab1.Active = false; button_next_tab1.Enabled = true; buffpr = new Vect((string)listBox_prlist.Items[listBox_prlist.SelectedIndex]); label_pr_name.Text = "??????: " + (string)listBox_prlist.Items[listBox_prlist.SelectedIndex]; label_resolution.Text = "????????????????????: " + buffpr.Header.Width + "x" + buffpr.Header.Height; label_pr_connum.Text = "??????-???? ????????????????: " + buffpr.RowData.Length; label_pr_points.Text = "??????-???? ??????????: " + buffpr.Points; label_source.Text = "??????: " + buffpr.Header.VectType; button_next_tab1.Enabled = false; button_refreshlist.Enabled = false; button_removepr.Enabled = false; loadingCircle_tab1.Visible = true; loadingCircle_tab1.Active = true; prt = new Thread(ImgPr); prt.Start(); } } private void button_refreshlist_Click(object sender, EventArgs e) { if (!ignoreload) { listBox_prlist.Items.Clear(); string[] paths = Directory.GetFiles("Data\\Vect\\", "*.prres"); listBox_prlist.Items.AddRange(paths); paths = Directory.GetFiles("Data\\Vect\\", "*.cvf"); listBox_prlist.Items.AddRange(paths); } } private void button_exit_Click(object sender, EventArgs e) { state = 0; CheckState(); tabControl1.SelectedIndex = 4; } private void button_removepr_Click(object sender, EventArgs e) { File.Delete((string)listBox_prlist.Items[listBox_prlist.SelectedIndex]); button_refreshlist_Click(null,null); } private void button_openfolder_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("Data\\Vect\\"); } private void button_next_tab1_Click_set(bool a) { if (InvokeRequired) { SetVisibleCallback d = new SetVisibleCallback(button_next_tab1_Click_set); Invoke(d, new object[] { a }); } else { radioButton_xsize.Checked = true; comboBox_com.Items.AddRange(SerialPort.GetPortNames()); comboBox_bdrate.SelectedItem = GlobalOptions.Mainbd.ToString(); comboBox_com.SelectedItem = GlobalOptions.Mainport; main_header = pr.Header; bmp = new Bitmap(297, 210); long gdc = Helper.Helper.GCD((int)main_header.Width, (int)main_header.Height); label_ratio.Text = "??????????. ????????????: " + main_header.Height / gdc + '/' + main_header.Width / gdc; textBox_xsize.Text = "50"; loadingCircle1.Visible = false; loadingCircle1.Active = false; bmp = new Bitmap(210, 297); using (Graphics gr = Graphics.FromImage(bmp)) { gr.SmoothingMode = SmoothingMode.AntiAlias; Rectangle rect = new Rectangle(0, 0, (int)ysize, (int)xsize); gr.FillRectangle(Brushes.White, rect); using (Pen thick_pen = new Pen(Color.Red, 0.2f)) { Bitmap tm = new Bitmap(pictureBox_prpreview.Image); //tm.RotateFlip(RotateFlipType.Rotate90FlipNone); gr.DrawRectangle(thick_pen, rect); gr.DrawImage(tm, rect); } } pictureBox1.Image = bmp; pr = null; tabControl1.SelectedIndex = 1; button2.Enabled = true; } } private void button_next_tab1_Click_th() { pr = new Vect(path); pictureBox_prpreview.Image = pr.ToBitmap(2, Color.Black); button_next_tab1_Click_set(false); } private void button_next_tab1_Click(object sender, EventArgs e) { state = 2; CheckState(); listBox_prlist.Enabled = false; button_preview.Enabled = false; path = (string)listBox_prlist.Items[listBox_prlist.SelectedIndex]; loadingCircle1.Visible = true; button_openfolder.Enabled = false; button_refreshlist.Enabled = false; button_removepr.Enabled = false; loadingCircle1.Active = true; new Thread(button_next_tab1_Click_th).Start(); button_next_tab1.Enabled = false; button_exit.Enabled = false; } private void radioButton_xsize_CheckedChanged(object sender, EventArgs e) { textBox_xsize.Enabled = true; textBox_ysize.Enabled = false; } private void radioButton_ysize_CheckedChanged(object sender, EventArgs e) { textBox_xsize.Enabled = false; textBox_ysize.Enabled = true; } private void textBox_xsize_TextChanged(object sender, EventArgs e) { if (radioButton_xsize.Checked) { bool err = false; foreach (char a in textBox_xsize.Text) { if (!num.Contains(a)) { MessageBox.Show("It`s float number. It can not contain '" + a + "'", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); textBox_xsize.Text = textBox_xsize_laststring; err = true; return; } } if (textBox_xsize.Text != "") { if (float.Parse(textBox_xsize.Text) + xoffest > 297) { MessageBox.Show((int.Parse(textBox_xsize.Text) +xoffest)+ " (xsize + xoffset) more than the allowable size. XSize can`t be more than 297 (??4)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); textBox_xsize.Text = textBox_xsize_laststring; err = true; return; } } if (!err) { if (textBox_xsize.Text != "") { xsize = float.Parse(textBox_xsize.Text); textBox_ysize.Text = Print_HM.GetXsize((float)main_header.Width, (float)main_header.Height, xsize).ToString(); if (textBox_ysize.Text != "") { ysize = float.Parse(textBox_ysize.Text); } if (ysize > 210) { MessageBox.Show(ysize + " more than the allowable size. YSize can`t be more than 210 (??4)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); textBox_ysize.Text = textBox_ysize_laststring; textBox_xsize.Text = textBox_xsize_laststring; err = true; return; } textBox_xsize_laststring = textBox_xsize.Text; bmp = new Bitmap(210, 297); using (Graphics gr = Graphics.FromImage(bmp)) { gr.SmoothingMode = SmoothingMode.AntiAlias; Rectangle rect = new Rectangle((int)yoffest, (int)xoffest, (int)ysize, (int)xsize); gr.FillRectangle(Brushes.White, rect); using (Pen thick_pen = new Pen(Color.Red, 0.2f)) { Bitmap tm = new Bitmap(pictureBox_prpreview.Image); gr.DrawRectangle(thick_pen, rect); gr.DrawImage(tm, rect); } } pictureBox1.Image = bmp; } } } } private void textBox_ysize_TextChanged(object sender, EventArgs e) { if (radioButton_ysize.Checked) { bool err = false; foreach (char a in textBox_ysize.Text) { if (!num.Contains(a)) { MessageBox.Show("It`s float number. It can not contain '" + a + "'", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); textBox_ysize.Text = textBox_ysize_laststring; err = true; } } if (textBox_ysize.Text != "") { if (float.Parse(textBox_ysize.Text) + yoffest> 210) { MessageBox.Show((int.Parse(textBox_ysize.Text) + xoffest) + " (ysize + yoffset) more than the allowable size. YSize can`t be more than 210 (??4)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); textBox_ysize.Text = textBox_ysize_laststring; err = true; return; } } if (!err) { textBox_ysize_laststring = textBox_ysize.Text; if (textBox_ysize_laststring != "") { ysize = float.Parse(textBox_ysize_laststring); textBox_xsize.Text = Print_HM.GetYsize((float)main_header.Width, (float)main_header.Height, ysize).ToString(); if (textBox_xsize.Text != "") { xsize = float.Parse(textBox_xsize.Text); } textBox_ysize_laststring = textBox_ysize.Text; bmp = new Bitmap(210, 297); using (Graphics gr = Graphics.FromImage(bmp)) { gr.SmoothingMode = SmoothingMode.AntiAlias; Rectangle rect = new Rectangle((int)yoffest, (int)xoffest, (int)ysize, (int)xsize); gr.FillRectangle(Brushes.White, rect); using (Pen thick_pen = new Pen(Color.Red, 0.2f)) { Bitmap tm = new Bitmap(pictureBox_prpreview.Image); gr.DrawRectangle(thick_pen, rect); gr.DrawImage(tm, rect); } } pictureBox1.Image = bmp; } } } } private void button_preview_Click(object sender, EventArgs e) { new Bitmap(pictureBox_prpreview.Image).Save("Temp\\tmp1_.png"); System.Diagnostics.Process.Start("Temp\\tmp1_.png"); } private void checkBox_useoffset_CheckedChanged(object sender, EventArgs e) { if(!checkBox_useoffset.Checked) { xoffest = 0; yoffest = 0; } else { float.TryParse(textBox_xoffset.Text, out xoffest); float.TryParse(textBox_yoffset.Text, out yoffest); } textBox_xoffset.Enabled = checkBox_useoffset.Checked; textBox_yoffset.Enabled = checkBox_useoffset.Checked; } private void textBox_xoffset_TextChanged(object sender, EventArgs e) { bool err = false; foreach (char a in textBox_xoffset.Text) { if (!num.Contains(a)) { MessageBox.Show("It`s float number. It can not contain '" + a + "'", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); textBox_xoffset.Text = textbox_xoffset_laststring; err = true; } } float.TryParse(textBox_xoffset.Text, out xoffest); float.TryParse(textBox_yoffset.Text, out yoffest); if (textBox_xoffset.Text != "") { if (float.Parse(textBox_xoffset.Text) + xoffest > 297) { MessageBox.Show((int.Parse(textBox_xsize.Text) + xoffest) + " (xsize + xoffset) more than the allowable size. XSize can`t be more than 297 (??4)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); textBox_xoffset.Text = textbox_xoffset_laststring; err = true; return; } } if (!err) { if (textBox_xoffset.Text != "") xoffest = float.Parse(textBox_xoffset.Text); else xoffest = 0; if (textBox_yoffset.Text != "") yoffest = float.Parse(textBox_yoffset.Text); else yoffest = 0; textbox_xoffset_laststring = textBox_xoffset.Text; bmp = new Bitmap(210, 297); using (Graphics gr = Graphics.FromImage(bmp)) { gr.SmoothingMode = SmoothingMode.AntiAlias; Rectangle rect = new Rectangle((int)yoffest, (int)xoffest, (int)ysize, (int)xsize); gr.FillRectangle(Brushes.White, rect); using (Pen thick_pen = new Pen(Color.Red, 0.2f)) { Bitmap tm = new Bitmap(pictureBox_prpreview.Image); gr.DrawRectangle(thick_pen, rect); gr.DrawImage(tm, rect); } pictureBox1.Image = bmp; } } } private void textBox_yoffset_TextChanged(object sender, EventArgs e) { bool err = false; foreach (char a in textBox_yoffset.Text) { if (!num.Contains(a)) { MessageBox.Show("It`s float number. It can not contain '" + a + "'", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); textBox_yoffset.Text = textbox_yoffset_laststring; err = true; } } float.TryParse(textBox_xoffset.Text, out xoffest); float.TryParse(textBox_yoffset.Text, out yoffest); if (textBox_yoffset.Text != "") { if (float.Parse(textBox_ysize.Text) + yoffest > 210) { MessageBox.Show((int.Parse(textBox_ysize.Text) + yoffest) + " (ysize + yoffset) more than the allowable size. YSize can`t be more than 210 (??4)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); textBox_yoffset.Text = textbox_yoffset_laststring; err = true; return; } } if (!err) { if (textBox_yoffset.Text != "") yoffest = float.Parse(textBox_yoffset.Text); else yoffest = 0; if (textBox_xoffset.Text != "") xoffest = float.Parse(textBox_xoffset.Text); else xoffest = 0; textbox_yoffset_laststring = textBox_yoffset.Text; bmp = new Bitmap(210, 297); using (Graphics gr = Graphics.FromImage(bmp)) { gr.SmoothingMode = SmoothingMode.AntiAlias; Rectangle rect = new Rectangle((int)yoffest, (int)xoffest, (int)ysize, (int)xsize); gr.FillRectangle(Brushes.White, rect); using (Pen thick_pen = new Pen(Color.Red, 0.2f)) { Bitmap tm = new Bitmap(pictureBox_prpreview.Image); gr.DrawRectangle(thick_pen, rect); gr.DrawImage(tm, rect); } pictureBox1.Image = bmp; } } } private void comboBox_com_MouseClick(object sender, MouseEventArgs e) { comboBox_com.Items.Clear(); comboBox_com.Items.AddRange(SerialPort.GetPortNames()); } private void comboBox_com_SelectedIndexChanged(object sender, EventArgs e) { if(comboBox_com.SelectedIndex!=-1 && comboBox_bdrate.SelectedIndex!=-1) { button_open.Enabled = true; } } private void comboBox_bdrate_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox_com.SelectedIndex != -1 && comboBox_bdrate.SelectedIndex != -1) { button_open.Enabled = true; } } private void button_open_Click(object sender, EventArgs e) { try { int bd = int.Parse(comboBox_bdrate.Text); main_port = new SerialPort(comboBox_com.Text, bd); main_port.Open(); MessageBox.Show("???????? \" " + comboBox_com.Text + "\" ????????????", "????????", MessageBoxButtons.OK, MessageBoxIcon.Information); button_print.Enabled = true; } catch { MessageBox.Show("???????????????????? ?????????????? ???????? \" " + comboBox_com.Text + "\"", "????????????", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void button_tab2_back_Click(object sender, EventArgs e) { if (button_tab2_back.Text == "??????????") Close(); button_refreshlist.PerformClick(); state = 1; CheckState(); listBox_prlist.Enabled = true; button_preview.Enabled = true; loadingCircle1.Visible = false; button_openfolder.Enabled = true; button_refreshlist.Enabled = true; button_removepr.Enabled = true; loadingCircle1.Active = false; button_next_tab1.Enabled = true; button_exit.Enabled = true; tabControl1.SelectedIndex = 0; } private void button_print_Click(object sender, EventArgs e) { state = 3; CheckState(); tabControl1.SelectedIndex = 2; PrintOptions op = new PrintOptions(); op.YOffset = yoffest; op.XOffset = xoffest; op.XMM = GlobalOptions.XMM; op.YMM = GlobalOptions.YMM; op.PrintSize = new SizeF(xsize, ysize); pr = new Vect(path); op.ImageSize = new Size((int)pr.Header.Width, (int)pr.Header.Height); print = new Print(pr, op, GlobalOptions.Def_SPO, GlobalOptions.Def_RBO, main_port); print.ProceedStatusChanged += Print_ProceedStatusChanged; print.PrintError += Print_PrintError; print.PrintChanged += Print_PrintChanged; print.ProceedEnd += Print_ProceedEnd; print.TimeChanged += Print_TimeChanged; print.PrintingDone += Print_PrintingDone; print.ComputeCommands(); } private void Print_PrintingDone(object sender, EventArgs e) { End(false); } private void End(bool a) { if (InvokeRequired) { SetVisibleCallback d = new SetVisibleCallback(End); Invoke(d, new object[] { a }); } else { print.Abort(); Thread.Sleep(1000); label2.Text = string.Format("???? {0:0.##} ??????. ?????? {1:0.##} ??????.",time,time/60); state = 5; CheckState(); tabControl1.SelectedIndex = 5; } } private void OnError(bool a) { if (InvokeRequired) { SetVisibleCallback d = new SetVisibleCallback(OnError); Invoke(d, new object[] { a }); } else { MessageBox.Show("???????????? ???????????????? ?? ?????????? ????????????:\" " + errorarg + "\"", "????????????", MessageBoxButtons.OK, MessageBoxIcon.Warning); tabControl1.SelectedIndex = 1; } } private void Print_PrintError(object sender, CNCWFA_API.ErrorEventArgs e) { errorarg = e; OnError(false); } private void Print_TimeChanged__(TimeEventArgs a) { if (InvokeRequired) { Print_TimeChanged_ d = new Print_TimeChanged_(Print_TimeChanged__); Invoke(d, new object[] { a }); } else { time = a.time_spend; label_spendtime.Text = string.Format("??????????????????: {0:0.##}s({1:0.##}m)", (a.time_spend), (a.time_spend /60)); label_lefttime.Text = string.Format("????????????????: {0:0.##}s({1:0.##}m)", (a.time_left), (a.time_left / 60)); } } private void Print_TimeChanged(object sender, TimeEventArgs e) { Print_TimeChanged__(e); } private void Print_PrintChanged(object sender, PrintedEventArgs e) { Print_PrintChanged_(e); } private void Print_PrintChanged_(PrintedEventArgs a) { if (InvokeRequired) { SetLabelTextFeedBack_ d = new SetLabelTextFeedBack_(Print_PrintChanged_); Invoke(d, new object[] { a }); } else { progressBar1.Maximum = (int)a.CountTotal; progressBar1.Value = (int)a.CountDone; label_complete_percentage.Text = string.Format("??????????????????: {0:0.##}%", ((float)a.CountDone / (float)a.CountTotal * 100)); label_complete_number.Text = "????????????????: " + a.CountDone + '\\' + a.CountTotal; pictureBox2.Image = print.ProcessBmp; } } private void SetLabelText(string a) { if (InvokeRequired) { SetLabelTextFeedBack d = new SetLabelTextFeedBack(SetLabelText); Invoke(d, new object[] { a }); } else { label_complete.Text = "??????????????????: " + a + '%'; } } private void SetLabelText_(string a) { if (InvokeRequired) { SetLabelTextFeedBack d = new SetLabelTextFeedBack(SetLabelText_); Invoke(d, new object[] { a }); } else { state = 4; CheckState(); bmp_ = new Bitmap((int)pr.Header.Width, (int)pr.Header.Height); label_prtime_print.Text = label_prtime.Text; label_resolution_print.Text = label_resolution.Text; label_type_print.Text = label_source.Text; label_num_of_cont.Text = "??????-???? ????????????????: " + pr.ContorurCount; tabControl1.SelectedIndex = 3; } } private void Print_ProceedEnd(object sender, EventArgs e) { SetLabelText_("23"); print.PrintVector(); } private void Print_ProceedStatusChanged(object sender, ProceedStatusChangedArgs e) { SetLabelText(e.Percentage.ToString()); } private void Form_print_FormClosing(object sender, FormClosingEventArgs e) { print?.Abort(); } private void button_reset_Click(object sender, EventArgs e) { radioButton_xsize.Checked = true; textBox_xsize.Text = "100"; textBox_xoffset.Text= "0"; textBox_yoffset.Text = "0"; checkBox_useoffset.Checked = false; } private void label_source_Click(object sender, EventArgs e) { } private void button_abort_Click(object sender, EventArgs e) { if (MessageBox.Show("???????????????? ?????????????", "??????????????????????????", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { print.Abort(); Thread.Sleep(1000); label2.Text = string.Format("???? {0:0.##} ??????. ?????? {1:0.##} ??????.", time, time / 60); state = 5; CheckState(); tabControl1.SelectedIndex = 5; } } private void button_pause_Click(object sender, EventArgs e) { // print.Pause(); } private void button1_Click(object sender, EventArgs e) { panel1.Visible = !panel1.Visible; SetProbe(); } private void button2_Click(object sender, EventArgs e) { var a = colorDialog1.ShowDialog(); if(a== DialogResult.OK) { print.DrawColor = colorDialog1.Color; } SetProbe(); } private void SetProbe() { Bitmap colorprobe_back = new Bitmap(pictureBox_backcolor.Width, pictureBox_backcolor.Height); Bitmap colorprobe_draw = new Bitmap(pictureBox_backcolor.Width, pictureBox_backcolor.Height); Rectangle rect = new Rectangle(0, 0, pictureBox_backcolor.Width, pictureBox_backcolor.Height); using (Graphics gr = Graphics.FromImage(colorprobe_back)) { gr.FillRectangle(new SolidBrush(print.BackColor), rect); } using (Graphics gr = Graphics.FromImage(colorprobe_draw)) { gr.FillRectangle(new SolidBrush(print.DrawColor), rect); } pictureBox_drawcolor.Image = colorprobe_draw; pictureBox_backcolor.Image = colorprobe_back; } private void button_backcolor_Click(object sender, EventArgs e) { var a = colorDialog2.ShowDialog(); if (a == DialogResult.OK) { print.BackColor = colorDialog2.Color; } SetProbe(); } private void textBox_penwidth_TextChanged(object sender, EventArgs e) { bool err = false; foreach (char a in textBox_penwidth.Text) { if (!num.Contains(a)) { MessageBox.Show("It`s float number. It can not contain '" + a + "'", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); textBox_penwidth.Text = textBox_penwidth_laststring; err = true; } } if(!err) { print.PenWidth = float.Parse(textBox_penwidth.Text); } } private void button4_Click(object sender, EventArgs e) { state = 1; CheckState(); tabControl1.SelectedIndex = 0; } private void button5_Click(object sender, EventArgs e) { Close(); } private void button6_Click(object sender, EventArgs e) { Close(); } private void button2_Click_1(object sender, EventArgs e) { if(openFileDialog1.ShowDialog() == DialogResult.OK) { try { File.Copy(openFileDialog1.FileName, "Data\\Vect\\" + new FileInfo(openFileDialog1.FileName).Name); } catch { } state = 2; CheckState(); listBox_prlist.Enabled = false; button_preview.Enabled = false; path = openFileDialog1.FileName; loadingCircle1.Visible = true; button_openfolder.Enabled = false; button_refreshlist.Enabled = false; button_removepr.Enabled = false; loadingCircle1.Active = true; new Thread(button_next_tab1_Click_th).Start(); button_next_tab1.Enabled = false; button_exit.Enabled = false; } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.NotificationHubs { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for NamespacesOperations. /// </summary> public static partial class NamespacesOperationsExtensions { /// <summary> /// Checks the availability of the given service namespace across all Azure /// subscriptions. This is useful because the domain name is created based on /// the service namespace name. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='parameters'> /// The namespace name. /// </param> public static CheckAvailabilityResult CheckAvailability(this INamespacesOperations operations, CheckAvailabilityParameters parameters) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).CheckAvailabilityAsync(parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks the availability of the given service namespace across all Azure /// subscriptions. This is useful because the domain name is created based on /// the service namespace name. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='parameters'> /// The namespace name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<CheckAvailabilityResult> CheckAvailabilityAsync(this INamespacesOperations operations, CheckAvailabilityParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CheckAvailabilityWithHttpMessagesAsync(parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates/Updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Namespace Resource. /// </param> public static NamespaceResource CreateOrUpdate(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).CreateOrUpdateAsync(resourceGroupName, namespaceName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates/Updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Namespace Resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<NamespaceResource> CreateOrUpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// notificationHubs under the namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> public static void Delete(this INamespacesOperations operations, string resourceGroupName, string namespaceName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).DeleteAsync(resourceGroupName, namespaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// notificationHubs under the namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task DeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// notificationHubs under the namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> public static void BeginDelete(this INamespacesOperations operations, string resourceGroupName, string namespaceName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).BeginDeleteAsync(resourceGroupName, namespaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// notificationHubs under the namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task BeginDeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns the description for the specified namespace. /// <see href="http://msdn.microsoft.com/library/azure/dn140232.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> public static NamespaceResource Get(this INamespacesOperations operations, string resourceGroupName, string namespaceName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).GetAsync(resourceGroupName, namespaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns the description for the specified namespace. /// <see href="http://msdn.microsoft.com/library/azure/dn140232.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<NamespaceResource> GetAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates an authorization rule for a namespace /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Aauthorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> public static SharedAccessAuthorizationRuleResource CreateOrUpdateAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates an authorization rule for a namespace /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Aauthorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<SharedAccessAuthorizationRuleResource> CreateOrUpdateAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a namespace authorization rule /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> public static void DeleteAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a namespace authorization rule /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task DeleteAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets an authorization rule for a namespace by name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// Authorization rule name. /// </param> public static SharedAccessAuthorizationRuleResource GetAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).GetAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets an authorization rule for a namespace by name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// Authorization rule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<SharedAccessAuthorizationRuleResource> GetAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the available namespaces within a resourceGroup. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. If resourceGroupName value is null the /// method lists all the namespaces within subscription /// </param> public static Microsoft.Rest.Azure.IPage<NamespaceResource> List(this INamespacesOperations operations, string resourceGroupName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAsync(resourceGroupName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the available namespaces within a resourceGroup. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. If resourceGroupName value is null the /// method lists all the namespaces within subscription /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<NamespaceResource>> ListAsync(this INamespacesOperations operations, string resourceGroupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the available namespaces within the subscription irrespective of /// the resourceGroups. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Microsoft.Rest.Azure.IPage<NamespaceResource> ListAll(this INamespacesOperations operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAllAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all the available namespaces within the subscription irrespective of /// the resourceGroups. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<NamespaceResource>> ListAllAsync(this INamespacesOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the authorization rules for a namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> public static Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRules(this INamespacesOperations operations, string resourceGroupName, string namespaceName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAuthorizationRulesAsync(resourceGroupName, namespaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the authorization rules for a namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the namespace /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the namespace for the specified authorizationRule. /// </param> public static ResourceListKeys ListKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListKeysAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the namespace /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the namespace for the specified authorizationRule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ResourceListKeys> ListKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the namespace for the specified authorizationRule. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the Namespace Authorization Rule Key. /// </param> public static ResourceListKeys RegenerateKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, PolicykeyResource parameters) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).RegenerateKeysAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the namespace for the specified authorizationRule. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the Namespace Authorization Rule Key. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ResourceListKeys> RegenerateKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, PolicykeyResource parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the available namespaces within a resourceGroup. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<NamespaceResource> ListNext(this INamespacesOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the available namespaces within a resourceGroup. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<NamespaceResource>> ListNextAsync(this INamespacesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the available namespaces within the subscription irrespective of /// the resourceGroups. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<NamespaceResource> ListAllNext(this INamespacesOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAllNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all the available namespaces within the subscription irrespective of /// the resourceGroups. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<NamespaceResource>> ListAllNextAsync(this INamespacesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the authorization rules for a namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRulesNext(this INamespacesOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAuthorizationRulesNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the authorization rules for a namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesNextAsync(this INamespacesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using UnityEngine; using System; using System.Collections.Generic; using System.IO; using System.Text; /* Created 2/25/2011 - Adam Reilly This class is designed to be the main entry/exit point of a Unity Project. */ /* * Unity Execution order, taken from http://unity3d.com/support/documentation/Manual/Execution%20Order.html * * -=Initialization=- * Awake() - once * OnEnable() - once, only called if the gameobject is active, just after the object is enabled * Start() - once * * -=Update=- * FixedUpdate() - every frame sometimes multiple times per frame. Called more frequently than update. Do all physics calculations here * Update() - every frame, once per frame * LateUpdate() - every frame, once per frame. All calculations in Update are completed before LateUpdate is called * * -=Coroutines=- * Executed after all Update functions. If you start a coroutine in LateUpdate, it will be called after LateUpdate, just before rendering * * -=Combined Execution order=- * So in conclusion, this is the execution order for any given script: * All Awake calls * All Start Calls * while (stepping towards variable delta time) o All FixedUpdate functions o Physics simulation o OnEnter/Exit/Stay trigger functions o OnEnter/Exit/Stay collision functions * Rigidbody interpolation applies transform.position and rotation * OnMouseDown/OnMouseUp etc. events * All Update functions * Animations are advanced, blended and applied to transform * All LateUpdate functions * Rendering */ public class VHMain : MonoBehaviour { #region Constants protected const string VhMsgCommand = "vhmsg"; protected const string ToggleFullScreenCommand = "toggle_fullscreen"; protected const string SetResolutionCommand = "set_resolution"; protected const string CutsceneCommand = "cutscene"; #endregion #region Variables public DebugConsole m_Console; public string m_configIniFilename = ""; public string m_procId; protected IniParser m_ConfigFile; // used for reading config files protected int m_debugTextLineNumber = 0; // reset this at the beginning of every OnGUI() protected bool m_displaySubtitles = false; protected bool m_displayUserDialogs = false; protected string m_subtitleText = ""; protected string m_userDialogText = ""; #endregion public bool DisplaySubtitles { get { return m_displaySubtitles; } set { m_displaySubtitles = value; } } public bool DisplayUserDialog { get { return m_displayUserDialogs; } set { m_displayUserDialogs = value; } } #region Unity Messages public virtual void Awake() { // this initializes the www system and prevents a delay on the loading of the first file new WWW("file://"); Debug.Log("Unity Version: " + Application.unityVersion); Debug.Log("Platform: " + Application.platform); if (!VHUtils.IsWebGL()) { Debug.Log(string.Format("Application.streamingAssetsPath - '{0}'", Application.streamingAssetsPath)); Debug.Log(string.Format("Directory.GetCurrentDirectory() - '{0}'", Directory.GetCurrentDirectory())); Debug.Log(string.Format("Application.dataPath - '{0}'", Application.dataPath)); Debug.Log(string.Format("Application.persistantDataPath - '{0}'", Application.persistentDataPath)); Debug.Log(string.Format("Path.GetFullPath('.') - '{0}'", Path.GetFullPath("."))); } Application.runInBackground = true; } public virtual void Start() { DebugConsole console = DebugConsole.Get(); if (console != null) { console.AddCommandCallback(VhMsgCommand, new DebugConsole.ConsoleCallback(HandleConsoleMessage)); console.AddCommandCallback(ToggleFullScreenCommand, new DebugConsole.ConsoleCallback(HandleConsoleMessage)); console.AddCommandCallback(SetResolutionCommand, new DebugConsole.ConsoleCallback(HandleConsoleMessage)); console.AddCommandCallback(CutsceneCommand, new DebugConsole.ConsoleCallback(HandleConsoleMessage)); } LoadConfigFile(); VHMsgBase vhmsg = VHMsgBase.Get(); if (vhmsg != null) { vhmsg.SubscribeMessage("renderer"); vhmsg.AddMessageEventHandler(new VHMsgBase.MessageEventHandler(VHMsg_MessageHandler)); } if (VHUtils.HasCommandLineArgument(CutsceneCommand)) { PlayCutscene(VHUtils.GetCommandLineArgumentValue(CutsceneCommand), true); } } public virtual void OnGUI() { if (DisplaySubtitles && !string.IsNullOrEmpty(m_subtitleText)) { // subtitle text Rect subtitleTextPos = new Rect(0.5f, 0.8f, 0.8f, 0.25f); subtitleTextPos.x -= subtitleTextPos.width / 2; Rect subtitleTextBackdropPos = new Rect(subtitleTextPos); subtitleTextBackdropPos.x += 0.001f; subtitleTextBackdropPos.y -= 0.001f; var labelStyle = GUI.skin.GetStyle("Label"); var previousAlignment = labelStyle.alignment; labelStyle.alignment = TextAnchor.UpperCenter; GUI.color = Color.black; VHGUI.Label(subtitleTextBackdropPos, m_subtitleText, labelStyle); GUI.color = Color.white; VHGUI.Label(subtitleTextPos, m_subtitleText, labelStyle, Color.yellow); labelStyle.alignment = previousAlignment; } if (DisplayUserDialog && !string.IsNullOrEmpty(m_userDialogText)) { // user dialog text Rect userDialogTextPos = new Rect(0.5f, 0.2f, 0.8f, 0.25f); userDialogTextPos.x -= userDialogTextPos.width / 2; Rect m_UserDialogTextBackdropPos = new Rect(userDialogTextPos.x * Screen.width, userDialogTextPos.y * Screen.height, userDialogTextPos.width * Screen.width, userDialogTextPos.height * Screen.height); m_UserDialogTextBackdropPos.x += 1f; m_UserDialogTextBackdropPos.y -= 1f; GUI.color = Color.black; GUI.Label(m_UserDialogTextBackdropPos, m_userDialogText); GUI.color = Color.white; VHGUI.Label(userDialogTextPos, m_userDialogText, Color.white); } } public virtual void OnApplicationQuit() { } virtual protected void LoadConfigFile() { string configFileName = VHUtils.GetCommandLineArgumentValue("config"); if (!String.IsNullOrEmpty(configFileName)) { m_configIniFilename = configFileName; } if (!String.IsNullOrEmpty(m_configIniFilename)) { configFileName = "Config/" + m_configIniFilename; m_ConfigFile = new IniParser(configFileName); } } #endregion #region Main Functionality protected virtual void HandleConsoleMessage(string commandEntered, DebugConsole console) { Vector2 vec2Data = Vector2.zero; string strData = string.Empty; if (commandEntered.IndexOf(ToggleFullScreenCommand) != -1) { Screen.fullScreen = !Screen.fullScreen; } else if (commandEntered.IndexOf(SetResolutionCommand) != -1) { if (console.ParseVector2(commandEntered, ref vec2Data)) { Screen.SetResolution((int)vec2Data.x, (int)vec2Data.y, Screen.fullScreen); } else { Debug.LogError("set_resolution requires a width and hieght parameter. Example: set_resolution 1024 768"); } } else if (commandEntered.IndexOf(CutsceneCommand) != -1) { console.ParseSingleParameter(commandEntered, ref strData, CutsceneCommand.Length); PlayCutscene(strData, false); } } protected virtual void VHMsg_MessageHandler(object sender, VHMsgBase.Message message) { string [] splitargs = message.s.Split(" ".ToCharArray()); if (splitargs.Length > 0) { if (splitargs[0] == "renderer") { string procid = ""; if (splitargs.Length > 2) { if (splitargs[1] == "id") { procid = splitargs[2]; } } if (!string.IsNullOrEmpty(m_procId) && !string.IsNullOrEmpty(procid) && procid != m_procId) { return; } // remove the id from the message. terribly inefficient, but I don't want to mess up the parsing code below if (!string.IsNullOrEmpty(procid)) { List<string> removeId = new List<string>(splitargs); removeId.RemoveAt(1); removeId.RemoveAt(1); splitargs = removeId.ToArray(); } if (splitargs.Length > 2 && splitargs[1] == "time") { // 'renderer [id procid] time 1.0' float timeScale; if (float.TryParse(splitargs[2], out timeScale)) { Time.timeScale = timeScale; } } else if (splitargs.Length > 3 && splitargs[1] == "create") { // 'renderer [id procid] create pawnName SmartbodyPawn' string name = splitargs[2]; string objectType = splitargs[3]; UnityEngine.Object obj = Instantiate(Resources.Load(objectType), Vector3.zero, Quaternion.identity); obj.name = name; Debug.Log(string.Format("Object {0} ({1}) created!", name, objectType)); } else if (splitargs.Length > 2 && splitargs[1] == "destroy") { // 'renderer [id procid] destroy objectName' DestroyGameObject(splitargs[2]); } } else if (splitargs[0] == "vrSpeech") { // vrSpeech interp user<somenumber> 1 1.0 normal <TEXT> // vrSpeech interp user0004 1 1.0 normal What's your name? // user is speaking into the mic if (splitargs.Length >= 2 && splitargs[1] == "interp") { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('\"'); for (int i = 6; i < splitargs.Length; i++) { stringBuilder.Append(splitargs[i]); stringBuilder.Append(' '); } stringBuilder.Insert(stringBuilder.Length - 1, '\"'); m_userDialogText = stringBuilder.ToString(); } } else if (splitargs[0] == "vrSpeak" || splitargs[0] == "vrExpress") { /* vrExpress ChrBrad user 1346294984756-28-1 <?xml version="1.0" encoding="UTF-8" standalone="no" ?> <act> <participant id="ChrBrad" role="actor" /> <fml> <turn start="take" end="give" /> <affect type="neutral" target="addressee"></affect> <culture type="neutral"></culture> <personality type="neutral"></personality> </fml> <bml> <speech id="sp1" ref="brad_self_firstbrad" type="application/ssml+xml">My first name is Brad.</speech> </bml> </act> vrExpress ChrBrad user 1346294984756-28-1 <?xml version="1.0" encoding="UTF-8" standalone="no" ?> <act> <participant id="ChrBrad" role="actor" /> <fml> <turn start="take" end="give" /> <affect type="neutral" target="addressee"></affect> <culture type="neutral"></culture> <personality type="neutral"></personality> </fml> <bml> <speech id="sp1" ref="brad_self_firstbrad" type="application/ssml+xml">My first name is Brad.</speech> </bml> </act> */ var args = VHMsgBase.SplitIntoOpArg(message.s); string subtitleText = ParseSpeechText(args.Value); if (!string.IsNullOrEmpty(subtitleText.Trim())) m_subtitleText = subtitleText; } else if (splitargs[0] == "vrSpoke") { // vrSpoke ChrBrad user 1346294984756-28-1 My first name is Brad. } } } protected void DestroyGameObject(string objectName) { GameObject obj = GameObject.Find(objectName); if (obj != null) { Destroy(obj); Debug.Log(string.Format("Object '{0}' destroyed.", objectName)); } else { Debug.Log(string.Format("Object '{0}' not found!", objectName)); } } protected virtual void PlayCutscene(string cutsceneName, bool exitApplicationAfterwards) { Cutscene[] cutscenes = (Cutscene[])FindObjectsOfType(typeof(Cutscene)); bool cutsceneFound = false; if (!string.IsNullOrEmpty(cutsceneName)) { for (int i = 0; i < cutscenes.Length; i++) { if (cutsceneName == cutscenes[i].CutsceneName) { cutscenes[i].Play(); if (exitApplicationAfterwards) { cutscenes[i].AddOnFinishedCutsceneCallback(FinishedStartupCutscene); } cutsceneFound = true; break; } } } if (!cutsceneFound) { string cutscenNames = string.Empty; for (int i = 0; i < cutscenes.Length; i++) { cutscenNames += cutscenes[i].CutsceneName; cutscenNames += " "; } Debug.LogError(string.Format("Cutscene not found. Available cutscenes: {0}", cutscenNames)); } } void FinishedStartupCutscene(Cutscene cutscene) { VHUtils.ApplicationQuit(); } static string ParseSpeechText(string text) { int endOfSpeechIndex = text.IndexOf("</speech>"); if (endOfSpeechIndex == -1) { // there is no speech text return ""; } int startOfSpeechIndex = text.LastIndexOf('>', endOfSpeechIndex); if (startOfSpeechIndex == -1) { // broken xml tags return ""; } return text.Substring(startOfSpeechIndex + 1, endOfSpeechIndex - startOfSpeechIndex - 1); } #endregion }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DeOps.Implementation; using DeOps.Interface; using DeOps.Interface.TLVex; using DeOps.Interface.Views; using DeOps.Services.Assist; using DeOps.Services.Trust; namespace DeOps.Services.Plan { public partial class GoalsView : ViewShell { public CoreUI UI; public OpCore Core; public PlanService Plans; public TrustService Trust; public ulong UserID; public uint ProjectID; List<int> SpecialList = new List<int>(); List<PlanGoal> RootList = new List<PlanGoal>(); List<PlanGoal> ArchiveList = new List<PlanGoal>(); public int LoadIdent; public int LoadBranch; StringBuilder Details = new StringBuilder(4096); const string DefaultPage = @"<html> <head> <style> body { font-family:tahoma; font-size:12px;margin-top:3px;} td { font-size:10px;vertical-align: middle; } </style> </head> <body bgcolor=#f5f5f5> </body> </html>"; const string GoalPage = @"<html> <head> <style> body { font-family:tahoma; font-size:12px;margin-top:3px;} td { font-size:10px;vertical-align: middle; } </style> <script> function SetElement(id, text) { document.getElementById(id).innerHTML = text; } </script> </head> <body bgcolor=#f5f5f5> <br> <b><u><span id='title'><?=title?></span></u></b><br> <br> <b>Due</b><br> <span id='due'><?=due?></span><br> <br> <b>Assigned to</b><br> <span id='person'><?=person?></span><br> <br> <b>Notes</b><br> <span id='notes'><?=notes?></span> </body> </html>"; const string ItemPage = @"<html> <head> <style> body { font-family:tahoma; font-size:12px;margin-top:3px;} td { font-size:10px;vertical-align: middle; } </style> <script> function SetElement(id, text) { document.getElementById(id).innerHTML = text; } </script> </head> <body bgcolor=#f5f5f5> <br> <b><u><span id='title'><?=title?></span></u></b><br> <br> <b>Progress</b><br> <span id='progress'><?=progress?></span><br> <br> <b>Notes</b><br> <span id='notes'><?=notes?></span> </body> </html>"; public GoalsView(CoreUI ui, PlanService plans, ulong id, uint project) { InitializeComponent(); UI = ui; Core = ui.Core; Plans = plans; Trust = Core.Trust; UserID = id; ProjectID = project; GuiUtils.SetupToolstrip(toolStrip1, new OpusColorTable()); GuiUtils.FixMonoDropDownOpening(SelectGoalButton, SelectGoal_DropDownOpening); splitContainer1.Panel2Collapsed = true; SetDetails(null, null); } public override string GetTitle(bool small) { if (small) return "Goals"; string title = ""; if (UserID == Core.UserID) title += "My "; else title += Core.GetName(UserID) + "'s "; if (ProjectID != 0) title += Trust.GetProjectName(ProjectID) + " "; title += "Goals"; return title; } public override Size GetDefaultSize() { return new Size(475, 325); } public override Icon GetIcon() { return PlanRes.Goals; } public override void Init() { Trust.GuiUpdate += new LinkGuiUpdateHandler(Trust_Update); Plans.PlanUpdate += new PlanUpdateHandler(Plans_Update); Core.KeepDataGui += new KeepDataHandler(Core_KeepData); splitContainer1.Height = Height - toolStrip1.Height; MainPanel.Init(this); // research highers for assignments List<ulong> ids = Trust.GetUplinkIDs(UserID, ProjectID); foreach (ulong id in ids) Plans.Research(id); RefreshAssigned(); } private void GoalsView_Load(object sender, EventArgs e) { if(LoadIdent != 0) foreach(PlanGoal goal in RootList) if (goal.Ident == LoadIdent) { //crit go to specific branch ((GoalPage)tab).SelectBranch(LoadBranch); // schedule needs to pass a list of the branches from the root to this node // so appropriate path can be expanded MainPanel.LoadGoal(goal); return; } if (RootList.Count > 0) MainPanel.LoadGoal(RootList[0]); } public override bool Fin() { bool save = false; if (SaveButton.Visible) { DialogResult result = MessageBox.Show(this, "Save Chages to Goals?", "DeOps", MessageBoxButtons.YesNoCancel); if (result == DialogResult.Yes) save = true; if (result == DialogResult.Cancel) return false; } Trust.GuiUpdate -= new LinkGuiUpdateHandler(Trust_Update); Plans.PlanUpdate -= new PlanUpdateHandler(Plans_Update); Core.KeepDataGui -= new KeepDataHandler(Core_KeepData); if(save) Plans.SaveLocal(); // save down here so events arent triggered return true; } void Core_KeepData() { MainPanel.GetFocused(); } void Trust_Update(ulong key) { RefreshAssigned(); MainPanel.TrustUpdate(key); } void Plans_Update(OpPlan plan) { RefreshAssigned(); MainPanel.PlanUpdate(plan); SetDetails(LastGoal, LastItem); } void RefreshAssigned() { RootList.Clear(); ArchiveList.Clear(); Plans.GetAssignedGoals(UserID, ProjectID, RootList, ArchiveList); string label = RootList.Count.ToString(); label += (RootList.Count == 1) ? " Goal" : " Goals"; SelectGoalButton.Text = label; } public void ChangesMade() { Plans_Update(Plans.LocalPlan); SaveButton.Visible = true; DiscardButton.Visible = true; splitContainer1.Height = Height - toolStrip1.Height - SaveButton.Height - 8; if (GuiUtils.IsRunningOnMono()) { // buttons aren't positioned when they aren't visible SaveButton.Location = new Point(Width - 156, Height - 22); DiscardButton.Location = new Point(Width - 86, Height - 22); } } private void SaveButton_Click(object sender, EventArgs e) { SaveButton.Visible = false; DiscardButton.Visible = false; splitContainer1.Height = Height - toolStrip1.Height; Plans.SaveLocal(); } private void DiscardButton_Click(object sender, EventArgs e) { SaveButton.Visible = false; DiscardButton.Visible = false; splitContainer1.Height = Height - toolStrip1.Height; Plans.LoadPlan(Core.UserID); Plans_Update(Plans.LocalPlan); } private void SelectGoal_DropDownOpening(object sender, EventArgs e) { SelectGoalButton.DropDownItems.Clear(); // add plans foreach(PlanGoal goal in RootList) SelectGoalButton.DropDownItems.Add(new SelectMenuItem(goal, new EventHandler(SelectGoalMenu_Click))); // add archived if exists if (ArchiveList.Count > 0) { ToolStripMenuItem archived = new ToolStripMenuItem("Archived"); foreach (PlanGoal goal in ArchiveList) archived.DropDownItems.Add(new SelectMenuItem(goal, new EventHandler(SelectGoalMenu_Click))); SelectGoalButton.DropDownItems.Add(archived); } // if local, add create option if (UserID == Core.UserID) { SelectGoalButton.DropDownItems.Add(new ToolStripSeparator()); SelectGoalButton.DropDownItems.Add(new ToolStripMenuItem("Create Goal", null, SelectGoalMenu_Create)); } } private void SelectGoalMenu_Click(object sender, EventArgs e) { SelectMenuItem item = sender as SelectMenuItem; if (item == null) return; MainPanel.LoadGoal(item.Goal); } private void SelectGoalMenu_Create(object sender, EventArgs e) { PlanGoal goal = new PlanGoal(); goal.Ident = Core.RndGen.Next(); goal.Project = ProjectID; goal.Person = Core.UserID; goal.End = Core.TimeNow.AddDays(30).ToUniversalTime(); EditGoal form = new EditGoal(EditGoalMode.New, this, goal); if (form.ShowDialog(this) == DialogResult.OK) { ChangesMade(); MainPanel.LoadGoal(goal); } } private void DetailsButton_CheckedChanged(object sender, EventArgs e) { splitContainer1.Panel2Collapsed = !DetailsButton.Checked; if (DetailsButton.Checked) DetailsButton.Image = PlanRes.details2; else DetailsButton.Image = PlanRes.details1; } /*private void ArchivedList_SelectedIndexChanged(object sender, EventArgs e) { ArchiveItem item = GetSelectedArchive(); if (item == null) { HideLinks(); return; } bool local = false ; if (item.Goal.Person == Core.LocalDhtID) local = true; ViewLink.Visible = true; UnarchiveLink.Visible = local; EditLink.Visible = local; DeleteLink.Visible = local; // view or hide bool viewing = false; foreach (TabPage tab in GoalTabs.TabPages) if (tab.GetType() == typeof(GoalPage)) if (((GoalPage)tab).Goal.Ident == item.Goal.Ident) { viewing = true; break; } ViewLink.Text = viewing ? "Hide" : "View"; } void HideLinks() { ViewLink.Visible = false; UnarchiveLink.Visible = false; EditLink.Visible = false; DeleteLink.Visible = false; } private void ViewLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { ArchiveItem item = GetSelectedArchive(); bool found = false; foreach (TabPage tab in GoalTabs.TabPages) if (tab.GetType() == typeof(GoalPage)) if (((GoalPage)tab).Goal.Ident == item.Goal.Ident) { found = true; SpecialList.Remove(item.Goal.Ident); GoalTabs.TabPages.Remove(tab); break; } if (!found) { SpecialList.Add(item.Goal.Ident); AddTab(item.Goal); } ViewLink.Text = found ? "View" : "Hide"; } private void UnarchiveLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { ArchiveItem item = GetSelectedArchive(); if (item == null) return; DialogResult result = MessageBox.Show(this, "Are you sure you want to unarchive:\n" + item.Goal.Title + "?", "DeOps", MessageBoxButtons.YesNo); if (result == DialogResult.No) return; item.Goal.Archived = false; if (SpecialList.Contains(item.Goal.Ident)) SpecialList.Remove(item.Goal.Ident); ChangesMade(); ArchivedList_SelectedIndexChanged(null, null); } private void EditLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { ArchiveItem item = GetSelectedArchive(); if (item == null) return; EditGoal form = new EditGoal(EditGoalMode.Edit, Core, item.Goal); if (form.ShowDialog(this) == DialogResult.OK) ChangesMade(); } private void DeleteLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { ArchiveItem item = GetSelectedArchive(); if (item == null) return; DialogResult result = MessageBox.Show(this, "Are you sure you want to delete:\n" + item.Goal.Title + "?", "DeOps", MessageBoxButtons.YesNo); if (result == DialogResult.No) return; Plans.LocalPlan.RemoveGoal(item.Goal); if (SpecialList.Contains(item.Goal.Ident)) SpecialList.Remove(item.Goal.Ident); ChangesMade(); ArchivedList_SelectedIndexChanged(null, null); }*/ PlanGoal LastGoal; PlanItem LastItem; enum DetailsModeType { Uninit, None, Goal, Item }; DetailsModeType DetailsMode; public void SetDetails(PlanGoal goal, PlanItem item) { LastGoal = goal; LastItem = item; List<string[]> tuples = new List<string[]>(); string notes = null; DetailsModeType mode = DetailsModeType.None; // get inof that needs to be set if (goal != null) { tuples.Add(new string[] { "title", goal.Title }); tuples.Add(new string[] { "due", goal.End.ToLocalTime().ToString("D") }); tuples.Add(new string[] { "person", Core.GetName(goal.Person) }); tuples.Add(new string[] { "notes", goal.Description.Replace("\r\n", "<br>") }); notes = goal.Description; mode = DetailsModeType.Goal; } else if (item != null) { tuples.Add(new string[] { "title", item.Title }); tuples.Add(new string[] { "progress", item.HoursCompleted.ToString() + " of " + item.HoursTotal.ToString() + " Hours Completed" }); tuples.Add(new string[] { "notes", item.Description.Replace("\r\n", "<br>") }); notes = item.Description; mode = DetailsModeType.Item; } // set details button DetailsButton.ForeColor = Color.Black; if (splitContainer1.Panel2Collapsed && notes != null && notes != "") DetailsButton.ForeColor = Color.Red; if (mode != DetailsMode) { DetailsMode = mode; Details.Length = 0; if (mode == DetailsModeType.Goal) Details.Append(GoalPage); else if (mode == DetailsModeType.Item) Details.Append(ItemPage); else Details.Append(DefaultPage); foreach (string[] tuple in tuples) Details.Replace("<?=" + tuple[0] + "?>", tuple[1]); SetDisplay(Details.ToString()); } else { foreach (string[] tuple in tuples) DetailsBrowser.SafeInvokeScript("SetElement", new String[] { tuple[0], tuple[1] }); } } private void SetDisplay(string html) { Debug.Assert(!html.Contains("<?")); // prevents clicking sound when browser navigates DetailsBrowser.SetDocNoClick(html); } private void DetailsButton_Click(object sender, EventArgs e) { } } class SelectMenuItem : ToolStripMenuItem { public PlanGoal Goal; public SelectMenuItem(PlanGoal goal, EventHandler onClick) : base(goal.Title, null, onClick) { Goal = goal; } } }
using System.Runtime.InteropServices.ComTypes; using FluentAssertions; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; #if MSTEST using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using SetUpAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute; using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #else using NUnit.Framework; #endif namespace Velox.DB.Test { [TestFixture] public class WithEmptyDB { private MyContext DB = MyContext.Instance; [SetUp] public void SetupTest() { DB.PurgeAll(); } public WithEmptyDB() { DB.CreateAllTables(); } [Test] public void Events_ObjectCreated() { int counter = 0; DB.Customers.Events.ObjectCreated += (sender, args) => { counter++; }; DB.Customers.Events.ObjectCreated += (sender, args) => { counter++; }; DB.Save(new Customer() {Name = "A"}); DB.Save(new Customer() {Name = "A"}); counter.Should().Be(4); } [Test] public void Events_ObjectCreating() { int counter = 0; EventHandler<Vx.ObjectWithCancelEventArgs<Customer>> ev1 = (sender, args) => { counter++; }; EventHandler<Vx.ObjectWithCancelEventArgs<Customer>> ev2 = (sender, args) => { counter++; }; DB.Customers.Events.ObjectCreating += ev1; DB.Customers.Events.ObjectCreating += ev2; try { bool saveResult = DB.Save(new Customer() {Name = "A"}); DB.Customers.FirstOrDefault(c => c.Name == "A").Should().NotBeNull(); saveResult.Should().Be(true); counter.Should().Be(2); } finally { DB.Customers.Events.ObjectCreating -= ev1; DB.Customers.Events.ObjectCreating -= ev2; } } [Test] public void Events_ObjectCreatingWithCancel1() { int counter = 0; EventHandler<Vx.ObjectWithCancelEventArgs<Customer>> ev = (sender, args) => { counter++; }; EventHandler<Vx.ObjectWithCancelEventArgs<Customer>> evWithCancel = (sender, args) => { counter++; args.Cancel = true; }; DB.Customers.Events.ObjectCreating += ev; DB.Customers.Events.ObjectCreating += evWithCancel; try { bool saveResult = DB.Save(new Customer() { Name = "A" }); DB.Customers.FirstOrDefault(c => c.Name == "A").Should().BeNull(); saveResult.Should().Be(false); counter.Should().Be(2); } finally { DB.Customers.Events.ObjectCreating -= ev; DB.Customers.Events.ObjectCreating -= evWithCancel; } } [Test] public void Events_ObjectCreatingWithCancel2() { int counter = 0; EventHandler<Vx.ObjectWithCancelEventArgs<Customer>> ev = (sender, args) => { counter++; }; EventHandler<Vx.ObjectWithCancelEventArgs<Customer>> evWithCancel = (sender, args) => { counter++; args.Cancel = true; }; DB.Customers.Events.ObjectCreating += evWithCancel; DB.Customers.Events.ObjectCreating += ev; try { bool saveResult = DB.Save(new Customer() { Name = "A" }); DB.Customers.FirstOrDefault(c => c.Name == "A").Should().BeNull(); saveResult.Should().Be(false); counter.Should().Be(1); } finally { DB.Customers.Events.ObjectCreating -= ev; DB.Customers.Events.ObjectCreating -= evWithCancel; } } [Test] public void ManyToOne() { Customer customer = new Customer { Name = "x" }; customer.Save(); SalesPerson salesPerson = new SalesPerson {Name = "Test"}; salesPerson.Save(); var order = new Order { SalesPersonID = null, CustomerID = customer.CustomerID }; DB.Orders.Insert(order); int id = order.OrderID; order = DB.Orders.Read(id, o => o.Customer); Assert.AreEqual(order.Customer.CustomerID, customer.CustomerID); order.SalesPersonID = salesPerson.ID; order.Save(); order = DB.Orders.Read(id, (o) => o.SalesPerson); Assert.AreEqual(salesPerson.ID, order.SalesPerson.ID); order.SalesPersonID = null; order.SalesPerson = null; order.Save(); order = DB.Orders.Read(id, o => o.SalesPerson); Assert.IsNull(order.SalesPerson); Assert.IsNull(order.SalesPersonID); } [Test] public void ReverseRelation_Generic() { Order order = new Order() { Customer = new Customer() {Name = "A"}, OrderItems = new List<OrderItem>() { new OrderItem() {Description = "X"}, new OrderItem() {Description = "X"}, new OrderItem() {Description = "X"}, new OrderItem() {Description = "X"}, new OrderItem() {Description = "X"}, } }; var originalOrder = order; DB.Orders.Insert(order, true); order = DB.Orders.Read(originalOrder.OrderID); Vx.LoadRelations(order, o => o.OrderItems); order.OrderItems.Should().HaveCount(5).And.OnlyContain(item => item.Order == order); } [Test] public void ReverseRelation_DataSet() { Customer customer = new Customer() {Name = "A"}; DB.Customers.Insert(customer); for (int i = 0; i < 5; i++) DB.Orders.Insert(new Order() { CustomerID = customer.CustomerID }); customer = DB.Customers.Read(customer.CustomerID); customer.Orders.Should().HaveCount(5).And.OnlyContain(order => order.Customer == customer); } [Test] public void ReverseRelation_OneToOne() { OneToOneRec1 rec1 = new OneToOneRec1(); OneToOneRec2 rec2 = new OneToOneRec2(); DB.Insert(rec1); DB.Insert(rec2); rec1.OneToOneRec2ID = rec2.OneToOneRec2ID; rec2.OneToOneRec1ID = rec1.OneToOneRec1ID; DB.Update(rec1); DB.Update(rec2); rec1 = DB.Read<OneToOneRec1>(rec1.OneToOneRec1ID, r=> r.Rec2 ); rec1.Rec2.Rec1.Should().Be(rec1); } [Test] public void OneToManyWithOptionalRelation() { Customer customer = new Customer { Name = "x" }; customer.Save(); SalesPerson salesPerson = new SalesPerson { Name = "Test" }; salesPerson.Save(); Order[] orders = new[] { new Order() { CustomerID = customer.CustomerID, OrderDate = DateTime.Today, SalesPersonID = null}, new Order() { CustomerID = customer.CustomerID, OrderDate = DateTime.Today, SalesPersonID = salesPerson.ID} }; foreach (var order in orders) { DB.Insert(order); } salesPerson = DB.SalesPeople.First(); salesPerson.Orders.Count().Should().Be(1); salesPerson.Orders.First().OrderID.Should().Be(orders[1].OrderID); } [Test] public void AsyncInsert() { const int numThreads = 100; List<string> failedList = new List<string>(); Task<bool>[] saveTasks = new Task<bool>[numThreads]; Customer[] customers = new Customer[numThreads]; List<Customer> createdCustomers = new List<Customer>(); HashSet<int> ids = new HashSet<int>(); for (int i = 0; i < numThreads; i++) { string name = "C" + (i + 1); Customer customer = new Customer { Name = name }; customers[i] = customer; saveTasks[i] = DB.Customers.Async().Insert(customer); saveTasks[i].ContinueWith(t => { if (customer.CustomerID == 0) lock (failedList) failedList.Add("CustomerID == 0"); lock (ids) { if (ids.Contains(customer.CustomerID)) failedList.Add("Dupicate CustomerID " + customer.CustomerID + " for " + customer.Name); ids.Add(customer.CustomerID); } lock (createdCustomers) createdCustomers.Add(customer); DB.Customers.Async().Read(customer.CustomerID).ContinueWith(tRead => { if (customer.Name != tRead.Result.Name) lock (failedList) failedList.Add(string.Format("Customer == ({0},{1})" + ", but should be ({2},{3})", tRead.Result.CustomerID, tRead.Result.Name, customer.CustomerID, customer.Name)); }); }); } Task.WaitAll(saveTasks); saveTasks.Should().NotContain(t => t.IsFaulted); createdCustomers.Count.Should().Be(numThreads); foreach (var fail in failedList) { Assert.Fail(fail); } } [Test] public void ParallelTest1() { const int numThreads = 100; Task[] tasks = new Task[numThreads]; List<string> failedList = new List<string>(); Customer[] customers = new Customer[numThreads]; List<Customer> createdCustomers = new List<Customer>(); HashSet<int> ids = new HashSet<int>(); for (int i = 0; i < numThreads; i++) { string name = "C" + (i + 1); tasks[i] = Task.Factory.StartNew(() => { Customer customer = new Customer { Name = name }; customer.Save(); if (customer.CustomerID == 0) lock (failedList) failedList.Add("CustomerID == 0"); lock (ids) { if (ids.Contains(customer.CustomerID)) failedList.Add("Dupicate CustomerID " + customer.CustomerID + " for " + customer.Name); ids.Add(customer.CustomerID); } lock (createdCustomers) createdCustomers.Add(customer); var newCustomer = Vx.DataSet<Customer>().Read(customer.CustomerID); if (customer.Name != newCustomer.Name) lock (failedList) failedList.Add(string.Format("Customer == ({0},{1})" + ", but should be ({2},{3})", newCustomer.CustomerID, newCustomer.Name, customer.CustomerID, customer.Name)); }); } foreach (var task in tasks) { task.Wait(); } foreach (var fail in failedList) { Assert.Fail(fail); } createdCustomers.Count.Should().Be(numThreads); } private void CreateRandomPricedProducts() { Random rnd = new Random(); var products = Enumerable.Range(1, 20).Select(i => new Product() { ProductID = "P" + i, Description = "Product " + i, Price = (decimal)(rnd.NextDouble() * 100), MinQty = 1 }); foreach (var product in products) DB.Products.Insert(product); } [Test] public void StartsWith() { var products = Enumerable.Range(1, 20).Select(i => new Product() { ProductID = "P" + i, Description = (char)('A'+(i%10)) + "-Product", Price = 0.0m, MinQty = 1 }); foreach (var product in products) DB.Products.Insert(product); var pr = (from p in DB.Products where p.Description.StartsWith("B") select p).ToArray(); pr.Count().Should().Be(2); pr.All(p => p.Description.StartsWith("B")).Should().BeTrue(); } [Test] public void EndsWith() { var products = Enumerable.Range(1, 20).Select(i => new Product() { ProductID = "P" + i, Description = "Product-"+(char)('A' + (i % 10)), Price = 0.0m, MinQty = 1 }); foreach (var product in products) DB.Products.Insert(product); var pr = (from p in DB.Products where p.Description.EndsWith("B") select p).ToArray(); pr.Count().Should().Be(2); pr.All(p => p.Description.EndsWith("B")).Should().BeTrue(); } [Test] public void SortNumeric_Linq() { CreateRandomPricedProducts(); var sortedProducts = from product in DB.Products orderby product.Price select product; sortedProducts.Should().BeInAscendingOrder(product => product.Price); sortedProducts = from product in DB.Products orderby product.Price descending select product; sortedProducts.Should().BeInDescendingOrder(product => product.Price); } [Test] public void CreateAndReadSingleObject() { Customer customer = new Customer { Name = "A" }; customer.Save(); Assert.IsTrue(customer.CustomerID > 0); customer = DB.Customers.Read(customer.CustomerID); Assert.AreEqual("A",customer.Name); } [Test] public void CreateAndUpdateSingleObject() { Customer customer = new Customer { Name = "A" }; customer.Save(); customer = DB.Customers.Read(customer.CustomerID); customer.Name = "B"; customer.Save(); customer = DB.Customers.Read(customer.CustomerID); Assert.AreEqual("B",customer.Name); } [Test] public void ReadNonexistantObject() { Customer customer = DB.Customers.Read(70000); Assert.IsNull(customer); } [Test] public void CreateWithRelation_ManyToOne_ByID() { Customer customer = new Customer { Name = "A" }; customer.Save(); var order = new Order { Remark = "test", CustomerID = customer.CustomerID }; Assert.IsTrue(order.Save()); Order order2 = DB.Orders.Read(order.OrderID, o => o.Customer); Vx.LoadRelations(() => order.Customer); order2.Customer.Name.Should().Be(order.Customer.Name); order2.Customer.CustomerID.Should().Be(order.Customer.CustomerID); order2.Customer.CustomerID.Should().Be(order.CustomerID); } [Test] public void CreateWithRelation_ManyToOne_ByRelationObject() { Customer customer = new Customer() { Name = "me" }; customer.Save(); var order = new Order { Remark = "test", Customer = customer }; Assert.IsTrue(order.Save()); Order order2 = DB.Orders.Read(order.OrderID, o => o.Customer); Vx.LoadRelations(() => order.Customer); Assert.AreEqual(order2.Customer.Name, order.Customer.Name); Assert.AreEqual(order2.Customer.CustomerID, order.Customer.CustomerID); Assert.AreEqual(order2.Customer.CustomerID, order.CustomerID); } [Test] public void CreateWithRelation_ManyToOne_ByRelationObject_New() { Customer customer = new Customer() { Name = "me" }; var order = new Order { Remark = "test", Customer = customer }; Assert.IsTrue(order.Save(true)); Order order2 = DB.Orders.Read(order.OrderID, o => o.Customer); Vx.LoadRelations(() => order.Customer); Assert.AreEqual(order2.Customer.Name, order.Customer.Name); Assert.AreEqual(order2.Customer.CustomerID, order.Customer.CustomerID); Assert.AreEqual(order2.Customer.CustomerID, order.CustomerID); } [Test] public void CreateOrderWithNewCustomer() { Customer customer = new Customer() {Name = "me"}; customer.Save(); var order = new Order { Remark = "test", CustomerID = customer.CustomerID }; Assert.IsTrue(order.Save()); Vx.LoadRelations(() => order.Customer); Order order2 = DB.Orders.Read(order.OrderID , o => o.Customer); Assert.AreEqual(order2.Customer.Name, order.Customer.Name); Assert.AreEqual(order2.Customer.CustomerID, order.Customer.CustomerID); Assert.AreEqual(order2.Customer.CustomerID, order.CustomerID); Vx.LoadRelations(() => order2.Customer.Orders); Assert.AreEqual(order2.Customer.Orders.First().CustomerID, order.CustomerID); } [Test] public void CreateOrderWithExistingCustomer() { Customer cust = new Customer { Name = "A" }; cust.Save(); cust = DB.Customers.Read(cust.CustomerID); Order order = new Order(); order.CustomerID = cust.CustomerID; Assert.IsTrue(order.Save()); order = DB.Orders.Read(order.OrderID); Vx.LoadRelations(() => order.Customer); Vx.LoadRelations(() => order.Customer.Orders); Assert.AreEqual(order.Customer.Name, cust.Name); Assert.AreEqual(order.Customer.CustomerID, cust.CustomerID); Assert.AreEqual(order.CustomerID, cust.CustomerID); Assert.AreEqual((order.Customer.Orders.First()).CustomerID, cust.CustomerID); order.Customer.Name = "B"; order.Customer.Save(); order = DB.Orders.Read(order.OrderID); Vx.LoadRelations(() => order.Customer); Assert.AreEqual(order.CustomerID, cust.CustomerID); Assert.AreEqual("B", order.Customer.Name); } [Test] public void DeleteSingleObject() { List<Customer> customers = new List<Customer>(); for (int i = 0; i < 10; i++) { Customer customer = new Customer() {Name = "Customer " + (i + 1)}; customer.Save(); customers.Add(customer); } DB.Customers.Delete(customers[5]); Assert.IsNull(DB.Customers.Read(customers[5].CustomerID)); Assert.AreEqual(9,DB.Customers.Count()); } [Test] public void DeleteMultipleObjects() { List<Customer> customers = new List<Customer>(); for (int i = 0; i < 10; i++) { Customer customer = new Customer() { Name = "Customer " + (i + 1) }; customer.Save(); customers.Add(customer); } DB.Customers.Delete(c => c.Name == "Customer 2" || c.Name == "Customer 4"); Assert.IsNotNull(DB.Customers.Read(customers[0].CustomerID)); Assert.IsNull(DB.Customers.Read(customers[1].CustomerID)); Assert.IsNotNull(DB.Customers.Read(customers[2].CustomerID)); Assert.IsNull(DB.Customers.Read(customers[3].CustomerID)); Assert.AreEqual(8, DB.Customers.Count()); } [Test] public void CreateOrderWithNewItems() { Order order = new Order { Customer = new Customer { Name = "test" }, OrderItems = new List<OrderItem> { new OrderItem {Description = "test", Qty = 5, Price = 200.0}, new OrderItem {Description = "test", Qty = 3, Price = 45.0} } }; Assert.IsTrue(order.Save(true)); order = DB.Orders.Read(order.OrderID, o => o.OrderItems); //double totalPrice = Convert.ToDouble(order.OrderItems.GetScalar("Qty * Price", CSAggregate.Sum)); Assert.AreEqual(2, order.OrderItems.Count, "Order items not added"); //Assert.AreEqual(1135.0, totalPrice, "Incorrect total amount"); order.OrderItems.Add(new OrderItem { Description = "test", Qty = 2, Price = 1000.0 }); Assert.IsTrue(order.Save(true)); order = DB.Orders.Read(order.OrderID, o => o.OrderItems); //totalPrice = Convert.ToDouble(order.OrderItems.GetScalar("Qty * Price", CSAggregate.Sum)); Assert.AreEqual(3, order.OrderItems.Count, "Order item not added"); //Assert.AreEqual(3135.0, totalPrice, "Total price incorrect"); /* order.OrderItems.DeleteAll(); order = Order.Read(order.OrderID); Assert.AreEqual(0, order.OrderItems.Count, "Order items not deleted"); Assert.IsTrue(order.Delete()); */ } [Test] public void RandomCreation() { Random rnd = new Random(); Customer cust = new Customer(); cust.Name = "A"; cust.Save(); double total = 0.0; for (int i = 0; i < 5; i++) { Order order = new Order { Customer = cust }; order.Save(); for (int j = 0; j < 20; j++) { int qty = rnd.Next(1, 10); double price = rnd.NextDouble() * 500.0; OrderItem item = new OrderItem() { Description = "test", Qty = (short)qty, Price = price, OrderID = order.OrderID }; item.Save(); total += qty * price; } } var orders = DB.Orders.ToArray(); Assert.AreEqual(5, orders.Length); double total2 = DB.OrderItems.Sum(item => item.Qty*item.Price); Assert.AreEqual(total, total2, 0.000001); foreach (Order order in orders) { Vx.LoadRelations(order, o => o.Customer, o => o.OrderItems); Assert.AreEqual(cust.CustomerID, order.Customer.CustomerID); Assert.AreEqual(20, order.OrderItems.Count); Assert.AreEqual(cust.Name, order.Customer.Name); DB.OrderItems.Delete(order.OrderItems.First()); } total2 = DB.OrderItems.Sum(item => item.Qty * item.Price); total.Should().BeGreaterThan(total2); Assert.AreEqual(95, DB.OrderItems.Count()); } [Test] public void CompositeKeyCreateAndRead() { DB.Insert(new RecordWithCompositeKey { Key1 = 1, Key2 = 2, Name = "John" }); var rec = DB.Read<RecordWithCompositeKey>(new {Key1 = 1, Key2 = 2}); rec.Should().NotBeNull(); rec.Key1.Should().Be(1); rec.Key2.Should().Be(2); rec.Name.Should().Be("John"); } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // 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 Jaroslaw Kowalski 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. // #define DEBUG #if !__IOS__ && !__ANDROID__ namespace NLog.UnitTests.Common { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using NLog.Common; using Xunit; using Xunit.Extensions; public class InternalLoggerTests_Trace : NLogTestBase { [Theory] [InlineData(null, null)] [InlineData(false, null)] [InlineData(null, false)] [InlineData(false, false)] public void ShouldNotLogInternalWhenLogToTraceIsDisabled(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Trace, internalLogToTrace, logToTrace); InternalLogger.Trace("Logger1 Hello"); Assert.Equal(0, mockTraceListener.Messages.Count); } [Theory] [InlineData(null, null)] [InlineData(false, null)] [InlineData(null, false)] [InlineData(false, false)] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldNotLogInternalWhenLogLevelIsOff(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Off, internalLogToTrace, logToTrace); InternalLogger.Trace("Logger1 Hello"); Assert.Equal(0, mockTraceListener.Messages.Count); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void VerifyInternalLoggerLevelFilter(bool? internalLogToTrace, bool? logToTrace) { foreach (LogLevel logLevelConfig in LogLevel.AllLevels) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(logLevelConfig, internalLogToTrace, logToTrace); List<string> expected = new List<string>(); string input = "Logger1 Hello"; expected.Add(input); InternalLogger.Trace(input); InternalLogger.Debug(input); InternalLogger.Info(input); InternalLogger.Warn(input); InternalLogger.Error(input); InternalLogger.Fatal(input); input += "No.{0}"; expected.Add(string.Format(input, 1)); InternalLogger.Trace(input, 1); InternalLogger.Debug(input, 1); InternalLogger.Info(input, 1); InternalLogger.Warn(input, 1); InternalLogger.Error(input, 1); InternalLogger.Fatal(input, 1); input += ", We come in {1}"; expected.Add(string.Format(input, 1, "Peace")); InternalLogger.Trace(input, 1, "Peace"); InternalLogger.Debug(input, 1, "Peace"); InternalLogger.Info(input, 1, "Peace"); InternalLogger.Warn(input, 1, "Peace"); InternalLogger.Error(input, 1, "Peace"); InternalLogger.Fatal(input, 1, "Peace"); input += " and we are {2} to god"; expected.Add(string.Format(input, 1, "Peace", true)); InternalLogger.Trace(input, 1, "Peace", true); InternalLogger.Debug(input, 1, "Peace", true); InternalLogger.Info(input, 1, "Peace", true); InternalLogger.Warn(input, 1, "Peace", true); InternalLogger.Error(input, 1, "Peace", true); InternalLogger.Fatal(input, 1, "Peace", true); input += ", Please don't {3}"; expected.Add(string.Format(input, 1, "Peace", true, null)); InternalLogger.Trace(input, 1, "Peace", true, null); InternalLogger.Debug(input, 1, "Peace", true, null); InternalLogger.Info(input, 1, "Peace", true, null); InternalLogger.Warn(input, 1, "Peace", true, null); InternalLogger.Error(input, 1, "Peace", true, null); InternalLogger.Fatal(input, 1, "Peace", true, null); input += " the {4}"; expected.Add(string.Format(input, 1, "Peace", true, null, "Messenger")); InternalLogger.Trace(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Debug(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Info(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Warn(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Error(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Fatal(input, 1, "Peace", true, null, "Messenger"); Assert.Equal(expected.Count * (LogLevel.Fatal.Ordinal - logLevelConfig.Ordinal + 1), mockTraceListener.Messages.Count); for (int i = 0; i < expected.Count; ++i) { int msgCount = LogLevel.Fatal.Ordinal - logLevelConfig.Ordinal + 1; for (int j = 0; j < msgCount; ++j) { Assert.True(mockTraceListener.Messages.First().Contains(expected[i])); mockTraceListener.Messages.RemoveAt(0); } } Assert.Equal(0, mockTraceListener.Messages.Count); } } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsTrace(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Trace, internalLogToTrace, logToTrace); InternalLogger.Trace("Logger1 Hello"); Assert.Equal(1, mockTraceListener.Messages.Count); Assert.Equal("NLog: Trace Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsDebug(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Debug, internalLogToTrace, logToTrace); InternalLogger.Debug("Logger1 Hello"); Assert.Equal(1, mockTraceListener.Messages.Count); Assert.Equal("NLog: Debug Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsInfo(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Info, internalLogToTrace, logToTrace); InternalLogger.Info("Logger1 Hello"); Assert.Equal(1, mockTraceListener.Messages.Count); Assert.Equal("NLog: Info Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsWarn(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Warn, internalLogToTrace, logToTrace); InternalLogger.Warn("Logger1 Hello"); Assert.Equal(1, mockTraceListener.Messages.Count); Assert.Equal("NLog: Warn Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsError(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Error, internalLogToTrace, logToTrace); InternalLogger.Error("Logger1 Hello"); Assert.Equal(1, mockTraceListener.Messages.Count); Assert.Equal("NLog: Error Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsFatal(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Fatal, internalLogToTrace, logToTrace); InternalLogger.Fatal("Logger1 Hello"); Assert.Equal(1, mockTraceListener.Messages.Count); Assert.Equal("NLog: Fatal Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Fact(Skip = "This test's not working - explenation is in documentation: https://msdn.microsoft.com/pl-pl/library/system.stackoverflowexception(v=vs.110).aspx#Anchor_5. To clarify if StackOverflowException should be thrown.")] public void ShouldThrowStackOverFlowExceptionWhenUsingNLogTraceListener() { SetupTestConfiguration<NLogTraceListener>(LogLevel.Trace, true, null); Assert.Throws<StackOverflowException>(() => Trace.WriteLine("StackOverFlowException")); } /// <summary> /// Helper method to setup tests configuration /// </summary> /// <param name="logLevel">The <see cref="NLog.LogLevel"/> for the log event.</param> /// <param name="internalLogToTrace">internalLogToTrace XML attribute value. If <c>null</c> attribute is omitted.</param> /// <param name="logToTrace">Value of <see cref="InternalLogger.LogToTrace"/> property. If <c>null</c> property is not set.</param> /// <returns><see cref="TraceListener"/> instance.</returns> private T SetupTestConfiguration<T>(LogLevel logLevel, bool? internalLogToTrace, bool? logToTrace) where T : TraceListener { var internalLogToTraceAttribute = ""; if (internalLogToTrace.HasValue) { internalLogToTraceAttribute = string.Format(" internalLogToTrace='{0}'", internalLogToTrace.Value); } var xmlConfiguration = string.Format(XmlConfigurationFormat, logLevel, internalLogToTraceAttribute); LogManager.Configuration = CreateConfigurationFromString(xmlConfiguration); InternalLogger.IncludeTimestamp = false; if (logToTrace.HasValue) { InternalLogger.LogToTrace = logToTrace.Value; } T traceListener; if (typeof (T) == typeof (MockTraceListener)) { traceListener = CreateMockTraceListener() as T; } else { traceListener = CreateNLogTraceListener() as T; } Trace.Listeners.Clear(); if (traceListener == null) { return null; } Trace.Listeners.Add(traceListener); return traceListener; } private const string XmlConfigurationFormat = @"<nlog internalLogLevel='{0}'{1}> <targets> <target name='debug' type='Debug' layout='${{logger}} ${{level}} ${{message}}'/> </targets> <rules> <logger name='*' level='{0}' writeTo='debug'/> </rules> </nlog>"; /// <summary> /// Creates <see cref="MockTraceListener"/> instance. /// </summary> /// <returns><see cref="MockTraceListener"/> instance.</returns> private static MockTraceListener CreateMockTraceListener() { return new MockTraceListener(); } /// <summary> /// Creates <see cref="NLogTraceListener"/> instance. /// </summary> /// <returns><see cref="NLogTraceListener"/> instance.</returns> private static NLogTraceListener CreateNLogTraceListener() { return new NLogTraceListener {Name = "Logger1", ForceLogLevel = LogLevel.Trace}; } private class MockTraceListener : TraceListener { internal readonly List<string> Messages = new List<string>(); /// <summary> /// When overridden in a derived class, writes the specified message to the listener you create in the derived class. /// </summary> /// <param name="message">A message to write. </param> public override void Write(string message) { Messages.Add(message); } /// <summary> /// When overridden in a derived class, writes a message to the listener you create in the derived class, followed by a line terminator. /// </summary> /// <param name="message">A message to write. </param> public override void WriteLine(string message) { Messages.Add(message + Environment.NewLine); } } } } #endif
// 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.Reflection; using System.Text; using System.Collections; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System { [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { #region Private Constants private const char enumSeparatorChar = ','; private const String enumSeparatorString = ", "; #endregion #region Private Static Methods [System.Security.SecuritySafeCritical] // auto-generated private static TypeValuesAndNames GetCachedValuesAndNames(RuntimeType enumType, bool getNames) { TypeValuesAndNames entry = enumType.GenericCache as TypeValuesAndNames; if (entry == null || (getNames && entry.Names == null)) { ulong[] values = null; String[] names = null; bool isFlags = enumType.IsDefined(typeof(System.FlagsAttribute), false); GetEnumValuesAndNames( enumType.GetTypeHandleInternal(), JitHelpers.GetObjectHandleOnStack(ref values), JitHelpers.GetObjectHandleOnStack(ref names), getNames); entry = new TypeValuesAndNames(isFlags, values, names); enumType.GenericCache = entry; } return entry; } [System.Security.SecuritySafeCritical] private unsafe String InternalFormattedHexString() { fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: case CorElementType.U1: return (*(byte*)pValue).ToString("X2", null); case CorElementType.Boolean: // direct cast from bool to byte is not allowed return Convert.ToByte(*(bool*)pValue).ToString("X2", null); case CorElementType.I2: case CorElementType.U2: case CorElementType.Char: return (*(ushort*)pValue).ToString("X4", null); case CorElementType.I4: case CorElementType.U4: return (*(uint*)pValue).ToString("X8", null); case CorElementType.I8: case CorElementType.U8: return (*(ulong*)pValue).ToString("X16", null); default: Contract.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } } } private static String InternalFormattedHexString(object value) { TypeCode typeCode = Convert.GetTypeCode(value); switch (typeCode) { case TypeCode.SByte: return ((byte)(sbyte)value).ToString("X2", null); case TypeCode.Byte: return ((byte)value).ToString("X2", null); case TypeCode.Boolean: // direct cast from bool to byte is not allowed return Convert.ToByte((bool)value).ToString("X2", null); case TypeCode.Int16: return ((UInt16)(Int16)value).ToString("X4", null); case TypeCode.UInt16: return ((UInt16)value).ToString("X4", null); case TypeCode.Char: return ((UInt16)(Char)value).ToString("X4", null); case TypeCode.UInt32: return ((UInt32)value).ToString("X8", null); case TypeCode.Int32: return ((UInt32)(Int32)value).ToString("X8", null); case TypeCode.UInt64: return ((UInt64)value).ToString("X16", null); case TypeCode.Int64: return ((UInt64)(Int64)value).ToString("X16", null); // All unsigned types will be directly cast default: Contract.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } } internal static String GetEnumName(RuntimeType eT, ulong ulValue) { Contract.Requires(eT != null); ulong[] ulValues = Enum.InternalGetValues(eT); int index = Array.BinarySearch(ulValues, ulValue); if (index >= 0) { string[] names = Enum.InternalGetNames(eT); return names[index]; } return null; // return null so the caller knows to .ToString() the input } private static String InternalFormat(RuntimeType eT, ulong value) { Contract.Requires(eT != null); // These values are sorted by value. Don't change this TypeValuesAndNames entry = GetCachedValuesAndNames(eT, true); if (!entry.IsFlag) // Not marked with Flags attribute { return Enum.GetEnumName(eT, value); } else // These are flags OR'ed together (We treat everything as unsigned types) { return InternalFlagsFormat(eT, entry, value); } } private static String InternalFlagsFormat(RuntimeType eT,ulong result) { // These values are sorted by value. Don't change this TypeValuesAndNames entry = GetCachedValuesAndNames(eT, true); return InternalFlagsFormat(eT, entry, result); } private static String InternalFlagsFormat(RuntimeType eT, TypeValuesAndNames entry, ulong result) { Contract.Requires(eT != null); String[] names = entry.Names; ulong[] values = entry.Values; Contract.Assert(names.Length == values.Length); int index = values.Length - 1; StringBuilder retval = new StringBuilder(); bool firstTime = true; ulong saveResult = result; // We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied // to minimize the comparsions required. This code works the same for the best/worst case. In general the number of // items in an enum are sufficiently small and not worth the optimization. while (index >= 0) { if ((index == 0) && (values[index] == 0)) break; if ((result & values[index]) == values[index]) { result -= values[index]; if (!firstTime) retval.Insert(0, enumSeparatorString); retval.Insert(0, names[index]); firstTime = false; } index--; } // We were unable to represent this number as a bitwise or of valid flags if (result != 0) return null; // return null so the caller knows to .ToString() the input // For the case when we have zero if (saveResult == 0) { if (values.Length > 0 && values[0] == 0) return names[0]; // Zero was one of the enum values. else return "0"; } else { return retval.ToString(); // Return the string representation } } internal static ulong ToUInt64(Object value) { // Helper function to silently convert the value to UInt64 from the other base types for enum without throwing an exception. // This is need since the Convert functions do overflow checks. TypeCode typeCode = Convert.GetTypeCode(value); ulong result; switch (typeCode) { case TypeCode.SByte: result = (ulong)(sbyte)value; break; case TypeCode.Byte: result = (byte)value; break; case TypeCode.Boolean: // direct cast from bool to byte is not allowed result = Convert.ToByte((bool)value); break; case TypeCode.Int16: result = (ulong)(Int16)value; break; case TypeCode.UInt16: result = (UInt16)value; break; case TypeCode.Char: result = (UInt16)(Char)value; break; case TypeCode.UInt32: result = (UInt32)value; break; case TypeCode.Int32: result = (ulong)(int)value; break; case TypeCode.UInt64: result = (ulong)value; break; case TypeCode.Int64: result = (ulong)(Int64)value; break; // All unsigned types will be directly cast default: Contract.Assert(false, "Invalid Object type in ToUInt64"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } return result; } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int InternalCompareTo(Object o1, Object o2); [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern RuntimeType InternalGetUnderlyingType(RuntimeType enumType); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [System.Security.SuppressUnmanagedCodeSecurity] private static extern void GetEnumValuesAndNames(RuntimeTypeHandle enumType, ObjectHandleOnStack values, ObjectHandleOnStack names, bool getNames); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object InternalBoxEnum(RuntimeType enumType, long value); #endregion #region Public Static Methods private enum ParseFailureKind { None = 0, Argument = 1, ArgumentNull = 2, ArgumentWithParameter = 3, UnhandledException = 4 } // This will store the result of the parsing. private struct EnumResult { internal object parsedEnum; internal bool canThrow; internal ParseFailureKind m_failure; internal string m_failureMessageID; internal string m_failureParameter; internal object m_failureMessageFormatArgument; internal Exception m_innerException; internal void SetFailure(Exception unhandledException) { m_failure = ParseFailureKind.UnhandledException; m_innerException = unhandledException; } internal void SetFailure(ParseFailureKind failure, string failureParameter) { m_failure = failure; m_failureParameter = failureParameter; if (canThrow) throw GetEnumParseException(); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { m_failure = failure; m_failureMessageID = failureMessageID; m_failureMessageFormatArgument = failureMessageFormatArgument; if (canThrow) throw GetEnumParseException(); } internal Exception GetEnumParseException() { switch (m_failure) { case ParseFailureKind.Argument: return new ArgumentException(Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.ArgumentNull: return new ArgumentNullException(m_failureParameter); case ParseFailureKind.ArgumentWithParameter: return new ArgumentException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument)); case ParseFailureKind.UnhandledException: return m_innerException; default: Contract.Assert(false, "Unknown EnumParseFailure: " + m_failure); return new ArgumentException(Environment.GetResourceString("Arg_EnumValueNotFound")); } } } public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct { return TryParse(value, false, out result); } public static bool TryParse<TEnum>(String value, bool ignoreCase, out TEnum result) where TEnum : struct { result = default(TEnum); EnumResult parseResult = new EnumResult(); bool retValue; if (retValue = TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult)) result = (TEnum)parseResult.parsedEnum; return retValue; } [System.Runtime.InteropServices.ComVisible(true)] public static Object Parse(Type enumType, String value) { return Parse(enumType, value, false); } [System.Runtime.InteropServices.ComVisible(true)] public static Object Parse(Type enumType, String value, bool ignoreCase) { EnumResult parseResult = new EnumResult() { canThrow = true }; if (TryParseEnum(enumType, value, ignoreCase, ref parseResult)) return parseResult.parsedEnum; else throw parseResult.GetEnumParseException(); } private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, ref EnumResult parseResult) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); if (value == null) { parseResult.SetFailure(ParseFailureKind.ArgumentNull, "value"); return false; } int firstNonWhitespaceIndex = -1; for (int i = 0; i < value.Length; i++) { if (!Char.IsWhiteSpace(value[i])) { firstNonWhitespaceIndex = i; break; } } if (firstNonWhitespaceIndex == -1) { parseResult.SetFailure(ParseFailureKind.Argument, "Arg_MustContainEnumInfo", null); return false; } // We have 2 code paths here. One if they are values else if they are Strings. // values will have the first character as as number or a sign. ulong result = 0; char firstNonWhitespaceChar = value[firstNonWhitespaceIndex]; if (Char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '-' || firstNonWhitespaceChar == '+') { Type underlyingType = GetUnderlyingType(enumType); Object temp; try { value = value.Trim(); temp = Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture); parseResult.parsedEnum = ToObject(enumType, temp); return true; } catch (FormatException) { // We need to Parse this as a String instead. There are cases // when you tlbimp enums that can have values of the form "3D". // Don't fix this code. } catch (Exception ex) { if (parseResult.canThrow) throw; else { parseResult.SetFailure(ex); return false; } } } // Find the field. Let's assume that these are always static classes // because the class is an enum. TypeValuesAndNames entry = GetCachedValuesAndNames(rtType, true); String[] enumNames = entry.Names; ulong[] enumValues = entry.Values; StringComparison comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; int valueIndex = firstNonWhitespaceIndex; while (valueIndex <= value.Length) // '=' is to handle invalid case of an ending comma { // Find the next separator, if there is one, otherwise the end of the string. int endIndex = value.IndexOf(enumSeparatorChar, valueIndex); if (endIndex == -1) { endIndex = value.Length; } // Shift the starting and ending indices to eliminate whitespace int endIndexNoWhitespace = endIndex; while (valueIndex < endIndex && Char.IsWhiteSpace(value[valueIndex])) valueIndex++; while (endIndexNoWhitespace > valueIndex && Char.IsWhiteSpace(value[endIndexNoWhitespace - 1])) endIndexNoWhitespace--; int valueSubstringLength = endIndexNoWhitespace - valueIndex; // Try to match this substring against each enum name bool success = false; for (int i = 0; i < enumNames.Length; i++) { if (enumNames[i].Length == valueSubstringLength && string.Compare(enumNames[i], 0, value, valueIndex, valueSubstringLength, comparison) == 0) { result |= enumValues[i]; success = true; break; } } // If we couldn't find a match, throw an argument exception. if (!success) { // Not found, throw an argument exception. parseResult.SetFailure(ParseFailureKind.ArgumentWithParameter, "Arg_EnumValueNotFound", value); return false; } // Move our pointer to the ending index to go again. valueIndex = endIndex + 1; } try { parseResult.parsedEnum = ToObject(enumType, result); return true; } catch (Exception ex) { if (parseResult.canThrow) throw; else { parseResult.SetFailure(ex); return false; } } } [System.Runtime.InteropServices.ComVisible(true)] public static Type GetUnderlyingType(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.Ensures(Contract.Result<Type>() != null); Contract.EndContractBlock(); return enumType.GetEnumUnderlyingType(); } [System.Runtime.InteropServices.ComVisible(true)] public static Array GetValues(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.Ensures(Contract.Result<Array>() != null); Contract.EndContractBlock(); return enumType.GetEnumValues(); } internal static ulong[] InternalGetValues(RuntimeType enumType) { // Get all of the values return GetCachedValuesAndNames(enumType, false).Values; } [System.Runtime.InteropServices.ComVisible(true)] public static String GetName(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.EndContractBlock(); return enumType.GetEnumName(value); } [System.Runtime.InteropServices.ComVisible(true)] public static String[] GetNames(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return enumType.GetEnumNames(); } internal static String[] InternalGetNames(RuntimeType enumType) { // Get all of the names return GetCachedValuesAndNames(enumType, true).Names; } [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, Object value) { if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); // Delegate rest of error checking to the other functions TypeCode typeCode = Convert.GetTypeCode(value); switch (typeCode) { case TypeCode.Int32 : return ToObject(enumType, (int)value); case TypeCode.SByte : return ToObject(enumType, (sbyte)value); case TypeCode.Int16 : return ToObject(enumType, (short)value); case TypeCode.Int64 : return ToObject(enumType, (long)value); case TypeCode.UInt32 : return ToObject(enumType, (uint)value); case TypeCode.Byte : return ToObject(enumType, (byte)value); case TypeCode.UInt16 : return ToObject(enumType, (ushort)value); case TypeCode.UInt64 : return ToObject(enumType, (ulong)value); case TypeCode.Char: return ToObject(enumType, (char)value); case TypeCode.Boolean: return ToObject(enumType, (bool)value); default: // All unsigned types will be directly cast throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), "value"); } } [Pure] [System.Runtime.InteropServices.ComVisible(true)] public static bool IsDefined(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.EndContractBlock(); return enumType.IsEnumDefined(value); } [System.Runtime.InteropServices.ComVisible(true)] public static String Format(Type enumType, Object value, String format) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); if (value == null) throw new ArgumentNullException("value"); if (format == null) throw new ArgumentNullException("format"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); // Check if both of them are of the same type Type valueType = value.GetType(); Type underlyingType = GetUnderlyingType(enumType); // If the value is an Enum then we need to extract the underlying value from it if (valueType.IsEnum) { if (!valueType.IsEquivalentTo(enumType)) throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType", valueType.ToString(), enumType.ToString())); if (format.Length != 1) { // all acceptable format string are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } return ((Enum)value).ToString(format); } // The value must be of the same type as the Underlying type of the Enum else if (valueType != underlyingType) { throw new ArgumentException(Environment.GetResourceString("Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType", valueType.ToString(), underlyingType.ToString())); } if (format.Length != 1) { // all acceptable format string are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } char formatCh = format[0]; if (formatCh == 'G' || formatCh == 'g') return GetEnumName(rtType, ToUInt64(value)); if (formatCh == 'D' || formatCh == 'd') return value.ToString(); if (formatCh == 'X' || formatCh == 'x') return InternalFormattedHexString(value); if (formatCh == 'F' || formatCh == 'f') return Enum.InternalFlagsFormat(rtType, ToUInt64(value)) ?? value.ToString(); throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } #endregion #region Definitions private class TypeValuesAndNames { // Each entry contains a list of sorted pair of enum field names and values, sorted by values public TypeValuesAndNames(bool isFlag, ulong[] values, String[] names) { this.IsFlag = isFlag; this.Values = values; this.Names = names; } public bool IsFlag; public ulong[] Values; public String[] Names; } #endregion #region Private Methods [System.Security.SecuritySafeCritical] internal unsafe Object GetValue() { fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return *(sbyte*)pValue; case CorElementType.U1: return *(byte*)pValue; case CorElementType.Boolean: return *(bool*)pValue; case CorElementType.I2: return *(short*)pValue; case CorElementType.U2: return *(ushort*)pValue; case CorElementType.Char: return *(char*)pValue; case CorElementType.I4: return *(int*)pValue; case CorElementType.U4: return *(uint*)pValue; case CorElementType.R4: return *(float*)pValue; case CorElementType.I8: return *(long*)pValue; case CorElementType.U8: return *(ulong*)pValue; case CorElementType.R8: return *(double*)pValue; case CorElementType.I: return *(IntPtr*)pValue; case CorElementType.U: return *(UIntPtr*)pValue; default: Contract.Assert(false, "Invalid primitive type"); return null; } } } [System.Security.SecuritySafeCritical] private unsafe ulong ToUInt64() { fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return (ulong)*(sbyte*)pValue; case CorElementType.U1: return *(byte*)pValue; case CorElementType.Boolean: return Convert.ToUInt64(*(bool*)pValue, CultureInfo.InvariantCulture); case CorElementType.I2: return (ulong)*(short*)pValue; case CorElementType.U2: case CorElementType.Char: return *(ushort*)pValue; case CorElementType.I4: return (ulong)*(int*)pValue; case CorElementType.U4: case CorElementType.R4: return *(uint*)pValue; case CorElementType.I8: return (ulong)*(long*)pValue; case CorElementType.U8: case CorElementType.R8: return *(ulong*)pValue; case CorElementType.I: if (IntPtr.Size == 8) { return *(ulong*)pValue; } else { return (ulong)*(int*)pValue; } case CorElementType.U: if (IntPtr.Size == 8) { return *(ulong*)pValue; } else { return *(uint*)pValue; } default: Contract.Assert(false, "Invalid primitive type"); return 0; } } } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool InternalHasFlag(Enum flags); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern CorElementType InternalGetCorElementType(); #endregion #region Object Overrides [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern override bool Equals(Object obj); [System.Security.SecuritySafeCritical] public override unsafe int GetHashCode() { // Avoid boxing by inlining GetValue() // return GetValue().GetHashCode(); fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return (*(sbyte*)pValue).GetHashCode(); case CorElementType.U1: return (*(byte*)pValue).GetHashCode(); case CorElementType.Boolean: return (*(bool*)pValue).GetHashCode(); case CorElementType.I2: return (*(short*)pValue).GetHashCode(); case CorElementType.U2: return (*(ushort*)pValue).GetHashCode(); case CorElementType.Char: return (*(char*)pValue).GetHashCode(); case CorElementType.I4: return (*(int*)pValue).GetHashCode(); case CorElementType.U4: return (*(uint*)pValue).GetHashCode(); case CorElementType.R4: return (*(float*)pValue).GetHashCode(); case CorElementType.I8: return (*(long*)pValue).GetHashCode(); case CorElementType.U8: return (*(ulong*)pValue).GetHashCode(); case CorElementType.R8: return (*(double*)pValue).GetHashCode(); case CorElementType.I: return (*(IntPtr*)pValue).GetHashCode(); case CorElementType.U: return (*(UIntPtr*)pValue).GetHashCode(); default: Contract.Assert(false, "Invalid primitive type"); return 0; } } } public override String ToString() { // Returns the value in a human readable format. For PASCAL style enums who's value maps directly the name of the field is returned. // For PASCAL style enums who's values do not map directly the decimal value of the field is returned. // For BitFlags (indicated by the Flags custom attribute): If for each bit that is set in the value there is a corresponding constant //(a pure power of 2), then the OR string (ie "Red | Yellow") is returned. Otherwise, if the value is zero or if you can't create a string that consists of // pure powers of 2 OR-ed together, you return a hex value // Try to see if its one of the enum values, then we return a String back else the value return Enum.InternalFormat((RuntimeType)GetType(), ToUInt64()) ?? GetValue().ToString(); } #endregion #region IFormattable [Obsolete("The provider argument is not used. Please use ToString(String).")] public String ToString(String format, IFormatProvider provider) { return ToString(format); } #endregion #region IComparable [System.Security.SecuritySafeCritical] // auto-generated public int CompareTo(Object target) { const int retIncompatibleMethodTables = 2; // indicates that the method tables did not match const int retInvalidEnumType = 3; // indicates that the enum was of an unknown/unsupported unerlying type if (this == null) throw new NullReferenceException(); Contract.EndContractBlock(); int ret = InternalCompareTo(this, target); if (ret < retIncompatibleMethodTables) { // -1, 0 and 1 are the normal return codes return ret; } else if (ret == retIncompatibleMethodTables) { Type thisType = this.GetType(); Type targetType = target.GetType(); throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType", targetType.ToString(), thisType.ToString())); } else { // assert valid return code (3) Contract.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } } #endregion #region Public Methods public String ToString(String format) { char formatCh; if (format == null || format.Length == 0) formatCh = 'G'; else if (format.Length != 1) throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); else formatCh = format[0]; if (formatCh == 'G' || formatCh == 'g') return ToString(); if (formatCh == 'D' || formatCh == 'd') return GetValue().ToString(); if (formatCh == 'X' || formatCh == 'x') return InternalFormattedHexString(); if (formatCh == 'F' || formatCh == 'f') return InternalFlagsFormat((RuntimeType)GetType(), ToUInt64()) ?? GetValue().ToString(); throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } [Obsolete("The provider argument is not used. Please use ToString().")] public String ToString(IFormatProvider provider) { return ToString(); } [System.Security.SecuritySafeCritical] public Boolean HasFlag(Enum flag) { if (flag == null) throw new ArgumentNullException("flag"); Contract.EndContractBlock(); if (!this.GetType().IsEquivalentTo(flag.GetType())) { throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType())); } return InternalHasFlag(flag); } #endregion #region IConvertable public TypeCode GetTypeCode() { Type enumType = this.GetType(); Type underlyingType = GetUnderlyingType(enumType); if (underlyingType == typeof(Int32)) { return TypeCode.Int32; } if (underlyingType == typeof(sbyte)) { return TypeCode.SByte; } if (underlyingType == typeof(Int16)) { return TypeCode.Int16; } if (underlyingType == typeof(Int64)) { return TypeCode.Int64; } if (underlyingType == typeof(UInt32)) { return TypeCode.UInt32; } if (underlyingType == typeof(byte)) { return TypeCode.Byte; } if (underlyingType == typeof(UInt16)) { return TypeCode.UInt16; } if (underlyingType == typeof(UInt64)) { return TypeCode.UInt64; } if (underlyingType == typeof(Boolean)) { return TypeCode.Boolean; } if (underlyingType == typeof(Char)) { return TypeCode.Char; } Contract.Assert(false, "Unknown underlying type."); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Enum", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } #endregion #region ToObject [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, sbyte value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, short value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, int value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, byte value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, ushort value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, uint value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, long value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, ulong value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, unchecked((long)value)); } [System.Security.SecuritySafeCritical] // auto-generated private static Object ToObject(Type enumType, char value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated private static Object ToObject(Type enumType, bool value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value ? 1 : 0); } #endregion } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace DocuSign.eSign.Model { /// <summary> /// /// </summary> [DataContract] public class AuthenticationStatus : IEquatable<AuthenticationStatus> { /// <summary> /// Gets or Sets AccessCodeResult /// </summary> [DataMember(Name="accessCodeResult", EmitDefaultValue=false)] public EventResult AccessCodeResult { get; set; } /// <summary> /// Gets or Sets PhoneAuthResult /// </summary> [DataMember(Name="phoneAuthResult", EmitDefaultValue=false)] public EventResult PhoneAuthResult { get; set; } /// <summary> /// Gets or Sets IdLookupResult /// </summary> [DataMember(Name="idLookupResult", EmitDefaultValue=false)] public EventResult IdLookupResult { get; set; } /// <summary> /// Gets or Sets IdQuestionsResult /// </summary> [DataMember(Name="idQuestionsResult", EmitDefaultValue=false)] public EventResult IdQuestionsResult { get; set; } /// <summary> /// Gets or Sets AgeVerifyResult /// </summary> [DataMember(Name="ageVerifyResult", EmitDefaultValue=false)] public EventResult AgeVerifyResult { get; set; } /// <summary> /// Gets or Sets STANPinResult /// </summary> [DataMember(Name="sTANPinResult", EmitDefaultValue=false)] public EventResult STANPinResult { get; set; } /// <summary> /// Gets or Sets OfacResult /// </summary> [DataMember(Name="ofacResult", EmitDefaultValue=false)] public EventResult OfacResult { get; set; } /// <summary> /// Gets or Sets LiveIDResult /// </summary> [DataMember(Name="liveIDResult", EmitDefaultValue=false)] public EventResult LiveIDResult { get; set; } /// <summary> /// Gets or Sets FacebookResult /// </summary> [DataMember(Name="facebookResult", EmitDefaultValue=false)] public EventResult FacebookResult { get; set; } /// <summary> /// Gets or Sets GoogleResult /// </summary> [DataMember(Name="googleResult", EmitDefaultValue=false)] public EventResult GoogleResult { get; set; } /// <summary> /// Gets or Sets LinkedinResult /// </summary> [DataMember(Name="linkedinResult", EmitDefaultValue=false)] public EventResult LinkedinResult { get; set; } /// <summary> /// Gets or Sets SalesforceResult /// </summary> [DataMember(Name="salesforceResult", EmitDefaultValue=false)] public EventResult SalesforceResult { get; set; } /// <summary> /// Gets or Sets TwitterResult /// </summary> [DataMember(Name="twitterResult", EmitDefaultValue=false)] public EventResult TwitterResult { get; set; } /// <summary> /// Gets or Sets OpenIDResult /// </summary> [DataMember(Name="openIDResult", EmitDefaultValue=false)] public EventResult OpenIDResult { get; set; } /// <summary> /// Gets or Sets AnySocialIDResult /// </summary> [DataMember(Name="anySocialIDResult", EmitDefaultValue=false)] public EventResult AnySocialIDResult { get; set; } /// <summary> /// Gets or Sets YahooResult /// </summary> [DataMember(Name="yahooResult", EmitDefaultValue=false)] public EventResult YahooResult { get; set; } /// <summary> /// Gets or Sets SmsAuthResult /// </summary> [DataMember(Name="smsAuthResult", EmitDefaultValue=false)] public EventResult SmsAuthResult { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class AuthenticationStatus {\n"); sb.Append(" AccessCodeResult: ").Append(AccessCodeResult).Append("\n"); sb.Append(" PhoneAuthResult: ").Append(PhoneAuthResult).Append("\n"); sb.Append(" IdLookupResult: ").Append(IdLookupResult).Append("\n"); sb.Append(" IdQuestionsResult: ").Append(IdQuestionsResult).Append("\n"); sb.Append(" AgeVerifyResult: ").Append(AgeVerifyResult).Append("\n"); sb.Append(" STANPinResult: ").Append(STANPinResult).Append("\n"); sb.Append(" OfacResult: ").Append(OfacResult).Append("\n"); sb.Append(" LiveIDResult: ").Append(LiveIDResult).Append("\n"); sb.Append(" FacebookResult: ").Append(FacebookResult).Append("\n"); sb.Append(" GoogleResult: ").Append(GoogleResult).Append("\n"); sb.Append(" LinkedinResult: ").Append(LinkedinResult).Append("\n"); sb.Append(" SalesforceResult: ").Append(SalesforceResult).Append("\n"); sb.Append(" TwitterResult: ").Append(TwitterResult).Append("\n"); sb.Append(" OpenIDResult: ").Append(OpenIDResult).Append("\n"); sb.Append(" AnySocialIDResult: ").Append(AnySocialIDResult).Append("\n"); sb.Append(" YahooResult: ").Append(YahooResult).Append("\n"); sb.Append(" SmsAuthResult: ").Append(SmsAuthResult).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as AuthenticationStatus); } /// <summary> /// Returns true if AuthenticationStatus instances are equal /// </summary> /// <param name="other">Instance of AuthenticationStatus to be compared</param> /// <returns>Boolean</returns> public bool Equals(AuthenticationStatus other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AccessCodeResult == other.AccessCodeResult || this.AccessCodeResult != null && this.AccessCodeResult.Equals(other.AccessCodeResult) ) && ( this.PhoneAuthResult == other.PhoneAuthResult || this.PhoneAuthResult != null && this.PhoneAuthResult.Equals(other.PhoneAuthResult) ) && ( this.IdLookupResult == other.IdLookupResult || this.IdLookupResult != null && this.IdLookupResult.Equals(other.IdLookupResult) ) && ( this.IdQuestionsResult == other.IdQuestionsResult || this.IdQuestionsResult != null && this.IdQuestionsResult.Equals(other.IdQuestionsResult) ) && ( this.AgeVerifyResult == other.AgeVerifyResult || this.AgeVerifyResult != null && this.AgeVerifyResult.Equals(other.AgeVerifyResult) ) && ( this.STANPinResult == other.STANPinResult || this.STANPinResult != null && this.STANPinResult.Equals(other.STANPinResult) ) && ( this.OfacResult == other.OfacResult || this.OfacResult != null && this.OfacResult.Equals(other.OfacResult) ) && ( this.LiveIDResult == other.LiveIDResult || this.LiveIDResult != null && this.LiveIDResult.Equals(other.LiveIDResult) ) && ( this.FacebookResult == other.FacebookResult || this.FacebookResult != null && this.FacebookResult.Equals(other.FacebookResult) ) && ( this.GoogleResult == other.GoogleResult || this.GoogleResult != null && this.GoogleResult.Equals(other.GoogleResult) ) && ( this.LinkedinResult == other.LinkedinResult || this.LinkedinResult != null && this.LinkedinResult.Equals(other.LinkedinResult) ) && ( this.SalesforceResult == other.SalesforceResult || this.SalesforceResult != null && this.SalesforceResult.Equals(other.SalesforceResult) ) && ( this.TwitterResult == other.TwitterResult || this.TwitterResult != null && this.TwitterResult.Equals(other.TwitterResult) ) && ( this.OpenIDResult == other.OpenIDResult || this.OpenIDResult != null && this.OpenIDResult.Equals(other.OpenIDResult) ) && ( this.AnySocialIDResult == other.AnySocialIDResult || this.AnySocialIDResult != null && this.AnySocialIDResult.Equals(other.AnySocialIDResult) ) && ( this.YahooResult == other.YahooResult || this.YahooResult != null && this.YahooResult.Equals(other.YahooResult) ) && ( this.SmsAuthResult == other.SmsAuthResult || this.SmsAuthResult != null && this.SmsAuthResult.Equals(other.SmsAuthResult) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.AccessCodeResult != null) hash = hash * 57 + this.AccessCodeResult.GetHashCode(); if (this.PhoneAuthResult != null) hash = hash * 57 + this.PhoneAuthResult.GetHashCode(); if (this.IdLookupResult != null) hash = hash * 57 + this.IdLookupResult.GetHashCode(); if (this.IdQuestionsResult != null) hash = hash * 57 + this.IdQuestionsResult.GetHashCode(); if (this.AgeVerifyResult != null) hash = hash * 57 + this.AgeVerifyResult.GetHashCode(); if (this.STANPinResult != null) hash = hash * 57 + this.STANPinResult.GetHashCode(); if (this.OfacResult != null) hash = hash * 57 + this.OfacResult.GetHashCode(); if (this.LiveIDResult != null) hash = hash * 57 + this.LiveIDResult.GetHashCode(); if (this.FacebookResult != null) hash = hash * 57 + this.FacebookResult.GetHashCode(); if (this.GoogleResult != null) hash = hash * 57 + this.GoogleResult.GetHashCode(); if (this.LinkedinResult != null) hash = hash * 57 + this.LinkedinResult.GetHashCode(); if (this.SalesforceResult != null) hash = hash * 57 + this.SalesforceResult.GetHashCode(); if (this.TwitterResult != null) hash = hash * 57 + this.TwitterResult.GetHashCode(); if (this.OpenIDResult != null) hash = hash * 57 + this.OpenIDResult.GetHashCode(); if (this.AnySocialIDResult != null) hash = hash * 57 + this.AnySocialIDResult.GetHashCode(); if (this.YahooResult != null) hash = hash * 57 + this.YahooResult.GetHashCode(); if (this.SmsAuthResult != null) hash = hash * 57 + this.SmsAuthResult.GetHashCode(); return hash; } } } }
using System.Diagnostics; using u32 = System.UInt32; using Pgno = System.UInt32; namespace System.Data.SQLite { using sqlite3_pcache = Sqlite3.PCache1; internal partial class Sqlite3 { /* ** 2008 November 05 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file implements the default page cache implementation (the ** sqlite3_pcache interface). It also contains part of the implementation ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features. ** If the default page cache implementation is overriden, then neither of ** these two features are available. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" //typedef struct PCache1 PCache1; //typedef struct PgHdr1 PgHdr1; //typedef struct PgFreeslot PgFreeslot; //typedef struct PGroup PGroup; /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set ** of one or more PCaches that are able to recycle each others unpinned ** pages when they are under memory pressure. A PGroup is an instance of ** the following object. ** ** This page cache implementation works in one of two modes: ** ** (1) Every PCache is the sole member of its own PGroup. There is ** one PGroup per PCache. ** ** (2) There is a single global PGroup that all PCaches are a member ** of. ** ** Mode 1 uses more memory (since PCache instances are not able to rob ** unused pages from other PCaches) but it also operates without a mutex, ** and is therefore often faster. Mode 2 requires a mutex in order to be ** threadsafe, but is able recycle pages more efficient. ** ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single ** PGroup which is the pcache1.grp global variable and its mutex is ** SQLITE_MUTEX_STATIC_LRU. */ public class PGroup { public sqlite3_mutex mutex; /* MUTEX_STATIC_LRU or NULL */ public int nMaxPage; /* Sum of nMax for purgeable caches */ public int nMinPage; /* Sum of nMin for purgeable caches */ public int mxPinned; /* nMaxpage + 10 - nMinPage */ public int nCurrentPage; /* Number of purgeable pages allocated */ public PgHdr1 pLruHead, pLruTail; /* LRU list of unpinned pages */ // C# public PGroup() { mutex = new sqlite3_mutex(); } }; /* Each page cache is an instance of the following object. Every ** open database file (including each in-memory database and each ** temporary or transient database) has a single page cache which ** is an instance of this object. ** ** Pointers to structures of this type are cast and returned as ** opaque sqlite3_pcache* handles. */ public class PCache1 { /* Cache configuration parameters. Page size (szPage) and the purgeable ** flag (bPurgeable) are set when the cache is created. nMax may be ** modified at any time by a call to the pcache1CacheSize() method. ** The PGroup mutex must be held when accessing nMax. */ public PGroup pGroup; /* PGroup this cache belongs to */ public int szPage; /* Size of allocated pages in bytes */ public bool bPurgeable; /* True if cache is purgeable */ public int nMin; /* Minimum number of pages reserved */ public int nMax; /* Configured "cache_size" value */ public int n90pct; /* nMax*9/10 */ /* Hash table of all pages. The following variables may only be accessed ** when the accessor is holding the PGroup mutex. */ public int nRecyclable; /* Number of pages in the LRU list */ public int nPage; /* Total number of pages in apHash */ public int nHash; /* Number of slots in apHash[] */ public PgHdr1[] apHash; /* Hash table for fast lookup by key */ public Pgno iMaxKey; /* Largest key seen since xTruncate() */ public void Clear() { nRecyclable = 0; nPage = 0; nHash = 0; apHash = null; iMaxKey = 0; } }; /* ** Each cache entry is represented by an instance of the following ** structure. A buffer of PgHdr1.pCache.szPage bytes is allocated ** directly before this structure in memory (see the PGHDR1_TO_PAGE() ** macro below). */ public class PgHdr1 { public Pgno iKey; /* Key value (page number) */ public PgHdr1 pNext; /* Next in hash table chain */ public PCache1 pCache; /* Cache that currently owns this page */ public PgHdr1 pLruNext; /* Next in LRU list of unpinned pages */ public PgHdr1 pLruPrev; /* Previous in LRU list of unpinned pages */ // For C# public PgHdr pPgHdr = new PgHdr(); /* Pointer to Actual Page Header */ public void Clear() { this.iKey = 0; this.pNext = null; this.pCache = null; this.pPgHdr.Clear(); } }; /* ** Free slots in the allocator used to divide up the buffer provided using ** the SQLITE_CONFIG_PAGECACHE mechanism. */ public class PgFreeslot { public PgFreeslot pNext; /* Next free slot */ public PgHdr _PgHdr; /* Next Free Header */ }; /* ** Global data used by this cache. */ public class PCacheGlobal { public PGroup grp; /* The global PGroup for mode (2) */ /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all ** fixed at sqlite3_initialize() time and do not require mutex protection. ** The nFreeSlot and pFree values do require mutex protection. */ public bool isInit; /* True if initialized */ public int szSlot; /* Size of each free slot */ public int nSlot; /* The number of pcache slots */ public int nReserve; /* Try to keep nFreeSlot above this */ public object pStart, pEnd; /* Bounds of pagecache malloc range */ /* Above requires no mutex. Use mutex below for variable that follow. */ public sqlite3_mutex mutex; /* Mutex for accessing the following: */ public int nFreeSlot; /* Number of unused pcache slots */ public PgFreeslot pFree; /* Free page blocks */ /* The following value requires a mutex to change. We skip the mutex on ** reading because (1) most platforms read a 32-bit integer atomically and ** (2) even if an incorrect value is read, no great harm is done since this ** is really just an optimization. */ public bool bUnderPressure; /* True if low on PAGECACHE memory */ // C# public PCacheGlobal() { grp = new PGroup(); } } static PCacheGlobal pcache = new PCacheGlobal(); /* ** All code in this file should access the global structure above via the ** alias "pcache1". This ensures that the WSD emulation is used when ** compiling for systems that do not support real WSD. */ //#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g)) static PCacheGlobal pcache1 = pcache; /* ** When a PgHdr1 structure is allocated, the associated PCache1.szPage ** bytes of data are located directly before it in memory (i.e. the total ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as ** an argument and returns a pointer to the associated block of szPage ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is ** a pointer to a block of szPage bytes of data and the return value is ** a pointer to the associated PgHdr1 structure. ** ** Debug.Assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X ); */ //#define PGHDR1_TO_PAGE(p) (void)(((char)p) - p.pCache.szPage) static PgHdr PGHDR1_TO_PAGE(PgHdr1 p) { return p.pPgHdr; } //#define PAGE_TO_PGHDR1(c, p) (PgHdr1)(((char)p) + c.szPage) static PgHdr1 PAGE_TO_PGHDR1(PCache1 c, PgHdr p) { return p.pPgHdr1; } /* ** Macros to enter and leave the PCache LRU mutex. */ //#define pcache1EnterMutex(X) sqlite3_mutex_enter((X).mutex) static void pcache1EnterMutex(PGroup X) { sqlite3_mutex_enter(X.mutex); } //#define pcache1LeaveMutex(X) sqlite3_mutex_leave((X).mutex) static void pcache1LeaveMutex(PGroup X) { sqlite3_mutex_leave(X.mutex); } /******************************************************************************/ /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/ /* ** This function is called during initialization if a static buffer is ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE ** verb to sqlite3_config(). Parameter pBuf points to an allocation large ** enough to contain 'n' buffers of 'sz' bytes each. ** ** This routine is called from sqlite3_initialize() and so it is guaranteed ** to be serialized already. There is no need for further mutexing. */ static void sqlite3PCacheBufferSetup(object pBuf, int sz, int n) { if (pcache1.isInit) { PgFreeslot p; sz = ROUNDDOWN8(sz); pcache1.szSlot = sz; pcache1.nSlot = pcache1.nFreeSlot = n; pcache1.nReserve = n > 90 ? 10 : (n / 10 + 1); pcache1.pStart = null; pcache1.pEnd = null; pcache1.pFree = null; pcache1.bUnderPressure = false; while (n-- > 0) { p = new PgFreeslot();// (PgFreeslot)pBuf; p._PgHdr = new PgHdr(); p.pNext = pcache1.pFree; pcache1.pFree = p; //pBuf = (void)&((char)pBuf)[sz]; } pcache1.pEnd = pBuf; } } /* ** Malloc function used within this file to allocate space from the buffer ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no ** such buffer exists or there is no space left in it, this function falls ** back to sqlite3Malloc(). ** ** Multiple threads can run this routine at the same time. Global variables ** in pcache1 need to be protected via mutex. */ static PgHdr pcache1Alloc(int nByte) { PgHdr p = null; Debug.Assert(sqlite3_mutex_notheld(pcache1.grp.mutex)); sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte); if (nByte <= pcache1.szSlot) { sqlite3_mutex_enter(pcache1.mutex); p = pcache1.pFree._PgHdr; if (p != null) { pcache1.pFree = pcache1.pFree.pNext; pcache1.nFreeSlot--; pcache1.bUnderPressure = pcache1.nFreeSlot < pcache1.nReserve; Debug.Assert(pcache1.nFreeSlot >= 0); sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1); } sqlite3_mutex_leave(pcache1.mutex); } if (p == null) { /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get ** it from sqlite3Malloc instead. */ p = new PgHdr();// sqlite3Malloc( nByte ); //if ( p != null ) { int sz = nByte;//sqlite3MallocSize( p ); sqlite3_mutex_enter(pcache1.mutex); sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz); sqlite3_mutex_leave(pcache1.mutex); } sqlite3MemdebugSetType(p, MEMTYPE_PCACHE); } return p; } /* ** Free an allocated buffer obtained from pcache1Alloc(). */ static void pcache1Free(ref PgHdr p) { if (p == null) return; if (p.CacheAllocated)//if ( p >= pcache1.pStart && p < pcache1.pEnd ) { PgFreeslot pSlot = new PgFreeslot(); sqlite3_mutex_enter(pcache1.mutex); sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1); pSlot._PgHdr = p;// pSlot = (PgFreeslot)p; pSlot.pNext = pcache1.pFree; pcache1.pFree = pSlot; pcache1.nFreeSlot++; pcache1.bUnderPressure = pcache1.nFreeSlot < pcache1.nReserve; Debug.Assert(pcache1.nFreeSlot <= pcache1.nSlot); sqlite3_mutex_leave(pcache1.mutex); } else { int iSize; Debug.Assert(sqlite3MemdebugHasType(p, MEMTYPE_PCACHE)); sqlite3MemdebugSetType(p, MEMTYPE_HEAP); iSize = sqlite3MallocSize(p.pData); sqlite3_mutex_enter(pcache1.mutex); sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize); sqlite3_mutex_leave(pcache1.mutex); sqlite3_free(ref p.pData); } } #if SQLITE_ENABLE_MEMORY_MANAGEMENT /* ** Return the size of a pcache allocation */ static int pcache1MemSize(object p){ if( p>=pcache1.pStart && p<pcache1.pEnd ){ return pcache1.szSlot; }else{ int iSize; Debug.Assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) ); sqlite3MemdebugSetType(p, MEMTYPE_HEAP); iSize = sqlite3MallocSize(p); sqlite3MemdebugSetType(p, MEMTYPE_PCACHE); return iSize; } } #endif //* SQLITE_ENABLE_MEMORY_MANAGEMENT */ /* ** Allocate a new page object initially associated with cache pCache. */ static PgHdr1 pcache1AllocPage(PCache1 pCache) { //int nByte = sizeof( PgHdr1 ) + pCache.szPage; PgHdr pPg = pcache1Alloc(pCache.szPage);//nByte ); PgHdr1 p = null; //if ( pPg !=null) { //PAGE_TO_PGHDR1( pCache, pPg ); p = new PgHdr1(); p.pCache = pCache; p.pPgHdr = pPg; if (pCache.bPurgeable) { pCache.pGroup.nCurrentPage++; } } //else //{ // p = 0; //} return p; } /* ** Free a page object allocated by pcache1AllocPage(). ** ** The pointer is allowed to be NULL, which is prudent. But it turns out ** that the current implementation happens to never call this routine ** with a NULL pointer, so we mark the NULL test with ALWAYS(). */ static void pcache1FreePage(ref PgHdr1 p) { if (ALWAYS(p)) { PCache1 pCache = p.pCache; if (pCache.bPurgeable) { pCache.pGroup.nCurrentPage--; } pcache1Free(ref p.pPgHdr);//PGHDR1_TO_PAGE( p ); } } /* ** Malloc function used by SQLite to obtain space from the buffer configured ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer ** exists, this function falls back to sqlite3Malloc(). */ static PgHdr sqlite3PageMalloc(int sz) { return pcache1Alloc(sz); } /* ** Free an allocated buffer obtained from sqlite3PageMalloc(). */ static void sqlite3PageFree(ref byte[] p) { if (p != null) { sqlite3_free(ref p); p = null; } } static void sqlite3PageFree(ref PgHdr p) { pcache1Free(ref p); } /* ** Return true if it desirable to avoid allocating a new page cache ** entry. ** ** If memory was allocated specifically to the page cache using ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then ** it is desirable to avoid allocating a new page cache entry because ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient ** for all page cache needs and we should not need to spill the ** allocation onto the heap. ** ** Or, the heap is used for all page cache memory put the heap is ** under memory pressure, then again it is desirable to avoid ** allocating a new page cache entry in order to avoid stressing ** the heap even further. */ static bool pcache1UnderMemoryPressure(PCache1 pCache) { if (pcache1.nSlot != 0 && pCache.szPage <= pcache1.szSlot) { return pcache1.bUnderPressure; } else { return sqlite3HeapNearlyFull(); } } /******************************************************************************/ /******** General Implementation Functions ************************************/ /* ** This function is used to resize the hash table used by the cache passed ** as the first argument. ** ** The PCache mutex must be held when this function is called. */ static int pcache1ResizeHash(PCache1 p) { PgHdr1[] apNew; int nNew; int i; Debug.Assert(sqlite3_mutex_held(p.pGroup.mutex)); nNew = p.nHash * 2; if (nNew < 256) { nNew = 256; } pcache1LeaveMutex(p.pGroup); if (p.nHash != 0) { sqlite3BeginBenignMalloc(); } apNew = new PgHdr1[nNew];//(PgHdr1 *)sqlite3_malloc(sizeof(PgHdr1 )*nNew); if (p.nHash != 0) { sqlite3EndBenignMalloc(); } pcache1EnterMutex(p.pGroup); if (apNew != null) { //memset(apNew, 0, sizeof(PgHdr1 )*nNew); for (i = 0; i < p.nHash; i++) { PgHdr1 pPage; PgHdr1 pNext = p.apHash[i]; while ((pPage = pNext) != null) { Pgno h = (Pgno)(pPage.iKey % nNew); pNext = pPage.pNext; pPage.pNext = apNew[h]; apNew[h] = pPage; } } //sqlite3_free( p.apHash ); p.apHash = apNew; p.nHash = nNew; } return (p.apHash != null ? SQLITE_OK : SQLITE_NOMEM); } /* ** This function is used internally to remove the page pPage from the ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup ** LRU list, then this function is a no-op. ** ** The PGroup mutex must be held when this function is called. ** ** If pPage is NULL then this routine is a no-op. */ static void pcache1PinPage(PgHdr1 pPage) { PCache1 pCache; PGroup pGroup; if (pPage == null) return; pCache = pPage.pCache; pGroup = pCache.pGroup; Debug.Assert(sqlite3_mutex_held(pGroup.mutex)); if (pPage.pLruNext != null || pPage == pGroup.pLruTail) { if (pPage.pLruPrev != null) { pPage.pLruPrev.pLruNext = pPage.pLruNext; } if (pPage.pLruNext != null) { pPage.pLruNext.pLruPrev = pPage.pLruPrev; } if (pGroup.pLruHead == pPage) { pGroup.pLruHead = pPage.pLruNext; } if (pGroup.pLruTail == pPage) { pGroup.pLruTail = pPage.pLruPrev; } pPage.pLruNext = null; pPage.pLruPrev = null; pPage.pCache.nRecyclable--; } } /* ** Remove the page supplied as an argument from the hash table ** (PCache1.apHash structure) that it is currently stored in. ** ** The PGroup mutex must be held when this function is called. */ static void pcache1RemoveFromHash(PgHdr1 pPage) { int h; PCache1 pCache = pPage.pCache; PgHdr1 pp; PgHdr1 pPrev = null; Debug.Assert(sqlite3_mutex_held(pCache.pGroup.mutex)); h = (int)(pPage.iKey % pCache.nHash); for (pp = pCache.apHash[h]; pp != pPage; pPrev = pp, pp = pp.pNext) ; if (pPrev == null) pCache.apHash[h] = pp.pNext; else pPrev.pNext = pp.pNext; // pCache.apHash[h] = pp.pNext; pCache.nPage--; } /* ** If there are currently more than nMaxPage pages allocated, try ** to recycle pages to reduce the number allocated to nMaxPage. */ static void pcache1EnforceMaxPage(PGroup pGroup) { Debug.Assert(sqlite3_mutex_held(pGroup.mutex)); while (pGroup.nCurrentPage > pGroup.nMaxPage && pGroup.pLruTail != null) { PgHdr1 p = pGroup.pLruTail; Debug.Assert(p.pCache.pGroup == pGroup); pcache1PinPage(p); pcache1RemoveFromHash(p); pcache1FreePage(ref p); } } /* ** Discard all pages from cache pCache with a page number (key value) ** greater than or equal to iLimit. Any pinned pages that meet this ** criteria are unpinned before they are discarded. ** ** The PCache mutex must be held when this function is called. */ static void pcache1TruncateUnsafe( PCache1 pCache, /* The cache to truncate */ uint iLimit /* Drop pages with this pgno or larger */ ) { #if !NDEBUG || SQLITE_COVERAGE_TEST //TESTONLY( uint nPage = 0; ) /* To assert pCache.nPage is correct */ uint nPage = 0; #endif uint h; Debug.Assert(sqlite3_mutex_held(pCache.pGroup.mutex)); for (h = 0; h < pCache.nHash; h++) { PgHdr1 pPrev = null; PgHdr1 pp = pCache.apHash[h]; PgHdr1 pPage; while ((pPage = pp) != null) { if (pPage.iKey >= iLimit) { pCache.nPage--; pp = pPage.pNext; pcache1PinPage(pPage); if (pCache.apHash[h] == pPage) pCache.apHash[h] = pPage.pNext; else pPrev.pNext = pp; pcache1FreePage(ref pPage); } else { pp = pPage.pNext; #if !NDEBUG || SQLITE_COVERAGE_TEST //TESTONLY( nPage++; ) nPage++; #endif } pPrev = pPage; } } #if !NDEBUG || SQLITE_COVERAGE_TEST Debug.Assert( pCache.nPage == nPage ); #endif } /******************************************************************************/ /******** sqlite3_pcache Methods **********************************************/ /* ** Implementation of the sqlite3_pcache.xInit method. */ static int pcache1Init<T>(T NotUsed) { UNUSED_PARAMETER(NotUsed); Debug.Assert(pcache1.isInit == false); pcache1 = new PCacheGlobal();//memset(&pcache1, 0, sizeof(pcache1)); if (sqlite3GlobalConfig.bCoreMutex) { pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU); pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM); } pcache1.grp.mxPinned = 10; pcache1.isInit = true; return SQLITE_OK; } /* ** Implementation of the sqlite3_pcache.xShutdown method. ** Note that the static mutex allocated in xInit does ** not need to be freed. */ static void pcache1Shutdown<T>(T NotUsed) { UNUSED_PARAMETER(NotUsed); Debug.Assert(pcache1.isInit); pcache1 = new PCacheGlobal();//;memset( &pcache1, 0, sizeof( pcache1 ) ); } /* ** Implementation of the sqlite3_pcache.xCreate method. ** ** Allocate a new cache. */ static sqlite3_pcache pcache1Create(int szPage, bool bPurgeable) { PCache1 pCache; /* The newly created page cache */ PGroup pGroup; /* The group the new page cache will belong to */ int sz; /* Bytes of memory required to allocate the new cache */ /* ** The seperateCache variable is true if each PCache has its own private ** PGroup. In other words, separateCache is true for mode (1) where no ** mutexing is required. ** ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT ** ** * Always use a unified cache in single-threaded applications ** ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off) ** use separate caches (mode-1) */ #if (SQLITE_ENABLE_MEMORY_MANAGEMENT) || !SQLITE_THREADSAF const int separateCache = 0; #else int separateCache = sqlite3GlobalConfig.bCoreMutex>0; #endif //sz = sizeof( PCache1 ) + sizeof( PGroup ) * separateCache; pCache = new PCache1();//(PCache1)sqlite3_malloc( sz ); //if ( pCache != null ) { //memset( pCache, 0, sz ); if (separateCache != 0) { //pGroup = new PGroup();//(PGroup)pCache[1]; //pGroup.mxPinned = 10; } else { pGroup = pcache1.grp; } pCache.pGroup = pGroup; pCache.szPage = szPage; pCache.bPurgeable = bPurgeable;//( bPurgeable ? 1 : 0 ); if (bPurgeable) { pCache.nMin = 10; pcache1EnterMutex(pGroup); pGroup.nMinPage += (int)pCache.nMin; pGroup.mxPinned = pGroup.nMaxPage + 10 - pGroup.nMinPage; pcache1LeaveMutex(pGroup); } } return (sqlite3_pcache)pCache; } /* ** Implementation of the sqlite3_pcache.xCachesize method. ** ** Configure the cache_size limit for a cache. */ static void pcache1Cachesize(sqlite3_pcache p, int nMax) { PCache1 pCache = (PCache1)p; if (pCache.bPurgeable) { PGroup pGroup = pCache.pGroup; pcache1EnterMutex(pGroup); pGroup.nMaxPage += nMax - pCache.nMax; pGroup.mxPinned = pGroup.nMaxPage + 10 - pGroup.nMinPage; pCache.nMax = nMax; pCache.n90pct = pCache.nMax * 9 / 10; pcache1EnforceMaxPage(pGroup); pcache1LeaveMutex(pGroup); } } /* ** Implementation of the sqlite3_pcache.xPagecount method. */ static int pcache1Pagecount(sqlite3_pcache p) { int n; PCache1 pCache = (PCache1)p; pcache1EnterMutex(pCache.pGroup); n = (int)pCache.nPage; pcache1LeaveMutex(pCache.pGroup); return n; } /* ** Implementation of the sqlite3_pcache.xFetch method. ** ** Fetch a page by key value. ** ** Whether or not a new page may be allocated by this function depends on ** the value of the createFlag argument. 0 means do not allocate a new ** page. 1 means allocate a new page if space is easily available. 2 ** means to try really hard to allocate a new page. ** ** For a non-purgeable cache (a cache used as the storage for an in-memory ** database) there is really no difference between createFlag 1 and 2. So ** the calling function (pcache.c) will never have a createFlag of 1 on ** a non-purgable cache. ** ** There are three different approaches to obtaining space for a page, ** depending on the value of parameter createFlag (which may be 0, 1 or 2). ** ** 1. Regardless of the value of createFlag, the cache is searched for a ** copy of the requested page. If one is found, it is returned. ** ** 2. If createFlag==0 and the page is not already in the cache, NULL is ** returned. ** ** 3. If createFlag is 1, and the page is not already in the cache, then ** return NULL (do not allocate a new page) if any of the following ** conditions are true: ** ** (a) the number of pages pinned by the cache is greater than ** PCache1.nMax, or ** ** (b) the number of pages pinned by the cache is greater than ** the sum of nMax for all purgeable caches, less the sum of ** nMin for all other purgeable caches, or ** ** 4. If none of the first three conditions apply and the cache is marked ** as purgeable, and if one of the following is true: ** ** (a) The number of pages allocated for the cache is already ** PCache1.nMax, or ** ** (b) The number of pages allocated for all purgeable caches is ** already equal to or greater than the sum of nMax for all ** purgeable caches, ** ** (c) The system is under memory pressure and wants to avoid ** unnecessary pages cache entry allocations ** ** then attempt to recycle a page from the LRU list. If it is the right ** size, return the recycled buffer. Otherwise, free the buffer and ** proceed to step 5. ** ** 5. Otherwise, allocate and return a new page buffer. */ static PgHdr pcache1Fetch(sqlite3_pcache p, Pgno iKey, int createFlag) { int nPinned; PCache1 pCache = (PCache1)p; PGroup pGroup; PgHdr1 pPage = null; Debug.Assert(pCache.bPurgeable || createFlag != 1); Debug.Assert(pCache.bPurgeable || pCache.nMin == 0); Debug.Assert(pCache.bPurgeable == false || pCache.nMin == 10); Debug.Assert(pCache.nMin == 0 || pCache.bPurgeable); pcache1EnterMutex(pGroup = pCache.pGroup); /* Step 1: Search the hash table for an existing entry. */ if (pCache.nHash > 0) { int h = (int)(iKey % pCache.nHash); for (pPage = pCache.apHash[h]; pPage != null && pPage.iKey != iKey; pPage = pPage.pNext) ; } /* Step 2: Abort if no existing page is found and createFlag is 0 */ if (pPage != null || createFlag == 0) { pcache1PinPage(pPage); goto fetch_out; } /* The pGroup local variable will normally be initialized by the ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined, ** then pcache1EnterMutex() is a no-op, so we have to initialize the ** local variable here. Delaying the initialization of pGroup is an ** optimization: The common case is to exit the module before reaching ** this point. */ #if SQLITE_MUTEX_OMIT pGroup = pCache.pGroup; #endif /* Step 3: Abort if createFlag is 1 but the cache is nearly full */ nPinned = pCache.nPage - pCache.nRecyclable; Debug.Assert(nPinned >= 0); Debug.Assert(pGroup.mxPinned == pGroup.nMaxPage + 10 - pGroup.nMinPage); Debug.Assert(pCache.n90pct == pCache.nMax * 9 / 10); if (createFlag == 1 && ( nPinned >= pGroup.mxPinned || nPinned >= (int)pCache.n90pct || pcache1UnderMemoryPressure(pCache) )) { goto fetch_out; } if (pCache.nPage >= pCache.nHash && pcache1ResizeHash(pCache) != 0) { goto fetch_out; } /* Step 4. Try to recycle a page. */ if (pCache.bPurgeable && pGroup.pLruTail != null && ( (pCache.nPage + 1 >= pCache.nMax) || pGroup.nCurrentPage >= pGroup.nMaxPage || pcache1UnderMemoryPressure(pCache) )) { PCache1 pOtherCache; pPage = pGroup.pLruTail; pcache1RemoveFromHash(pPage); pcache1PinPage(pPage); if ((pOtherCache = pPage.pCache).szPage != pCache.szPage) { pcache1FreePage(ref pPage); pPage = null; } else { pGroup.nCurrentPage -= (pOtherCache.bPurgeable ? 1 : 0) - (pCache.bPurgeable ? 1 : 0); } } /* Step 5. If a usable page buffer has still not been found, ** attempt to allocate a new one. */ if (null == pPage) { if (createFlag == 1) sqlite3BeginBenignMalloc(); pcache1LeaveMutex(pGroup); pPage = pcache1AllocPage(pCache); pcache1EnterMutex(pGroup); if (createFlag == 1) sqlite3EndBenignMalloc(); } if (pPage != null) { int h = (int)(iKey % pCache.nHash); pCache.nPage++; pPage.iKey = iKey; pPage.pNext = pCache.apHash[h]; pPage.pCache = pCache; pPage.pLruPrev = null; pPage.pLruNext = null; PGHDR1_TO_PAGE(pPage).Clear();// *(void **)(PGHDR1_TO_PAGE(pPage)) = 0; pPage.pPgHdr.pPgHdr1 = pPage; pCache.apHash[h] = pPage; } fetch_out: if (pPage != null && iKey > pCache.iMaxKey) { pCache.iMaxKey = iKey; } pcache1LeaveMutex(pGroup); return (pPage != null ? PGHDR1_TO_PAGE(pPage) : null); } /* ** Implementation of the sqlite3_pcache.xUnpin method. ** ** Mark a page as unpinned (eligible for asynchronous recycling). */ static void pcache1Unpin(sqlite3_pcache p, PgHdr pPg, bool reuseUnlikely) { PCache1 pCache = (PCache1)p; PgHdr1 pPage = PAGE_TO_PGHDR1(pCache, pPg); PGroup pGroup = pCache.pGroup; Debug.Assert(pPage.pCache == pCache); pcache1EnterMutex(pGroup); /* It is an error to call this function if the page is already ** part of the PGroup LRU list. */ Debug.Assert(pPage.pLruPrev == null && pPage.pLruNext == null); Debug.Assert(pGroup.pLruHead != pPage && pGroup.pLruTail != pPage); if (reuseUnlikely || pGroup.nCurrentPage > pGroup.nMaxPage) { pcache1RemoveFromHash(pPage); pcache1FreePage(ref pPage); } else { /* Add the page to the PGroup LRU list. */ if (pGroup.pLruHead != null) { pGroup.pLruHead.pLruPrev = pPage; pPage.pLruNext = pGroup.pLruHead; pGroup.pLruHead = pPage; } else { pGroup.pLruTail = pPage; pGroup.pLruHead = pPage; } pCache.nRecyclable++; } pcache1LeaveMutex(pCache.pGroup); } /* ** Implementation of the sqlite3_pcache.xRekey method. */ static void pcache1Rekey( sqlite3_pcache p, PgHdr pPg, Pgno iOld, Pgno iNew ) { PCache1 pCache = (PCache1)p; PgHdr1 pPage = PAGE_TO_PGHDR1(pCache, pPg); PgHdr1 pp; int h; Debug.Assert(pPage.iKey == iOld); Debug.Assert(pPage.pCache == pCache); pcache1EnterMutex(pCache.pGroup); h = (int)(iOld % pCache.nHash); pp = pCache.apHash[h]; while ((pp) != pPage) { pp = (pp).pNext; } if (pp == pCache.apHash[h]) pCache.apHash[h] = pp.pNext; else pp.pNext = pPage.pNext; h = (int)(iNew % pCache.nHash); pPage.iKey = iNew; pPage.pNext = pCache.apHash[h]; pCache.apHash[h] = pPage; if (iNew > pCache.iMaxKey) { pCache.iMaxKey = iNew; } pcache1LeaveMutex(pCache.pGroup); } /* ** Implementation of the sqlite3_pcache.xTruncate method. ** ** Discard all unpinned pages in the cache with a page number equal to ** or greater than parameter iLimit. Any pinned pages with a page number ** equal to or greater than iLimit are implicitly unpinned. */ static void pcache1Truncate(sqlite3_pcache p, Pgno iLimit) { PCache1 pCache = (PCache1)p; pcache1EnterMutex(pCache.pGroup); if (iLimit <= pCache.iMaxKey) { pcache1TruncateUnsafe(pCache, iLimit); pCache.iMaxKey = iLimit - 1; } pcache1LeaveMutex(pCache.pGroup); } /* ** Implementation of the sqlite3_pcache.xDestroy method. ** ** Destroy a cache allocated using pcache1Create(). */ static void pcache1Destroy(ref sqlite3_pcache p) { PCache1 pCache = (PCache1)p; PGroup pGroup = pCache.pGroup; Debug.Assert(pCache.bPurgeable || (pCache.nMax == 0 && pCache.nMin == 0)); pcache1EnterMutex(pGroup); pcache1TruncateUnsafe(pCache, 0); pGroup.nMaxPage -= pCache.nMax; pGroup.nMinPage -= pCache.nMin; pGroup.mxPinned = pGroup.nMaxPage + 10 - pGroup.nMinPage; pcache1EnforceMaxPage(pGroup); pcache1LeaveMutex(pGroup); //sqlite3_free( pCache.apHash ); //sqlite3_free( pCache ); p = null; } /* ** This function is called during initialization (sqlite3_initialize()) to ** install the default pluggable cache module, assuming the user has not ** already provided an alternative. */ static void sqlite3PCacheSetDefault() { sqlite3_pcache_methods defaultMethods = new sqlite3_pcache_methods( 0, /* pArg */ (dxPC_Init)pcache1Init, /* xInit */ (dxPC_Shutdown)pcache1Shutdown, /* xShutdown */ (dxPC_Create)pcache1Create, /* xCreate */ (dxPC_Cachesize)pcache1Cachesize, /* xCachesize */ (dxPC_Pagecount)pcache1Pagecount, /* xPagecount */ (dxPC_Fetch)pcache1Fetch, /* xFetch */ (dxPC_Unpin)pcache1Unpin, /* xUnpin */ (dxPC_Rekey)pcache1Rekey, /* xRekey */ (dxPC_Truncate)pcache1Truncate, /* xTruncate */ (dxPC_Destroy)pcache1Destroy /* xDestroy */ ); sqlite3_config(SQLITE_CONFIG_PCACHE, defaultMethods); } #if SQLITE_ENABLE_MEMORY_MANAGEMENT /* ** This function is called to free superfluous dynamically allocated memory ** held by the pager system. Memory in use by any SQLite pager allocated ** by the current thread may be sqlite3_free()ed. ** ** nReq is the number of bytes of memory required. Once this much has ** been released, the function returns. The return value is the total number ** of bytes of memory released. */ int sqlite3PcacheReleaseMemory(int nReq){ int nFree = 0; Debug.Assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); Debug.Assert( sqlite3_mutex_notheld(pcache1.mutex) ); if( pcache1.pStart==0 ){ PgHdr1 p; pcache1EnterMutex(&pcache1.grp); while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){ nFree += pcache1MemSize(PGHDR1_TO_PAGE(p)); PCache1pinPage(p); pcache1RemoveFromHash(p); pcache1FreePage(p); } pcache1LeaveMutex(&pcache1.grp); } return nFree; } #endif //* SQLITE_ENABLE_MEMORY_MANAGEMENT */ #if SQLITE_TEST /* ** This function is used by test procedures to inspect the internal state ** of the global cache. */ static void sqlite3PcacheStats( out int pnCurrent, /* OUT: Total number of pages cached */ out int pnMax, /* OUT: Global maximum cache size */ out int pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */ out int pnRecyclable /* OUT: Total number of pages available for recycling */ ) { PgHdr1 p; int nRecyclable = 0; for ( p = pcache1.grp.pLruHead; p != null; p = p.pLruNext ) { nRecyclable++; } pnCurrent = pcache1.grp.nCurrentPage; pnMax = pcache1.grp.nMaxPage; pnMin = pcache1.grp.nMinPage; pnRecyclable = nRecyclable; } #endif } }
#pragma warning disable 1591 using AjaxControlToolkit.Design; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Web; using System.Web.Script.Serialization; using System.Web.UI; using System.Web.UI.WebControls; namespace AjaxControlToolkit { /// <summary> /// TabContainer is an ASP.NET AJAX Control, which creates a set of tabs that can be /// used to organize page content. TabContainer is a host for a number of TabPanel controls. /// </summary> [Designer(typeof(TabContainerDesigner))] [ParseChildren(typeof(TabPanel))] [RequiredScript(typeof(CommonToolkitScripts))] [ClientCssResource(Constants.TabsName)] [ClientScriptResource("Sys.Extended.UI.TabContainer", Constants.TabsName)] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.TabsName + Constants.IconPostfix)] public class TabContainer : ScriptControlBase, IPostBackEventHandler { static readonly object EventActiveTabChanged = new object(); int _activeTabIndex = -1; int _cachedActiveTabIndex = -1; bool _initialized; bool _autoPostBack; TabStripPlacement _tabStripPlacement; bool _useVerticalStripPlacement; Unit _verticalStripWidth = new Unit(120, UnitType.Pixel); bool _onDemand; TabCssTheme _cssTheme = TabCssTheme.XP; public TabContainer() : base(true, HtmlTextWriterTag.Div) { } /// <summary> /// Fires on the server side when a tab is changed after a postback /// </summary> [Category("Behavior")] public event EventHandler ActiveTabChanged { add { Events.AddHandler(EventActiveTabChanged, value); } remove { Events.RemoveHandler(EventActiveTabChanged, value); } } /// <summary> /// The first tab to show /// </summary> /// <remarks> /// For the client side /// </remarks> [DefaultValue(-1)] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Category("Behavior")] [ExtenderControlProperty] [ClientPropertyName("activeTabIndex")] public int ActiveTabIndexForClient { get { var counter = ActiveTabIndex; for(int i = 0; i <= ActiveTabIndex && i < Tabs.Count; i++) { if(!Tabs[i].Visible) counter--; } if(counter < 0) return 0; return counter; } } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeActiveTabIndexForClient() { return IsRenderingScript; } /// <summary> /// The first tab to show /// </summary> [DefaultValue(-1)] [Category("Behavior")] public virtual int ActiveTabIndex { get { if(_cachedActiveTabIndex > -1) return _cachedActiveTabIndex; if(Tabs.Count == 0) return -1; return _activeTabIndex; } set { if(value < -1) throw new ArgumentOutOfRangeException("value"); if(Tabs.Count == 0 && !_initialized) { _cachedActiveTabIndex = value; return; } if(ActiveTabIndex == value) return; if(ActiveTabIndex != -1 && ActiveTabIndex < Tabs.Count) Tabs[ActiveTabIndex].Active = false; if(value >= Tabs.Count) { _activeTabIndex = Tabs.Count - 1; _cachedActiveTabIndex = value; } else { _activeTabIndex = value; _cachedActiveTabIndex = -1; } if(ActiveTabIndex != -1 && ActiveTabIndex < Tabs.Count) Tabs[ActiveTabIndex].Active = true; } } int LastActiveTabIndex { get { return (int)(ViewState["LastActiveTabIndex"] ?? -1); } set { ViewState["LastActiveTabIndex"] = value; } } /// <summary> /// A collection of tabs /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public TabPanelCollection Tabs { get { return (TabPanelCollection)Controls; } } /// <summary> /// The current active tab /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public TabPanel ActiveTab { get { var i = ActiveTabIndex; if(i < 0 || i >= Tabs.Count) return null; EnsureActiveTab(); return Tabs[i]; } set { var i = Tabs.IndexOf(value); if(i < 0) throw new ArgumentOutOfRangeException("value"); ActiveTabIndex = i; } } /// <summary> /// Make an auto postback from JavaScript when a tab index changes /// </summary> [DefaultValue(false)] [Category("Behavior")] public bool AutoPostBack { get { return _autoPostBack; } set { _autoPostBack = value; } } /// <summary> /// Height of a tab body (does not include TabPanel headers) /// </summary> [DefaultValue(typeof(Unit), "")] [Category("Appearance")] public override Unit Height { get { return base.Height; } set { //if (!value.IsEmpty && value.Type != UnitType.Pixel) //{ // throw new ArgumentOutOfRangeException("value", "Height must be set in pixels only, or Empty."); //} base.Height = value; } } /// <summary> /// Width of the tab body /// </summary> [DefaultValue(typeof(Unit), "")] [Category("Appearance")] public override Unit Width { get { return base.Width; } set { base.Width = value; } } /// <summary> /// Gets or sets a CSS theme predefined in a CSS file /// </summary> [DefaultValue(TabCssTheme.XP)] [Category("Appearance")] [ExtenderControlProperty] [ClientPropertyName("cssTheme")] public TabCssTheme CssTheme { get { return (TabCssTheme)(ViewState["CssTheme"] ?? TabCssTheme.XP); } set { ViewState["CssTheme"] = value; } } /// <summary> /// Determines whether or not to display scrollbars (None, Horizontal, Vertical, Both, Auto) /// in the TabContainer body /// </summary> [DefaultValue(ScrollBars.None)] [Category("Behavior")] [ExtenderControlProperty] [ClientPropertyName("scrollBars")] public ScrollBars ScrollBars { get { return (ScrollBars)(ViewState["ScrollBars"] ?? ScrollBars.None); } set { ViewState["ScrollBars"] = value; } } /// <summary> /// Determines whether or not to render tabs on top of the container or below (Top, Bottom) /// </summary> [DefaultValue(TabStripPlacement.Top)] [Category("Appearance")] [ClientPropertyName("tabStripPlacement")] public TabStripPlacement TabStripPlacement { get { return _tabStripPlacement; } set { _tabStripPlacement = value; } } /// <summary> /// Fires on the client side when a tab is changed /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("activeTabChanged")] public string OnClientActiveTabChanged { get { return (string)(ViewState["OnClientActiveTabChanged"] ?? string.Empty); } set { ViewState["OnClientActiveTabChanged"] = value; } } /// <summary> /// AutoPostback ID /// </summary> [ExtenderControlProperty] [ClientPropertyName("autoPostBackId")] public new string UniqueID { get { return base.UniqueID; } set { /* need to add a setter for serialization to work properly.*/ } } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeUniqueID() { return IsRenderingScript && AutoPostBack; } /// <summary> /// Determines whether or not to render tabs on the left or right side of the container /// </summary> [Description("Change tab header placement vertically when value set to true")] [DefaultValue(false)] [Category("Appearance")] [ClientPropertyName("useVerticalStripPlacement")] public bool UseVerticalStripPlacement { get { return _useVerticalStripPlacement; } set { _useVerticalStripPlacement = value; } } /// <summary> /// Width of tab panels when tabs are displayed vertically /// </summary> [Description("Set width of tab strips when UseVerticalStripPlacement is set to true. Size must be in pixel")] [DefaultValue(typeof(Unit), "120px")] [Category("Appearance")] public Unit VerticalStripWidth { get { return _verticalStripWidth; } set { if(!value.IsEmpty && value.Type != UnitType.Pixel) throw new ArgumentOutOfRangeException("value", "VerticalStripWidth must be set in pixels only, or Empty."); _verticalStripWidth = value; } } /// <summary> /// Determines whether or not to render/load precise tabs on demand or all tabs on page load /// </summary> [DefaultValue(false)] [Category("Behavior")] [ClientPropertyName("onDemand")] public bool OnDemand { get { return _onDemand; } set { _onDemand = value; } } protected override void OnInit(EventArgs e) { base.OnInit(e); Page.RegisterRequiresControlState(this); _initialized = true; if(_cachedActiveTabIndex > -1) { ActiveTabIndex = _cachedActiveTabIndex; if(ActiveTabIndex < Tabs.Count) Tabs[ActiveTabIndex].Active = true; } else if(Tabs.Count > 0) { ActiveTabIndex = 0; } } protected virtual void OnActiveTabChanged(EventArgs e) { var eh = Events[EventActiveTabChanged] as EventHandler; if(eh != null) eh(this, e); } protected override void AddParsedSubObject(object obj) { var objTabPanel = obj as TabPanel; if(null != objTabPanel) { Controls.Add(objTabPanel); } else if(!(obj is LiteralControl)) { throw new HttpException(string.Format(CultureInfo.CurrentCulture, "TabContainer cannot have children of type '{0}'.", obj.GetType())); } } protected override void AddedControl(Control control, int index) { ((TabPanel)control).SetOwner(this); base.AddedControl(control, index); } protected override void RemovedControl(Control control) { var controlTabPanel = control as TabPanel; if(control != null && controlTabPanel.Active && ActiveTabIndex < Tabs.Count) EnsureActiveTab(); controlTabPanel.SetOwner(null); base.RemovedControl(control); } protected override ControlCollection CreateControlCollection() { return new TabPanelCollection(this); } protected override Style CreateControlStyle() { var style = new TabContainerStyle(ViewState); style.CssClass = CssClass; return style; } int GetServerActiveTabIndex(int clientActiveTabIndex) { int counter = -1; int result = clientActiveTabIndex; for(int i = 0; i < Tabs.Count; i++) { if(Tabs[i].Visible) counter++; if(counter == clientActiveTabIndex) { result = i; break; } } return result; } protected override void LoadClientState(string clientState) { var state = (Dictionary<string, object>)new JavaScriptSerializer().DeserializeObject(clientState); if(state != null) { ActiveTabIndex = (int)state["ActiveTabIndex"]; ActiveTabIndex = GetServerActiveTabIndex(ActiveTabIndex); object[] tabEnabledState = (object[])state["TabEnabledState"]; object[] tabWasLoadedOnceState = (object[])state["TabWasLoadedOnceState"]; for(int i = 0; i < tabEnabledState.Length; i++) { int j = GetServerActiveTabIndex(i); if(j < Tabs.Count) { Tabs[j].Enabled = (bool)tabEnabledState[i]; Tabs[j].WasLoadedOnce = (bool)tabWasLoadedOnceState[i]; } } } } protected override string SaveClientState() { var state = new Dictionary<string, object>(); state["ActiveTabIndex"] = ActiveTabIndex; var tabEnabledState = new List<object>(); var tabWasLoadedOnceState = new List<object>(); foreach(TabPanel tab in Tabs) { tabEnabledState.Add(tab.Enabled); tabWasLoadedOnceState.Add(tab.WasLoadedOnce); } state["TabEnabledState"] = tabEnabledState; state["TabWasLoadedOnceState"] = tabWasLoadedOnceState; return new JavaScriptSerializer().Serialize(state); } protected override void LoadControlState(object savedState) { var pair = (Pair)savedState; if(pair != null) { base.LoadControlState(pair.First); ActiveTabIndex = (int)pair.Second; } else { base.LoadControlState(null); } } protected override object SaveControlState() { // Saving last active tab index this.LastActiveTabIndex = this.ActiveTabIndex; var pair = new Pair(); pair.First = base.SaveControlState(); pair.Second = ActiveTabIndex; if(pair.First == null && pair.Second == null) return null; return pair; } protected override void AddAttributesToRender(HtmlTextWriter writer) { Style.Remove(HtmlTextWriterStyle.Visibility); if(!ControlStyleCreated && !String.IsNullOrWhiteSpace(CssClass)) writer.AddAttribute(HtmlTextWriterAttribute.Class, CssClass); if(_useVerticalStripPlacement) writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "block"); if(!Height.IsEmpty && Height.Type == UnitType.Percentage) writer.AddStyleAttribute(HtmlTextWriterStyle.Height, Height.ToString()); base.AddAttributesToRender(writer); writer.AddStyleAttribute(HtmlTextWriterStyle.Visibility, "hidden"); } protected override void RenderContents(HtmlTextWriter writer) { //base.Render(writer); Page.VerifyRenderingInServerForm(this); if(_tabStripPlacement == TabStripPlacement.Top || _tabStripPlacement == TabStripPlacement.TopRight || (_tabStripPlacement == TabStripPlacement.Bottom && _useVerticalStripPlacement) || (_tabStripPlacement == TabStripPlacement.BottomRight && _useVerticalStripPlacement) ) RenderHeader(writer); if(!Height.IsEmpty) writer.AddStyleAttribute(HtmlTextWriterStyle.Height, Height.ToString()); writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID + "_body"); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ajax__tab_body" + GetSuffixTabStripPlacementCss()); writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "block"); writer.RenderBeginTag(HtmlTextWriterTag.Div); RenderChildren(writer); writer.RenderEndTag(); if((_tabStripPlacement == TabStripPlacement.Bottom && !_useVerticalStripPlacement) || _tabStripPlacement == TabStripPlacement.BottomRight && !_useVerticalStripPlacement) RenderHeader(writer); } protected virtual void RenderHeader(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID + "_header"); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ajax__tab_header" + GetSuffixTabStripPlacementCss()); if(_tabStripPlacement == TabStripPlacement.BottomRight || _tabStripPlacement == TabStripPlacement.TopRight) writer.AddStyleAttribute(HtmlTextWriterStyle.Direction, "rtl"); if(_useVerticalStripPlacement) { writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "block"); if(_tabStripPlacement == TabStripPlacement.Bottom || _tabStripPlacement == TabStripPlacement.Top) writer.AddAttribute(HtmlTextWriterAttribute.Style, "float:left"); else writer.AddAttribute(HtmlTextWriterAttribute.Style, "float:right"); writer.AddStyleAttribute(HtmlTextWriterStyle.Width, _verticalStripWidth.ToString()); } writer.RenderBeginTag(HtmlTextWriterTag.Div); if(_tabStripPlacement == TabStripPlacement.Bottom || _tabStripPlacement == TabStripPlacement.BottomRight) RenderSpannerForVerticalTabs(writer); if(!_useVerticalStripPlacement && (_tabStripPlacement == TabStripPlacement.BottomRight || _tabStripPlacement == TabStripPlacement.TopRight)) { // reverse tab order placement var tabs = Tabs.Count; for(int i = tabs - 1; i >= 0; i--) { var panel = Tabs[i]; if(panel.Visible) panel.RenderHeader(writer); } } else { foreach(TabPanel panel in Tabs) { if(panel.Visible) panel.RenderHeader(writer); } } if(_tabStripPlacement == TabStripPlacement.Top || _tabStripPlacement == TabStripPlacement.TopRight) RenderSpannerForVerticalTabs(writer); writer.RenderEndTag(); } void RenderSpannerForVerticalTabs(HtmlTextWriter writer) { if(!_useVerticalStripPlacement) return; writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID + "_headerSpannerHeight"); writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "block"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.RenderEndTag(); } string GetSuffixTabStripPlacementCss() { var tabStripPlacementCss = ""; if(_useVerticalStripPlacement) { tabStripPlacementCss += "_vertical"; switch(_tabStripPlacement) { case TabStripPlacement.Top: case TabStripPlacement.Bottom: tabStripPlacementCss += "left"; break; case TabStripPlacement.TopRight: case TabStripPlacement.BottomRight: tabStripPlacementCss += "right"; break; } } else { switch(_tabStripPlacement) { case TabStripPlacement.Bottom: case TabStripPlacement.BottomRight: tabStripPlacementCss = "_bottom"; break; } } return tabStripPlacementCss; } protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { int tabIndex = ActiveTabIndex; bool result = base.LoadPostData(postDataKey, postCollection); if(ActiveTabIndex == 0 || tabIndex != ActiveTabIndex) return true; return result; } protected override void RaisePostDataChangedEvent() { // If the tab index changed if(LastActiveTabIndex == ActiveTabIndex) return; // Saving last active tab index LastActiveTabIndex = ActiveTabIndex; // The event fires only when the new active tab exists and has OnDemandMode = Always or // when OnDemandMode = Once and tab wasn't loaded yet var activeTab = this.ActiveTab; if(activeTab != null && (activeTab.OnDemandMode == OnDemandMode.Always || activeTab.OnDemandMode == OnDemandMode.Once && !activeTab.WasLoadedOnce)) OnActiveTabChanged(EventArgs.Empty); } void EnsureActiveTab() { if(_activeTabIndex < 0 || _activeTabIndex >= Tabs.Count) _activeTabIndex = 0; for(int i = 0; i < Tabs.Count; i++) { Tabs[i].Active = i == ActiveTabIndex; } } public void ResetLoadedOnceTabs() { foreach(TabPanel tab in this.Tabs) { if(tab.OnDemandMode == OnDemandMode.Once && tab.WasLoadedOnce) tab.WasLoadedOnce = false; } } sealed class TabContainerStyle : Style { public TabContainerStyle(StateBag state) : base(state) { } protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver) { base.FillStyleAttributes(attributes, urlResolver); attributes.Remove(HtmlTextWriterStyle.Height); // commented below line to fix the issue #25821 //attributes.Remove(HtmlTextWriterStyle.BackgroundColor); attributes.Remove(HtmlTextWriterStyle.BackgroundImage); } } void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) { if(eventArgument.StartsWith("activeTabChanged", StringComparison.Ordinal)) { // change the active tab. // int parseIndex = eventArgument.IndexOf(":", StringComparison.Ordinal); Debug.Assert(parseIndex != -1, "Expected new active tab index!"); if(parseIndex != -1 && Int32.TryParse(eventArgument.Substring(parseIndex + 1), out parseIndex)) { parseIndex = GetServerActiveTabIndex(parseIndex); if(parseIndex != ActiveTabIndex) { ActiveTabIndex = parseIndex; OnActiveTabChanged(EventArgs.Empty); } } } } protected override void DescribeComponent(ScriptComponentDescriptor descriptor) { base.DescribeComponent(descriptor); descriptor.AddProperty("tabStripPlacement", this.TabStripPlacement); descriptor.AddProperty("useVerticalStripPlacement", this.UseVerticalStripPlacement); descriptor.AddProperty("onDemand", this.OnDemand); } } } #pragma warning restore 1591
using System; using System.Globalization; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Transactions; using System.Workflow.ComponentModel; namespace System.Workflow.Runtime { #region Scheduler // Only one instance of this type is used for a workflow instance. // class Scheduler { #region data // state to be persisted for the scheduler internal static DependencyProperty HighPriorityEntriesQueueProperty = DependencyProperty.RegisterAttached("HighPriorityEntriesQueue", typeof(Queue<SchedulableItem>), typeof(Scheduler)); internal static DependencyProperty NormalPriorityEntriesQueueProperty = DependencyProperty.RegisterAttached("NormalPriorityEntriesQueue", typeof(Queue<SchedulableItem>), typeof(Scheduler)); Queue<SchedulableItem> highPriorityEntriesQueue; Queue<SchedulableItem> normalPriorityEntriesQueue; // non-persisted state for the scheduler WorkflowExecutor rootWorkflowExecutor; bool empty; bool canRun; bool threadRequested; bool abortOrTerminateRequested; Queue<SchedulableItem> transactedEntries; object syncObject = new object(); #endregion data #region ctors // loading with some state public Scheduler(WorkflowExecutor rootExec, bool canRun) { this.rootWorkflowExecutor = rootExec; this.threadRequested = false; // canRun is true if normal creation // false if loading from a persisted state. Will be set to true later at ResumeOnIdle this.canRun = canRun; this.highPriorityEntriesQueue = (Queue<SchedulableItem>)rootExec.RootActivity.GetValue(Scheduler.HighPriorityEntriesQueueProperty); this.normalPriorityEntriesQueue = (Queue<SchedulableItem>)rootExec.RootActivity.GetValue(Scheduler.NormalPriorityEntriesQueueProperty); if (this.highPriorityEntriesQueue == null) { this.highPriorityEntriesQueue = new Queue<SchedulableItem>(); rootExec.RootActivity.SetValue(Scheduler.HighPriorityEntriesQueueProperty, this.highPriorityEntriesQueue); } if (this.normalPriorityEntriesQueue == null) { this.normalPriorityEntriesQueue = new Queue<SchedulableItem>(); rootExec.RootActivity.SetValue(Scheduler.NormalPriorityEntriesQueueProperty, this.normalPriorityEntriesQueue); } this.empty = ((this.normalPriorityEntriesQueue.Count == 0) && (this.highPriorityEntriesQueue.Count == 0)); } #endregion ctors #region Misc properties public override string ToString() { return "Scheduler('" + ((Activity)this.RootWorkflowExecutor.WorkflowDefinition).QualifiedName + "')"; } protected WorkflowExecutor RootWorkflowExecutor { get { return this.rootWorkflowExecutor; } } public bool IsStalledNow { get { return empty; } } public bool CanRun { get { return canRun; } set { canRun = value; } } internal bool AbortOrTerminateRequested { get { return abortOrTerminateRequested; } set { abortOrTerminateRequested = value; } } #endregion Misc properties #region Run work public void Run() { do { this.RootWorkflowExecutor.ProcessQueuedEvents(); // Get item to run SchedulableItem item = GetItemToRun(); bool runningItem = false; // no ready work to run... go away if (item == null) break; Activity itemActivity = null; Exception exp = null; TransactionalProperties transactionalProperties = null; int contextId = item.ContextId; // This function gets the root or enclosing while-loop activity Activity contextActivity = this.RootWorkflowExecutor.GetContextActivityForId(contextId); if (contextActivity == null) throw new InvalidOperationException(ExecutionStringManager.InvalidExecutionContext); // This is the activity corresponding to the item's ActivityId itemActivity = contextActivity.GetActivityByName(item.ActivityId); using (new ServiceEnvironment(itemActivity)) { exp = null; bool ignoreFinallyBlock = false; try { // item preamble // set up the item transactional context if necessary // Debug.Assert(itemActivity != null, "null itemActivity"); if (itemActivity == null) throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InvalidActivityName, item.ActivityId)); Activity atomicActivity = null; if (this.RootWorkflowExecutor.IsActivityInAtomicContext(itemActivity, out atomicActivity)) { transactionalProperties = (TransactionalProperties)atomicActivity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty); // If we've aborted for any reason stop now! // If we attempt to enter a new TransactionScope the com+ context will get corrupted // See windows se bug 137267 if (!WorkflowExecutor.CheckAndProcessTransactionAborted(transactionalProperties)) { if (transactionalProperties.TransactionScope == null) { // Use TimeSpan.Zero so scope will not create timeout independent of the transaction // Use EnterpriseServicesInteropOption.Full to flow transaction to COM+ transactionalProperties.TransactionScope = new TransactionScope(transactionalProperties.Transaction, TimeSpan.Zero, EnterpriseServicesInteropOption.Full); WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 0, "Workflow Runtime: Scheduler: instanceId: " + this.RootWorkflowExecutor.InstanceIdString + "Entered into TransactionScope, Current atomic acitivity " + atomicActivity.Name); } } } // Run the item // runningItem = true; WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 1, "Workflow Runtime: Scheduler: InstanceId: {0} : Running scheduled entry: {1}", this.RootWorkflowExecutor.InstanceIdString, item.ToString()); // running any entry implicitly changes some state of the workflow instance this.RootWorkflowExecutor.stateChangedSincePersistence = true; item.Run(this.RootWorkflowExecutor); } catch (Exception e) { if (WorkflowExecutor.IsIrrecoverableException(e)) { ignoreFinallyBlock = true; throw; } else { if (transactionalProperties != null) transactionalProperties.TransactionState = TransactionProcessState.AbortProcessed; exp = e; } } finally { if (!ignoreFinallyBlock) { if (runningItem) WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 1, "Workflow Runtime: Scheduler: InstanceId: {0} : Done with running scheduled entry: {1}", this.RootWorkflowExecutor.InstanceIdString, item.ToString()); // Process exception // if (exp != null) { // this.RootWorkflowExecutor.ExceptionOccured(exp, itemActivity == null ? contextActivity : itemActivity, null); exp = null; } } } } } while (true); } private SchedulableItem GetItemToRun() { SchedulableItem ret = null; lock (this.syncObject) { bool workToDo = false; if ((this.highPriorityEntriesQueue.Count > 0) || (this.normalPriorityEntriesQueue.Count > 0)) { workToDo = true; // If an abort or termination of the workflow has been requested, // then the workflow should try to terminate ASAP. Even transaction scopes // in progress shouldn't be executed to completion. (Ref: 16534) if (this.AbortOrTerminateRequested) { ret = null; } // got work to do in the scheduler else if ((this.highPriorityEntriesQueue.Count > 0)) { ret = this.highPriorityEntriesQueue.Dequeue(); } else if (this.CanRun) { // the scheduler can run right now // // pick an entry to run // if (((IWorkflowCoreRuntime)this.RootWorkflowExecutor).CurrentAtomicActivity == null && (this.normalPriorityEntriesQueue.Count > 0)) ret = this.normalPriorityEntriesQueue.Dequeue(); } else { // scheduler can't run right now.. even though there is ready work // do nothing in the scheduler ret = null; } } if (!workToDo) { // no ready work to do in the scheduler... // we are gonna return the thread back this.empty = true; } // set it to true only iff there is something to run this.threadRequested = (ret != null); } return ret; } // This method should be called only after we have determined that // this instance can start running now public void Resume() { canRun = true; if (!empty) { // There is scheduled work // ask the threadprovider for a thread this.RootWorkflowExecutor.ScheduleForWork(); } } // This method should be called only after we have determined that // this instance can start running now public void ResumeIfRunnable() { if (!canRun) return; if (!empty) { // There is scheduled work // ask the threadprovider for a thread this.RootWorkflowExecutor.ScheduleForWork(); } } #endregion Run work #region Schedule work public void ScheduleItem(SchedulableItem s, bool isInAtomicTransaction, bool transacted) { lock (this.syncObject) { WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 1, "Workflow Runtime: Scheduler: InstanceId: {0} : Scheduling entry: {1}", this.RootWorkflowExecutor.InstanceIdString, s.ToString()); // SchedulableItems in AtomicTransaction has higher priority Queue<SchedulableItem> q = isInAtomicTransaction ? this.highPriorityEntriesQueue : this.normalPriorityEntriesQueue; q.Enqueue(s); if (transacted) { if (transactedEntries == null) transactedEntries = new Queue<SchedulableItem>(); transactedEntries.Enqueue(s); } if (!this.threadRequested) { if (this.CanRun) { this.RootWorkflowExecutor.ScheduleForWork(); this.threadRequested = true; } } this.empty = false; } } #endregion Schedule work #region psuedo-transacted support public void PostPersist() { transactedEntries = null; } public void Rollback() { if (transactedEntries != null && transactedEntries.Count > 0) { // make a list of non-transacted entries // @undone: bmalhi: transacted entries only on priority-0 IEnumerator<SchedulableItem> e = this.normalPriorityEntriesQueue.GetEnumerator(); Queue<SchedulableItem> newScheduled = new Queue<SchedulableItem>(); while (e.MoveNext()) { if (!transactedEntries.Contains(e.Current)) newScheduled.Enqueue(e.Current); } // clear the scheduled items this.normalPriorityEntriesQueue.Clear(); // schedule the non-transacted items back e = newScheduled.GetEnumerator(); while (e.MoveNext()) this.normalPriorityEntriesQueue.Enqueue(e.Current); transactedEntries = null; } } #endregion psuedo-transacted support } #endregion Scheduler }
using System; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Text.RegularExpressions; using System.Collections.Concurrent; using Microsoft.Extensions.Configuration; using System.Diagnostics; namespace Zyborg.Logentries { public class LogentriesAsyncLogger { #region -- Constants -- // Current version number. public const String Version = "2.6.7"; // Size of the internal event queue. public const int QUEUE_SIZE = 32768; // Minimal delay between attempts to reconnect in milliseconds. public const int MIN_DELAY = 100; // Maximal delay between attempts to reconnect in milliseconds. public const int MAX_DELAY = 10000; // Appender signature - used for debugging messages. public const String LE_SIGNATURE = "LE: "; // Legacy Logentries configuration names. public const String LegacyConfigTokenName = "LOGENTRIES_TOKEN"; public const String LegacyConfigAccountKeyName = "LOGENTRIES_ACCOUNT_KEY"; public const String LegacyConfigLocationName = "LOGENTRIES_LOCATION"; // New Logentries configuration names. public const String ConfigTokenName = "Logentries.Token"; public const String ConfigAccountKeyName = "Logentries.AccountKey"; public const String ConfigLocationName = "Logentries.Location"; // Error message displayed when invalid token is detected. protected const String InvalidTokenMessage = "\n\nIt appears your LOGENTRIES_TOKEN value is invalid or missing.\n\n"; // Error message displayed when invalid account_key or location parameters are detected. protected const String InvalidHttpPutCredentialsMessage = "\n\nIt appears your LOGENTRIES_ACCOUNT_KEY or LOGENTRIES_LOCATION values are invalid or missing.\n\n"; // Error message deisplayed when queue overflow occurs. protected const String QueueOverflowMessage = "\n\nLogentries buffer queue overflow. Message dropped.\n\n"; // Newline char to trim from message for formatting. protected static char[] _trimChars = { '\r', '\n' }; /** Non-Unix and Unix Newline */ protected static string[] _posixNewline = { "\r\n", "\n" }; /** Unicode line separator character */ protected static string _lineSeparator = "\u2028"; // Restricted symbols that should not appear in host name. // See http://support.microsoft.com/kb/228275/en-us for details. private static Regex _forbiddenHostNameChars = new Regex( @"[/\\\[\]\""\:\;\|\<\>\+\=\,\?\* _]{1,}", RegexOptions.Compiled); #endregion -- Constants -- protected readonly BlockingCollection<string> _queue; protected readonly CancellationTokenSource _cancel = new CancellationTokenSource(); protected IConfiguration _config; protected readonly Thread _workerThread; protected readonly Random _random = new Random(); private LogentriesClient _leClient = null; protected bool _isRunning = false; #region -- Singletons -- // UTF-8 output character set. //protected static readonly UTF8Encoding UTF8 = new UTF8Encoding(); // ASCII character set used by HTTP. //protected static readonly ASCIIEncoding ASCII = new ASCIIEncoding(); //static list of all the queues the le appender might be managing. private static ConcurrentBag<BlockingCollection<string>> _allQueues = new ConcurrentBag<BlockingCollection<string>>(); /// <summary> /// Determines if the queue is empty after waiting the specified waitTime. /// Returns true or false if the underlying queues are empty. /// </summary> /// <param name="waitTime">The length of time the method should block before giving up /// waiting for it to empty.</param> /// <returns>True if the queue is empty, false if there are still items waiting to be /// written.</returns> public static bool AreAllQueuesEmpty(TimeSpan waitTime) { var start = DateTime.UtcNow; var then = DateTime.UtcNow; while (start.Add(waitTime) > then) { if (_allQueues.All(x => x.Count == 0)) return true; Thread.Sleep(100); then = DateTime.UtcNow; } return _allQueues.All(x => x.Count == 0); } public IConfiguration BuildDefaultConfiguration() { var cb = new ConfigurationBuilder() .AddEnvironmentVariables(); return cb.Build(); } #endregion -- Singletons -- public LogentriesAsyncLogger(IConfiguration config = null) { _queue = new BlockingCollection<string>(QUEUE_SIZE); _allQueues.Add(_queue); _config = config; if (_config == null) _config = BuildDefaultConfiguration(); _workerThread = new Thread(new ThreadStart(Run)); _workerThread.Name = "Logentries Log Appender"; _workerThread.IsBackground = true; } #region -- Configuration Properties -- public string Token { get; set; } public string AccountKey { get; set; } public string Location { get; set; } public bool ImmediateFlush { get; set; } public bool Debug { get; set; } public bool UseHttpPut { get; set; } public bool UseSsl { get; set; } // Properties for defining location of DataHub instance if one is used. /// By default Logentries service is used instead of DataHub instance. public bool UseDataHub { get; set; } public string DataHubAddr { get; set; } public int DataHubPort { get; set; } // Properties to define host name of user's machine and define user-specified log ID. /// Defines whether to prefix log message with HostName or not. public bool UseHostName { get; set; } /// User-defined or auto-defined host name (if not set in config. file) public string HostName { get; set; } /// User-defined log ID to be prefixed to the log message. public string LogID { get; set; } #endregion -- Configuration Properties -- #region -- Protected methods -- protected virtual void Run() { var ct = _cancel.Token; ct.ThrowIfCancellationRequested(); try { // Open connection. ReopenConnection(); ct.ThrowIfCancellationRequested(); string logMessagePrefix = String.Empty; if (UseHostName) { // If LogHostName is set to "true", but HostName is not defined - // try to get host name from Environment. if (string.IsNullOrWhiteSpace(HostName)) { try { WriteDebugMessages("HostName parameter is not defined " + "- trying to get it from System.Environment.MachineName"); HostName = "HostName={System.Environment.MachineName} "; } catch (InvalidOperationException ) { // Cannot get host name automatically, so assume that HostName is not used // and log message is sent without it. UseHostName = false; WriteDebugMessages("Failed to get HostName parameter using" + " System.Environment.MachineName. Log messages will" + " not be prefixed by HostName"); } } else { if (!CheckIfHostNameValid(HostName)) { // If user-defined host name is incorrect - we cannot use it // and log message is sent without it. UseHostName = false; WriteDebugMessages("HostName parameter contains prohibited characters." + " Log messages will not be prefixed by HostName"); } else { HostName = $"HostName={HostName} "; } } } if (! string.IsNullOrWhiteSpace(LogID)) { logMessagePrefix = $"{LogID} "; } if (UseHostName) { logMessagePrefix += HostName; } // Flag that is set if logMessagePrefix is empty. bool isPrefixEmpty = string.IsNullOrWhiteSpace(logMessagePrefix); // Send data in queue. while (true) { ct.ThrowIfCancellationRequested(); // added debug here WriteDebugMessages("Await queue data"); // Take data from queue. var line = _queue.Take(); //added debug message here WriteDebugMessages("Queue data obtained"); // Replace newline chars with line separator to format multi-line events nicely. foreach (String newline in _posixNewline) { line = line.Replace(newline, _lineSeparator); } // If m_UseDataHub == true (logs are sent to DataHub instance) then m_Token is not // appended to the message. string finalLine = ((!UseHttpPut && !UseDataHub) ? this.Token + line : line) + '\n'; // Add prefixes: LogID and HostName if they are defined. if (!isPrefixEmpty) { finalLine = logMessagePrefix + finalLine; } byte[] data = Encoding.UTF8.GetBytes(finalLine); // Send data, reconnect if needed. while (true) { ct.ThrowIfCancellationRequested(); try { //removed iff loop and added debug message // Le.Client writes data WriteDebugMessages("Write data"); this._leClient.Write(data, 0, data.Length); WriteDebugMessages("Write complete, flush"); // if (m_ImmediateFlush) was removed, always flushed now. this._leClient.Flush(); WriteDebugMessages("Flush complete"); } catch (IOException e) { ct.ThrowIfCancellationRequested(); WriteDebugMessages("IOException during write, reopen: " + e.Message); // Reopen the lost connection. ReopenConnection(); continue; } break; } } } // TODO: This isn't reintroduced to .NET Core till .NET Standard 2.0 //catch (ThreadInterruptedException ex) catch (OperationCanceledException ex) { WriteDebugMessages("Logentries asynchronous socket client was interrupted.", ex); } } protected virtual void OpenConnection() { try { if (_leClient == null) { // Create LeClient instance providing all needed parameters. If DataHub-related properties // have not been overridden by log4net or NLog configurators, then DataHub is not used, // because m_UseDataHub == false by default. _leClient = new LogentriesClient(UseHttpPut, UseSsl, UseDataHub, DataHubAddr, DataHubPort); } _leClient.Connect(); if (UseHttpPut) { var header = String.Format("PUT /{0}/hosts/{1}/?realtime=1 HTTP/1.1\r\n\r\n", AccountKey, Location); _leClient.Write(Encoding.ASCII.GetBytes(header), 0, header.Length); } } catch (Exception ex) { throw new IOException("An error occurred while opening the connection.", ex); } } protected virtual void ReopenConnection() { WriteDebugMessages("ReopenConnection"); CloseConnection(); var rootDelay = MIN_DELAY; while (true) { try { OpenConnection(); return; } catch (Exception ex) { if (Debug) WriteDebugMessages("Unable to connect to Logentries API.", ex); } rootDelay *= 2; if (rootDelay > MAX_DELAY) rootDelay = MAX_DELAY; var waitFor = rootDelay + _random.Next(rootDelay); try { Thread.Sleep(waitFor); } catch { // TODO: This isn't reintroduced to .NET Core till .NET Standard 2.0 //throw new ThreadInterruptedException(); throw new Exception(); } } } protected virtual void CloseConnection() { if (_leClient != null) _leClient.Close(); } public string GetSetting(string name) { return _config?[name]; } // /* Retrieve configuration settings // * Will check Enviroment Variable as the last fall back. // * // */ // private string retrieveSetting(String name) // { // string cloudconfig = null; // if (Environment.OSVersion.Platform == PlatformID.Unix) // { // cloudconfig = ConfigurationManager.AppSettings.Get(name); // } // else // { // cloudconfig = CloudConfigurationManager.GetSetting(name); // } // if (!String.IsNullOrWhiteSpace(cloudconfig)) // { // WriteDebugMessages(String.Format("Found Cloud Configuration settings for {0}", name)); // return cloudconfig; // } // var appconfig = ConfigurationManager.AppSettings[name]; // if (!String.IsNullOrWhiteSpace(appconfig)) // { // WriteDebugMessages(String.Format("Found App Settings for {0}", name)); // return appconfig; // } // var envconfig = Environment.GetEnvironmentVariable(name); // if (!String.IsNullOrWhiteSpace(envconfig)) // { // WriteDebugMessages(String.Format("Found Enviromental Variable for {0}", name)); // return envconfig; // } // WriteDebugMessages(String.Format("Unable to find Logentries Configuration Setting for {0}.", name)); // return null; // } /* * Use CloudConfigurationManager with .NET4.0 and fallback to System.Configuration for previous frameworks. * * * One issue is that there are two appsetting keys for each setting - the "legacy" key, such as "LOGENTRIES_TOKEN" * and the "non-legacy" key, such as "Logentries.Token". Again, I'm not sure of the reasons behind this, so the code below checks * both the legacy and non-legacy keys, defaulting to the legacy keys if they are found. * * It probably should be investigated whether the fallback to ConfigurationManager is needed at all, as CloudConfigurationManager * will retrieve settings from appSettings in a non-Azure environment. */ public virtual bool LoadCredentials() { if (!UseHttpPut) { if (GetIsValidGuid(Token)) return true; var configToken = GetSetting(LegacyConfigTokenName) ?? GetSetting(ConfigTokenName); if (!String.IsNullOrEmpty(configToken) && GetIsValidGuid(configToken)) { Token = configToken; return true; } WriteDebugMessages(InvalidTokenMessage); return false; } if (!string.IsNullOrEmpty(AccountKey) && GetIsValidGuid(AccountKey) && !string.IsNullOrEmpty(Location)) return true; var configAccountKey = GetSetting(LegacyConfigAccountKeyName) ?? GetSetting(ConfigAccountKeyName); if (!string.IsNullOrEmpty(configAccountKey) && GetIsValidGuid(configAccountKey)) { AccountKey = configAccountKey; var configLocation = GetSetting(LegacyConfigLocationName) ?? GetSetting(ConfigLocationName); if (!string.IsNullOrEmpty(configLocation)) { Location = configLocation; return true; } } WriteDebugMessages(InvalidHttpPutCredentialsMessage); return false; } private bool CheckIfHostNameValid(String hostName) { return !_forbiddenHostNameChars.IsMatch(hostName); // Returns false if reg.ex. matches any of forbidden chars. } protected virtual bool GetIsValidGuid(string guidString) { if (String.IsNullOrEmpty(guidString)) return false; System.Guid newGuid = System.Guid.NewGuid(); return System.Guid.TryParse(guidString, out newGuid); } protected virtual void WriteDebugMessages(string message, Exception ex) { if (!Debug) return; message = LE_SIGNATURE + message; string[] messages = { message, ex.ToString() }; foreach (var msg in messages) { Trace.WriteLine(msg); } } protected virtual void WriteDebugMessages(string message) { if (!Debug) return; message = LE_SIGNATURE + message; Trace.WriteLine(message); } #endregion -- Protected methods -- #region -- Public Methods -- public virtual void AddLine(string line) { WriteDebugMessages("Adding Line: " + line); if (!_isRunning) { // We need to load user credentials only // if the configuration does not state that DataHub is used; // credentials needed only if logs are sent to LE service directly. bool credentialsLoaded = false; if (!UseDataHub) { credentialsLoaded = LoadCredentials(); } // If in DataHub mode credentials are ignored. if (credentialsLoaded || UseDataHub) { WriteDebugMessages("Starting Logentries asynchronous socket client."); _workerThread.Start(); _isRunning = true; } } WriteDebugMessages("Queueing: " + line); String trimmedEvent = line.TrimEnd(_trimChars); // Try to append data to queue. if (!_queue.TryAdd(trimmedEvent)) { _queue.Take(); if (!_queue.TryAdd(trimmedEvent)) WriteDebugMessages(QueueOverflowMessage); } } public void interruptWorker() { _cancel.Cancel(); //_workerThread.Interrupt(); } #endregion -- Public Methods -- } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.IdentityModel { using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Principal; using System.Text; enum EXTENDED_NAME_FORMAT { NameUnknown = 0, NameFullyQualifiedDN = 1, NameSamCompatible = 2, NameDisplay = 3, NameUniqueId = 6, NameCanonical = 7, NameUserPrincipalName = 8, NameCanonicalEx = 9, NameServicePrincipalName = 10, NameDnsDomainName = 12 } enum TokenInformationClass : uint { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert } enum Win32Error { ERROR_SUCCESS = 0, ERROR_INSUFFICIENT_BUFFER = 122, ERROR_NO_TOKEN = 1008, ERROR_NONE_MAPPED = 1332, } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CREDUI_INFO { public int cbSize; public IntPtr hwndParent; public string pszMessageText; public string pszCaptionText; public IntPtr hbmBanner; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal class SEC_WINNT_AUTH_IDENTITY_EX { public uint Version; public uint Length; public string User; public uint UserLength; public string Domain; public uint DomainLength; public string Password; public uint PasswordLength; public uint Flags; public string PackageList; public uint PackageListLength; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SID_AND_ATTRIBUTES { internal IntPtr Sid; internal uint Attributes; internal static readonly long SizeOf = (long)Marshal.SizeOf(typeof(SID_AND_ATTRIBUTES)); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TOKEN_GROUPS { internal uint GroupCount; internal SID_AND_ATTRIBUTES Groups; // SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY]; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct PLAINTEXTKEYBLOBHEADER { internal byte bType; internal byte bVersion; internal short reserved; internal int aiKeyAlg; internal int keyLength; internal static readonly int SizeOf = Marshal.SizeOf(typeof(PLAINTEXTKEYBLOBHEADER)); }; [StructLayout(LayoutKind.Sequential)] internal struct LUID { internal uint LowPart; internal uint HighPart; } [StructLayout(LayoutKind.Sequential)] internal struct LUID_AND_ATTRIBUTES { internal LUID Luid; internal uint Attributes; } [StructLayout(LayoutKind.Sequential)] internal struct TOKEN_PRIVILEGE { internal uint PrivilegeCount; internal LUID_AND_ATTRIBUTES Privilege; internal static readonly uint Size = (uint)Marshal.SizeOf(typeof(TOKEN_PRIVILEGE)); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct UNICODE_INTPTR_STRING { internal UNICODE_INTPTR_STRING(int length, int maximumLength, IntPtr buffer) { this.Length = (ushort)length; this.MaxLength = (ushort)maximumLength; this.Buffer = buffer; } internal ushort Length; internal ushort MaxLength; internal IntPtr Buffer; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct KERB_CERTIFICATE_S4U_LOGON { internal KERB_LOGON_SUBMIT_TYPE MessageType; internal uint Flags; internal UNICODE_INTPTR_STRING UserPrincipalName; // OPTIONAL, certificate mapping hints: username or username@domain internal UNICODE_INTPTR_STRING DomainName; // used to locate the forest // OPTIONAL, certificate mapping hints: if missing, using the local machine's domain internal uint CertificateLength; // for the client certificate internal IntPtr Certificate; // for the client certificate, BER encoded internal static int Size = Marshal.SizeOf(typeof(KERB_CERTIFICATE_S4U_LOGON)); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TOKEN_SOURCE { private const int TOKEN_SOURCE_LENGTH = 8; [MarshalAs(UnmanagedType.ByValArray, SizeConst = TOKEN_SOURCE_LENGTH)] internal char[] Name; internal LUID SourceIdentifier; } internal enum KERB_LOGON_SUBMIT_TYPE { KerbInteractiveLogon = 2, KerbSmartCardLogon = 6, KerbWorkstationUnlockLogon = 7, KerbSmartCardUnlockLogon = 8, KerbProxyLogon = 9, KerbTicketLogon = 10, KerbTicketUnlockLogon = 11, //#if (_WIN32_WINNT >= 0x0501) -- Disabled until IIS fixes their target version. KerbS4ULogon = 12, //#endif //#if (_WIN32_WINNT >= 0x0600) KerbCertificateLogon = 13, KerbCertificateS4ULogon = 14, KerbCertificateUnlockLogon = 15, //#endif } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct QUOTA_LIMITS { internal IntPtr PagedPoolLimit; internal IntPtr NonPagedPoolLimit; internal IntPtr MinimumWorkingSetSize; internal IntPtr MaximumWorkingSetSize; internal IntPtr PagefileLimit; internal IntPtr TimeLimit; } internal enum SECURITY_IMPERSONATION_LEVEL { Anonymous = 0, Identification = 1, Impersonation = 2, Delegation = 3, } internal enum TokenType : int { TokenPrimary = 1, TokenImpersonation } internal enum SecurityLogonType : int { Interactive = 2, Network, Batch, Service, Proxy, Unlock } [SuppressUnmanagedCodeSecurity] static class NativeMethods { const string ADVAPI32 = "advapi32.dll"; const string KERNEL32 = "kernel32.dll"; const string SECUR32 = "secur32.dll"; const string CREDUI = "credui.dll"; // Error codes from ntstatus.h //internal const uint STATUS_SOME_NOT_MAPPED = 0x00000107; internal const uint STATUS_NO_MEMORY = 0xC0000017; //internal const uint STATUS_NONE_MAPPED = 0xC0000073; internal const uint STATUS_INSUFFICIENT_RESOURCES = 0xC000009A; internal const uint STATUS_ACCESS_DENIED = 0xC0000022; // From WinStatus.h internal const uint STATUS_ACCOUNT_RESTRICTION = 0xC000006E; internal static byte[] LsaSourceName = new byte[] { (byte)'W', (byte)'C', (byte)'F' }; // we set the source name to "WCF". internal static byte[] LsaKerberosName = new byte[] { (byte)'K', (byte)'e', (byte)'r', (byte)'b', (byte)'e', (byte)'r', (byte)'o', (byte)'s' }; internal const uint KERB_CERTIFICATE_S4U_LOGON_FLAG_CHECK_DUPLICATES = 0x1; internal const uint KERB_CERTIFICATE_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2; // Error codes from WinError.h internal const int ERROR_ACCESS_DENIED = 0x5; internal const int ERROR_BAD_LENGTH = 0x18; internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; internal const uint SE_GROUP_ENABLED = 0x00000004; internal const uint SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010; internal const uint SE_GROUP_LOGON_ID = 0xC0000000; internal const int PROV_RSA_AES = 24; internal const int KP_IV = 1; internal const uint CRYPT_DELETEKEYSET = 0x00000010; internal const uint CRYPT_VERIFYCONTEXT = 0xF0000000; internal const byte PLAINTEXTKEYBLOB = 0x8; internal const byte CUR_BLOB_VERSION = 0x2; internal const int ALG_CLASS_DATA_ENCRYPT = (3 << 13); internal const int ALG_TYPE_BLOCK = (3 << 9); internal const int CALG_AES_128 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 14); internal const int CALG_AES_192 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 15); internal const int CALG_AES_256 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 16); [DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern bool LogonUser( [In] string lpszUserName, [In] string lpszDomain, [In] string lpszPassword, [In] uint dwLogonType, [In] uint dwLogonProvider, [Out] out SafeCloseHandle phToken ); [DllImport(ADVAPI32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern bool GetTokenInformation( [In] IntPtr tokenHandle, [In] uint tokenInformationClass, [In] SafeHGlobalHandle tokenInformation, [In] uint tokenInformationLength, [Out] out uint returnLength); [DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern bool CryptAcquireContextW( [Out] out SafeProvHandle phProv, [In] string pszContainer, [In] string pszProvider, [In] uint dwProvType, [In] uint dwFlags ); [DllImport(ADVAPI32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static extern bool CryptImportKey( [In] SafeProvHandle hProv, [In] void* pbData, [In] uint dwDataLen, [In] IntPtr hPubKey, [In] uint dwFlags, [Out] out SafeKeyHandle phKey ); [DllImport(ADVAPI32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern bool CryptGetKeyParam( [In] SafeKeyHandle phKey, [In] uint dwParam, [In] IntPtr pbData, [In, Out] ref uint dwDataLen, [In] uint dwFlags ); [DllImport(ADVAPI32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal unsafe static extern bool CryptSetKeyParam( [In] SafeKeyHandle phKey, [In] uint dwParam, [In] void* pbData, [In] uint dwFlags ); [DllImport(ADVAPI32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceExposure(ResourceScope.None)] unsafe internal static extern bool CryptEncrypt( [In] SafeKeyHandle phKey, [In] IntPtr hHash, [In] bool final, [In] uint dwFlags, [In] void* pbData, [In, Out] ref int dwDataLen, [In] int dwBufLen ); [DllImport(ADVAPI32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceExposure(ResourceScope.None)] unsafe internal static extern bool CryptDecrypt( [In] SafeKeyHandle phKey, [In] IntPtr hHash, [In] bool final, [In] uint dwFlags, [In] void* pbData, [In, Out] ref int dwDataLen ); [DllImport(ADVAPI32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern bool CryptDestroyKey( [In] IntPtr phKey ); [DllImport(ADVAPI32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern bool CryptReleaseContext( [In] IntPtr hProv, [In] uint dwFlags ); [DllImport(ADVAPI32, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern bool LookupPrivilegeValueW( [In] string lpSystemName, [In] string lpName, [Out] out LUID Luid ); [DllImport(ADVAPI32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern bool AdjustTokenPrivileges( [In] SafeCloseHandle tokenHandle, [In] bool disableAllPrivileges, [In] ref TOKEN_PRIVILEGE newState, [In] uint bufferLength, [Out] out TOKEN_PRIVILEGE previousState, [Out] out uint returnLength ); [DllImport(ADVAPI32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern bool RevertToSelf(); [DllImport(ADVAPI32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceConsumption(ResourceScope.Process)] [ResourceExposure(ResourceScope.Process)] internal static extern bool OpenProcessToken( [In] IntPtr processToken, [In] TokenAccessLevels desiredAccess, [Out] out SafeCloseHandle tokenHandle ); [DllImport(ADVAPI32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern bool OpenThreadToken( [In] IntPtr threadHandle, [In] TokenAccessLevels desiredAccess, [In] bool openAsSelf, [Out] out SafeCloseHandle tokenHandle ); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceExposure(ResourceScope.Process)] internal static extern IntPtr GetCurrentProcess(); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern IntPtr GetCurrentThread(); [DllImport(ADVAPI32, CharSet = CharSet.Auto, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern bool DuplicateTokenEx( [In] SafeCloseHandle existingTokenHandle, [In] TokenAccessLevels desiredAccess, [In] IntPtr tokenAttributes, [In] SECURITY_IMPERSONATION_LEVEL impersonationLevel, [In] TokenType tokenType, [Out] out SafeCloseHandle duplicateTokenHandle ); [DllImport(ADVAPI32, CharSet = CharSet.Auto, SetLastError = true)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [ResourceExposure(ResourceScope.None)] internal static extern bool SetThreadToken( [In] IntPtr threadHandle, [In] SafeCloseHandle threadToken ); [DllImport(SECUR32, CharSet = CharSet.Auto, SetLastError = false)] [ResourceExposure(ResourceScope.None)] internal static extern int LsaRegisterLogonProcess( [In] ref UNICODE_INTPTR_STRING logonProcessName, [Out] out SafeLsaLogonProcessHandle lsaHandle, [Out] out IntPtr securityMode ); [DllImport(SECUR32, CharSet = CharSet.Auto, SetLastError = false)] [ResourceExposure(ResourceScope.None)] internal static extern int LsaConnectUntrusted( [Out] out SafeLsaLogonProcessHandle lsaHandle ); [DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = false)] [ResourceExposure(ResourceScope.None)] internal static extern int LsaNtStatusToWinError( [In] int status ); [DllImport(SECUR32, CharSet = CharSet.Auto, SetLastError = false)] [ResourceExposure(ResourceScope.None)] internal static extern int LsaLookupAuthenticationPackage( [In] SafeLsaLogonProcessHandle lsaHandle, [In] ref UNICODE_INTPTR_STRING packageName, [Out] out uint authenticationPackage ); [DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern bool AllocateLocallyUniqueId( [Out] out LUID Luid ); [DllImport(SECUR32, SetLastError = false)] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern int LsaFreeReturnBuffer( IntPtr handle ); [DllImport(SECUR32, CharSet = CharSet.Auto, SetLastError = false)] [ResourceExposure(ResourceScope.None)] internal static extern int LsaLogonUser( [In] SafeLsaLogonProcessHandle LsaHandle, [In] ref UNICODE_INTPTR_STRING OriginName, [In] SecurityLogonType LogonType, [In] uint AuthenticationPackage, [In] IntPtr AuthenticationInformation, [In] uint AuthenticationInformationLength, [In] IntPtr LocalGroups, [In] ref TOKEN_SOURCE SourceContext, [Out] out SafeLsaReturnBufferHandle ProfileBuffer, [Out] out uint ProfileBufferLength, [Out] out LUID LogonId, [Out] out SafeCloseHandle Token, [Out] out QUOTA_LIMITS Quotas, [Out] out int SubStatus ); [DllImport(SECUR32, CharSet = CharSet.Auto, SetLastError = false)] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern int LsaDeregisterLogonProcess( [In] IntPtr handle ); [DllImport(CREDUI, CharSet = CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal unsafe static extern uint SspiPromptForCredentials( string pszTargetName, ref CREDUI_INFO pUiInfo, uint dwAuthError, string pszPackage, IntPtr authIdentity, out IntPtr ppAuthIdentity, [MarshalAs(UnmanagedType.Bool)] ref bool pfSave, uint dwFlags ); [DllImport(CREDUI, CharSet = CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.None)] [return: MarshalAs(UnmanagedType.U1)] internal unsafe static extern bool SspiIsPromptingNeeded(uint ErrorOrNtStatus); [DllImport(SECUR32, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.U1)] internal extern static bool TranslateName( string input, EXTENDED_NAME_FORMAT inputFormat, EXTENDED_NAME_FORMAT outputFormat, StringBuilder outputString, out uint size ); } }
// 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.ComponentModel; using System.Collections.Generic; using System.Collections.Specialized; using WebsitePanel.Providers.ResultObjects; namespace WebsitePanel.Providers.Web { /// <summary> /// Summary description for WebSiteItem. /// </summary> [Serializable] public class WebSite : WebVirtualDirectory { #region String constants public const string IIS7_SITE_ID = "WebSiteId_IIS7"; public const string IIS7_LOG_EXT_FILE_FIELDS = "IIS7_LogExtFileFields"; #endregion private string siteId; private string siteIPAddress; private int siteIPAddressId; private bool isDedicatedIP; private string dataPath; private ServerBinding[] bindings; private bool frontPageAvailable; private bool frontPageInstalled; private bool coldFusionAvailable; private bool createCFVirtualDirectories; private bool createCFVirtualDirectoriesPol; private string frontPageAccount; private string frontPagePassword; private string coldFusionVersion; private ServerState siteState; private bool securedFoldersInstalled; private bool heliconApeInstalled; private bool heliconApeEnabled; private HeliconApeStatus heliconApeStatus; private bool sniEnabled; private string siteInternalIPAddress; public WebSite() { } [Persistent] public string SiteId { get { return siteId; } set { siteId = value; } } public string SiteIPAddress { get { return siteIPAddress; } set { siteIPAddress = value; } } [Persistent] public int SiteIPAddressId { get { return siteIPAddressId; } set { siteIPAddressId = value; } } public bool IsDedicatedIP { get { return isDedicatedIP; } set { isDedicatedIP = value; } } /// <summary> /// Gets or sets logs path for the web site /// </summary> [Persistent] public string LogsPath { get; set; } [Persistent] public string DataPath { get { return dataPath; } set { dataPath = value; } } public ServerBinding[] Bindings { get { return bindings; } set { bindings = value; } } [Persistent] public string FrontPageAccount { get { return this.frontPageAccount; } set { this.frontPageAccount = value; } } [Persistent] public string FrontPagePassword { get { return this.frontPagePassword; } set { this.frontPagePassword = value; } } public bool FrontPageAvailable { get { return this.frontPageAvailable; } set { this.frontPageAvailable = value; } } public bool FrontPageInstalled { get { return this.frontPageInstalled; } set { this.frontPageInstalled = value; } } public bool ColdFusionAvailable { get { return this.coldFusionAvailable; } set { this.coldFusionAvailable = value; } } public string ColdFusionVersion { get { return this.coldFusionVersion; } set { this.coldFusionVersion = value; } } public bool CreateCFVirtualDirectories { get { return this.createCFVirtualDirectories; } set { this.createCFVirtualDirectories = value; } } public bool CreateCFVirtualDirectoriesPol { get { return this.createCFVirtualDirectoriesPol; } set { this.createCFVirtualDirectoriesPol = value; } } public ServerState SiteState { get { return this.siteState; } set { this.siteState = value; } } public bool SecuredFoldersInstalled { get { return this.securedFoldersInstalled; } set { this.securedFoldersInstalled = value; } } public bool HeliconApeInstalled { get { return this.heliconApeInstalled; } set { this.heliconApeInstalled = value; } } public bool HeliconApeEnabled { get { return this.heliconApeEnabled; } set { this.heliconApeEnabled = value; } } public HeliconApeStatus HeliconApeStatus { get { return this.heliconApeStatus; } set { this.heliconApeStatus = value; } } public bool SniEnabled { get { return this.sniEnabled; } set { this.sniEnabled = value; } } public string SiteInternalIPAddress { get { return siteInternalIPAddress; } set { siteInternalIPAddress = value; } } } [Flags] public enum SiteAppPoolMode { Dedicated = 1, Shared = 2, Classic = 4, Integrated = 8, dotNetFramework1 = 16, dotNetFramework2 = 32, dotNetFramework4 = 64 }; public class WSHelper { public const int IIS6 = 0; public const int IIS7 = 1; // public static Dictionary<SiteAppPoolMode, string[]> MMD = new Dictionary<SiteAppPoolMode, string[]> { { SiteAppPoolMode.dotNetFramework1, new string[] {"", "v1.1"} }, { SiteAppPoolMode.dotNetFramework2, new string[] {"2.0", "v2.0"} }, { SiteAppPoolMode.dotNetFramework4, new string[] {"4.0", "v4.0"} }, }; public static string InferAppPoolName(string formatString, string siteName, SiteAppPoolMode NHRT) { if (String.IsNullOrEmpty(formatString)) throw new ArgumentNullException("formatString"); // NHRT |= SiteAppPoolMode.Dedicated; // formatString = formatString.Replace("#SITE-NAME#", siteName); // foreach (var fwVersionKey in MMD.Keys) { if ((NHRT & fwVersionKey) == fwVersionKey) { formatString = formatString.Replace("#IIS6-ASPNET-VERSION#", MMD[fwVersionKey][IIS6]); formatString = formatString.Replace("#IIS7-ASPNET-VERSION#", MMD[fwVersionKey][IIS7]); // break; } } // SiteAppPoolMode pipeline = NHRT & (SiteAppPoolMode.Classic | SiteAppPoolMode.Integrated); formatString = formatString.Replace("#PIPELINE-MODE#", pipeline.ToString()); // return formatString.Trim(); } public static string WhatFrameworkVersionIs(SiteAppPoolMode value) { SiteAppPoolMode dotNetVersion = value & (SiteAppPoolMode.dotNetFramework1 | SiteAppPoolMode.dotNetFramework2 | SiteAppPoolMode.dotNetFramework4); // return String.Format("v{0}", MMD[dotNetVersion][IIS7]); } } }
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: 383115 $ * $Date: 2006-03-04 15:21:51 +0100 (sam., 04 mars 2006) $ * * iBATIS.NET Data Mapper * Copyright (C) 2004 - Gilles Bayon * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion using System; using System.Collections; using System.Data; using Castle.DynamicProxy; namespace IBatisNet.Common.Logging { /// <summary> /// Requires at least v1.1.5.0 of Castle.DynamicProxy /// </summary> /// <remarks> /// It is common for the user to expect a DataReader with zero or one DataRecords: /// /// <code> /// if (dr.Read()) /// { /// processDataReader(dr); /// } /// </code> /// /// There is no way to know when the user is done processing the DataReader. There may be a lot more /// code executed before 'dr' is Disposed() or Closed(). When Read() is called, we print out the /// column headers as well as the data from the first DataRecord. /// /// DataReaders with 2 or more DataRecords benefit from a simple cache in which the code to generate the /// log message does not make a call to the underlying _dataReader if the user has already requested the /// value. If a DataRecord contains 50 columns and the user accessed 45 of those, the code to produce the /// log message for the DataRecord will only need to make 5 calls to GetValue(i) for the missing columns /// rather than iterating through all the columns and calling GetValue(i) to retrieve their value. One /// could argue that unaccessed columns should not printed to the log. Since IBatisNet now supports /// discriminator nodes in resultMaps, its important to display everything in the DataRecord /// or else log messages may contain column values that are mis-aligned with column headers (i.e. some /// log messages may have more column values than others when discriminators are in use). /// /// _isFirstRow and _isSecondRow could be replaced with: /// /// <code> /// private int _dataRecordsProcessed = 0; /// </code> /// /// We don't need to maintain a counter for the number of rows processed. We are only concerned with /// the first and second DataRecords. /// </remarks> public class IDataReaderProxy : IInterceptor { private IDataReader _dataReader = null; private bool _isFirstRow = true; private bool _isSecondRow = false; private object[] _columnValuesCache = null; private static readonly ILog _logger = LogManager.GetLogger("System.Data.IDataReader"); private static readonly ArrayList _getters; static IDataReaderProxy() { // the following methods have a 0th argument of type int _getters = new ArrayList(15); _getters.Add("GetInt32"); _getters.Add("GetValue"); _getters.Add("GetBytes"); _getters.Add("GetByte"); _getters.Add("GetDecimal"); _getters.Add("GetInt64"); _getters.Add("GetDouble"); _getters.Add("GetBoolean"); _getters.Add("GetGuid"); _getters.Add("GetDateTime"); _getters.Add("GetFloat"); _getters.Add("GetChars"); _getters.Add("GetString"); _getters.Add("GetChar"); _getters.Add("GetIn16"); } internal IDataReaderProxy(IDataReader dataReader) { _dataReader = dataReader; } public static IDataReader NewInstance(IDataReader dataReader) { IInterceptor handler = new IDataReaderProxy(dataReader); object proxyDataReader = new ProxyGenerator().CreateProxy(typeof(IDataReader), handler, dataReader); return (IDataReader)proxyDataReader; } public object Intercept(IInvocation invocation, params object[] arguments) { if (invocation.Method.Name == "Read") { #region Read() if (_isFirstRow) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < _dataReader.FieldCount; i++) { sb.Append(_dataReader.GetName(i) + ", "); } _logger.Debug("Headers for \"" + _dataReader.GetHashCode() + "\": [" + sb.ToString(0, sb.Length - 2) + "]"); _isFirstRow = false; // advance to the next DataRecord // (bool)invocation.Method.Invoke(_dataReader, arguments); bool read = _dataReader.Read(); if (read == true) { // log values of the first (non-header) DataRecord _columnValuesCache = new object[_dataReader.FieldCount]; logColumnValues(); // if the user has chosen the 'while (dr.Read())' syntax, tell the second DataRecord // that its contents have already been logged _isSecondRow = true; } return read; } else { if (_isSecondRow) { // we've already called logColumnValues() _isSecondRow = false; } else { // the user is most likely iterating through the records using the 'while (dr.Read())' notation logColumnValues(); } _columnValuesCache = new object[_dataReader.FieldCount]; return invocation.Method.Invoke(_dataReader, arguments); } #endregion } else if (_getters.Contains(invocation.Method.Name)) { #region GetInt32(int), GetString(int), GetDateTime(int), etc. // Cache repeated lookups: checking for null is probably faster than calling Invoke ??? object value = _columnValuesCache[(int)arguments[0]]; if (value == null) { value = invocation.Method.Invoke(_dataReader, arguments); _columnValuesCache[(int)arguments[0]] = value; } else { // If someone wrote a custom type handler that makes repeated calls to GetXXXXX(int), we only make one call to Invoke // _logger.Debug("Using cached value for column: [" + (int)arguments[0] + "]"); } return value; #endregion } else { return invocation.Method.Invoke(_dataReader, arguments); } } private void logColumnValues() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < _columnValuesCache.Length; i++) { object value = _columnValuesCache[i]; if (value == null) { // _logger.Debug("Could not find existing value for column [" + i + "]"); value = _dataReader.GetValue(i); if (value == DBNull.Value) { value = "NULL"; } } sb.Append(value + ", "); } // remove trailing comma and space if (sb.Length > 2) { sb.Length -= 2; } _logger.Debug("Results for \"" + _dataReader.GetHashCode() + "\": [" + sb.ToString() + "]"); } } }
//----------------------------------------------------------------------------- // // <copyright file="Errors.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // This file contains Error Constants defined by the promethium SDK and an exception mapping mechanism // // // History: // 06/13/2005: IgorBel: Initial implementation. // //----------------------------------------------------------------------------- using System; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Security.RightsManagement; using System.Windows; using SR=MS.Internal.WindowsBase.SR; using SRID=MS.Internal.WindowsBase.SRID; // Enable presharp pragma warning suppress directives. #pragma warning disable 1634, 1691 namespace MS.Internal.Security.RightsManagement { internal static class Errors { internal static string GetLocalizedFailureCodeMessageWithDefault(RightsManagementFailureCode failureCode) { string errorMessage = GetLocalizedFailureCodeMessage(failureCode); if (errorMessage != null) { return errorMessage; } else { return SR.Get(SRID.RmExceptionGenericMessage); } } /// <summary> /// This function throws the exception if hr doesn't indicate a success. In case of recognized /// Rights Management Failure code it will throw a RightsManagementException with an appropriate /// message. Otherwise, if code isn't recognized as Rights Management specific, it will throw /// RightsManagementException which has a COMException as an inner exception with the /// appropriate hr code. /// </summary> /// <SecurityNote> /// Critical: This code calls into ThrowExceptionForHr which has a link demand /// TreatAsSafe: The net effect is the same as throwing an exception from your app /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal static void ThrowOnErrorCode(int hr) { // we can return if it is not a failure right away // there is no reason to attempt to look-up codes and // messages which is somewhat expensive in the case of success if (hr >=0) { return; } string errorMessage = GetLocalizedFailureCodeMessage((RightsManagementFailureCode)hr); if (errorMessage != null) { throw new RightsManagementException((RightsManagementFailureCode)hr, errorMessage); } else { try { // It seems that ThrowExceptionForHR is the most consistent way // to get a platform representation of the unmanaged HR code Marshal.ThrowExceptionForHR(hr); } // disabling PreSharp false positive. In this case we are actually re-throwing the same exception // wrapped in a more specific message #pragma warning disable 56500 catch (Exception e) { // rethrow the exception as an inner exception of the RmExceptionGenericMessage throw new RightsManagementException(SR.Get(SRID.RmExceptionGenericMessage), e); } #pragma warning restore 56500 } } private static string GetLocalizedFailureCodeMessage(RightsManagementFailureCode failureCode) { string result; switch (failureCode) { case RightsManagementFailureCode.InvalidLicense: result=SRID.RmExceptionInvalidLicense; break; case RightsManagementFailureCode.InfoNotInLicense: result=SRID.RmExceptionInfoNotInLicense; break; case RightsManagementFailureCode.InvalidLicenseSignature: result=SRID.RmExceptionInvalidLicenseSignature; break; case RightsManagementFailureCode.EncryptionNotPermitted: result=SRID.RmExceptionEncryptionNotPermitted; break; case RightsManagementFailureCode.RightNotGranted: result=SRID.RmExceptionRightNotGranted; break; case RightsManagementFailureCode.InvalidVersion: result=SRID.RmExceptionInvalidVersion; break; case RightsManagementFailureCode.InvalidEncodingType: result=SRID.RmExceptionInvalidEncodingType; break; case RightsManagementFailureCode.InvalidNumericalValue: result=SRID.RmExceptionInvalidNumericalValue; break; case RightsManagementFailureCode.InvalidAlgorithmType: result=SRID.RmExceptionInvalidAlgorithmType; break; case RightsManagementFailureCode.EnvironmentNotLoaded: result=SRID.RmExceptionEnvironmentNotLoaded; break; case RightsManagementFailureCode.EnvironmentCannotLoad: result=SRID.RmExceptionEnvironmentCannotLoad; break; case RightsManagementFailureCode.TooManyLoadedEnvironments: result=SRID.RmExceptionTooManyLoadedEnvironments; break; case RightsManagementFailureCode.IncompatibleObjects: result=SRID.RmExceptionIncompatibleObjects; break; case RightsManagementFailureCode.LibraryFail: result=SRID.RmExceptionLibraryFail; break; case RightsManagementFailureCode.EnablingPrincipalFailure: result=SRID.RmExceptionEnablingPrincipalFailure; break; case RightsManagementFailureCode.InfoNotPresent: result=SRID.RmExceptionInfoNotPresent; break; case RightsManagementFailureCode.BadGetInfoQuery: result=SRID.RmExceptionBadGetInfoQuery; break; case RightsManagementFailureCode.KeyTypeUnsupported: result=SRID.RmExceptionKeyTypeUnsupported; break; case RightsManagementFailureCode.CryptoOperationUnsupported: result=SRID.RmExceptionCryptoOperationUnsupported; break; case RightsManagementFailureCode.ClockRollbackDetected: result=SRID.RmExceptionClockRollbackDetected; break; case RightsManagementFailureCode.QueryReportsNoResults: result=SRID.RmExceptionQueryReportsNoResults; break; case RightsManagementFailureCode.UnexpectedException: result=SRID.RmExceptionUnexpectedException; break; case RightsManagementFailureCode.BindValidityTimeViolated: result=SRID.RmExceptionBindValidityTimeViolated; break; case RightsManagementFailureCode.BrokenCertChain: result=SRID.RmExceptionBrokenCertChain; break; case RightsManagementFailureCode.BindPolicyViolation: result=SRID.RmExceptionBindPolicyViolation; break; case RightsManagementFailureCode.ManifestPolicyViolation: result=SRID.RmExceptionManifestPolicyViolation; break; case RightsManagementFailureCode.BindRevokedLicense: result=SRID.RmExceptionBindRevokedLicense; break; case RightsManagementFailureCode.BindRevokedIssuer: result=SRID.RmExceptionBindRevokedIssuer; break; case RightsManagementFailureCode.BindRevokedPrincipal: result=SRID.RmExceptionBindRevokedPrincipal; break; case RightsManagementFailureCode.BindRevokedResource: result=SRID.RmExceptionBindRevokedResource; break; case RightsManagementFailureCode.BindRevokedModule: result=SRID.RmExceptionBindRevokedModule; break; case RightsManagementFailureCode.BindContentNotInEndUseLicense: result=SRID.RmExceptionBindContentNotInEndUseLicense; break; case RightsManagementFailureCode.BindAccessPrincipalNotEnabling: result=SRID.RmExceptionBindAccessPrincipalNotEnabling; break; case RightsManagementFailureCode.BindAccessUnsatisfied: result=SRID.RmExceptionBindAccessUnsatisfied; break; case RightsManagementFailureCode.BindIndicatedPrincipalMissing: result=SRID.RmExceptionBindIndicatedPrincipalMissing; break; case RightsManagementFailureCode.BindMachineNotFoundInGroupIdentity: result=SRID.RmExceptionBindMachineNotFoundInGroupIdentity; break; case RightsManagementFailureCode.LibraryUnsupportedPlugIn: result=SRID.RmExceptionLibraryUnsupportedPlugIn; break; case RightsManagementFailureCode.BindRevocationListStale: result=SRID.RmExceptionBindRevocationListStale; break; case RightsManagementFailureCode.BindNoApplicableRevocationList: result=SRID.RmExceptionBindNoApplicableRevocationList; break; case RightsManagementFailureCode.InvalidHandle: result=SRID.RmExceptionInvalidHandle; break; case RightsManagementFailureCode.BindIntervalTimeViolated: result=SRID.RmExceptionBindIntervalTimeViolated; break; case RightsManagementFailureCode.BindNoSatisfiedRightsGroup: result=SRID.RmExceptionBindNoSatisfiedRightsGroup; break; case RightsManagementFailureCode.BindSpecifiedWorkMissing: result=SRID.RmExceptionBindSpecifiedWorkMissing; break; case RightsManagementFailureCode.NoMoreData: result=SRID.RmExceptionNoMoreData; break; case RightsManagementFailureCode.LicenseAcquisitionFailed: result=SRID.RmExceptionLicenseAcquisitionFailed; break; case RightsManagementFailureCode.IdMismatch: result=SRID.RmExceptionIdMismatch; break; case RightsManagementFailureCode.TooManyCertificates: result=SRID.RmExceptionTooManyCertificates; break; case RightsManagementFailureCode.NoDistributionPointUrlFound: result=SRID.RmExceptionNoDistributionPointUrlFound; break; case RightsManagementFailureCode.AlreadyInProgress: result=SRID.RmExceptionAlreadyInProgress; break; case RightsManagementFailureCode.GroupIdentityNotSet: result=SRID.RmExceptionGroupIdentityNotSet; break; case RightsManagementFailureCode.RecordNotFound: result=SRID.RmExceptionRecordNotFound; break; case RightsManagementFailureCode.NoConnect: result=SRID.RmExceptionNoConnect; break; case RightsManagementFailureCode.NoLicense: result=SRID.RmExceptionNoLicense; break; case RightsManagementFailureCode.NeedsMachineActivation: result=SRID.RmExceptionNeedsMachineActivation; break; case RightsManagementFailureCode.NeedsGroupIdentityActivation: result=SRID.RmExceptionNeedsGroupIdentityActivation; break; case RightsManagementFailureCode.ActivationFailed: result=SRID.RmExceptionActivationFailed; break; case RightsManagementFailureCode.Aborted: result=SRID.RmExceptionAborted; break; case RightsManagementFailureCode.OutOfQuota: result=SRID.RmExceptionOutOfQuota; break; case RightsManagementFailureCode.AuthenticationFailed: result=SRID.RmExceptionAuthenticationFailed; break; case RightsManagementFailureCode.ServerError: result=SRID.RmExceptionServerError; break; case RightsManagementFailureCode.InstallationFailed: result=SRID.RmExceptionInstallationFailed; break; case RightsManagementFailureCode.HidCorrupted: result=SRID.RmExceptionHidCorrupted; break; case RightsManagementFailureCode.InvalidServerResponse: result=SRID.RmExceptionInvalidServerResponse; break; case RightsManagementFailureCode.ServiceNotFound: result=SRID.RmExceptionServiceNotFound; break; case RightsManagementFailureCode.UseDefault: result=SRID.RmExceptionUseDefault; break; case RightsManagementFailureCode.ServerNotFound: result=SRID.RmExceptionServerNotFound; break; case RightsManagementFailureCode.InvalidEmail: result=SRID.RmExceptionInvalidEmail; break; case RightsManagementFailureCode.ValidityTimeViolation: result=SRID.RmExceptionValidityTimeViolation; break; case RightsManagementFailureCode.OutdatedModule: result=SRID.RmExceptionOutdatedModule; break; case RightsManagementFailureCode.ServiceMoved: result=SRID.RmExceptionServiceMoved; break; case RightsManagementFailureCode.ServiceGone: result=SRID.RmExceptionServiceGone; break; case RightsManagementFailureCode.AdEntryNotFound: result=SRID.RmExceptionAdEntryNotFound; break; case RightsManagementFailureCode.NotAChain: result=SRID.RmExceptionNotAChain; break; case RightsManagementFailureCode.RequestDenied: result=SRID.RmExceptionRequestDenied; break; case RightsManagementFailureCode.NotSet: result=SRID.RmExceptionNotSet; break; case RightsManagementFailureCode.MetadataNotSet: result=SRID.RmExceptionMetadataNotSet; break; case RightsManagementFailureCode.RevocationInfoNotSet: result=SRID.RmExceptionRevocationInfoNotSet; break; case RightsManagementFailureCode.InvalidTimeInfo: result=SRID.RmExceptionInvalidTimeInfo; break; case RightsManagementFailureCode.RightNotSet: result=SRID.RmExceptionRightNotSet; break; case RightsManagementFailureCode.LicenseBindingToWindowsIdentityFailed: result=SRID.RmExceptionLicenseBindingToWindowsIdentityFailed; break; case RightsManagementFailureCode.InvalidIssuanceLicenseTemplate: result=SRID.RmExceptionInvalidIssuanceLicenseTemplate; break; case RightsManagementFailureCode.InvalidKeyLength: result=SRID.RmExceptionInvalidKeyLength; break; case RightsManagementFailureCode.ExpiredOfficialIssuanceLicenseTemplate: result=SRID.RmExceptionExpiredOfficialIssuanceLicenseTemplate; break; case RightsManagementFailureCode.InvalidClientLicensorCertificate: result=SRID.RmExceptionInvalidClientLicensorCertificate; break; case RightsManagementFailureCode.HidInvalid: result=SRID.RmExceptionHidInvalid; break; case RightsManagementFailureCode.EmailNotVerified: result=SRID.RmExceptionEmailNotVerified; break; case RightsManagementFailureCode.DebuggerDetected: result=SRID.RmExceptionDebuggerDetected; break; case RightsManagementFailureCode.InvalidLockboxType: result=SRID.RmExceptionInvalidLockboxType; break; case RightsManagementFailureCode.InvalidLockboxPath: result=SRID.RmExceptionInvalidLockboxPath; break; case RightsManagementFailureCode.InvalidRegistryPath: result=SRID.RmExceptionInvalidRegistryPath; break; case RightsManagementFailureCode.NoAesCryptoProvider: result=SRID.RmExceptionNoAesCryptoProvider; break; case RightsManagementFailureCode.GlobalOptionAlreadySet: result=SRID.RmExceptionGlobalOptionAlreadySet; break; case RightsManagementFailureCode.OwnerLicenseNotFound: result=SRID.RmExceptionOwnerLicenseNotFound; break; default: return null; } return SR.Get(result); } } }
// Copyright (c) 2017 Jan Pluskal // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. using System; using System.Collections.Generic; using System.Linq; using Netfox.Core.Enums; using Netfox.Framework.CaptureProcessor.L7Tracking.CustomCollections; using Netfox.Framework.Models; using Netfox.Framework.Models.PmLib.Frames; namespace Netfox.Framework.CaptureProcessor.L7Tracking.TCP { internal class TCPFlowReassembler { public TCPFlowReassembler(L4Conversation l4Conversation, FlowStore flowStore, TimeSpan tcpSessionAliveTimeout, long tcpSessionMaxDataLooseOnTCPLoop) { this.L4Conversation = l4Conversation; this.FlowStore = flowStore; this.TCPSessionAliveTimeout = tcpSessionAliveTimeout; this.TCPSessionMaxDataLooseOnTCPLoop = tcpSessionMaxDataLooseOnTCPLoop; } public L4Conversation L4Conversation { get; } public FlowStore FlowStore { get; } public uint ExpectedSequenceNumber { get; set; } private FsUnidirectionalFlow CurrentTCPFlow { get; set; } private LinkedIterableList<PmFrameBase>.Enumerator TCPFlowEnumerator { get; set; } private DaRFlowDirection FlowDirection { get; set; } private DaRFrameCollection TCPSynOrderedFrames { get; set; } private L7PDU CurrentPDU { get; set; } private DateTime LastTimestamp { get; set; } private PmFrameBase CurrentFrame { get; set; } private TimeSpan TCPSessionAliveTimeout { get; } private long TCPSessionMaxDataLooseOnTCPLoop { get; } public void ProcessTCPSession(FramesSequenceNumberSortedCollection tcpFlow, DaRFlowDirection flowDirection) { this.TCPSynOrderedFrames = new DaRFrameCollection(tcpFlow.Values); this.FlowDirection = flowDirection; foreach(var synFrame in this.TCPSynOrderedFrames) { this.ProcessTcpSession(synFrame); } while(this.TCPSynOrderedFrames.Any()) { this.ProcessTcpSession(this.TCPSynOrderedFrames.First.Value); } } /// <summary> Adds a non data frame.</summary> private void AddNonDataFrame() => this.CurrentTCPFlow.NonDataFrames.Add(this.CurrentFrame); /// <summary> Adds a non data frame.</summary> /// <param name="frame"> The frame. </param> private void AddNonDataFrame(PmFrameBase frame) => this.CurrentTCPFlow.NonDataFrames.Add(frame); private IEnumerable<PmFrameBase> FindFragments(PmFrameBase firstFrame, out Int64 extractedBytes) { // _log.Info(String.Format("Located IPv4 fragmented frame {0}", firstFrame)); extractedBytes = 0; var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var limit = 2 * 60 * 1000; // max difference in timestamps of two IPv4 fragments //Select framew with the same Ipv4FIdentification var list = from frame in this.L4Conversation.L3Conversation.NonL4Frames //CaptureProcessor.CaptureProcessor.GetRealFramesEnumerable() where frame.Ipv4FIdentification == firstFrame.Ipv4FIdentification orderby frame.Ipv4FragmentOffset select frame; //IOrderedEnumerable<PmFrameBase> list = from frame in _currentFlow.RealFrames // where frame.Ipv4FIdentification == firstFrame.Ipv4FIdentification // orderby frame.Ipv4FragmentOffset // select frame; //List of ordered fragments var fragmentList = new List<PmFrameBase> { firstFrame }; //Process of defragmentation var expectedOffset = (Int64) Math.Ceiling((firstFrame.IncludedLength - (firstFrame.L7Offset - firstFrame.L2Offset)) / (Double) 8) + 1; while(true) { var currentFrameList = list.Where(frame => frame.Ipv4FragmentOffset == expectedOffset); if(!currentFrameList.Any()) { return null; } var bestFrame = currentFrameList.Aggregate( (curmin, x) => (curmin == null || Math.Abs((x.TimeStamp - firstFrame.TimeStamp).TotalMilliseconds) < (curmin.TimeStamp - epoch).TotalMilliseconds? x : curmin)); if(Math.Abs((bestFrame.TimeStamp - firstFrame.TimeStamp).TotalMilliseconds) > limit) { return null; } fragmentList.Add(bestFrame); if(bestFrame.Ipv4FMf == false) { extractedBytes = expectedOffset * 8 + bestFrame.L7PayloadLength - 8; //8 - UDP header size break; } expectedOffset += (Int64) Math.Ceiling(bestFrame.L7PayloadLength / (Double) 8); } //foreach(var frame in fragmentList) { this.L4Conversation.L3Conversation.NonL4Frames.Remove(frame); } //todo! release references to already used frames return fragmentList; } // TODO accepted: Ducplicit code with UDPFLowReassembler. private void FiNorRstProcess() { var finorRstSeq = this.CurrentFrame.TcpSequenceNumber; UInt32 nextAck; UInt32 spuriousRetransmissions; //http://blog.packet-foo.com/2013/06/spurious-retransmissions/ example icq1.cap, frame 1056 if(this.CurrentFrame.L7PayloadLength <= 0) { this.AddNonDataFrame(); nextAck = ((UInt32) this.CurrentFrame.TcpSequenceNumber) + 1; spuriousRetransmissions = nextAck; //cannot occur; } else { nextAck = ((UInt32) this.CurrentFrame.TcpSequenceNumber) + ((UInt32) this.CurrentFrame.L7PayloadLength) + 1; spuriousRetransmissions = ((UInt32) this.CurrentFrame.TcpSequenceNumber) + ((UInt32) this.CurrentFrame.L7PayloadLength); } this.NextFrame(); //to consume possible rest of communication ACKs and/or retransmits while(this.CurrentFrame != null && (this.CurrentFrame.TcpSequenceNumber == finorRstSeq || this.CurrentFrame.TcpSequenceNumber == nextAck || this.CurrentFrame.TcpSequenceNumber == spuriousRetransmissions)) { this.AddNonDataFrame(); this.NextFrame(); } } private void NextFrame() { this.LastTimestamp = this.CurrentFrame.TimeStamp; this.TCPFlowEnumerator.RemoveCurrent(); this.TCPFlowEnumerator.MoveNext(); this.CurrentFrame = this.TCPFlowEnumerator.Current; } private void ProcessTcpSession(PmFrameBase synFrame) { var wasTCPSeqLoop = false; this.TCPFlowEnumerator = this.TCPSynOrderedFrames.GetEnumerator(); //find first frame frame of session while(this.TCPFlowEnumerator.Current != synFrame) { if(!this.TCPFlowEnumerator.MoveNext()) { throw new InvalidOperationException("Init frame does not exists!"); } } this.CurrentFrame = this.TCPFlowEnumerator.Current; this.CurrentTCPFlow = this.FlowStore.CreateAndAddFlow(this.FlowDirection); this.LastTimestamp = this.CurrentFrame.TimeStamp; this.CurrentPDU = null; //Init flow direction identifier if(this.CurrentFrame.TcpFSyn && !this.CurrentFrame.TcpFAck) //SYN packet { this.CurrentTCPFlow.FlowIdentifier = this.CurrentFrame.TcpSequenceNumber + 1; } else if(this.CurrentFrame.TcpFSyn && this.CurrentFrame.TcpFAck) //SYN+ACK packet { this.CurrentTCPFlow.FlowIdentifier = this.CurrentFrame.TcpAcknowledgementNumber; } if(this.CurrentFrame.TcpFSyn) { // while in a case that there are more retransmitted frames with SYN flag while(this.CurrentFrame != null && this.CurrentFrame.TcpFSyn && this.CurrentFrame.TcpSequenceNumber == synFrame.TcpSequenceNumber && this.CurrentFrame.TcpAcknowledgementNumber == synFrame.TcpAcknowledgementNumber) { this.ExpectedSequenceNumber = (UInt32) this.CurrentFrame.TcpSequenceNumber + 1; this.AddNonDataFrame(); this.NextFrame(); } // in a case that there are captured only a SYN frames and not the rest of the session if(this.CurrentFrame == null) { return; } } else { this.ExpectedSequenceNumber = (UInt32) this.CurrentFrame.TcpSequenceNumber; } while(this.TestTCPSessionEnd(ref wasTCPSeqLoop)) { if(this.CurrentFrame.IsMalformed) { this.AddNonDataFrame(); this.NextFrame(); continue; } if(this.CurrentFrame.TimeStamp.Subtract(this.LastTimestamp).Duration() > this.TCPSessionAliveTimeout) { this.SkipFrame(); continue; } if(this.CurrentPDU == null) { this.CurrentPDU = this.CurrentTCPFlow.CreateL7PDU(); } var x = this.CurrentFrame.TcpSequenceNumber - this.ExpectedSequenceNumber; if(x > 0) { this.TCPMissingSegment(x); } else if(x < 0) { //in case that packet is TCPSyn retranssmit //if (_currentFrame.TcpFSyn || _currentFrame.TcpFFin || _currentFrame.TcpFRst) //{ // NextFrame(); // continue; //} // TCP keep live packet, TCP ACK if(this.CurrentFrame.TcpFAck && (this.CurrentFrame.L7PayloadLength == -1 || this.CurrentFrame.L7PayloadLength == 1)) //if (x == -1 && _currentFrame.TcpFAck && (_currentFrame.L7PayloadLength == -1 || _currentFrame.L7PayloadLength == 1)) // && _currentFrame.L7PayloadLength == -1 //could be also _currentFrame.L7PayloadLength == 1 { this.AddNonDataFrame(); this.NextFrame(); //skip keepalive frame continue; } ////TODO find what causes this //if (_currentFrame.L7PayloadLength == -1) //{ // AddNonDataFrame(); // NextFrame(); //skip keepalive frame // continue; //} //in case of retransmission, TCP Checksum must be computed var parsedFrame = this.CurrentFrame.PmPacket; if(parsedFrame.IsValidChecksum) // frame is valid, let's use it { //end of current TCP session if(this.CurrentFrame.TcpFFin || this.CurrentFrame.TcpFRst) { this.FiNorRstProcess(); break; } if(!this.CurrentPDU.FrameList.Any() && // _currentPDU has no frames this.CurrentTCPFlow.PDUs.Any()) // CurrentTCPFlow has some PDUs { this.CurrentPDU = this.CurrentTCPFlow.GetLastPDU(); } if(this.CurrentPDU.FrameList.Any()) // _currentPDU has some frames { var lastPduFrame = this.CurrentPDU.FrameList.Last(); if(this.CurrentFrame.TcpSequenceNumber == lastPduFrame.TcpSequenceNumber && lastPduFrame.PmPacket.IsValidChecksum) { this.AddNonDataFrame(); //end of current L7PDU if((this.CurrentFrame.TcpFPsh || this.CurrentFrame.L7PayloadLength < this.L4Conversation.L4FlowMTU) && this.CurrentPDU.FrameList.Any()) { this.CurrentPDU = null; } this.NextFrame(); continue; } //todo SACK http://superuser.com/questions/598574/if-a-tcp-packet-got-partially-acknowledged-how-will-the-retransmission-mechanis //example tcp_retr1.pcapng 7,8,11,12 frames //this bypass and ignores SACK ... assuming that correct packet have been captred and lost occured on the way if(this.CurrentFrame.TcpSequenceNumber > lastPduFrame.TcpSequenceNumber && x < lastPduFrame.L7PayloadLength && lastPduFrame.PmPacket.IsValidChecksum) { this.AddNonDataFrame(); //end of current L7PDU if((this.CurrentFrame.TcpFPsh || this.CurrentFrame.L7PayloadLength < this.L4Conversation.L4FlowMTU) && this.CurrentPDU.FrameList.Any()) { this.CurrentPDU = null; } this.NextFrame(); continue; } var removedFrame = this.CurrentPDU.RemoveLastFrame(); this.AddNonDataFrame(removedFrame); } else // _currentPDU has no frames, get rid of it { this.CurrentTCPFlow.RemoveL7PDU(this.CurrentPDU); this.CurrentPDU = this.CurrentTCPFlow.CreateL7PDU(); } } else //if checksum is not valid frame is skipped { this.AddNonDataFrame(); //end of current L7PDU if((this.CurrentFrame.TcpFPsh || this.CurrentFrame.L7PayloadLength < this.L4Conversation.L4FlowMTU) && this.CurrentPDU.FrameList.Any()) { this.CurrentPDU = null; } this.NextFrame(); continue; } } //else //x == 0{//normal state} //L4PDU add frame to list if(this.CurrentFrame.L7PayloadLength > 0) { if(this.CurrentPDU.LowestTCPSeq == null) { this.CurrentPDU.LowestTCPSeq = this.CurrentFrame.TcpSequenceNumber; } this.CurrentPDU.ExtractedBytes += this.CurrentFrame.L7PayloadLength; this.CurrentPDU.AddFrame(this.CurrentFrame); //If frame is IPv4 fragmented find remaining fragments if(this.CurrentFrame.Ipv4FMf) { Int64 extractedBytes; var defragmentedFrames = this.FindFragments(this.CurrentFrame, out extractedBytes); this.CurrentPDU.RemoveLastFrame(); this.CurrentPDU.ExtractedBytes -= this.CurrentFrame.L7PayloadLength; this.CurrentPDU.AddFrameRange(defragmentedFrames); this.CurrentPDU.ExtractedBytes += extractedBytes; this.ExpectedSequenceNumber = (UInt32) (this.CurrentFrame.TcpSequenceNumber + extractedBytes); } else { //Normal state, increment expected sequence number this.ExpectedSequenceNumber = (UInt32) (this.CurrentFrame.TcpSequenceNumber + this.CurrentFrame.L7PayloadLength); } } //end of current TCP session if(this.CurrentFrame.TcpFSyn) { break; } if(this.CurrentFrame.TcpFFin || this.CurrentFrame.TcpFRst) { this.FiNorRstProcess(); break; } //end of current L7PDU if((this.CurrentFrame.TcpFPsh || this.CurrentFrame.L7PayloadLength < this.L4Conversation.L4FlowMTU) && this.CurrentPDU.FrameList.Any()) { this.CurrentPDU = null; } if(this.CurrentFrame.L7PayloadLength <= 0) { this.AddNonDataFrame(); } this.NextFrame(); } } /// <summary> Skip frame.</summary> private void SkipFrame() { this.TCPFlowEnumerator.MoveNext(); this.CurrentFrame = this.TCPFlowEnumerator.Current; } /// <summary> TCP missing segment.</summary> /// <param name="x"> The x coordinate. </param> private void TCPMissingSegment(Int64 x) { // we missed segment - insert 0 instead of data: this.CurrentPDU.MissingBytes += x; this.CurrentPDU.MissingFrameSequences++; var vfId = new PmFrameVirtualBlank(this.CurrentFrame,x,this.CurrentFrame.TimeStamp.AddTicks(-1)); while(this.CurrentTCPFlow.VirtualFrames.Contains(vfId)) { vfId.TimeStamp = new DateTime().AddTicks(vfId.TimeStamp.Ticks - 1); } this.CurrentTCPFlow.VirtualFrames.Add(vfId); this.CurrentPDU.AddFrame(vfId); this.CurrentPDU.IsContainingCorruptedData = true; if(this.CurrentPDU.LowestTCPSeq == null) { this.CurrentPDU.LowestTCPSeq = this.ExpectedSequenceNumber; } } private Boolean TestTCPSessionEnd(ref Boolean wasTCPSeqLoop) { //normal state, tcpFlowEnumerator.Current == currentFrame if(this.TCPFlowEnumerator.Current != null && !this.TCPFlowEnumerator.Current.TcpFSyn) { return true; } if(this.TCPFlowEnumerator.Current != null && this.TCPFlowEnumerator.Current.TcpFSyn) { return false; } if(wasTCPSeqLoop) { return false; } wasTCPSeqLoop = true; //at the end of seq numbers, reset structure this.TCPFlowEnumerator.Reset(); this.SkipFrame(); if(this.TCPFlowEnumerator.Current == null || this.TCPFlowEnumerator.Current.TcpFSyn) { return false; } //return tcpFlowEnumerator.Current.TcpSequenceNumber - _expectedSequenceNumber < TCP_SESSION_MAX_DATA_LOOSE_ON_TCP_LOOP; //looking for exact match, frame that is next in tcp seq number sequence while(this.TCPFlowEnumerator.Current != null && this.TCPFlowEnumerator.Current.TcpSequenceNumber - this.ExpectedSequenceNumber < this.TCPSessionMaxDataLooseOnTCPLoop) { if(this.TCPFlowEnumerator.Current.TcpSequenceNumber - this.ExpectedSequenceNumber == 0) { return true; } this.SkipFrame(); } //at the end of possible seq numbers, reset structure this.TCPFlowEnumerator.Reset(); this.SkipFrame(); //looking for tolerable match, some data are missing but in tolrance of TCP_SESSION_MAX_DATA_LOOSE_ON_TCP_LOOP //frame is identify by occurrence in TCP_SESSION_ALIVE_TIMEOUT interval while(this.TCPFlowEnumerator.Current != null && this.TCPFlowEnumerator.Current.TcpSequenceNumber - this.ExpectedSequenceNumber < this.TCPSessionMaxDataLooseOnTCPLoop) { if(this.CurrentFrame.TimeStamp.Subtract(this.LastTimestamp).Duration() < this.TCPSessionAliveTimeout) { return true; } this.SkipFrame(); } return false; } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Feed Item ///<para>SObject Name: FeedItem</para> ///<para>Custom Object: False</para> ///</summary> public class SfFeedItem : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "FeedItem"; } } ///<summary> /// Feed Item ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Parent ID /// <para>Name: ParentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "parentId")] [Updateable(false), Createable(true)] public string ParentId { get; set; } ///<summary> /// Feed Item Type /// <para>Name: Type</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "type")] [Updateable(false), Createable(true)] public string Type { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(true)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(true)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Revision /// <para>Name: Revision</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "revision")] [Updateable(false), Createable(true)] public int? Revision { get; set; } ///<summary> /// Last Edit By ID /// <para>Name: LastEditById</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastEditById")] [Updateable(false), Createable(true)] public string LastEditById { get; set; } ///<summary> /// Last Edit Date /// <para>Name: LastEditDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastEditDate")] [Updateable(false), Createable(true)] public DateTimeOffset? LastEditDate { get; set; } ///<summary> /// Comment Count /// <para>Name: CommentCount</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "commentCount")] [Updateable(false), Createable(false)] public int? CommentCount { get; set; } ///<summary> /// Like Count /// <para>Name: LikeCount</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "likeCount")] [Updateable(false), Createable(false)] public int? LikeCount { get; set; } ///<summary> /// Title /// <para>Name: Title</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "title")] public string Title { get; set; } ///<summary> /// Body /// <para>Name: Body</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "body")] public string Body { get; set; } ///<summary> /// Link Url /// <para>Name: LinkUrl</para> /// <para>SF Type: url</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "linkUrl")] [Updateable(false), Createable(true)] public string LinkUrl { get; set; } ///<summary> /// Is Rich Text /// <para>Name: IsRichText</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isRichText")] public bool? IsRichText { get; set; } ///<summary> /// Related Record ID /// <para>Name: RelatedRecordId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "relatedRecordId")] [Updateable(false), Createable(true)] public string RelatedRecordId { get; set; } ///<summary> /// InsertedBy ID /// <para>Name: InsertedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "insertedById")] [Updateable(false), Createable(false)] public string InsertedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: InsertedBy</para> ///</summary> [JsonProperty(PropertyName = "insertedBy")] [Updateable(false), Createable(false)] public SfUser InsertedBy { get; set; } ///<summary> /// Best Comment ID /// <para>Name: BestCommentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "bestCommentId")] [Updateable(false), Createable(false)] public string BestCommentId { get; set; } ///<summary> /// ReferenceTo: FeedComment /// <para>RelationshipName: BestComment</para> ///</summary> [JsonProperty(PropertyName = "bestComment")] [Updateable(false), Createable(false)] public SfFeedComment BestComment { get; set; } ///<summary> /// Has Content /// <para>Name: HasContent</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "hasContent")] [Updateable(false), Createable(false)] public bool? HasContent { get; set; } ///<summary> /// Has Link /// <para>Name: HasLink</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "hasLink")] [Updateable(false), Createable(false)] public bool? HasLink { get; set; } ///<summary> /// Has Feed Entity Attachment /// <para>Name: HasFeedEntity</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "hasFeedEntity")] [Updateable(false), Createable(false)] public bool? HasFeedEntity { get; set; } ///<summary> /// Has Verified Comment /// <para>Name: HasVerifiedComment</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "hasVerifiedComment")] [Updateable(false), Createable(false)] public bool? HasVerifiedComment { get; set; } ///<summary> /// Is Closed /// <para>Name: IsClosed</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isClosed")] [Updateable(false), Createable(false)] public bool? IsClosed { get; set; } ///<summary> /// Status /// <para>Name: Status</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 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. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Aurora.Simulation.Base; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; namespace Aurora.Modules.Archivers { /// <summary> /// This module loads and saves OpenSimulator inventory archives /// </summary> public class InventoryArchiverModule : IService, IInventoryArchiverModule { /// <summary> /// The file to load and save inventory if no filename has been specified /// </summary> protected const string DEFAULT_INV_BACKUP_FILENAME = "user-inventory.iar"; /// <value> /// All scenes that this module knows about /// </value> private readonly Dictionary<UUID, IScene> m_scenes = new Dictionary<UUID, IScene>(); /// <value> /// Pending save completions initiated from the console /// </value> protected List<Guid> m_pendingConsoleSaves = new List<Guid>(); private IRegistryCore m_registry; public string Name { get { return "Inventory Archiver Module"; } } #region IInventoryArchiverModule Members public event InventoryArchiveSaved OnInventoryArchiveSaved; public bool ArchiveInventory( Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream) { return ArchiveInventory(id, firstName, lastName, invPath, pass, saveStream, new Dictionary<string, object>()); } public bool ArchiveInventory( Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream, Dictionary<string, object> options) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { try { bool UseAssets = true; if (options.ContainsKey("assets")) { object Assets = null; options.TryGetValue("assets", out Assets); bool.TryParse(Assets.ToString(), out UseAssets); } new InventoryArchiveWriteRequest(id, this, m_registry, userInfo, invPath, saveStream, UseAssets, null, new List<AssetBase>()).Execute(); } catch (EntryPointNotFoundException e) { MainConsole.Instance.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); MainConsole.Instance.Error(e); return false; } return true; } return false; } public bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, Stream loadStream) { return DearchiveInventory(firstName, lastName, invPath, pass, loadStream, new Dictionary<string, object>()); } public bool DearchiveInventory( string firstName, string lastName, string invPath, string pass, Stream loadStream, Dictionary<string, object> options) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { InventoryArchiveReadRequest request; bool merge = (options.ContainsKey("merge") && (bool)options["merge"]); try { request = new InventoryArchiveReadRequest(m_registry, userInfo, invPath, loadStream, merge, UUID.Zero); } catch (EntryPointNotFoundException e) { MainConsole.Instance.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); MainConsole.Instance.Error(e); return false; } request.Execute(false); return true; } return false; } #endregion #region IService Members public void Initialize(IConfigSource config, IRegistryCore registry) { m_registry = registry; m_registry.RegisterModuleInterface<IInventoryArchiverModule>(this); if (m_scenes.Count == 0) { OnInventoryArchiveSaved += SaveInvConsoleCommandCompleted; if (MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand( "load iar", "load iar <first> <last> <inventory path> <password> [<IAR path>]", //"load iar [--merge] <first> <last> <inventory path> <password> [<IAR path>]", "Load user inventory archive (IAR). " + "--merge is an option which merges the loaded IAR with existing inventory folders where possible, rather than always creating new ones" + "<first> is user's first name." + Environment.NewLine + "<last> is user's last name." + Environment.NewLine + "<inventory path> is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine + "<password> is the user's password." + Environment.NewLine + "<IAR path> is the filesystem path or URI from which to load the IAR." + string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME), HandleLoadInvConsoleCommand); MainConsole.Instance.Commands.AddCommand( "save iar", "save iar <first> <last> <inventory path> <password> [<IAR path>]", "Save user inventory archive (IAR). <first> is the user's first name." + Environment.NewLine + "<last> is the user's last name." + Environment.NewLine + "<inventory path> is the path inside the user's inventory for the folder/item to be saved." + Environment.NewLine + "<IAR path> is the filesystem path at which to save the IAR." + string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME), HandleSaveInvConsoleCommand); MainConsole.Instance.Commands.AddCommand( "save iar withoutassets", "save iar withoutassets <first> <last> <inventory path> <password> [<IAR path>]", "Save user inventory archive (IAR) withOUT assets. This version will NOT load on another grid/standalone other than the current grid/standalone! " + "<first> is the user's first name." + Environment.NewLine + "<last> is the user's last name." + Environment.NewLine + "<inventory path> is the path inside the user's inventory for the folder/item to be saved." + Environment.NewLine + "<IAR path> is the filesystem path at which to save the IAR." + string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME), HandleSaveInvWOAssetsConsoleCommand); } } } public void Start(IConfigSource config, IRegistryCore registry) { } public void FinishedStartup() { } #endregion /// <summary> /// Trigger the inventory archive saved event. /// </summary> protected internal void TriggerInventoryArchiveSaved( Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, Exception reportedException) { InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved; if (handlerInventoryArchiveSaved != null) handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException); } public bool ArchiveInventory( Guid id, string firstName, string lastName, string invPath, string pass, string savePath, Dictionary<string, object> options) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { try { bool UseAssets = true; if (options.ContainsKey("assets")) { object Assets = null; options.TryGetValue("assets", out Assets); bool.TryParse(Assets.ToString(), out UseAssets); } new InventoryArchiveWriteRequest(id, this, m_registry, userInfo, invPath, savePath, UseAssets). Execute(); } catch (EntryPointNotFoundException e) { MainConsole.Instance.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); MainConsole.Instance.Error(e); return false; } return true; } return false; } public bool DearchiveInventory( string firstName, string lastName, string invPath, string pass, string loadPath, Dictionary<string, object> options) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { InventoryArchiveReadRequest request; bool merge = (options.ContainsKey("merge") && (bool)options["merge"]); try { request = new InventoryArchiveReadRequest(m_registry, userInfo, invPath, loadPath, merge, UUID.Zero); } catch (EntryPointNotFoundException e) { MainConsole.Instance.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); MainConsole.Instance.Error(e); return false; } request.Execute(false); return true; } return false; } /// <summary> /// Load inventory from an inventory file archive /// </summary> /// <param name = "cmdparams"></param> protected void HandleLoadInvConsoleCommand(string[] cmdparams) { try { MainConsole.Instance.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL. BUG REPORTS WELCOME."); Dictionary<string, object> options = new Dictionary<string, object>(); List<string> newParams = new List<string>(cmdparams); foreach (string param in cmdparams) { if (param.StartsWith("--skip-assets", StringComparison.CurrentCultureIgnoreCase)) { options["skip-assets"] = true; newParams.Remove(param); } if (param.StartsWith("--merge", StringComparison.CurrentCultureIgnoreCase)) { options["merge"] = true; newParams.Remove(param); } } if (newParams.Count < 6) { MainConsole.Instance.Error( "[INVENTORY ARCHIVER]: usage is load iar [--merge] <first name> <last name> <inventory path> <user password> [<load file path>]"); return; } string firstName = newParams[2]; string lastName = newParams[3]; string invPath = newParams[4]; string pass = newParams[5]; string loadPath = (newParams.Count > 6 ? newParams[6] : DEFAULT_INV_BACKUP_FILENAME); MainConsole.Instance.InfoFormat( "[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}", loadPath, invPath, firstName, lastName); if (DearchiveInventory(firstName, lastName, invPath, pass, loadPath, options)) MainConsole.Instance.InfoFormat( "[INVENTORY ARCHIVER]: Loaded archive {0} for {1} {2}", loadPath, firstName, lastName); } catch (InventoryArchiverException e) { MainConsole.Instance.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message); } } /// <summary> /// Save inventory to a file archive /// </summary> /// <param name = "cmdparams"></param> protected void HandleSaveInvWOAssetsConsoleCommand(string[] cmdparams) { if (cmdparams.Length < 7) { MainConsole.Instance.Error( "[INVENTORY ARCHIVER]: usage is save iar <first name> <last name> <inventory path> <user password> [<save file path>]"); return; } MainConsole.Instance.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL. BUG REPORTS WELCOME."); string firstName = cmdparams[3]; string lastName = cmdparams[4]; string invPath = cmdparams[5]; string pass = cmdparams[6]; string savePath = (cmdparams.Length > 7 ? cmdparams[7] : DEFAULT_INV_BACKUP_FILENAME); MainConsole.Instance.InfoFormat( "[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3} without assets", savePath, invPath, firstName, lastName); Guid id = Guid.NewGuid(); Dictionary<string, object> options = new Dictionary<string, object> { { "Assets", false } }; ArchiveInventory(id, firstName, lastName, invPath, pass, savePath, options); lock (m_pendingConsoleSaves) m_pendingConsoleSaves.Add(id); } /// <summary> /// Save inventory to a file archive /// </summary> /// <param name = "cmdparams"></param> protected void HandleSaveInvConsoleCommand(string[] cmdparams) { try { MainConsole.Instance.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL. BUG REPORTS WELCOME."); string firstName = cmdparams[2]; string lastName = cmdparams[3]; string invPath = cmdparams[4]; string pass = cmdparams[5]; string savePath = (cmdparams.Length > 6 ? cmdparams[6] : DEFAULT_INV_BACKUP_FILENAME); MainConsole.Instance.InfoFormat( "[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}", savePath, invPath, firstName, lastName); Guid id = Guid.NewGuid(); Dictionary<string, object> options = new Dictionary<string, object> { { "Assets", true } }; ArchiveInventory(id, firstName, lastName, invPath, pass, savePath, options); lock (m_pendingConsoleSaves) m_pendingConsoleSaves.Add(id); } catch (InventoryArchiverException e) { MainConsole.Instance.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message); } } private void SaveInvConsoleCommandCompleted( Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, Exception reportedException) { lock (m_pendingConsoleSaves) { if (m_pendingConsoleSaves.Contains(id)) m_pendingConsoleSaves.Remove(id); else return; } if (succeeded) { MainConsole.Instance.InfoFormat("[INVENTORY ARCHIVER]: Saved archive for {0} {1}", userInfo.FirstName, userInfo.LastName); } else { MainConsole.Instance.ErrorFormat( "[INVENTORY ARCHIVER]: Archive save for {0} {1} failed - {2}", userInfo.FirstName, userInfo.LastName, reportedException.Message); } } /// <summary> /// Get user information for the given name. /// </summary> /// <param name = "firstName"></param> /// <param name = "lastName"></param> /// <param name = "pass">User password</param> /// <returns></returns> protected UserAccount GetUserInfo(string firstName, string lastName, string pass) { UserAccount account = m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, firstName, lastName); if (null == account) { MainConsole.Instance.ErrorFormat( "[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}", firstName, lastName); return null; } try { string encpass = Util.Md5Hash(pass); if ( m_registry.RequestModuleInterface<IAuthenticationService>().Authenticate(account.PrincipalID, "UserAccount", encpass, 1) != string.Empty) { return account; } else { MainConsole.Instance.ErrorFormat( "[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect. Please try again.", firstName, lastName); return null; } } catch (Exception e) { MainConsole.Instance.ErrorFormat("[INVENTORY ARCHIVER]: Could not authenticate password, {0}", e.Message); 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 Microsoft.Win32.SafeHandles; using System.ComponentModel; using System.Diagnostics; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.NetworkInformation { public partial class Ping { private static readonly object s_socketInitializationLock = new object(); private static bool s_socketInitialized; private int _sendSize = 0; // Needed to determine what the reply size is for ipv6 in callback. private bool _ipv6 = false; private ManualResetEvent _pingEvent; private RegisteredWaitHandle _registeredWait; private SafeLocalAllocHandle _requestBuffer; private SafeLocalAllocHandle _replyBuffer; private Interop.IpHlpApi.SafeCloseIcmpHandle _handlePingV4; private Interop.IpHlpApi.SafeCloseIcmpHandle _handlePingV6; private TaskCompletionSource<PingReply> _taskCompletionSource; // Any exceptions that escape synchronously will be caught by the caller and wrapped in a PingException. // We do not need to or want to capture such exceptions into the returned task. private Task<PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options) { var tcs = new TaskCompletionSource<PingReply>(); _taskCompletionSource = tcs; _ipv6 = (address.AddressFamily == AddressFamily.InterNetworkV6); _sendSize = buffer.Length; // Get and cache correct handle. if (!_ipv6 && _handlePingV4 == null) { _handlePingV4 = Interop.IpHlpApi.IcmpCreateFile(); if (_handlePingV4.IsInvalid) { _handlePingV4 = null; throw new Win32Exception(); // Gets last error. } } else if (_ipv6 && _handlePingV6 == null) { _handlePingV6 = Interop.IpHlpApi.Icmp6CreateFile(); if (_handlePingV6.IsInvalid) { _handlePingV6 = null; throw new Win32Exception(); // Gets last error. } } var ipOptions = new Interop.IpHlpApi.IPOptions(options); if (_replyBuffer == null) { _replyBuffer = SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket); } // Queue the event. int error; try { if (_pingEvent == null) { _pingEvent = new ManualResetEvent(false); } else { _pingEvent.Reset(); } _registeredWait = ThreadPool.RegisterWaitForSingleObject(_pingEvent, (state, _) => ((Ping)state).PingCallback(), this, -1, true); SetUnmanagedStructures(buffer); if (!_ipv6) { SafeWaitHandle pingEventSafeWaitHandle = _pingEvent.GetSafeWaitHandle(); error = (int)Interop.IpHlpApi.IcmpSendEcho2( _handlePingV4, pingEventSafeWaitHandle, IntPtr.Zero, IntPtr.Zero, #pragma warning disable CS0618 // Address is marked obsolete (uint)address.Address, #pragma warning restore CS0618 _requestBuffer, (ushort)buffer.Length, ref ipOptions, _replyBuffer, MaxUdpPacket, (uint)timeout); } else { IPEndPoint ep = new IPEndPoint(address, 0); Internals.SocketAddress remoteAddr = IPEndPointExtensions.Serialize(ep); byte[] sourceAddr = new byte[28]; SafeWaitHandle pingEventSafeWaitHandle = _pingEvent.GetSafeWaitHandle(); error = (int)Interop.IpHlpApi.Icmp6SendEcho2( _handlePingV6, pingEventSafeWaitHandle, IntPtr.Zero, IntPtr.Zero, sourceAddr, remoteAddr.Buffer, _requestBuffer, (ushort)buffer.Length, ref ipOptions, _replyBuffer, MaxUdpPacket, (uint)timeout); } } catch { UnregisterWaitHandle(); throw; } if (error == 0) { error = Marshal.GetLastWin32Error(); // Only skip Async IO Pending error value. if (error != Interop.IpHlpApi.ERROR_IO_PENDING) { // Cleanup. FreeUnmanagedStructures(); UnregisterWaitHandle(); throw new Win32Exception(error); } } return tcs.Task; } /*private*/ partial void InternalDisposeCore() { if (_handlePingV4 != null) { _handlePingV4.Dispose(); _handlePingV4 = null; } if (_handlePingV6 != null) { _handlePingV6.Dispose(); _handlePingV6 = null; } UnregisterWaitHandle(); if (_pingEvent != null) { _pingEvent.Dispose(); _pingEvent = null; } if (_replyBuffer != null) { _replyBuffer.Dispose(); _replyBuffer = null; } } private void UnregisterWaitHandle() { lock (_lockObject) { if (_registeredWait != null) { // If Unregister returns false, it is sufficient to nullify registeredWait // and let its own finalizer clean up later. _registeredWait.Unregister(null); _registeredWait = null; } } } // Private callback invoked when icmpsendecho APIs succeed. private void PingCallback() { TaskCompletionSource<PingReply> tcs = _taskCompletionSource; _taskCompletionSource = null; PingReply reply = null; Exception error = null; bool canceled = false; try { lock (_lockObject) { canceled = _canceled; // Parse reply buffer. SafeLocalAllocHandle buffer = _replyBuffer; // Marshals and constructs new reply. if (_ipv6) { Interop.IpHlpApi.Icmp6EchoReply icmp6Reply = Marshal.PtrToStructure<Interop.IpHlpApi.Icmp6EchoReply>(buffer.DangerousGetHandle()); reply = CreatePingReplyFromIcmp6EchoReply(icmp6Reply, buffer.DangerousGetHandle(), _sendSize); } else { Interop.IpHlpApi.IcmpEchoReply icmpReply = Marshal.PtrToStructure<Interop.IpHlpApi.IcmpEchoReply>(buffer.DangerousGetHandle()); reply = CreatePingReplyFromIcmpEchoReply(icmpReply); } } } catch (Exception e) { // In case of failure, create a failed event arg. error = new PingException(SR.net_ping, e); } finally { FreeUnmanagedStructures(); UnregisterWaitHandle(); Finish(); } // Once we've called Finish, complete the task if (canceled) { tcs.SetCanceled(); } else if (reply != null) { tcs.SetResult(reply); } else { Debug.Assert(error != null); tcs.SetException(error); } } // Copies _requestBuffer into unmanaged memory for async icmpsendecho APIs. private unsafe void SetUnmanagedStructures(byte[] buffer) { _requestBuffer = SafeLocalAllocHandle.LocalAlloc(buffer.Length); byte* dst = (byte*)_requestBuffer.DangerousGetHandle(); for (int i = 0; i < buffer.Length; ++i) { dst[i] = buffer[i]; } } // Releases the unmanaged memory after ping completion. private void FreeUnmanagedStructures() { if (_requestBuffer != null) { _requestBuffer.Dispose(); _requestBuffer = null; } } private static PingReply CreatePingReplyFromIcmpEchoReply(Interop.IpHlpApi.IcmpEchoReply reply) { const int DontFragmentFlag = 2; IPAddress address = new IPAddress(reply.address); IPStatus ipStatus = (IPStatus)reply.status; // The icmpsendecho IP status codes. long rtt; PingOptions options; byte[] buffer; if (ipStatus == IPStatus.Success) { // Only copy the data if we succeed w/ the ping operation. rtt = reply.roundTripTime; options = new PingOptions(reply.options.ttl, (reply.options.flags & DontFragmentFlag) > 0); buffer = new byte[reply.dataSize]; Marshal.Copy(reply.data, buffer, 0, reply.dataSize); } else { rtt = default(long); options = default(PingOptions); buffer = Array.Empty<byte>(); } return new PingReply(address, options, ipStatus, rtt, buffer); } private static PingReply CreatePingReplyFromIcmp6EchoReply(Interop.IpHlpApi.Icmp6EchoReply reply, IntPtr dataPtr, int sendSize) { IPAddress address = new IPAddress(reply.Address.Address, reply.Address.ScopeID); IPStatus ipStatus = (IPStatus)reply.Status; // The icmpsendecho IP status codes. long rtt; byte[] buffer; if (ipStatus == IPStatus.Success) { // Only copy the data if we succeed w/ the ping operation. rtt = reply.RoundTripTime; buffer = new byte[sendSize]; Marshal.Copy(IntPtrHelper.Add(dataPtr, 36), buffer, 0, sendSize); } else { rtt = default(long); buffer = Array.Empty<byte>(); } return new PingReply(address, default(PingOptions), ipStatus, rtt, buffer); } /*private*/ static partial void InitializeSockets() { if (!Volatile.Read(ref s_socketInitialized)) { lock (s_socketInitializationLock) { if (!s_socketInitialized) { // Ensure that WSAStartup has been called once per process. // The System.Net.NameResolution contract is responsible with the initialization. Dns.GetHostName(); // Cache some settings locally. s_socketInitialized = true; } } } } } }
using System; using System.Diagnostics; using CoreGraphics; using Foundation; using UIKit; using TwitterImagePipeline; namespace TwitterImagePipelineDemo { public class ZoomingTweetImageViewController : UIViewController, IUIScrollViewDelegate, ITIPImageFetchDelegate { private readonly TweetImageInfo tweetImageInfo; private UIScrollView scrollView; private UIImageView imageView; private UIProgressView progressView; private UITapGestureRecognizer doubleTapGuestureRecognizer; private TIPImageFetchOperation fetchOp; public ZoomingTweetImageViewController(TweetImageInfo imageInfo) { tweetImageInfo = imageInfo; NavigationItem.Title = "Tweet Image"; } public override void ViewDidLoad() { base.ViewDidLoad(); var targetSize = tweetImageInfo.OriginalDimensions; var scale = UIScreen.MainScreen.Scale; if (scale != 1) { targetSize.Height /= scale; targetSize.Width /= scale; } progressView = new UIProgressView(new CGRect(0, 0, View.Bounds.Width, 4)); progressView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleBottomMargin; progressView.TintColor = UIColor.Yellow; progressView.Progress = 0; imageView = new UIImageView(new CGRect(0, 0, targetSize.Width, targetSize.Height)); imageView.ContentMode = UIViewContentMode.ScaleAspectFill; imageView.ClipsToBounds = true; imageView.BackgroundColor = UIColor.Gray; scrollView = new UIScrollView(View.Bounds); scrollView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; scrollView.BackgroundColor = UIColor.Black; doubleTapGuestureRecognizer = new UITapGestureRecognizer(DoubleTapTriggered); doubleTapGuestureRecognizer.NumberOfTapsRequired = 2; imageView.Image = null; imageView.AddGestureRecognizer(doubleTapGuestureRecognizer); imageView.UserInteractionEnabled = true; scrollView.Delegate = this; scrollView.MinimumZoomScale = 0.01f; // start VERY small scrollView.MaximumZoomScale = 2.0f; scrollView.ContentSize = targetSize; View.AddSubview(scrollView); View.AddSubview(progressView); scrollView.AddSubview(imageView); scrollView.ZoomToRect(imageView.Frame, false); scrollView.MinimumZoomScale = scrollView.ZoomScale; // readjust minimum if (scrollView.MinimumZoomScale > scrollView.MaximumZoomScale) { scrollView.MaximumZoomScale = scrollView.MinimumZoomScale; } DidZoom(scrollView); Load(); } public override void ViewDidLayoutSubviews() { base.ViewDidLayoutSubviews(); DidZoom(scrollView); var frame = progressView.Frame; frame.Y = scrollView.ContentInset.Top; progressView.Frame = frame; } private void Load() { var request = new TweetImageFetchRequest(tweetImageInfo, imageView, false); fetchOp = AppDelegate.Current.ImagePipeline.CreateFetchOperation(request, null, this); AppDelegate.Current.ImagePipeline.FetchImage(fetchOp); } private void DoubleTapTriggered(UITapGestureRecognizer tapper) { if (tapper.State == UIGestureRecognizerState.Recognized) { if (scrollView.ZoomScale == scrollView.MaximumZoomScale) { scrollView.SetZoomScale(scrollView.MinimumZoomScale, true); } else { scrollView.SetZoomScale(scrollView.MaximumZoomScale, true); } } } // IUIScrollViewDelegate [Export("viewForZoomingInScrollView:")] public UIView ViewForZoomingInScrollView(UIScrollView scrollView) => imageView; [Export("scrollViewDidZoom:")] public void DidZoom(UIScrollView scrollView) { var offsetX = Math.Max((scrollView.Bounds.Width - scrollView.ContentInset.Left - scrollView.ContentInset.Right - scrollView.ContentSize.Width) * 0.5, 0.0); var offsetY = Math.Max((scrollView.Bounds.Height - scrollView.ContentInset.Top - scrollView.ContentInset.Bottom - scrollView.ContentSize.Height) * 0.5, 0.0); imageView.Center = new CGPoint(scrollView.ContentSize.Width * 0.5 + offsetX, scrollView.ContentSize.Height * 0.5 + offsetY); } // ITIPImageFetchDelegate [Export("tip_imageFetchOperationDidStart:")] public void ImageFetchOperationDidStart(TIPImageFetchOperation op) { Debug.WriteLine("starting Zoom fetch..."); } [Export("tip_imageFetchOperation:willAttemptToLoadFromSource:")] public void ImageFetchOperationWillAttemptToLoad(TIPImageFetchOperation op, TIPImageLoadSource source) { Debug.WriteLine($"...attempting load from next source: {source}..."); } [Export("tip_imageFetchOperation:didLoadPreviewImage:completion:")] public void ImageFetchOperationDidLoadPreviewImage(TIPImageFetchOperation op, ITIPImageFetchResult previewResult, TIPImageFetchDidLoadPreviewCallback completion) { Debug.WriteLine("...preview loaded..."); progressView.TintColor = UIColor.Blue; imageView.Image = previewResult.ImageContainer.Image; completion(TIPImageFetchPreviewLoadedBehavior.ContinueLoading); } [Export("tip_imageFetchOperation:shouldLoadProgressivelyWithIdentifier:URL:imageType:originalDimensions:")] public bool ImageFetchOperationShouldLoadProgressively(TIPImageFetchOperation op, string identifier, NSUrl url, string imageType, CGSize originalDimensions) { var isNull = false; InvokeOnMainThread(() => isNull = (imageView.Image == null)); return isNull; } [Export("tip_imageFetchOperation:didUpdateProgressiveImage:progress:")] public void ImageFetchOperationDidUpdateProgressiveImage(TIPImageFetchOperation op, ITIPImageFetchResult progressiveResult, float progress) { Debug.WriteLine($"...progressive update ({progress:0.000})..."); progressView.TintColor = UIColor.Orange; progressView.SetProgress(progress, true); imageView.Image = progressiveResult.ImageContainer.Image; } [Export("tip_imageFetchOperation:didLoadFirstAnimatedImageFrame:progress:")] public void ImageFetchOperationDidLoadFirstAnimatedImageFrame(TIPImageFetchOperation op, ITIPImageFetchResult progressiveResult, float progress) { Debug.WriteLine($"...animated first frame ({progress:0.000})..."); imageView.Image = progressiveResult.ImageContainer.Image; progressView.TintColor = UIColor.Purple; progressView.SetProgress(progress, true); } [Export("tip_imageFetchOperation:didUpdateProgress:")] public void ImageFetchOperationDidUpdateProgress(TIPImageFetchOperation op, float progress) { Debug.WriteLine($"...progress ({progress:0.000})..."); progressView.SetProgress(progress, true); } [Export("tip_imageFetchOperation:didLoadFinalImage:")] public void ImageFetchOperationDidLoadFinalImage(TIPImageFetchOperation op, ITIPImageFetchResult finalResult) { Debug.WriteLine("...completed zoom fetch"); progressView.TintColor = UIColor.Green; progressView.SetProgress(1, true); imageView.Image = finalResult.ImageContainer.Image; fetchOp = null; } [Export("tip_imageFetchOperation:didFailToLoadFinalImage:")] public void ImageFetchOperationDidFailToLoadFinalImage(TIPImageFetchOperation op, NSError error) { Debug.WriteLine($"...failed zoom fetch: {error}"); progressView.TintColor = UIColor.Red; fetchOp = null; } } }
using System; namespace EasyStorage { /// <summary> /// Defines the interface for an object that can perform the ISaveDevice operations in /// an asynchronous fashion. /// </summary> /// <remarks> /// This class was based on the event-based asynchronous pattern, which is the new /// recommended method for asynchronous APIs in .NET. For more information, see this page: /// http://msdn.microsoft.com/en-us/library/hkasytyf.aspx /// /// Our pattern deviates from the standard in that our events don't use the standard /// EventHandler or AsyncCompletedEventArgs as that would cause us to generate garbage. /// Instead we have substituted those events with a delegate based event that uses structs /// for arguments, allowing us to avoid garbage generation. /// /// Additionally, we choose, in the built in implementations, to not throw an exception if /// a single-invocation method is called while an operation is pending. Instead we simply /// queue it up without issue. This is done as a convenience to the game developer, even if /// it does deviate from the pattern. /// /// We also choose not to support cancellation due to the complexities of the implementation /// and because there is little benefit from the ability to cancel a storage operation which /// should be a relatively quick process in and of itself. /// </remarks> public interface IAsyncSaveDevice : ISaveDevice { /// <summary> /// Gets whether or not the device is busy performing a file operation. /// </summary> /// <remarks> /// Games can query this property to determine when to show an indication that game is saving /// such as a spinner or other icon. /// </remarks> bool IsBusy { get; } /// <summary> /// Raised when a SaveAsync operation has completed. /// </summary> event SaveCompletedEventHandler SaveCompleted; /// <summary> /// Raised when a LoadAsync operation has completed. /// </summary> event LoadCompletedEventHandler LoadCompleted; /// <summary> /// Raised when a DeleteAsync operation has completed. /// </summary> event DeleteCompletedEventHandler DeleteCompleted; /// <summary> /// Raised when a FileExistsAsync operation has completed. /// </summary> event FileExistsCompletedEventHandler FileExistsCompleted; /// <summary> /// Raised when a GetFilesAsync operation has completed. /// </summary> event GetFilesCompletedEventHandler GetFilesCompleted; /// <summary> /// Saves a file asynchronously. /// </summary> /// <param name="containerName">The name of the container in which to save the file.</param> /// <param name="fileName">The file to save.</param> /// <param name="saveAction">The save action to perform.</param> void SaveAsync(string containerName, string fileName, FileAction saveAction); /// <summary> /// Saves a file asynchronously. /// </summary> /// <param name="containerName">The name of the container in which to save the file.</param> /// <param name="fileName">The file to save.</param> /// <param name="saveAction">The save action to perform.</param> /// <param name="userState">A state object used to identify the async operation.</param> void SaveAsync(string containerName, string fileName, FileAction saveAction, object userState); /// <summary> /// Loads a file asynchronously. /// </summary> /// <param name="containerName">The name of the container from which to load the file.</param> /// <param name="fileName">The file to load.</param> /// <param name="loadAction">The load action to perform.</param> void LoadAsync(string containerName, string fileName, FileAction loadAction); /// <summary> /// Loads a file asynchronously. /// </summary> /// <param name="containerName">The name of the container from which to load the file.</param> /// <param name="fileName">The file to load.</param> /// <param name="loadAction">The load action to perform.</param> /// <param name="userState">A state object used to identify the async operation.</param> void LoadAsync(string containerName, string fileName, FileAction loadAction, object userState); /// <summary> /// Deletes a file asynchronously. /// </summary> /// <param name="containerName">The name of the container from which to delete the file.</param> /// <param name="fileName">The file to delete.</param> void DeleteAsync(string containerName, string fileName); /// <summary> /// Deletes a file asynchronously. /// </summary> /// <param name="containerName">The name of the container from which to delete the file.</param> /// <param name="fileName">The file to delete.</param> /// <param name="userState">A state object used to identify the async operation.</param> void DeleteAsync(string containerName, string fileName, object userState); /// <summary> /// Determines if a given file exists asynchronously. /// </summary> /// <param name="containerName">The name of the container in which to check for the file.</param> /// <param name="fileName">The name of the file.</param> void FileExistsAsync(string containerName, string fileName); /// <summary> /// Determines if a given file exists asynchronously. /// </summary> /// <param name="containerName">The name of the container in which to check for the file.</param> /// <param name="fileName">The name of the file.</param> /// <param name="userState">A state object used to identify the async operation.</param> void FileExistsAsync(string containerName, string fileName, object userState); /// <summary> /// Gets an array of all files available in a container asynchronously. /// </summary> /// <param name="containerName">The name of the container in which to search for files.</param> void GetFilesAsync(string containerName); /// <summary> /// Gets an array of all files available in a container asynchronously. /// </summary> /// <param name="containerName">The name of the container in which to search for files.</param> /// <param name="userState">A state object used to identify the async operation.</param> void GetFilesAsync(string containerName, object userState); /// <summary> /// Gets an array of all files available in a container that match the given pattern asynchronously. /// </summary> /// <param name="containerName">The name of the container in which to search for files.</param> /// <param name="pattern">A search pattern to use to find files.</param> void GetFilesAsync(string containerName, string pattern); /// <summary> /// Gets an array of all files available in a container that match the given pattern asynchronously. /// </summary> /// <param name="containerName">The name of the container in which to search for files.</param> /// <param name="pattern">A search pattern to use to find files.</param> /// <param name="userState">A state object used to identify the async operation.</param> void GetFilesAsync(string containerName, string pattern, object userState); } /// <summary> /// Used for the arguments for SaveAsync, LoadAsync, and DeleteAsync. /// </summary> public struct FileActionCompletedEventArgs { /// <summary> /// The exception, if any, that occurred during the operation. /// </summary> public Exception Error { get; private set; } /// <summary> /// The user state passed into the async method. /// </summary> public object UserState { get; private set; } public FileActionCompletedEventArgs(Exception error, object userState) : this() { Error = error; UserState = userState; } } /// <summary> /// Used for arguments for FileExistsAsync. /// </summary> public struct FileExistsCompletedEventArgs { /// <summary> /// The exception, if any, that occurred during the operation. /// </summary> public Exception Error { get; private set; } /// <summary> /// The user state passed into the async method. /// </summary> public object UserState { get; private set; } /// <summary> /// Whether or not the file exists. /// </summary> public bool Result { get; private set; } public FileExistsCompletedEventArgs(Exception error, bool result, object userState) : this() { Error = error; Result = result; UserState = userState; } } /// <summary> /// Used for arguments for GetFilesAsync. /// </summary> public struct GetFilesCompletedEventArgs { /// <summary> /// The exception, if any, that occurred during the operation. /// </summary> public Exception Error { get; private set; } /// <summary> /// The user state passed into the async method. /// </summary> public object UserState { get; private set; } /// <summary> /// The list of files returned by the operation. /// </summary> public string[] Result { get; private set; } public GetFilesCompletedEventArgs(Exception error, string[] result, object userState) : this() { Error = error; Result = result; UserState = userState; } } /// <summary> /// Defines an event handler signature for handling the SaveCompleted event. /// </summary> /// <param name="sender">The IAsyncSaveDevice that raised the event.</param> /// <param name="args">The results of the operation.</param> public delegate void SaveCompletedEventHandler(object sender, FileActionCompletedEventArgs args); /// <summary> /// Defines an event handler signature for handling the LoadCompleted event. /// </summary> /// <param name="sender">The IAsyncSaveDevice that raised the event.</param> /// <param name="args">The results of the operation.</param> public delegate void LoadCompletedEventHandler(object sender, FileActionCompletedEventArgs args); /// <summary> /// Defines an event handler signature for handling the DeleteCompleted event. /// </summary> /// <param name="sender">The IAsyncSaveDevice that raised the event.</param> /// <param name="args">The results of the operation.</param> public delegate void DeleteCompletedEventHandler(object sender, FileActionCompletedEventArgs args); /// <summary> /// Defines an event handler signature for handling the FileExistsCompleted event. /// </summary> /// <param name="sender">The IAsyncSaveDevice that raised the event.</param> /// <param name="args">The results of the operation.</param> public delegate void FileExistsCompletedEventHandler(object sender, FileExistsCompletedEventArgs args); /// <summary> /// Defines an event handler signature for handling the GetFilesCompleted event. /// </summary> /// <param name="sender">The IAsyncSaveDevice that raised the event.</param> /// <param name="args">The results of the operation.</param> public delegate void GetFilesCompletedEventHandler(object sender, GetFilesCompletedEventArgs args); }
using System; using System.Collections.Specialized; using System.IO; using System.Text; using HttpServer.Exceptions; using HttpServer.FormDecoders; namespace HttpServer.Test.TestHelpers { class HttpTestRequest : IHttpRequest { #region Implementation of ICloneable private bool _bodyIsComplete; private string[] _acceptTypes; private Stream _body = new MemoryStream(); private ConnectionType _connection; private int _contentLength; private NameValueCollection _headers = new NameValueCollection(); private string _httpVersion; private string _method; private HttpInput _queryString; private Uri _uri; private string[] _uriParts; private HttpParam _param; private HttpForm _form; private bool _isAjax; private RequestCookies _cookies; public HttpTestRequest() { _queryString = new HttpInput("QueryString"); _form = new HttpForm(); _param = new HttpParam(_form, _queryString); } /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> /// <filterpriority>2</filterpriority> public object Clone() { throw new System.NotImplementedException(); } #endregion #region Implementation of IHttpRequest /// <summary> /// Have all body content bytes been received? /// </summary> public bool BodyIsComplete { get { return _bodyIsComplete; } set { _bodyIsComplete = value; } } /// <summary> /// Kind of types accepted by the client. /// </summary> public string[] AcceptTypes { get { return _acceptTypes; } set { _acceptTypes = value; } } /// <summary> /// Submitted body contents /// </summary> public Stream Body { get { return _body; } set { _body = value; } } /// <summary> /// Kind of connection used for the session. /// </summary> public ConnectionType Connection { get { return _connection; } set { _connection = value; } } /// <summary> /// Number of bytes in the body /// </summary> public int ContentLength { get { return _contentLength; } set { _contentLength = value; } } /// <summary> /// Headers sent by the client. All names are in lower case. /// </summary> public NameValueCollection Headers { get { return _headers; } } /// <summary> /// Version of http. /// Probably HttpHelper.HTTP10 or HttpHelper.HTTP11 /// </summary> /// <seealso cref="HttpHelper"/> public string HttpVersion { get { return _httpVersion; } set { _httpVersion = value; } } /// <summary> /// Requested method, always upper case. /// </summary> /// <see cref="IHttpRequest.Method"/> public string Method { get { return _method; } set { _method = value; } } /// <summary> /// Variables sent in the query string /// </summary> public HttpInput QueryString { get { return _queryString; } set { _queryString = value; } } /// <summary> /// Requested URI (url) /// </summary> /// <seealso cref="IHttpRequest.UriPath"/> public Uri Uri { get { return _uri; } set { _uri = value; _uriParts = _uri.AbsolutePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); } } /// <summary> /// Uri absolute path splitted into parts. /// </summary> /// <example> /// // uri is: http://gauffin.com/code/tiny/ /// Console.WriteLine(request.UriParts[0]); // result: code /// Console.WriteLine(request.UriParts[1]); // result: tiny /// </example> /// <remarks> /// If you're using controllers than the first part is controller name, /// the second part is method name and the third part is Id property. /// </remarks> /// <seealso cref="IHttpRequest.Uri"/> public string[] UriParts { get { return _uriParts; } set { _uriParts = value; } } /// <summary> /// Gets or sets path and query. /// </summary> /// <see cref="IHttpRequest.Uri"/> /// <remarks> /// Are only used during request parsing. Cannot be set after "Host" header have been /// added. /// </remarks> public string UriPath { get { return _uri.AbsolutePath; } set { } } /// <summary> /// Check's both QueryString and Form after the parameter. /// </summary> public HttpParam Param { get { return _param; } set { _param = value; } } /// <summary> /// Form parameters. /// </summary> public HttpForm Form { get { return _form; } set { _form = value; } } /// <summary>Returns true if the request was made by Ajax (Asyncronous Javascript)</summary> public bool IsAjax { get { return _isAjax; } set { _isAjax = value; } } /// <summary>Returns set cookies for the request</summary> public RequestCookies Cookies { get { return _cookies; } set { _cookies = value; } } /// <summary> /// Decode body into a form. /// </summary> /// <param name="providers">A list with form decoders.</param> /// <exception cref="InvalidDataException">If body contents is not valid for the chosen decoder.</exception> /// <exception cref="InvalidOperationException">If body is still being transferred.</exception> public void DecodeBody(FormDecoderProvider providers) { _form = providers.Decode(_headers["content-type"], _body, Encoding.UTF8); } /// <summary> /// Sets the cookies. /// </summary> /// <param name="cookies">The cookies.</param> public void SetCookies(RequestCookies cookies) { _cookies = cookies; } /// <summary> /// Create a response object. /// </summary> /// <param name="context">Context for the connected client.</param> /// <returns>A new <see cref="IHttpResponse"/>.</returns> public IHttpResponse CreateResponse(IHttpClientContext context) { return new HttpResponse(context, this); } /// <summary> /// Called during parsing of a <see cref="IHttpRequest"/>. /// </summary> /// <param name="name">Name of the header, should not be URI encoded</param> /// <param name="value">Value of the header, should not be URI encoded</param> /// <exception cref="BadRequestException">If a header is incorrect.</exception> public void AddHeader(string name, string value) { _headers.Add(name, value); } /// <summary> /// Add bytes to the body /// </summary> /// <param name="bytes">buffer to read bytes from</param> /// <param name="offset">where to start read</param> /// <param name="length">number of bytes to read</param> /// <returns>Number of bytes actually read (same as length unless we got all body bytes).</returns> /// <exception cref="ArgumentException"></exception> /// <exception cref="InvalidOperationException">If body is not writable</exception> public int AddToBody(byte[] bytes, int offset, int length) { _body.Write(bytes, offset, length); return length; } /// <summary> /// Clear everything in the request /// </summary> public void Clear() { _uri = new Uri(string.Empty); _method = string.Empty; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace System { // Provides Windows-based support for System.Console. internal static class ConsolePal { private static IntPtr InvalidHandleValue => new IntPtr(-1); private static bool IsWindows7() { // Version lies for all apps from the OS kick in starting with Windows 8 (6.2). They can // also be added via appcompat (by the OS or the users) so this can only be used as a hint. Version version = Environment.OSVersion.Version; return version.Major == 6 && version.Minor == 1; } public static Stream OpenStandardInput() => GetStandardFile( Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE, FileAccess.Read, useFileAPIs: Console.InputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsInputRedirected); public static Stream OpenStandardOutput() => GetStandardFile( Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE, FileAccess.Write, useFileAPIs: Console.OutputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsOutputRedirected); public static Stream OpenStandardError() => GetStandardFile( Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE, FileAccess.Write, useFileAPIs: Console.OutputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsErrorRedirected); private static IntPtr InputHandle => Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE); private static IntPtr OutputHandle => Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE); private static IntPtr ErrorHandle => Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE); private static Stream GetStandardFile(int handleType, FileAccess access, bool useFileAPIs) { IntPtr handle = Interop.Kernel32.GetStdHandle(handleType); // If someone launches a managed process via CreateProcess, stdout, // stderr, & stdin could independently be set to INVALID_HANDLE_VALUE. // Additionally they might use 0 as an invalid handle. We also need to // ensure that if the handle is meant to be writable it actually is. if (handle == IntPtr.Zero || handle == InvalidHandleValue || (access != FileAccess.Read && !ConsoleHandleIsWritable(handle))) { return Stream.Null; } return new WindowsConsoleStream(handle, access, useFileAPIs); } // Checks whether stdout or stderr are writable. Do NOT pass // stdin here! The console handles are set to values like 3, 7, // and 11 OR if you've been created via CreateProcess, possibly -1 // or 0. -1 is definitely invalid, while 0 is probably invalid. // Also note each handle can independently be invalid or good. // For Windows apps, the console handles are set to values like 3, 7, // and 11 but are invalid handles - you may not write to them. However, // you can still spawn a Windows app via CreateProcess and read stdout // and stderr. So, we always need to check each handle independently for validity // by trying to write or read to it, unless it is -1. private static unsafe bool ConsoleHandleIsWritable(IntPtr outErrHandle) { // Windows apps may have non-null valid looking handle values for // stdin, stdout and stderr, but they may not be readable or // writable. Verify this by calling WriteFile in the // appropriate modes. This must handle console-less Windows apps. int bytesWritten; byte junkByte = 0x41; int r = Interop.Kernel32.WriteFile(outErrHandle, &junkByte, 0, out bytesWritten, IntPtr.Zero); return r != 0; // In Win32 apps w/ no console, bResult should be 0 for failure. } public static Encoding InputEncoding { get { return EncodingHelper.GetSupportedConsoleEncoding((int)Interop.Kernel32.GetConsoleCP()); } } public static void SetConsoleInputEncoding(Encoding enc) { if (enc.CodePage != Encoding.Unicode.CodePage) { if (!Interop.Kernel32.SetConsoleCP(enc.CodePage)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static Encoding OutputEncoding { get { return EncodingHelper.GetSupportedConsoleEncoding((int)Interop.Kernel32.GetConsoleOutputCP()); } } public static void SetConsoleOutputEncoding(Encoding enc) { if (enc.CodePage != Encoding.Unicode.CodePage) { if (!Interop.Kernel32.SetConsoleOutputCP(enc.CodePage)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } /// <summary>Gets whether Console.In is targeting a terminal display.</summary> public static bool IsInputRedirectedCore() { return IsHandleRedirected(InputHandle); } /// <summary>Gets whether Console.Out is targeting a terminal display.</summary> public static bool IsOutputRedirectedCore() { return IsHandleRedirected(OutputHandle); } /// <summary>Gets whether Console.In is targeting a terminal display.</summary> public static bool IsErrorRedirectedCore() { return IsHandleRedirected(ErrorHandle); } private static bool IsHandleRedirected(IntPtr handle) { // If handle is not to a character device, we must be redirected: uint fileType = Interop.Kernel32.GetFileType(handle); if ((fileType & Interop.Kernel32.FileTypes.FILE_TYPE_CHAR) != Interop.Kernel32.FileTypes.FILE_TYPE_CHAR) return true; // We are on a char device if GetConsoleMode succeeds and so we are not redirected. return (!Interop.Kernel32.IsGetConsoleModeCallSuccessful(handle)); } internal static TextReader GetOrCreateReader() { Stream inputStream = OpenStandardInput(); return SyncTextReader.GetSynchronizedTextReader(inputStream == Stream.Null ? StreamReader.Null : new StreamReader( stream: inputStream, encoding: new ConsoleEncoding(Console.InputEncoding), detectEncodingFromByteOrderMarks: false, bufferSize: Console.ReadBufferSize, leaveOpen: true)); } // Use this for blocking in Console.ReadKey, which needs to protect itself in case multiple threads call it simultaneously. // Use a ReadKey-specific lock though, to allow other fields to be initialized on this type. private static readonly object s_readKeySyncObject = new object(); // ReadLine & Read can't use this because they need to use ReadFile // to be able to handle redirected input. We have to accept that // we will lose repeated keystrokes when someone switches from // calling ReadKey to calling Read or ReadLine. Those methods should // ideally flush this cache as well. private static Interop.InputRecord _cachedInputRecord; // Skip non key events. Generally we want to surface only KeyDown event // and suppress KeyUp event from the same Key press but there are cases // where the assumption of KeyDown-KeyUp pairing for a given key press // is invalid. For example in IME Unicode keyboard input, we often see // only KeyUp until the key is released. private static bool IsKeyDownEvent(Interop.InputRecord ir) { return (ir.eventType == Interop.KEY_EVENT && ir.keyEvent.keyDown != Interop.BOOL.FALSE); } private static bool IsModKey(Interop.InputRecord ir) { // We should also skip over Shift, Control, and Alt, as well as caps lock. // Apparently we don't need to check for 0xA0 through 0xA5, which are keys like // Left Control & Right Control. See the ConsoleKey enum for these values. short keyCode = ir.keyEvent.virtualKeyCode; return ((keyCode >= 0x10 && keyCode <= 0x12) || keyCode == 0x14 || keyCode == 0x90 || keyCode == 0x91); } [Flags] internal enum ControlKeyState { RightAltPressed = 0x0001, LeftAltPressed = 0x0002, RightCtrlPressed = 0x0004, LeftCtrlPressed = 0x0008, ShiftPressed = 0x0010, NumLockOn = 0x0020, ScrollLockOn = 0x0040, CapsLockOn = 0x0080, EnhancedKey = 0x0100 } // For tracking Alt+NumPad unicode key sequence. When you press Alt key down // and press a numpad unicode decimal sequence and then release Alt key, the // desired effect is to translate the sequence into one Unicode KeyPress. // We need to keep track of the Alt+NumPad sequence and surface the final // unicode char alone when the Alt key is released. private static bool IsAltKeyDown(Interop.InputRecord ir) { return (((ControlKeyState)ir.keyEvent.controlKeyState) & (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0; } private const int NumberLockVKCode = 0x90; private const int CapsLockVKCode = 0x14; public static bool NumberLock { get { try { short s = Interop.User32.GetKeyState(NumberLockVKCode); return (s & 1) == 1; } catch (Exception) { // Since we depend on an extension api-set here // it is not guaranteed to work across the board. // In case of exception we simply throw PNSE throw new PlatformNotSupportedException(); } } } public static bool CapsLock { get { try { short s = Interop.User32.GetKeyState(CapsLockVKCode); return (s & 1) == 1; } catch (Exception) { // Since we depend on an extension api-set here // it is not guaranteed to work across the board. // In case of exception we simply throw PNSE throw new PlatformNotSupportedException(); } } } public static bool KeyAvailable { get { if (_cachedInputRecord.eventType == Interop.KEY_EVENT) return true; Interop.InputRecord ir = new Interop.InputRecord(); int numEventsRead = 0; while (true) { bool r = Interop.Kernel32.PeekConsoleInput(InputHandle, out ir, 1, out numEventsRead); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE) throw new InvalidOperationException(SR.InvalidOperation_ConsoleKeyAvailableOnFile); throw Win32Marshal.GetExceptionForWin32Error(errorCode, "stdin"); } if (numEventsRead == 0) return false; // Skip non key-down && mod key events. if (!IsKeyDownEvent(ir) || IsModKey(ir)) { r = Interop.Kernel32.ReadConsoleInput(InputHandle, out ir, 1, out numEventsRead); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } else { return true; } } } // get } private const short AltVKCode = 0x12; public static ConsoleKeyInfo ReadKey(bool intercept) { Interop.InputRecord ir; int numEventsRead = -1; bool r; lock (s_readKeySyncObject) { if (_cachedInputRecord.eventType == Interop.KEY_EVENT) { // We had a previous keystroke with repeated characters. ir = _cachedInputRecord; if (_cachedInputRecord.keyEvent.repeatCount == 0) _cachedInputRecord.eventType = -1; else { _cachedInputRecord.keyEvent.repeatCount--; } // We will return one key from this method, so we decrement the // repeatCount here, leaving the cachedInputRecord in the "queue". } else { // We did NOT have a previous keystroke with repeated characters: while (true) { r = Interop.Kernel32.ReadConsoleInput(InputHandle, out ir, 1, out numEventsRead); if (!r || numEventsRead == 0) { // This will fail when stdin is redirected from a file or pipe. // We could theoretically call Console.Read here, but I // think we might do some things incorrectly then. throw new InvalidOperationException(SR.InvalidOperation_ConsoleReadKeyOnFile); } short keyCode = ir.keyEvent.virtualKeyCode; // First check for non-keyboard events & discard them. Generally we tap into only KeyDown events and ignore the KeyUp events // but it is possible that we are dealing with a Alt+NumPad unicode key sequence, the final unicode char is revealed only when // the Alt key is released (i.e when the sequence is complete). To avoid noise, when the Alt key is down, we should eat up // any intermediate key strokes (from NumPad) that collectively forms the Unicode character. if (!IsKeyDownEvent(ir)) { // REVIEW: Unicode IME input comes through as KeyUp event with no accompanying KeyDown. if (keyCode != AltVKCode) continue; } char ch = (char)ir.keyEvent.uChar; // In a Alt+NumPad unicode sequence, when the alt key is released uChar will represent the final unicode character, we need to // surface this. VirtualKeyCode for this event will be Alt from the Alt-Up key event. This is probably not the right code, // especially when we don't expose ConsoleKey.Alt, so this will end up being the hex value (0x12). VK_PACKET comes very // close to being useful and something that we could look into using for this purpose... if (ch == 0) { // Skip mod keys. if (IsModKey(ir)) continue; } // When Alt is down, it is possible that we are in the middle of a Alt+NumPad unicode sequence. // Escape any intermediate NumPad keys whether NumLock is on or not (notepad behavior) ConsoleKey key = (ConsoleKey)keyCode; if (IsAltKeyDown(ir) && ((key >= ConsoleKey.NumPad0 && key <= ConsoleKey.NumPad9) || (key == ConsoleKey.Clear) || (key == ConsoleKey.Insert) || (key >= ConsoleKey.PageUp && key <= ConsoleKey.DownArrow))) { continue; } if (ir.keyEvent.repeatCount > 1) { ir.keyEvent.repeatCount--; _cachedInputRecord = ir; } break; } } // we did NOT have a previous keystroke with repeated characters. } ControlKeyState state = (ControlKeyState)ir.keyEvent.controlKeyState; bool shift = (state & ControlKeyState.ShiftPressed) != 0; bool alt = (state & (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0; bool control = (state & (ControlKeyState.LeftCtrlPressed | ControlKeyState.RightCtrlPressed)) != 0; ConsoleKeyInfo info = new ConsoleKeyInfo((char)ir.keyEvent.uChar, (ConsoleKey)ir.keyEvent.virtualKeyCode, shift, alt, control); if (!intercept) Console.Write(ir.keyEvent.uChar); return info; } public static bool TreatControlCAsInput { get { IntPtr handle = InputHandle; if (handle == InvalidHandleValue) throw new IOException(SR.IO_NoConsole); int mode = 0; if (!Interop.Kernel32.GetConsoleMode(handle, out mode)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); return (mode & Interop.Kernel32.ENABLE_PROCESSED_INPUT) == 0; } set { IntPtr handle = InputHandle; if (handle == InvalidHandleValue) throw new IOException(SR.IO_NoConsole); int mode = 0; Interop.Kernel32.GetConsoleMode(handle, out mode); // failure ignored in full framework if (value) { mode &= ~Interop.Kernel32.ENABLE_PROCESSED_INPUT; } else { mode |= Interop.Kernel32.ENABLE_PROCESSED_INPUT; } if (!Interop.Kernel32.SetConsoleMode(handle, mode)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } // For ResetColor private static volatile bool _haveReadDefaultColors; private static volatile byte _defaultColors; public static ConsoleColor BackgroundColor { get { bool succeeded; Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded); return succeeded ? ColorAttributeToConsoleColor((Interop.Kernel32.Color)csbi.wAttributes & Interop.Kernel32.Color.BackgroundMask) : ConsoleColor.Black; // for code that may be used from Windows app w/ no console } set { Interop.Kernel32.Color c = ConsoleColorToColorAttribute(value, true); bool succeeded; Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded); // For code that may be used from Windows app w/ no console if (!succeeded) return; Debug.Assert(_haveReadDefaultColors, "Setting the background color before we've read the default foreground color!"); short attrs = csbi.wAttributes; attrs &= ~((short)Interop.Kernel32.Color.BackgroundMask); // C#'s bitwise-or sign-extends to 32 bits. attrs = (short)(((uint)(ushort)attrs) | ((uint)(ushort)c)); // Ignore errors here - there are some scenarios for running code that wants // to print in colors to the console in a Windows application. Interop.Kernel32.SetConsoleTextAttribute(OutputHandle, attrs); } } public static ConsoleColor ForegroundColor { get { bool succeeded; Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded); // For code that may be used from Windows app w/ no console return succeeded ? ColorAttributeToConsoleColor((Interop.Kernel32.Color)csbi.wAttributes & Interop.Kernel32.Color.ForegroundMask) : ConsoleColor.Gray; } set { Interop.Kernel32.Color c = ConsoleColorToColorAttribute(value, false); bool succeeded; Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded); // For code that may be used from Windows app w/ no console if (!succeeded) return; Debug.Assert(_haveReadDefaultColors, "Setting the foreground color before we've read the default foreground color!"); short attrs = csbi.wAttributes; attrs &= ~((short)Interop.Kernel32.Color.ForegroundMask); // C#'s bitwise-or sign-extends to 32 bits. attrs = (short)(((uint)(ushort)attrs) | ((uint)(ushort)c)); // Ignore errors here - there are some scenarios for running code that wants // to print in colors to the console in a Windows application. Interop.Kernel32.SetConsoleTextAttribute(OutputHandle, attrs); } } public static void ResetColor() { if (!_haveReadDefaultColors) // avoid the costs of GetBufferInfo if we already know we checked it { bool succeeded; GetBufferInfo(false, out succeeded); if (!succeeded) return; // For code that may be used from Windows app w/ no console Debug.Assert(_haveReadDefaultColors, "Resetting color before we've read the default foreground color!"); } // Ignore errors here - there are some scenarios for running code that wants // to print in colors to the console in a Windows application. Interop.Kernel32.SetConsoleTextAttribute(OutputHandle, (short)(ushort)_defaultColors); } public static int CursorSize { get { Interop.Kernel32.CONSOLE_CURSOR_INFO cci; if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); return cci.dwSize; } set { // Value should be a percentage from [1, 100]. if (value < 1 || value > 100) throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_CursorSize); Interop.Kernel32.CONSOLE_CURSOR_INFO cci; if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); cci.dwSize = value; if (!Interop.Kernel32.SetConsoleCursorInfo(OutputHandle, ref cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static bool CursorVisible { get { Interop.Kernel32.CONSOLE_CURSOR_INFO cci; if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); return cci.bVisible; } set { Interop.Kernel32.CONSOLE_CURSOR_INFO cci; if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); cci.bVisible = value; if (!Interop.Kernel32.SetConsoleCursorInfo(OutputHandle, ref cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static int CursorLeft { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.dwCursorPosition.X; } } public static int CursorTop { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.dwCursorPosition.Y; } } public static unsafe string Title { get { Span<char> initialBuffer = stackalloc char[256]; ValueStringBuilder builder = new ValueStringBuilder(initialBuffer); while (true) { uint result = Interop.Errors.ERROR_SUCCESS; fixed (char* c = &builder.GetPinnableReference()) { result = Interop.Kernel32.GetConsoleTitleW(c, (uint)builder.Capacity); } // The documentation asserts that the console's title is stored in a shared 64KB buffer. // The magic number that used to exist here (24500) is likely related to that. // A full UNICODE_STRING is 32K chars... Debug.Assert(result <= short.MaxValue, "shouldn't be possible to grow beyond UNICODE_STRING size"); if (result == 0) { int error = Marshal.GetLastWin32Error(); switch (error) { case Interop.Errors.ERROR_INSUFFICIENT_BUFFER: // Typically this API truncates but there was a bug in RS2 so we'll make an attempt to handle builder.EnsureCapacity(builder.Capacity * 2); continue; case Interop.Errors.ERROR_SUCCESS: // The title is empty. break; default: throw Win32Marshal.GetExceptionForWin32Error(error, string.Empty); } } else if (result >= builder.Capacity - 1 || (IsWindows7() && result >= builder.Capacity / sizeof(char) - 1)) { // Our buffer was full. As this API truncates we need to increase our size and reattempt. // Note that Windows 7 copies count of bytes into the output buffer but returns count of chars // and as such our buffer is only "half" its actual size. // // (If we're Windows 10 with a version lie to 7 this will be inefficient so we'll want to remove // this workaround when we no longer support Windows 7) builder.EnsureCapacity(builder.Capacity * 2); continue; } builder.Length = (int)result; break; } return builder.ToString(); } set { if (!Interop.Kernel32.SetConsoleTitle(value)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static void Beep() { const int BeepFrequencyInHz = 800; const int BeepDurationInMs = 200; Interop.Kernel32.Beep(BeepFrequencyInHz, BeepDurationInMs); } public static void Beep(int frequency, int duration) { const int MinBeepFrequency = 37; const int MaxBeepFrequency = 32767; if (frequency < MinBeepFrequency || frequency > MaxBeepFrequency) throw new ArgumentOutOfRangeException(nameof(frequency), frequency, SR.Format(SR.ArgumentOutOfRange_BeepFrequency, MinBeepFrequency, MaxBeepFrequency)); if (duration <= 0) throw new ArgumentOutOfRangeException(nameof(duration), duration, SR.ArgumentOutOfRange_NeedPosNum); Interop.Kernel32.Beep(frequency, duration); } public static unsafe void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) { if (sourceForeColor < ConsoleColor.Black || sourceForeColor > ConsoleColor.White) throw new ArgumentException(SR.Arg_InvalidConsoleColor, nameof(sourceForeColor)); if (sourceBackColor < ConsoleColor.Black || sourceBackColor > ConsoleColor.White) throw new ArgumentException(SR.Arg_InvalidConsoleColor, nameof(sourceBackColor)); Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); Interop.Kernel32.COORD bufferSize = csbi.dwSize; if (sourceLeft < 0 || sourceLeft > bufferSize.X) throw new ArgumentOutOfRangeException(nameof(sourceLeft), sourceLeft, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (sourceTop < 0 || sourceTop > bufferSize.Y) throw new ArgumentOutOfRangeException(nameof(sourceTop), sourceTop, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (sourceWidth < 0 || sourceWidth > bufferSize.X - sourceLeft) throw new ArgumentOutOfRangeException(nameof(sourceWidth), sourceWidth, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (sourceHeight < 0 || sourceTop > bufferSize.Y - sourceHeight) throw new ArgumentOutOfRangeException(nameof(sourceHeight), sourceHeight, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); // Note: if the target range is partially in and partially out // of the buffer, then we let the OS clip it for us. if (targetLeft < 0 || targetLeft > bufferSize.X) throw new ArgumentOutOfRangeException(nameof(targetLeft), targetLeft, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (targetTop < 0 || targetTop > bufferSize.Y) throw new ArgumentOutOfRangeException(nameof(targetTop), targetTop, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); // If we're not doing any work, bail out now (Windows will return // an error otherwise) if (sourceWidth == 0 || sourceHeight == 0) return; // Read data from the original location, blank it out, then write // it to the new location. This will handle overlapping source and // destination regions correctly. // Read the old data Interop.Kernel32.CHAR_INFO[] data = new Interop.Kernel32.CHAR_INFO[sourceWidth * sourceHeight]; bufferSize.X = (short)sourceWidth; bufferSize.Y = (short)sourceHeight; Interop.Kernel32.COORD bufferCoord = new Interop.Kernel32.COORD(); Interop.Kernel32.SMALL_RECT readRegion = new Interop.Kernel32.SMALL_RECT(); readRegion.Left = (short)sourceLeft; readRegion.Right = (short)(sourceLeft + sourceWidth - 1); readRegion.Top = (short)sourceTop; readRegion.Bottom = (short)(sourceTop + sourceHeight - 1); bool r; fixed (Interop.Kernel32.CHAR_INFO* pCharInfo = data) r = Interop.Kernel32.ReadConsoleOutput(OutputHandle, pCharInfo, bufferSize, bufferCoord, ref readRegion); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); // Overwrite old section Interop.Kernel32.COORD writeCoord = new Interop.Kernel32.COORD(); writeCoord.X = (short)sourceLeft; Interop.Kernel32.Color c = ConsoleColorToColorAttribute(sourceBackColor, true); c |= ConsoleColorToColorAttribute(sourceForeColor, false); short attr = (short)c; int numWritten; for (int i = sourceTop; i < sourceTop + sourceHeight; i++) { writeCoord.Y = (short)i; r = Interop.Kernel32.FillConsoleOutputCharacter(OutputHandle, sourceChar, sourceWidth, writeCoord, out numWritten); Debug.Assert(numWritten == sourceWidth, "FillConsoleOutputCharacter wrote the wrong number of chars!"); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); r = Interop.Kernel32.FillConsoleOutputAttribute(OutputHandle, attr, sourceWidth, writeCoord, out numWritten); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } // Write text to new location Interop.Kernel32.SMALL_RECT writeRegion = new Interop.Kernel32.SMALL_RECT(); writeRegion.Left = (short)targetLeft; writeRegion.Right = (short)(targetLeft + sourceWidth); writeRegion.Top = (short)targetTop; writeRegion.Bottom = (short)(targetTop + sourceHeight); fixed (Interop.Kernel32.CHAR_INFO* pCharInfo = data) Interop.Kernel32.WriteConsoleOutput(OutputHandle, pCharInfo, bufferSize, bufferCoord, ref writeRegion); } public static void Clear() { Interop.Kernel32.COORD coordScreen = new Interop.Kernel32.COORD(); Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi; bool success; int conSize; IntPtr hConsole = OutputHandle; if (hConsole == InvalidHandleValue) throw new IOException(SR.IO_NoConsole); // get the number of character cells in the current buffer // Go through my helper method for fetching a screen buffer info // to correctly handle default console colors. csbi = GetBufferInfo(); conSize = csbi.dwSize.X * csbi.dwSize.Y; // fill the entire screen with blanks int numCellsWritten = 0; success = Interop.Kernel32.FillConsoleOutputCharacter(hConsole, ' ', conSize, coordScreen, out numCellsWritten); if (!success) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); // now set the buffer's attributes accordingly numCellsWritten = 0; success = Interop.Kernel32.FillConsoleOutputAttribute(hConsole, csbi.wAttributes, conSize, coordScreen, out numCellsWritten); if (!success) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); // put the cursor at (0, 0) success = Interop.Kernel32.SetConsoleCursorPosition(hConsole, coordScreen); if (!success) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } public static void SetCursorPosition(int left, int top) { IntPtr hConsole = OutputHandle; Interop.Kernel32.COORD coords = new Interop.Kernel32.COORD(); coords.X = (short)left; coords.Y = (short)top; if (!Interop.Kernel32.SetConsoleCursorPosition(hConsole, coords)) { // Give a nice error message for out of range sizes int errorCode = Marshal.GetLastWin32Error(); Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); if (left >= csbi.dwSize.X) throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (top >= csbi.dwSize.Y) throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } public static int BufferWidth { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.dwSize.X; } set { SetBufferSize(value, BufferHeight); } } public static int BufferHeight { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.dwSize.Y; } set { SetBufferSize(BufferWidth, value); } } public static void SetBufferSize(int width, int height) { // Ensure the new size is not smaller than the console window Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); Interop.Kernel32.SMALL_RECT srWindow = csbi.srWindow; if (width < srWindow.Right + 1 || width >= short.MaxValue) throw new ArgumentOutOfRangeException(nameof(width), width, SR.ArgumentOutOfRange_ConsoleBufferLessThanWindowSize); if (height < srWindow.Bottom + 1 || height >= short.MaxValue) throw new ArgumentOutOfRangeException(nameof(height), height, SR.ArgumentOutOfRange_ConsoleBufferLessThanWindowSize); Interop.Kernel32.COORD size = new Interop.Kernel32.COORD(); size.X = (short)width; size.Y = (short)height; if (!Interop.Kernel32.SetConsoleScreenBufferSize(OutputHandle, size)) { throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static int LargestWindowWidth { get { // Note this varies based on current screen resolution and // current console font. Do not cache this value. Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle); return bounds.X; } } public static int LargestWindowHeight { get { // Note this varies based on current screen resolution and // current console font. Do not cache this value. Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle); return bounds.Y; } } public static int WindowLeft { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.srWindow.Left; } set { SetWindowPosition(value, WindowTop); } } public static int WindowTop { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.srWindow.Top; } set { SetWindowPosition(WindowLeft, value); } } public static int WindowWidth { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.srWindow.Right - csbi.srWindow.Left + 1; } set { SetWindowSize(value, WindowHeight); } } public static int WindowHeight { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.srWindow.Bottom - csbi.srWindow.Top + 1; } set { SetWindowSize(WindowWidth, value); } } public static unsafe void SetWindowPosition(int left, int top) { // Get the size of the current console window Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); Interop.Kernel32.SMALL_RECT srWindow = csbi.srWindow; // Check for arithmetic underflows & overflows. int newRight = left + srWindow.Right - srWindow.Left + 1; if (left < 0 || newRight > csbi.dwSize.X || newRight < 0) throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleWindowPos); int newBottom = top + srWindow.Bottom - srWindow.Top + 1; if (top < 0 || newBottom > csbi.dwSize.Y || newBottom < 0) throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleWindowPos); // Preserve the size, but move the position. srWindow.Bottom -= (short)(srWindow.Top - top); srWindow.Right -= (short)(srWindow.Left - left); srWindow.Left = (short)left; srWindow.Top = (short)top; bool r = Interop.Kernel32.SetConsoleWindowInfo(OutputHandle, true, &srWindow); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } public static unsafe void SetWindowSize(int width, int height) { if (width <= 0) throw new ArgumentOutOfRangeException(nameof(width), width, SR.ArgumentOutOfRange_NeedPosNum); if (height <= 0) throw new ArgumentOutOfRangeException(nameof(height), height, SR.ArgumentOutOfRange_NeedPosNum); // Get the position of the current console window Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); // If the buffer is smaller than this new window size, resize the // buffer to be large enough. Include window position. bool resizeBuffer = false; Interop.Kernel32.COORD size = new Interop.Kernel32.COORD(); size.X = csbi.dwSize.X; size.Y = csbi.dwSize.Y; if (csbi.dwSize.X < csbi.srWindow.Left + width) { if (csbi.srWindow.Left >= short.MaxValue - width) throw new ArgumentOutOfRangeException(nameof(width), SR.Format(SR.ArgumentOutOfRange_ConsoleWindowBufferSize, short.MaxValue - width)); size.X = (short)(csbi.srWindow.Left + width); resizeBuffer = true; } if (csbi.dwSize.Y < csbi.srWindow.Top + height) { if (csbi.srWindow.Top >= short.MaxValue - height) throw new ArgumentOutOfRangeException(nameof(height), SR.Format(SR.ArgumentOutOfRange_ConsoleWindowBufferSize, short.MaxValue - height)); size.Y = (short)(csbi.srWindow.Top + height); resizeBuffer = true; } if (resizeBuffer) { if (!Interop.Kernel32.SetConsoleScreenBufferSize(OutputHandle, size)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } Interop.Kernel32.SMALL_RECT srWindow = csbi.srWindow; // Preserve the position, but change the size. srWindow.Bottom = (short)(srWindow.Top + height - 1); srWindow.Right = (short)(srWindow.Left + width - 1); if (!Interop.Kernel32.SetConsoleWindowInfo(OutputHandle, true, &srWindow)) { int errorCode = Marshal.GetLastWin32Error(); // If we resized the buffer, un-resize it. if (resizeBuffer) { Interop.Kernel32.SetConsoleScreenBufferSize(OutputHandle, csbi.dwSize); } // Try to give a better error message here Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle); if (width > bounds.X) throw new ArgumentOutOfRangeException(nameof(width), width, SR.Format(SR.ArgumentOutOfRange_ConsoleWindowSize_Size, bounds.X)); if (height > bounds.Y) throw new ArgumentOutOfRangeException(nameof(height), height, SR.Format(SR.ArgumentOutOfRange_ConsoleWindowSize_Size, bounds.Y)); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } private static Interop.Kernel32.Color ConsoleColorToColorAttribute(ConsoleColor color, bool isBackground) { if ((((int)color) & ~0xf) != 0) throw new ArgumentException(SR.Arg_InvalidConsoleColor); Interop.Kernel32.Color c = (Interop.Kernel32.Color)color; // Make these background colors instead of foreground if (isBackground) c = (Interop.Kernel32.Color)((int)c << 4); return c; } private static ConsoleColor ColorAttributeToConsoleColor(Interop.Kernel32.Color c) { // Turn background colors into foreground colors. if ((c & Interop.Kernel32.Color.BackgroundMask) != 0) { c = (Interop.Kernel32.Color)(((int)c) >> 4); } return (ConsoleColor)c; } private static Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo() { bool unused; return GetBufferInfo(true, out unused); } // For apps that don't have a console (like Windows apps), they might // run other code that includes color console output. Allow a mechanism // where that code won't throw an exception for simple errors. private static Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo(bool throwOnNoConsole, out bool succeeded) { succeeded = false; IntPtr outputHandle = OutputHandle; if (outputHandle == InvalidHandleValue) { if (throwOnNoConsole) { throw new IOException(SR.IO_NoConsole); } return new Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO(); } // Note that if stdout is redirected to a file, the console handle may be a file. // First try stdout; if this fails, try stderr and then stdin. Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi; if (!Interop.Kernel32.GetConsoleScreenBufferInfo(outputHandle, out csbi) && !Interop.Kernel32.GetConsoleScreenBufferInfo(ErrorHandle, out csbi) && !Interop.Kernel32.GetConsoleScreenBufferInfo(InputHandle, out csbi)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE && !throwOnNoConsole) return new Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } if (!_haveReadDefaultColors) { // Fetch the default foreground and background color for the ResetColor method. Debug.Assert((int)Interop.Kernel32.Color.ColorMask == 0xff, "Make sure one byte is large enough to store a Console color value!"); _defaultColors = (byte)(csbi.wAttributes & (short)Interop.Kernel32.Color.ColorMask); _haveReadDefaultColors = true; // also used by ResetColor to know when GetBufferInfo has been called successfully } succeeded = true; return csbi; } private sealed class WindowsConsoleStream : ConsoleStream { // We know that if we are using console APIs rather than file APIs, then the encoding // is Encoding.Unicode implying 2 bytes per character: private const int BytesPerWChar = 2; private readonly bool _isPipe; // When reading from pipes, we need to properly handle EOF cases. private IntPtr _handle; private readonly bool _useFileAPIs; internal WindowsConsoleStream(IntPtr handle, FileAccess access, bool useFileAPIs) : base(access) { Debug.Assert(handle != IntPtr.Zero && handle != InvalidHandleValue, "ConsoleStream expects a valid handle!"); _handle = handle; _isPipe = Interop.Kernel32.GetFileType(handle) == Interop.Kernel32.FileTypes.FILE_TYPE_PIPE; _useFileAPIs = useFileAPIs; } protected override void Dispose(bool disposing) { // We're probably better off not closing the OS handle here. First, // we allow a program to get multiple instances of ConsoleStreams // around the same OS handle, so closing one handle would invalidate // them all. Additionally, we want a second AppDomain to be able to // write to stdout if a second AppDomain quits. _handle = IntPtr.Zero; base.Dispose(disposing); } public override int Read(byte[] buffer, int offset, int count) { ValidateRead(buffer, offset, count); int bytesRead; int errCode = ReadFileNative(_handle, buffer, offset, count, _isPipe, out bytesRead, _useFileAPIs); if (Interop.Errors.ERROR_SUCCESS != errCode) throw Win32Marshal.GetExceptionForWin32Error(errCode); return bytesRead; } public override void Write(byte[] buffer, int offset, int count) { ValidateWrite(buffer, offset, count); int errCode = WriteFileNative(_handle, buffer, offset, count, _useFileAPIs); if (Interop.Errors.ERROR_SUCCESS != errCode) throw Win32Marshal.GetExceptionForWin32Error(errCode); } public override void Flush() { if (_handle == IntPtr.Zero) throw Error.GetFileNotOpen(); base.Flush(); } // P/Invoke wrappers for writing to and from a file, nearly identical // to the ones on FileStream. These are duplicated to save startup/hello // world working set and to avoid requiring a reference to the // System.IO.FileSystem contract. private static unsafe int ReadFileNative(IntPtr hFile, byte[] bytes, int offset, int count, bool isPipe, out int bytesRead, bool useFileAPIs) { Debug.Assert(offset >= 0, "offset >= 0"); Debug.Assert(count >= 0, "count >= 0"); Debug.Assert(bytes != null, "bytes != null"); // Don't corrupt memory when multiple threads are erroneously writing // to this stream simultaneously. if (bytes.Length - offset < count) throw new IndexOutOfRangeException(SR.IndexOutOfRange_IORaceCondition); // You can't use the fixed statement on an array of length 0. if (bytes.Length == 0) { bytesRead = 0; return Interop.Errors.ERROR_SUCCESS; } bool readSuccess; fixed (byte* p = &bytes[0]) { if (useFileAPIs) { readSuccess = (0 != Interop.Kernel32.ReadFile(hFile, p + offset, count, out bytesRead, IntPtr.Zero)); } else { // If the code page could be Unicode, we should use ReadConsole instead, e.g. int charsRead; readSuccess = Interop.Kernel32.ReadConsole(hFile, p + offset, count / BytesPerWChar, out charsRead, IntPtr.Zero); bytesRead = charsRead * BytesPerWChar; } } if (readSuccess) return Interop.Errors.ERROR_SUCCESS; // For pipes that are closing or broken, just stop. // (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing; // ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is mot an error, but EOF.) int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_NO_DATA || errorCode == Interop.Errors.ERROR_BROKEN_PIPE) return Interop.Errors.ERROR_SUCCESS; return errorCode; } private static unsafe int WriteFileNative(IntPtr hFile, byte[] bytes, int offset, int count, bool useFileAPIs) { Debug.Assert(offset >= 0, "offset >= 0"); Debug.Assert(count >= 0, "count >= 0"); Debug.Assert(bytes != null, "bytes != null"); Debug.Assert(bytes.Length >= offset + count, "bytes.Length >= offset + count"); // You can't use the fixed statement on an array of length 0. if (bytes.Length == 0) return Interop.Errors.ERROR_SUCCESS; bool writeSuccess; fixed (byte* p = &bytes[0]) { if (useFileAPIs) { int numBytesWritten; writeSuccess = (0 != Interop.Kernel32.WriteFile(hFile, p + offset, count, out numBytesWritten, IntPtr.Zero)); // In some cases we have seen numBytesWritten returned that is twice count; // so we aren't asserting the value of it. See corefx #24508 } else { // If the code page could be Unicode, we should use ReadConsole instead, e.g. // Note that WriteConsoleW has a max limit on num of chars to write (64K) // [https://docs.microsoft.com/en-us/windows/console/writeconsole] // However, we do not need to worry about that because the StreamWriter in Console has // a much shorter buffer size anyway. int charsWritten; writeSuccess = Interop.Kernel32.WriteConsole(hFile, p + offset, count / BytesPerWChar, out charsWritten, IntPtr.Zero); Debug.Assert(!writeSuccess || count / BytesPerWChar == charsWritten); } } if (writeSuccess) return Interop.Errors.ERROR_SUCCESS; // For pipes that are closing or broken, just stop. // (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing; // ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is not an error, but EOF.) int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_NO_DATA || errorCode == Interop.Errors.ERROR_BROKEN_PIPE) return Interop.Errors.ERROR_SUCCESS; return errorCode; } } internal sealed class ControlCHandlerRegistrar { private bool _handlerRegistered; private readonly Interop.Kernel32.ConsoleCtrlHandlerRoutine _handler; internal ControlCHandlerRegistrar() { _handler = new Interop.Kernel32.ConsoleCtrlHandlerRoutine(BreakEvent); } internal void Register() { Debug.Assert(!_handlerRegistered); bool r = Interop.Kernel32.SetConsoleCtrlHandler(_handler, true); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(); } _handlerRegistered = true; } internal void Unregister() { Debug.Assert(_handlerRegistered); bool r = Interop.Kernel32.SetConsoleCtrlHandler(_handler, false); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(); } _handlerRegistered = false; } private static bool BreakEvent(int controlType) { if (controlType != Interop.Kernel32.CTRL_C_EVENT && controlType != Interop.Kernel32.CTRL_BREAK_EVENT) { return false; } return Console.HandleBreakEvent(controlType == Interop.Kernel32.CTRL_C_EVENT ? ConsoleSpecialKey.ControlC : ConsoleSpecialKey.ControlBreak); } } } }
// // - Adaptable.cs - // // Copyright 2005, 2006, 2010 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Carbonfrost.Commons.ComponentModel.Annotations; using Carbonfrost.Commons.Shared.Runtime.Components; namespace Carbonfrost.Commons.Shared.Runtime { public static partial class Adaptable { const string DEVELOPER = "Developer"; static readonly WeakCache<IActivationProvider> activationProviderCache = new WeakCache<IActivationProvider>(MakeActivationProvider); public static Type GetConcreteClass(this PropertyDescriptor property, IServiceProvider serviceProvider = null) { if (property == null) throw new ArgumentNullException("property"); // $NON-NLS-1 var cca = GetConcreteClassProvider(property); Type type = property.PropertyType; if (cca == null) return (type.IsAbstract || type.IsInterface) ? null : type; else return cca.GetConcreteClass(property.PropertyType, serviceProvider); } public static Type GetConcreteClass(this Type type, IServiceProvider serviceProvider = null) { if (type == null) throw new ArgumentNullException("type"); // $NON-NLS-1 var cca = GetConcreteClassProvider(type); if (cca == null) return (type.IsAbstract || type.IsInterface) ? null : type; else return cca.GetConcreteClass(type, serviceProvider); } public static IConcreteClassProvider GetConcreteClassProvider(this Type type) { if (type == null) throw new ArgumentNullException("type"); // $NON-NLS-1 return type.GetCustomAttributes(false).OfType<IConcreteClassProvider>().FirstOrDefault(); } public static IConcreteClassProvider GetConcreteClassProvider(this PropertyDescriptor property) { if (property == null) throw new ArgumentNullException("property"); return property.Attributes.OfType<IConcreteClassProvider>().FirstOrDefault(); } public static AttributeUsageAttribute GetAttributeUsage(this Type attributeType) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Require.SubclassOf("attributeType", attributeType, typeof(Attribute)); return (AttributeUsageAttribute) Attribute.GetCustomAttribute(attributeType, typeof(AttributeUsageAttribute)) ?? new AttributeUsageAttribute(AttributeTargets.All); } public static StreamingSourceUsageAttribute GetStreamingSourceUsage(this Type streamingSourceType) { if (streamingSourceType == null) throw new ArgumentNullException("streamingSourceType"); Require.SubclassOf("streamingSourceType", streamingSourceType, typeof(StreamingSource)); return (StreamingSourceUsageAttribute) streamingSourceType.GetAttribute<StreamingSourceUsageAttribute>(); } public static ConstructorInfo GetActivationConstructor(this Type type) { if (type == null) throw new ArgumentNullException("type"); // $NON-NLS-1 ConstructorInfo[] ci = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (ci.Length == 0) return null; else return ci.FirstOrDefault(IsActivationConstructor) ?? ci[0]; } public static IActivationProvider[] GetActivationProviders(this PropertyDescriptor property) { if (property == null) throw new ArgumentNullException("property"); // $NON-NLS-1 return property.Attributes.OfType<IActivationProvider>().ToArray(); } public static IActivationProvider[] GetActivationProviders(this Type type) { if (type == null) throw new ArgumentNullException("type"); // Each interface is considered to see if it has an activation provider; the type's // attributes are also considered to see if they are IActivationProvider or define // an activation provider List<IActivationProvider> results = new List<IActivationProvider>(); HashSet<Type> e = new HashSet<Type>( type.GetInterfaces() .Select(i => i.GetActivationProviderType()) .WhereNotNull()); foreach (var f in type.GetCustomAttributes(true)) { IActivationProvider ap = f as IActivationProvider; if (ap != null) { results.Add(ap); } else e.AddIfNotNull(f.GetType().GetActivationProviderType()); } results.AddRange(activationProviderCache.GetAll(e)); return results.ToArray(); } public static SharedRuntimeOptionsAttribute GetSharedRuntimeOptions( this Assembly assembly) { if (assembly == null) throw new ArgumentNullException("assembly"); var attr = assembly.GetAttribute<SharedRuntimeOptionsAttribute>(); if (attr == null) { // Optimizations for system assemblies if (Utility.IsScannableAssembly(assembly)) return SharedRuntimeOptionsAttribute.Default; else return SharedRuntimeOptionsAttribute.Optimized; } else { return attr; } } public static IEnumerable<Type> FilterTypes( this AppDomain appDomain, Func<Type, bool> predicate) { if (appDomain == null) throw new ArgumentNullException("appDomain"); return DescribeTypes( appDomain, a => (predicate(a) ? new Type[] { a } : null)); } public static IEnumerable<Type> GetTypesByNamespaceUri( this Assembly assembly, NamespaceUri namespaceUri) { if (assembly == null) throw new ArgumentNullException("assembly"); if (namespaceUri == null) throw new ArgumentNullException("namespaceUri"); return assembly.GetTypesHelper().Where(t => t.GetQualifiedName().Namespace == namespaceUri); } public static IEnumerable<string> FilterNamespaces( this Assembly assembly, string namespacePattern) { if (assembly == null) throw new ArgumentNullException("assembly"); return Utility.FilterNamespaces(assembly.GetNamespaces(), namespacePattern); } public static IEnumerable<Assembly> FilterAssemblies( this AppDomain appDomain, Func<Assembly, bool> predicate) { if (appDomain == null) throw new ArgumentNullException("appDomain"); return DescribeAssemblies( appDomain, a => (predicate(a) ? new Assembly[] { a } : null)); } // TODO Actually consider the appdomain in use public static IEnumerable<Assembly> DescribeAssemblies( this AppDomain appDomain) { if (appDomain == null) throw new ArgumentNullException("appDomain"); return new Buffer<Assembly>(AssemblyBuffer.Instance); } public static IEnumerable<TValue> DescribeAssemblies<TValue>( this AppDomain appDomain, Func<Assembly, IEnumerable<TValue>> selector) { if (appDomain == null) throw new ArgumentNullException("appDomain"); if (selector == null) throw new ArgumentNullException("selector"); return new Buffer<TValue>( AssemblyBuffer.Instance.SelectMany(t => selector(t) ?? Empty<TValue>.Array)); } public static IDictionary<TKey, TValue> DescribeAssemblies<TKey, TValue>( this AppDomain appDomain, Func<Assembly, IEnumerable<KeyValuePair<TKey, TValue>>> selector) { if (appDomain == null) throw new ArgumentNullException("appDomain"); if (selector == null) throw new ArgumentNullException("selector"); return LazyDescriptionDictionary<TKey, TValue>.Create(selector); } public static IEnumerable<TValue> DescribeTypes<TValue>( this AppDomain appDomain, Func<Type, IEnumerable<TValue>> selector) { if (appDomain == null) throw new ArgumentNullException("appDomain"); if (selector == null) throw new ArgumentNullException("selector"); var s = AssemblyThunk(selector); return new Buffer<TValue>(AssemblyBuffer.Instance.SelectMany(s)); } public static IDictionary<TKey, TValue> DescribeTypes<TKey, TValue>( this AppDomain appDomain, Func<Type, IEnumerable<KeyValuePair<TKey, TValue>>> selector) { if (selector == null) throw new ArgumentNullException("selector"); return LazyDescriptionDictionary<TKey, TValue>.Create(AssemblyThunk(selector)); } static Func<Assembly, IEnumerable<TValue>> AssemblyThunk<TValue>(Func<Type, IEnumerable<TValue>> selector) { return (a) => (a.GetTypesHelper().SelectMany(selector) ?? Empty<TValue>.Array); } public static bool IsDefined<TAttribute>(this MemberInfo source, bool inherit = false) where TAttribute : Attribute { return source.GetAttribute<TAttribute>(inherit) != null; } public static IEnumerable<TAttribute> GetAttributes<TAttribute>(this MemberInfo source, bool inherit = false) where TAttribute : Attribute { // TODO Also obtain annotation attributes AttributeCompleteAppDomain(typeof(TAttribute)); return Attribute.GetCustomAttributes(source, typeof(TAttribute), inherit).Cast<TAttribute>(); } public static TAttribute GetAttribute<TAttribute>(this MemberInfo source, bool inherit = false) where TAttribute : Attribute { AttributeCompleteAppDomain(typeof(TAttribute)); return Attribute.GetCustomAttribute(source, typeof(TAttribute), inherit) as TAttribute; } public static TAttribute GetAttribute<TAttribute>(this Assembly source) where TAttribute : Attribute { AttributeCompleteAppDomain(typeof(TAttribute)); return Attribute.GetCustomAttribute(source, typeof(TAttribute), false) as TAttribute; } public static IEnumerable<MethodInfo> GetImplicitFilterMethods(this PropertyDescriptor property, Type attributeType) { if (property == null) throw new ArgumentNullException("property"); // $NON-NLS-1 if (attributeType == null) throw new ArgumentNullException("attributeType"); // $NON-NLS-1 // For instance, LocalizableAtrribute/Title ==> GetLocalizableTitle string nakedName = Utility.GetImpliedName(attributeType, "Attribute"); string methodName = string.Concat("Get", nakedName, property.Name); return property.ComponentType.GetMethods().Where(mi => mi.Name == methodName); } public static AssemblyName GetExtensionAssembly(this AssemblyName assemblyName) { return GetExtensionAssembly(assemblyName, null); } public static AssemblyName GetExtensionAssembly(this AssemblyName assemblyName, string extensionName) { if (assemblyName == null) throw new ArgumentNullException("assemblyName"); // $NON-NLS-1 if (string.IsNullOrEmpty(extensionName)) extensionName = "Extensions"; // Carbonfrost.Commons.Membership.Extensions.dll ComponentNameBuilder builder = new ComponentNameBuilder(ComponentName.FromAssemblyName(assemblyName)); Version v = assemblyName.Version; builder.Name += ("." + extensionName); builder.Culture = null; builder.Version = new Version(v.Major, v.Minor); return builder.Build().ToAssemblyName(); } public static Assembly GetDeveloperAssembly(this Assembly assembly) { if (assembly == null) throw new ArgumentNullException("assembly"); // $NON-NLS-1 return Assembly.Load(GetExtensionAssembly(assembly.GetName(), DEVELOPER)); } public static Assembly GetExtensionAssembly(this Assembly assembly) { if (assembly == null) throw new ArgumentNullException("assembly"); // $NON-NLS-1 return Assembly.Load(GetExtensionAssembly(assembly.GetName())); } public static Assembly GetExtensionAssembly(this Assembly assembly, string extensionName) { if (assembly == null) throw new ArgumentNullException("assembly"); // $NON-NLS-1 return Assembly.Load(GetExtensionAssembly(assembly.GetName(), extensionName)); } public static object GetInheritanceParent(this object instance) { if (instance == null) throw new ArgumentNullException("instance"); IHierarchyObject ho = Adaptable.TryAdapt<IHierarchyObject>(instance); if (ho != null) return ho.ParentObject; PropertyInfo pi = instance.GetType().GetProperty("InheritanceParent"); if (pi != null) return pi.GetValue(instance, null); return null; } public static object GetInheritanceAncestor(this object instance, Type ancestorType) { if (instance == null) throw new ArgumentNullException("instance"); Require.ReferenceType("ancestorType", ancestorType); object result = instance.GetInheritanceParent(); if (result == null) return null; if (ancestorType.IsInstanceOfType(instance)) return result; return GetInheritanceAncestor(result, ancestorType); } public static T GetInheritanceAncestor<T>(this object instance, T defaultValue = null) where T : class { if (instance == null) throw new ArgumentNullException("instance"); object result = instance.GetInheritanceParent(); if (result == null) return defaultValue; T t = result as T; if (t != null) return t; return GetInheritanceAncestor<T>(result); } public static TypeReference GetExtensionImplementationType( this Type sourceType, string feature) { if (sourceType == null) throw new ArgumentNullException("sourceType"); // $NON-NLS-1 if (string.IsNullOrWhiteSpace(feature)) throw Failure.AllWhitespace("sourceType"); return TypeReference.Parse(GetExtensionImplementation(sourceType, feature)); } public static object Adapt(this object source, string adapterRoleName, IServiceProvider serviceProvider = null) { object result = TryAdapt(source, adapterRoleName, serviceProvider); if (result == null) throw Failure.NotAdaptableTo("source", source, adapterRoleName); else return result; } public static object Adapt(this object source, Type adapterType, IServiceProvider serviceProvider = null) { object result = TryAdapt(source, adapterType, serviceProvider); if (result == null) throw Failure.NotAdaptableTo("source", source, adapterType); else return result; } public static T Adapt<T>(this object source, IServiceProvider serviceProvider = null) where T: class { return (T) Adapt(source, typeof(T), serviceProvider); } public static object TryAdapt(this object source, string adapterRoleName, IServiceProvider serviceProvider = null) { if (source == null) throw new ArgumentNullException("source"); // $NON-NLS-1 Require.NotNullOrEmptyString("adapterRoleName", adapterRoleName); // $NON-NLS-1 object result = null; var dict = Adaptable.GetAdapterRoles(source.GetType(), true); Type[] candidates; if (dict.TryGetValue(adapterRoleName, out candidates) && candidates.Length > 0) { var pms = Properties.FromArray(source); result = Activation.CreateInstance(candidates[0], pms); } return result; } public static object TryAdapt(this object source, Type adapterType, IServiceProvider serviceProvider = null) { if (source == null) throw new ArgumentNullException("source"); // $NON-NLS-1 if (adapterType == null) throw new ArgumentNullException("adapterType"); // $NON-NLS-1 if (adapterType.IsInstanceOfType(source)) return source; object result = null; IAdaptable a = source as IAdaptable; if (a != null) result = a.GetAdapter(adapterType); return result; } public static T TryAdapt<T>(this object source, IServiceProvider serviceProvider = null) where T: class { return (T) TryAdapt(source, typeof(T), serviceProvider); } public static Uri GetComponentUri(this Assembly assembly) { if (assembly == null) throw new ArgumentNullException("assembly"); Uri uriIfAny = null; if (assembly.CodeBase != null) uriIfAny = new Uri(assembly.CodeBase); return Components.Component.Assembly(assembly.GetName(), uriIfAny).ToUri(); } public static string[] GetAdapterRoleNames(this Type adapteeType) { if (adapteeType == null) throw new ArgumentNullException("adapteeType"); // $NON-NLS-1 return GetAdapterRoleNames(adapteeType, true); } public static string[] GetAdapterRoleNames(this Type adapteeType, bool inherit) { if (adapteeType == null) throw new ArgumentNullException("adapteeType"); return GetAdapterRoles(adapteeType, inherit).Keys.ToArray(); } public static IDictionary<string, Type[]> GetAdapterRoles(this Type adapteeType) { return GetAdapterRoles(adapteeType, true); } public static IDictionary<string, Type[]> GetAdapterRoles(this Type adapteeType, bool inherit) { if (adapteeType == null) throw new ArgumentNullException("adapteeType"); AdapterAttribute[] items = (AdapterAttribute[]) adapteeType.GetCustomAttributes(typeof(AdapterAttribute), inherit); var lookup = items.ToLookup(t => t.Role, t => t.AdapterType); return lookup.ToDictionary(t => t.Key, t => t.ToArray()); } public static Type GetAdapterType(this Type adapteeType, string adapterRoleName) { return _GetAdapterTypes(adapteeType, adapterRoleName, false).FirstOrDefault(); } public static Type GetAdapterType(this Type adapteeType, string adapterRoleName, bool inherit) { return _GetAdapterTypes(adapteeType, adapterRoleName, inherit).FirstOrDefault(); } public static Type[] GetAdapterTypes(this Type adapteeType, string adapterRoleName) { return _GetAdapterTypes(adapteeType, adapterRoleName, false).ToArray(); } public static Type[] GetAdapterTypes(this Type adapteeType, string adapterRoleName, bool inherit) { return _GetAdapterTypes(adapteeType, adapterRoleName, inherit).ToArray(); } public static IEnumerable<string> GetComponentTypes(this AppDomain appDomain) { if (appDomain == null) throw new ArgumentNullException("appDomain"); return appDomain.GetProviderNames(typeof(IRuntimeComponent)) .Select(t => t.LocalName); } public static Type GetImplicitAdapterType(this Type adapteeType, string adapterRoleName) { if (adapteeType == null) throw new ArgumentNullException("adapteeType"); // $NON-NLS-1 Require.NotNullOrAllWhitespace("adapterRoleName", adapterRoleName); Type result = adapteeType.Assembly.GetType( adapteeType.FullName + adapterRoleName); if (result != null && IsValidAdapter(result, adapterRoleName)) return result; else return null; } public static Type GetImplicitBuilderType(this Type adapteeType) { if (adapteeType == null) throw new ArgumentNullException("adapteeType"); // $NON-NLS-1 return GetImplicitAdapterType(adapteeType, AdapterRole.Builder); } public static Type GetImplicitStreamingSourceType(this Type adapteeType) { if (adapteeType == null) throw new ArgumentNullException("adapteeType"); // $NON-NLS-1 return GetImplicitAdapterType(adapteeType, AdapterRole.StreamingSource); } // N.B. These are needed because C# cannot infer Func<..> in most cases public static Func<TResult> CreateAdapterFunction<TResult>(this object instance, string name, Expression<Func<TResult>> signature) { return CreateAdapterFunction<Func<TResult>>(instance, name, signature); } public static Func<T, TResult> CreateAdapterFunction<T, TResult>(this object instance, string name, Expression<Func<T, TResult>> signature) { return CreateAdapterFunction<Func<T, TResult>>(instance, name, signature); } public static Func<T1, T2, TResult> CreateAdapterFunction<T1, T2, TResult>(this object instance, string name, Expression<Func<T1, T2, TResult>> signature) { return CreateAdapterFunction<Func<T1, T2, TResult>>(instance, name, signature); } public static Func<T1, T2, T3, TResult> CreateAdapterFunction<T1, T2, T3, TResult>(this object instance, string name, Expression<Func<T1, T2, T3, TResult>> signature) { return CreateAdapterFunction<Func<T1, T2, T3, TResult>>(instance, name, signature); } public static TDelegate CreateAdapterFunction<TDelegate>(this object instance, string methodName, Expression<TDelegate> signature) where TDelegate : class { if (instance == null) throw new ArgumentNullException("instance"); // $NON-NLS-1 MethodInfo mi = GetMethodBySignature<TDelegate>(instance.GetType(), methodName, signature); if (mi == null) return null; return (TDelegate) ((object) Delegate.CreateDelegate(typeof(TDelegate), instance, mi)); } public static MethodInfo GetMethodBySignature<TDelegate>(this Type instanceType, string name, Expression<TDelegate> signature) where TDelegate : class { return GetMethodBySignatureCore<TDelegate>( instanceType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, name, signature); } public static MethodInfo GetStaticMethodBySignature<TDelegate>(this Type instanceType, string name, Expression<TDelegate> signature) where TDelegate : class { return GetMethodBySignatureCore<TDelegate>( instanceType, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly, name, signature); } static MethodInfo GetMethodBySignatureCore<TDelegate>(Type instanceType, BindingFlags flags, string name, Expression<TDelegate> signature) where TDelegate : class { if (instanceType == null) throw new ArgumentNullException("instanceType"); // $NON-NLS-1 if (name == null) throw new ArgumentNullException("name"); // $NON-NLS-1 if (name.Length == 0) throw Failure.EmptyString("name"); Type[] argTypes = signature.Parameters.Select(p => p.Type).ToArray(); MethodInfo mi = instanceType.GetMethod(name, flags, null, argTypes, null); if (mi == null) return null; if (signature.ReturnType == null) return mi.ReturnType == null ? mi : null; if (signature.ReturnType.IsAssignableFrom(mi.ReturnType)) return mi; else return null; } public static Type GetBuilderType(this Type adapteeType) { if (adapteeType == null) throw new ArgumentNullException("adapteeType"); // $NON-NLS-1 return Adaptable.GetAdapterType(adapteeType, AdapterRole.Builder); } public static Type GetStreamingSourceType(this Type adapteeType) { if (adapteeType == null) throw new ArgumentNullException("adapteeType"); // $NON-NLS-1 return Adaptable.GetAdapterType(adapteeType, AdapterRole.StreamingSource); } public static Type GetActivationProviderType(this Type adapteeType) { if (adapteeType == null) throw new ArgumentNullException("adapteeType"); // $NON-NLS-1 if (typeof(IActivationProvider).IsAssignableFrom(adapteeType)) return adapteeType; return GetAdapterType(adapteeType, AdapterRole.ActivationProvider); } public static IEnumerable<Uri> GetStandards(this MemberDescriptor source) { if (source == null) throw new ArgumentNullException("source"); // $NON-NLS-1 var attrs = source.Attributes.OfType<StandardsCompliantAttribute>(); return SelectUris(attrs, GetAssemblyContext(source)); } public static IEnumerable<Uri> GetStandards(this MemberInfo source) { if (source == null) throw new ArgumentNullException("source"); // $NON-NLS-1 return GetStandardsCore(source, source.ReflectedType.Assembly); } public static IEnumerable<Uri> GetStandards(this Module source) { if (source == null) throw new ArgumentNullException("source"); // $NON-NLS-1 return GetStandardsCore(source, source.Assembly); } public static IEnumerable<Uri> GetStandards(this Assembly source) { if (source == null) throw new ArgumentNullException("source"); // $NON-NLS-1 return GetStandardsCore(source, source); } public static IEnumerable<Uri> GetStandards(this ParameterInfo source) { if (source == null) throw new ArgumentNullException("source"); // $NON-NLS-1 var attrs = source.GetCustomAttributes(typeof(StandardsCompliantAttribute), false) .OfType<StandardsCompliantAttribute>(); return SelectUris(attrs, source.Member.ReflectedType.Assembly); } public static bool IsServiceType(this Type type) { if (type == null) throw new ArgumentNullException("type"); bool isStatic = type.IsSealed && type.IsAbstract; return !(type.IsPrimitive || type.IsEnum || isStatic); } public static bool IsReusable(this Type type) { if (type == null) throw new ArgumentNullException("type"); return type.IsDefined<ReusableAttribute>(); } public static bool IsProcessIsolated(this Type type) { if (type == null) throw new ArgumentNullException("type"); return type.IsDefined<ProcessIsolatedAttribute>(); } public static bool IsAppDomainIsolated(this Type type) { if (type == null) throw new ArgumentNullException("type"); return type.IsDefined<AppDomainIsolatedAttribute>(); } public static bool IsValidAdapter(this Type adapterType, string adapterRole) { if (adapterType == null) throw new ArgumentNullException("adapterType"); return RequireAdapterRole(adapterRole).IsValidAdapter(adapterType); } public static bool IsValidAdapterMethod(this MethodInfo method, string adapterRole) { if (method == null) throw new ArgumentNullException("method"); // return RequireAdapterRole(adapterRole).FindAdapterMethod(adapterRole); // TODO IsValidAdapter // Need the adaptee type? throw new NotImplementedException(); } public static bool IsValidBuilder(this Type type) { if (type == null) throw new ArgumentNullException("type"); // $NON-NLS-1 return IsValidAdapter(type, AdapterRole.Builder); } public static bool IsValidBuilderMethod(this MethodInfo method) { if (method == null) throw new ArgumentNullException("method"); // $NON-NLS-1 return IsValidAdapterMethod(method, AdapterRole.Builder); } public static bool IsValidStreamingSource(this Type type) { if (type == null) throw new ArgumentNullException("type"); // $NON-NLS-1 return IsValidAdapter(type, AdapterRole.StreamingSource); } public static bool IsValidStreamingSourceMethod(this MethodInfo method) { if (method == null) throw new ArgumentNullException("method"); // $NON-NLS-1 return IsValidAdapterMethod(method, AdapterRole.StreamingSource); } internal static object InvokeBuilder( object instance, out MethodInfo buildMethod, IServiceProvider serviceProvider) { if (instance == null) throw new ArgumentNullException("instance"); Type componentType = instance.GetType(); // Invoke the builder Type[] argtypes = { typeof(IServiceProvider) }; buildMethod = componentType.GetMethod("Build", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, argtypes, null); if (buildMethod != null) { object[] arguments = { serviceProvider }; return buildMethod.Invoke(instance, arguments); } // Check for the parameterless implementation buildMethod = componentType.GetMethod("Build", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, // argtypes null); if (buildMethod != null) return buildMethod.Invoke(instance, null); return null; } public static object InvokeBuilder( this object instance, IServiceProvider serviceProvider) { MethodInfo info; return InvokeBuilder(instance, out info, serviceProvider); } static IEnumerable<Type> _GetAdapterTypes(Type adapteeType, string adapterRoleName, bool inherit) { if (adapteeType == null) throw new ArgumentNullException("adapteeType"); // $NON-NLS-1 Require.NotNullOrAllWhitespace("adapterRoleName", adapterRoleName); if (null == AdapterRoleData.FromName(adapterRoleName)) return Empty<Type>.Array; IEnumerable<Type> result; IEnumerable<Type> explicitAdapters = ((AdapterAttribute[]) adapteeType.GetCustomAttributes(typeof(AdapterAttribute), inherit)) .Where(a => a.Role == adapterRoleName) .Select(a => a.AdapterType); Type implicitAdapter = GetImplicitAdapterType(adapteeType, adapterRoleName); if (implicitAdapter == null) result = explicitAdapters; else { Type[] other = { implicitAdapter }; result = explicitAdapters.Concat(other); } result = result.Concat(DefineAdapterAttribute.GetAdapterTypes(adapteeType, adapterRoleName, inherit)); return result.Where(t => t.IsValidAdapter(adapterRoleName)); } public static string GetExtensionImplementationName(this Type type) { if (type == null) throw new ArgumentNullException("type"); const string IMPL = "Implementation."; int index = type.Namespace.IndexOf(IMPL); if (index < 0) return string.Empty; else return type.Namespace.Substring(index + IMPL.Length); } public static string GetImplementerName(this Type type) { if (type == null) throw new ArgumentNullException("type"); // $NON-NLS-1 ImplementationAttribute cca = Attribute.GetCustomAttribute(type, typeof(ImplementationAttribute)) as ImplementationAttribute; if (cca != null) return cca.Implementation; // Check assembly cca = Attribute.GetCustomAttribute(type.Assembly, typeof(ImplementationAttribute)) as ImplementationAttribute; if (cca == null) return null; else return cca.Implementation; } public static QualifiedName GetQualifiedName(this Type type) { if (type == null) throw new ArgumentNullException("type"); if (type.IsGenericParameter || (type.IsGenericType && !type.IsGenericTypeDefinition)) throw RuntimeFailure.QualifiedNameCannotBeGeneratedFromConstructed("type"); AssemblyInfo ai = AssemblyInfo.GetAssemblyInfo(type.Assembly); NamespaceUri xmlns = ai.GetXmlNamespace(type.Namespace); return xmlns + QualName(type); } static string QualName(Type type) { string name = type.Name.Replace("`", "-"); if (type.IsNested) return string.Concat(QualName(type.DeclaringType), '.', name); else return name; } public static Type GetTypeByQualifiedName(this AppDomain appDomain, QualifiedName name, bool throwOnError) { if (appDomain == null) throw new ArgumentNullException("appDomain"); if (name == null) throw new ArgumentNullException("name"); // $NON-NLS-1 string cleanName = name.LocalName.Replace('.', '+').Replace('-', '`'); foreach (var a in appDomain.GetAssemblies()) { AssemblyInfo ai = AssemblyInfo.GetAssemblyInfo(a); foreach (string clrns in ai.GetClrNamespaces(name.Namespace)) { Type result = a.GetType(CombinedTypeName(clrns, cleanName)); if (result != null) return result; } } if (throwOnError) throw RuntimeFailure.TypeMissingFromQualifiedName(name); return null; } public static Type GetTypeByQualifiedName(this AppDomain appDomain, QualifiedName name) { return GetTypeByQualifiedName(appDomain, name, false); } static string CombinedTypeName(string clrns, string name) { if (clrns.Length == 0) return name; else return string.Concat(clrns, ".", name); } static string GetExtensionImplementation( Type sourceType, string implementation) { // Carbonfrost.Commons.Membership.Implementation.Entity.EntityMembershipDataSource, Carbonfrost.Commons.Membership.Entity string pkt = Utility.BytesToHex(sourceType.Assembly.GetName().GetPublicKeyToken(), lowercase: true); AssemblyName name = sourceType.Assembly.GetName(); string typeName = string.Format( "{0}.Implementation.{2}.{2}{3}, {0}.{2}, Version={1}, PublicKeyToken={4}", name.Name, name.Version.ToString(2), implementation, sourceType.Name, pkt); return typeName; } static IEnumerable<Uri> SelectUris(IEnumerable<RelationshipAttribute> attrs, Assembly assemblyContext) { Uri baseUri = null; if (assemblyContext != null) baseUri = AssemblyInfo.GetAssemblyInfo(assemblyContext).Base; if (baseUri == null || !baseUri.IsAbsoluteUri) return attrs.Select(t => t.Uri); else return attrs.Select(t => new Uri(baseUri, t.Uri)); } static IEnumerable<Uri> GetStandardsCore(this ICustomAttributeProvider source, Assembly assembly) { var attrs = source.GetCustomAttributes(typeof(StandardsCompliantAttribute), false) .OfType<StandardsCompliantAttribute>(); return SelectUris(attrs, assembly); } static Assembly GetAssemblyContext(MemberDescriptor md) { EventDescriptor e = md as EventDescriptor; if (e != null) return e.ComponentType.Assembly; PropertyDescriptor p = md as PropertyDescriptor; if (p != null) return p.ComponentType.Assembly; return null; } static AdapterRoleData RequireAdapterRole(string adapterRole) { if (adapterRole == null) throw new ArgumentNullException("adapterRole"); if (adapterRole.Length == 0) throw Failure.EmptyString("adapterRole"); AdapterRoleData a = AdapterRoleData.FromName(adapterRole); if (a == null) throw RuntimeFailure.UnknownAdapterRole("adapterRole", adapterRole); return a; } static void AttributeCompleteAppDomain(Type attributeType) { if (typeof(IAssemblyInfoFilter).IsAssignableFrom(attributeType)) { AssemblyInfo.CompleteAppDomain(); } } static IActivationProvider MakeActivationProvider(Type type) { return (IActivationProvider) Activator.CreateInstance(type); } static bool IsActivationConstructor(ConstructorInfo t) { return t.IsDefined(typeof(ActivationConstructorAttribute), 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Collections { public partial class ArrayList : System.Collections.IEnumerable, System.Collections.IList { public ArrayList() { } public ArrayList(System.Collections.ICollection c) { } public ArrayList(int capacity) { } public virtual int Capacity { get { return default(int); } set { } } public virtual int Count { get { return default(int); } } public virtual bool IsFixedSize { get { return default(bool); } } public virtual bool IsReadOnly { get { return default(bool); } } public virtual bool IsSynchronized { get { return default(bool); } } public virtual object this[int index] { get { return default(object); } set { } } public virtual object SyncRoot { get { return default(object); } } public static System.Collections.ArrayList Adapter(System.Collections.IList list) { return default(System.Collections.ArrayList); } public virtual int Add(object value) { return default(int); } public virtual void AddRange(System.Collections.ICollection c) { } public virtual int BinarySearch(int index, int count, object value, System.Collections.IComparer comparer) { return default(int); } public virtual int BinarySearch(object value) { return default(int); } public virtual int BinarySearch(object value, System.Collections.IComparer comparer) { return default(int); } public virtual void Clear() { } public virtual object Clone() { return default(object); } public virtual bool Contains(object item) { return default(bool); } public virtual void CopyTo(System.Array array) { } public virtual void CopyTo(System.Array array, int arrayIndex) { } public virtual void CopyTo(int index, System.Array array, int arrayIndex, int count) { } public static System.Collections.ArrayList FixedSize(System.Collections.ArrayList list) { return default(System.Collections.ArrayList); } public static System.Collections.IList FixedSize(System.Collections.IList list) { return default(System.Collections.IList); } public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public virtual System.Collections.IEnumerator GetEnumerator(int index, int count) { return default(System.Collections.IEnumerator); } public virtual System.Collections.ArrayList GetRange(int index, int count) { return default(System.Collections.ArrayList); } public virtual int IndexOf(object value) { return default(int); } public virtual int IndexOf(object value, int startIndex) { return default(int); } public virtual int IndexOf(object value, int startIndex, int count) { return default(int); } public virtual void Insert(int index, object value) { } public virtual void InsertRange(int index, System.Collections.ICollection c) { } public virtual int LastIndexOf(object value) { return default(int); } public virtual int LastIndexOf(object value, int startIndex) { return default(int); } public virtual int LastIndexOf(object value, int startIndex, int count) { return default(int); } public static System.Collections.ArrayList ReadOnly(System.Collections.ArrayList list) { return default(System.Collections.ArrayList); } public static System.Collections.IList ReadOnly(System.Collections.IList list) { return default(System.Collections.IList); } public virtual void Remove(object obj) { } public virtual void RemoveAt(int index) { } public virtual void RemoveRange(int index, int count) { } public static System.Collections.ArrayList Repeat(object value, int count) { return default(System.Collections.ArrayList); } public virtual void Reverse() { } public virtual void Reverse(int index, int count) { } public virtual void SetRange(int index, System.Collections.ICollection c) { } public virtual void Sort() { } public virtual void Sort(System.Collections.IComparer comparer) { } public virtual void Sort(int index, int count, System.Collections.IComparer comparer) { } public static System.Collections.ArrayList Synchronized(System.Collections.ArrayList list) { return default(System.Collections.ArrayList); } public static System.Collections.IList Synchronized(System.Collections.IList list) { return default(System.Collections.IList); } public virtual object[] ToArray() { return default(object[]); } public virtual System.Array ToArray(System.Type type) { return default(System.Array); } public virtual void TrimToSize() { } } public partial class CaseInsensitiveComparer : System.Collections.IComparer { public CaseInsensitiveComparer() { } public CaseInsensitiveComparer(System.Globalization.CultureInfo culture) { } public static System.Collections.CaseInsensitiveComparer Default { get { return default(System.Collections.CaseInsensitiveComparer); } } public static System.Collections.CaseInsensitiveComparer DefaultInvariant { get { return default(System.Collections.CaseInsensitiveComparer); } } public int Compare(object a, object b) { return default(int); } } public abstract partial class CollectionBase : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { protected CollectionBase() { } protected CollectionBase(int capacity) { } public int Capacity { get { return default(int); } set { } } public int Count { get { return default(int); } } protected System.Collections.ArrayList InnerList { get { return default(System.Collections.ArrayList); } } protected System.Collections.IList List { get { return default(System.Collections.IList); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } bool System.Collections.IList.IsFixedSize { get { return default(bool); } } bool System.Collections.IList.IsReadOnly { get { return default(bool); } } object System.Collections.IList.this[int index] { get { return default(object); } set { } } public void Clear() { } public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } protected virtual void OnClear() { } protected virtual void OnClearComplete() { } protected virtual void OnInsert(int index, object value) { } protected virtual void OnInsertComplete(int index, object value) { } protected virtual void OnRemove(int index, object value) { } protected virtual void OnRemoveComplete(int index, object value) { } protected virtual void OnSet(int index, object oldValue, object newValue) { } protected virtual void OnSetComplete(int index, object oldValue, object newValue) { } protected virtual void OnValidate(object value) { } public void RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } int System.Collections.IList.Add(object value) { return default(int); } bool System.Collections.IList.Contains(object value) { return default(bool); } int System.Collections.IList.IndexOf(object value) { return default(int); } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } } public sealed partial class Comparer : System.Collections.IComparer { public static readonly System.Collections.Comparer Default; public static readonly System.Collections.Comparer DefaultInvariant; public Comparer(System.Globalization.CultureInfo culture) { } public int Compare(object a, object b) { return default(int); } } public abstract partial class DictionaryBase : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { protected DictionaryBase() { } public int Count { get { return default(int); } } protected System.Collections.IDictionary Dictionary { get { return default(System.Collections.IDictionary); } } protected System.Collections.Hashtable InnerHashtable { get { return default(System.Collections.Hashtable); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } } bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } } object System.Collections.IDictionary.this[object key] { get { return default(object); } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { return default(System.Collections.ICollection); } } System.Collections.ICollection System.Collections.IDictionary.Values { get { return default(System.Collections.ICollection); } } public void Clear() { } public void CopyTo(System.Array array, int index) { } public System.Collections.IDictionaryEnumerator GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } protected virtual void OnClear() { } protected virtual void OnClearComplete() { } protected virtual object OnGet(object key, object currentValue) { return default(object); } protected virtual void OnInsert(object key, object value) { } protected virtual void OnInsertComplete(object key, object value) { } protected virtual void OnRemove(object key, object value) { } protected virtual void OnRemoveComplete(object key, object value) { } protected virtual void OnSet(object key, object oldValue, object newValue) { } protected virtual void OnSetComplete(object key, object oldValue, object newValue) { } protected virtual void OnValidate(object key, object value) { } void System.Collections.IDictionary.Add(object key, object value) { } bool System.Collections.IDictionary.Contains(object key) { return default(bool); } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public partial class Hashtable : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public Hashtable() { } public Hashtable(System.Collections.IDictionary d) { } public Hashtable(System.Collections.IDictionary d, System.Collections.IEqualityComparer equalityComparer) { } public Hashtable(System.Collections.IDictionary d, float loadFactor) { } public Hashtable(System.Collections.IDictionary d, float loadFactor, System.Collections.IEqualityComparer equalityComparer) { } public Hashtable(System.Collections.IEqualityComparer equalityComparer) { } public Hashtable(int capacity) { } public Hashtable(int capacity, System.Collections.IEqualityComparer equalityComparer) { } public Hashtable(int capacity, float loadFactor) { } public Hashtable(int capacity, float loadFactor, System.Collections.IEqualityComparer equalityComparer) { } public virtual int Count { get { return default(int); } } protected System.Collections.IEqualityComparer EqualityComparer { get { return default(System.Collections.IEqualityComparer); } } public virtual bool IsFixedSize { get { return default(bool); } } public virtual bool IsReadOnly { get { return default(bool); } } public virtual bool IsSynchronized { get { return default(bool); } } public virtual object this[object key] { get { return default(object); } set { } } public virtual System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } } public virtual object SyncRoot { get { return default(object); } } public virtual System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } } public virtual void Add(object key, object value) { } public virtual void Clear() { } public virtual object Clone() { return default(object); } public virtual bool Contains(object key) { return default(bool); } public virtual bool ContainsKey(object key) { return default(bool); } public virtual bool ContainsValue(object value) { return default(bool); } public virtual void CopyTo(System.Array array, int arrayIndex) { } public virtual System.Collections.IDictionaryEnumerator GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } protected virtual int GetHash(object key) { return default(int); } protected virtual bool KeyEquals(object item, object key) { return default(bool); } public virtual void Remove(object key) { } public static System.Collections.Hashtable Synchronized(System.Collections.Hashtable table) { return default(System.Collections.Hashtable); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public partial class Queue : System.Collections.ICollection, System.Collections.IEnumerable { public Queue() { } public Queue(System.Collections.ICollection col) { } public Queue(int capacity) { } public Queue(int capacity, float growFactor) { } public virtual int Count { get { return default(int); } } public virtual bool IsSynchronized { get { return default(bool); } } public virtual object SyncRoot { get { return default(object); } } public virtual void Clear() { } public virtual object Clone() { return default(object); } public virtual bool Contains(object obj) { return default(bool); } public virtual void CopyTo(System.Array array, int index) { } public virtual object Dequeue() { return default(object); } public virtual void Enqueue(object obj) { } public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public virtual object Peek() { return default(object); } public static System.Collections.Queue Synchronized(System.Collections.Queue queue) { return default(System.Collections.Queue); } public virtual object[] ToArray() { return default(object[]); } public virtual void TrimToSize() { } } public abstract partial class ReadOnlyCollectionBase : System.Collections.ICollection, System.Collections.IEnumerable { protected ReadOnlyCollectionBase() { } public virtual int Count { get { return default(int); } } protected System.Collections.ArrayList InnerList { get { return default(System.Collections.ArrayList); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } } public partial class SortedList : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public SortedList() { } public SortedList(System.Collections.IComparer comparer) { } public SortedList(System.Collections.IComparer comparer, int capacity) { } public SortedList(System.Collections.IDictionary d) { } public SortedList(System.Collections.IDictionary d, System.Collections.IComparer comparer) { } public SortedList(int initialCapacity) { } public virtual int Capacity { get { return default(int); } set { } } public virtual int Count { get { return default(int); } } public virtual bool IsFixedSize { get { return default(bool); } } public virtual bool IsReadOnly { get { return default(bool); } } public virtual bool IsSynchronized { get { return default(bool); } } public virtual object this[object key] { get { return default(object); } set { } } public virtual System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } } public virtual object SyncRoot { get { return default(object); } } public virtual System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } } public virtual void Add(object key, object value) { } public virtual void Clear() { } public virtual object Clone() { return default(object); } public virtual bool Contains(object key) { return default(bool); } public virtual bool ContainsKey(object key) { return default(bool); } public virtual bool ContainsValue(object value) { return default(bool); } public virtual void CopyTo(System.Array array, int arrayIndex) { } public virtual object GetByIndex(int index) { return default(object); } public virtual System.Collections.IDictionaryEnumerator GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } public virtual object GetKey(int index) { return default(object); } public virtual System.Collections.IList GetKeyList() { return default(System.Collections.IList); } public virtual System.Collections.IList GetValueList() { return default(System.Collections.IList); } public virtual int IndexOfKey(object key) { return default(int); } public virtual int IndexOfValue(object value) { return default(int); } public virtual void Remove(object key) { } public virtual void RemoveAt(int index) { } public virtual void SetByIndex(int index, object value) { } public static System.Collections.SortedList Synchronized(System.Collections.SortedList list) { return default(System.Collections.SortedList); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public virtual void TrimToSize() { } } public partial class Stack : System.Collections.ICollection, System.Collections.IEnumerable { public Stack() { } public Stack(System.Collections.ICollection col) { } public Stack(int initialCapacity) { } public virtual int Count { get { return default(int); } } public virtual bool IsSynchronized { get { return default(bool); } } public virtual object SyncRoot { get { return default(object); } } public virtual void Clear() { } public virtual object Clone() { return default(object); } public virtual bool Contains(object obj) { return default(bool); } public virtual void CopyTo(System.Array array, int index) { } public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public virtual object Peek() { return default(object); } public virtual object Pop() { return default(object); } public virtual void Push(object obj) { } public static System.Collections.Stack Synchronized(System.Collections.Stack stack) { return default(System.Collections.Stack); } public virtual object[] ToArray() { return default(object[]); } } } namespace System.Collections.Specialized { public partial class CollectionsUtil { public CollectionsUtil() { } public static System.Collections.Hashtable CreateCaseInsensitiveHashtable() { return default(System.Collections.Hashtable); } public static System.Collections.Hashtable CreateCaseInsensitiveHashtable(System.Collections.IDictionary d) { return default(System.Collections.Hashtable); } public static System.Collections.Hashtable CreateCaseInsensitiveHashtable(int capacity) { return default(System.Collections.Hashtable); } public static System.Collections.SortedList CreateCaseInsensitiveSortedList() { return default(System.Collections.SortedList); } } }
// 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 osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Audio.Sample; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Events; using osu.Framework.Logging; using osu.Framework.Screens; using osu.Framework.Threading; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Input.Bindings; using osu.Game.Overlays; using osu.Game.Overlays.Mods; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Screens.Edit; using osu.Game.Screens.Menu; using osu.Game.Screens.Select.Options; using osuTK; using osuTK.Graphics; using osuTK.Input; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using osu.Framework.Audio.Track; using osu.Framework.Graphics.Sprites; using osu.Framework.Input.Bindings; using osu.Game.Collections; using osu.Game.Graphics.UserInterface; using System.Diagnostics; using osu.Game.Screens.Play; using osu.Game.Database; namespace osu.Game.Screens.Select { public abstract class SongSelect : ScreenWithBeatmapBackground, IKeyBindingHandler<GlobalAction> { public static readonly float WEDGE_HEIGHT = 245; protected const float BACKGROUND_BLUR = 20; private const float left_area_padding = 20; public FilterControl FilterControl { get; private set; } protected virtual bool ShowFooter => true; protected virtual bool DisplayStableImportPrompt => legacyImportManager?.SupportsImportFromStable == true; public override bool? AllowTrackAdjustments => true; /// <summary> /// Can be null if <see cref="ShowFooter"/> is false. /// </summary> protected BeatmapOptionsOverlay BeatmapOptions { get; private set; } /// <summary> /// Can be null if <see cref="ShowFooter"/> is false. /// </summary> protected Footer Footer { get; private set; } /// <summary> /// Contains any panel which is triggered by a footer button. /// Helps keep them located beneath the footer itself. /// </summary> protected Container FooterPanels { get; private set; } /// <summary> /// Whether entering editor mode should be allowed. /// </summary> public virtual bool AllowEditing => true; public bool BeatmapSetsLoaded => IsLoaded && Carousel?.BeatmapSetsLoaded == true; [Resolved] private Bindable<IReadOnlyList<Mod>> selectedMods { get; set; } protected BeatmapCarousel Carousel { get; private set; } protected Container LeftArea { get; private set; } private BeatmapInfoWedge beatmapInfoWedge; private DialogOverlay dialogOverlay; [Resolved] private BeatmapManager beatmaps { get; set; } [Resolved(CanBeNull = true)] private LegacyImportManager legacyImportManager { get; set; } protected ModSelectOverlay ModSelect { get; private set; } protected Sample SampleConfirm { get; private set; } private Sample sampleChangeDifficulty; private Sample sampleChangeBeatmap; private Container carouselContainer; protected BeatmapDetailArea BeatmapDetails { get; private set; } private readonly Bindable<RulesetInfo> decoupledRuleset = new Bindable<RulesetInfo>(); private double audioFeedbackLastPlaybackTime; [Resolved] private MusicController music { get; set; } [BackgroundDependencyLoader(true)] private void load(AudioManager audio, DialogOverlay dialog, OsuColour colours, ManageCollectionsDialog manageCollectionsDialog, DifficultyRecommender recommender) { // initial value transfer is required for FilterControl (it uses our re-cached bindables in its async load for the initial filter). transferRulesetValue(); LoadComponentAsync(Carousel = new BeatmapCarousel { AllowSelection = false, // delay any selection until our bindables are ready to make a good choice. Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, RelativeSizeAxes = Axes.Both, BleedTop = FilterControl.HEIGHT, BleedBottom = Footer.HEIGHT, SelectionChanged = updateSelectedBeatmap, BeatmapSetsChanged = carouselBeatmapsLoaded, GetRecommendedBeatmap = s => recommender?.GetRecommendedBeatmap(s), }, c => carouselContainer.Child = c); AddRangeInternal(new Drawable[] { new ResetScrollContainer(() => Carousel.ScrollToSelected()) { RelativeSizeAxes = Axes.Y, Width = 250, }, new VerticalMaskingContainer { Children = new Drawable[] { new GridContainer // used for max width implementation { RelativeSizeAxes = Axes.Both, ColumnDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.Relative, 0.5f, maxSize: 850), }, Content = new[] { new Drawable[] { new ParallaxContainer { ParallaxAmount = 0.005f, RelativeSizeAxes = Axes.Both, Child = new WedgeBackground { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Right = -150 }, }, }, carouselContainer = new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Top = FilterControl.HEIGHT, Bottom = Footer.HEIGHT }, Child = new LoadingSpinner(true) { State = { Value = Visibility.Visible } } } }, } }, FilterControl = new FilterControl { RelativeSizeAxes = Axes.X, Height = FilterControl.HEIGHT, FilterChanged = ApplyFilterToCarousel, }, new GridContainer // used for max width implementation { RelativeSizeAxes = Axes.Both, ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, 0.5f, maxSize: 650), }, Content = new[] { new Drawable[] { LeftArea = new Container { Origin = Anchor.BottomLeft, Anchor = Anchor.BottomLeft, RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Top = left_area_padding }, Children = new Drawable[] { beatmapInfoWedge = new BeatmapInfoWedge { Height = WEDGE_HEIGHT, RelativeSizeAxes = Axes.X, Margin = new MarginPadding { Right = left_area_padding, Left = -BeatmapInfoWedge.BORDER_THICKNESS, // Hide the left border }, }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Bottom = Footer.HEIGHT, Top = WEDGE_HEIGHT, Left = left_area_padding, Right = left_area_padding * 2, }, Child = BeatmapDetails = CreateBeatmapDetailArea().With(d => { d.RelativeSizeAxes = Axes.Both; d.Padding = new MarginPadding { Top = 10, Right = 5 }; }) }, } }, }, } } } }, }); if (ShowFooter) { AddRangeInternal(new Drawable[] { new GridContainer // used for max height implementation { RelativeSizeAxes = Axes.Both, RowDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.Relative, 1f, maxSize: ModSelectOverlay.HEIGHT + Footer.HEIGHT), }, Content = new[] { null, new Drawable[] { FooterPanels = new Container { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Bottom = Footer.HEIGHT }, Children = new Drawable[] { BeatmapOptions = new BeatmapOptionsOverlay(), ModSelect = CreateModSelectOverlay() } } } } }, Footer = new Footer() }); } if (Footer != null) { foreach (var (button, overlay) in CreateFooterButtons()) Footer.AddButton(button, overlay); BeatmapOptions.AddButton(@"Manage", @"collections", FontAwesome.Solid.Book, colours.Green, () => manageCollectionsDialog?.Show()); BeatmapOptions.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, colours.Pink, () => delete(Beatmap.Value.BeatmapSetInfo)); BeatmapOptions.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, colours.Purple, null); BeatmapOptions.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, colours.Purple, () => clearScores(Beatmap.Value.BeatmapInfo)); } dialogOverlay = dialog; sampleChangeDifficulty = audio.Samples.Get(@"SongSelect/select-difficulty"); sampleChangeBeatmap = audio.Samples.Get(@"SongSelect/select-expand"); SampleConfirm = audio.Samples.Get(@"SongSelect/confirm-selection"); if (dialogOverlay != null) { Schedule(() => { // if we have no beatmaps, let's prompt the user to import from over a stable install if he has one. if (!beatmaps.GetAllUsableBeatmapSetsEnumerable(IncludedDetails.Minimal).Any() && DisplayStableImportPrompt) { dialogOverlay.Push(new ImportFromStablePopup(() => { Task.Run(() => legacyImportManager.ImportFromStableAsync(StableContent.All)); })); } }); } } /// <summary> /// Creates the buttons to be displayed in the footer. /// </summary> /// <returns>A set of <see cref="FooterButton"/> and an optional <see cref="OverlayContainer"/> which the button opens when pressed.</returns> protected virtual IEnumerable<(FooterButton, OverlayContainer)> CreateFooterButtons() => new (FooterButton, OverlayContainer)[] { (new FooterButtonMods { Current = Mods }, ModSelect), (new FooterButtonRandom { NextRandom = () => Carousel.SelectNextRandom(), PreviousRandom = Carousel.SelectPreviousRandom }, null), (new FooterButtonOptions(), BeatmapOptions) }; protected virtual ModSelectOverlay CreateModSelectOverlay() => new UserModSelectOverlay(); protected virtual void ApplyFilterToCarousel(FilterCriteria criteria) { // if not the current screen, we want to get carousel in a good presentation state before displaying (resume or enter). bool shouldDebounce = this.IsCurrentScreen(); Carousel.Filter(criteria, shouldDebounce); } private DependencyContainer dependencies; protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); dependencies.CacheAs(this); dependencies.CacheAs(decoupledRuleset); dependencies.CacheAs<IBindable<RulesetInfo>>(decoupledRuleset); return dependencies; } /// <summary> /// Creates the beatmap details to be displayed underneath the wedge. /// </summary> protected abstract BeatmapDetailArea CreateBeatmapDetailArea(); public void Edit(BeatmapInfo beatmapInfo = null) { if (!AllowEditing) throw new InvalidOperationException($"Attempted to edit when {nameof(AllowEditing)} is disabled"); Beatmap.Value = beatmaps.GetWorkingBeatmap(beatmapInfo ?? beatmapInfoNoDebounce); this.Push(new EditorLoader()); } /// <summary> /// Call to make a selection and perform the default action for this SongSelect. /// </summary> /// <param name="beatmapInfo">An optional beatmap to override the current carousel selection.</param> /// <param name="ruleset">An optional ruleset to override the current carousel selection.</param> /// <param name="customStartAction">An optional custom action to perform instead of <see cref="OnStart"/>.</param> public void FinaliseSelection(BeatmapInfo beatmapInfo = null, RulesetInfo ruleset = null, Action customStartAction = null) { // This is very important as we have not yet bound to screen-level bindables before the carousel load is completed. if (!Carousel.BeatmapSetsLoaded) return; if (ruleset != null) Ruleset.Value = ruleset; transferRulesetValue(); // while transferRulesetValue will flush, it only does so if the ruleset changes. // the user could have changed a filter, and we want to ensure we are 100% up-to-date and consistent here. Carousel.FlushPendingFilterOperations(); // avoid attempting to continue before a selection has been obtained. // this could happen via a user interaction while the carousel is still in a loading state. if (Carousel.SelectedBeatmapInfo == null) return; if (beatmapInfo != null) Carousel.SelectBeatmap(beatmapInfo); if (selectionChangedDebounce?.Completed == false) { selectionChangedDebounce.RunTask(); selectionChangedDebounce?.Cancel(); // cancel the already scheduled task. selectionChangedDebounce = null; } if (customStartAction != null) { customStartAction(); Carousel.AllowSelection = false; } else if (OnStart()) Carousel.AllowSelection = false; } /// <summary> /// Called when a selection is made. /// </summary> /// <returns>If a resultant action occurred that takes the user away from SongSelect.</returns> protected abstract bool OnStart(); private ScheduledDelegate selectionChangedDebounce; private void workingBeatmapChanged(ValueChangedEvent<WorkingBeatmap> e) { if (e.NewValue is DummyWorkingBeatmap || !this.IsCurrentScreen()) return; Logger.Log($"Song select working beatmap updated to {e.NewValue}"); if (!Carousel.SelectBeatmap(e.NewValue.BeatmapInfo, false)) { // A selection may not have been possible with filters applied. // There was possibly a ruleset mismatch. This is a case we can help things along by updating the game-wide ruleset to match. if (e.NewValue.BeatmapInfo.Ruleset != null && !e.NewValue.BeatmapInfo.Ruleset.Equals(decoupledRuleset.Value)) { Ruleset.Value = e.NewValue.BeatmapInfo.Ruleset; transferRulesetValue(); } // Even if a ruleset mismatch was not the cause (ie. a text filter is applied), // we still want to temporarily show the new beatmap, bypassing filters. // This will be undone the next time the user changes the filter. var criteria = FilterControl.CreateCriteria(); criteria.SelectedBeatmapSet = e.NewValue.BeatmapInfo.BeatmapSet; Carousel.Filter(criteria); Carousel.SelectBeatmap(e.NewValue.BeatmapInfo); } } // We need to keep track of the last selected beatmap ignoring debounce to play the correct selection sounds. private BeatmapInfo beatmapInfoPrevious; private BeatmapInfo beatmapInfoNoDebounce; private RulesetInfo rulesetNoDebounce; private void updateSelectedBeatmap(BeatmapInfo beatmapInfo) { if (beatmapInfo == null && beatmapInfoNoDebounce == null) return; if (beatmapInfo?.Equals(beatmapInfoNoDebounce) == true) return; beatmapInfoNoDebounce = beatmapInfo; performUpdateSelected(); } private void updateSelectedRuleset(RulesetInfo ruleset) { if (ruleset == null && rulesetNoDebounce == null) return; if (ruleset?.Equals(rulesetNoDebounce) == true) return; rulesetNoDebounce = ruleset; performUpdateSelected(); } /// <summary> /// Selection has been changed as the result of a user interaction. /// </summary> private void performUpdateSelected() { var beatmap = beatmapInfoNoDebounce; var ruleset = rulesetNoDebounce; selectionChangedDebounce?.Cancel(); if (beatmapInfoNoDebounce == null) run(); else selectionChangedDebounce = Scheduler.AddDelayed(run, 200); if (beatmap != beatmapInfoPrevious) { if (beatmap != null && beatmapInfoPrevious != null && Time.Current - audioFeedbackLastPlaybackTime >= 50) { if (beatmap.BeatmapSetInfoID == beatmapInfoPrevious.BeatmapSetInfoID) sampleChangeDifficulty.Play(); else sampleChangeBeatmap.Play(); audioFeedbackLastPlaybackTime = Time.Current; } beatmapInfoPrevious = beatmap; } void run() { // clear pending task immediately to track any potential nested debounce operation. selectionChangedDebounce = null; Logger.Log($"updating selection with beatmap:{beatmap?.ID.ToString() ?? "null"} ruleset:{ruleset?.ID.ToString() ?? "null"}"); if (transferRulesetValue()) { Mods.Value = Array.Empty<Mod>(); // transferRulesetValue() may trigger a re-filter. If the current selection does not match the new ruleset, we want to switch away from it. // The default logic on WorkingBeatmap change is to switch to a matching ruleset (see workingBeatmapChanged()), but we don't want that here. // We perform an early selection attempt and clear out the beatmap selection to avoid a second ruleset change (revert). if (beatmap != null && !Carousel.SelectBeatmap(beatmap, false)) beatmap = null; } if (selectionChangedDebounce != null) { // a new nested operation was started; switch to it for further selection. // this avoids having two separate debounces trigger from the same source. selectionChangedDebounce.RunTask(); return; } // We may be arriving here due to another component changing the bindable Beatmap. // In these cases, the other component has already loaded the beatmap, so we don't need to do so again. if (!EqualityComparer<BeatmapInfo>.Default.Equals(beatmap, Beatmap.Value.BeatmapInfo)) { Logger.Log($"beatmap changed from \"{Beatmap.Value.BeatmapInfo}\" to \"{beatmap}\""); Beatmap.Value = beatmaps.GetWorkingBeatmap(beatmap); } if (this.IsCurrentScreen()) ensurePlayingSelected(); updateComponentFromBeatmap(Beatmap.Value); } } public override void OnEntering(IScreen last) { base.OnEntering(last); this.FadeInFromZero(250); FilterControl.Activate(); ModSelect.SelectedMods.BindTo(selectedMods); beginLooping(); } private const double logo_transition = 250; protected override void LogoArriving(OsuLogo logo, bool resuming) { base.LogoArriving(logo, resuming); Vector2 position = new Vector2(0.95f, 0.96f); if (logo.Alpha > 0.8f) { logo.MoveTo(position, 500, Easing.OutQuint); } else { logo.Hide(); logo.ScaleTo(0.2f); logo.MoveTo(position); } logo.FadeIn(logo_transition, Easing.OutQuint); logo.ScaleTo(0.4f, logo_transition, Easing.OutQuint); logo.Action = () => { FinaliseSelection(); return false; }; } protected override void LogoExiting(OsuLogo logo) { base.LogoExiting(logo); logo.ScaleTo(0.2f, logo_transition / 2, Easing.Out); logo.FadeOut(logo_transition / 2, Easing.Out); } public override void OnResuming(IScreen last) { base.OnResuming(last); // required due to https://github.com/ppy/osu-framework/issues/3218 ModSelect.SelectedMods.Disabled = false; ModSelect.SelectedMods.BindTo(selectedMods); Carousel.AllowSelection = true; BeatmapDetails.Refresh(); beginLooping(); music.ResetTrackAdjustments(); if (Beatmap != null && !Beatmap.Value.BeatmapSetInfo.DeletePending) { updateComponentFromBeatmap(Beatmap.Value); // restart playback on returning to song select, regardless. // not sure this should be a permanent thing (we may want to leave a user pause paused even on returning) music.Play(requestedByUser: true); } this.FadeIn(250); this.ScaleTo(1, 250, Easing.OutSine); FilterControl.Activate(); } public override void OnSuspending(IScreen next) { ModSelect.SelectedMods.UnbindFrom(selectedMods); ModSelect.Hide(); BeatmapOptions.Hide(); endLooping(); this.ScaleTo(1.1f, 250, Easing.InSine); this.FadeOut(250); FilterControl.Deactivate(); base.OnSuspending(next); } public override bool OnExiting(IScreen next) { if (base.OnExiting(next)) return true; beatmapInfoWedge.Hide(); this.FadeOut(100); FilterControl.Deactivate(); endLooping(); return false; } private bool isHandlingLooping; private void beginLooping() { Debug.Assert(!isHandlingLooping); isHandlingLooping = true; ensureTrackLooping(Beatmap.Value, TrackChangeDirection.None); music.TrackChanged += ensureTrackLooping; } private void endLooping() { // may be called multiple times during screen exit process. if (!isHandlingLooping) return; music.CurrentTrack.Looping = isHandlingLooping = false; music.TrackChanged -= ensureTrackLooping; } private void ensureTrackLooping(IWorkingBeatmap beatmap, TrackChangeDirection changeDirection) => beatmap.PrepareTrackForPreviewLooping(); public override bool OnBackButton() { if (ModSelect.State.Value == Visibility.Visible) { ModSelect.Hide(); return true; } return false; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); decoupledRuleset.UnbindAll(); if (music != null) music.TrackChanged -= ensureTrackLooping; } /// <summary> /// Allow components in SongSelect to update their loaded beatmap details. /// This is a debounced call (unlike directly binding to WorkingBeatmap.ValueChanged). /// </summary> /// <param name="beatmap">The working beatmap.</param> private void updateComponentFromBeatmap(WorkingBeatmap beatmap) { ApplyToBackground(backgroundModeBeatmap => { backgroundModeBeatmap.Beatmap = beatmap; backgroundModeBeatmap.BlurAmount.Value = BACKGROUND_BLUR; backgroundModeBeatmap.FadeColour(Color4.White, 250); }); beatmapInfoWedge.Beatmap = beatmap; BeatmapDetails.Beatmap = beatmap; } private readonly WeakReference<ITrack> lastTrack = new WeakReference<ITrack>(null); /// <summary> /// Ensures some music is playing for the current track. /// Will resume playback from a manual user pause if the track has changed. /// </summary> private void ensurePlayingSelected() { ITrack track = music.CurrentTrack; bool isNewTrack = !lastTrack.TryGetTarget(out var last) || last != track; if (!track.IsRunning && (music.UserPauseRequested != true || isNewTrack)) music.Play(true); lastTrack.SetTarget(track); } private void carouselBeatmapsLoaded() { bindBindables(); Carousel.AllowSelection = true; // If a selection was already obtained, do not attempt to update the selected beatmap. if (Carousel.SelectedBeatmapSet != null) return; // Attempt to select the current beatmap on the carousel, if it is valid to be selected. if (!Beatmap.IsDefault && Beatmap.Value.BeatmapSetInfo?.DeletePending == false && Beatmap.Value.BeatmapSetInfo?.Protected == false) { if (Carousel.SelectBeatmap(Beatmap.Value.BeatmapInfo, false)) return; // prefer not changing ruleset at this point, so look for another difficulty in the currently playing beatmap var found = Beatmap.Value.BeatmapSetInfo.Beatmaps.FirstOrDefault(b => b.Ruleset.Equals(decoupledRuleset.Value)); if (found != null && Carousel.SelectBeatmap(found, false)) return; } // If the current active beatmap could not be selected, select a new random beatmap. if (!Carousel.SelectNextRandom()) { // in the case random selection failed, we want to trigger selectionChanged // to show the dummy beatmap (we have nothing else to display). performUpdateSelected(); } } private bool boundLocalBindables; private void bindBindables() { if (boundLocalBindables) return; // manual binding to parent ruleset to allow for delayed load in the incoming direction. transferRulesetValue(); Ruleset.ValueChanged += r => updateSelectedRuleset(r.NewValue); decoupledRuleset.ValueChanged += r => Ruleset.Value = r.NewValue; decoupledRuleset.DisabledChanged += r => Ruleset.Disabled = r; Beatmap.BindValueChanged(workingBeatmapChanged); boundLocalBindables = true; } /// <summary> /// Transfer the game-wide ruleset to the local decoupled ruleset. /// Will immediately run filter operations if required. /// </summary> /// <returns>Whether a transfer occurred.</returns> private bool transferRulesetValue() { if (decoupledRuleset.Value?.Equals(Ruleset.Value) == true) return false; Logger.Log($"decoupled ruleset transferred (\"{decoupledRuleset.Value}\" -> \"{Ruleset.Value}\")"); rulesetNoDebounce = decoupledRuleset.Value = Ruleset.Value; // if we have a pending filter operation, we want to run it now. // it could change selection (ie. if the ruleset has been changed). Carousel?.FlushPendingFilterOperations(); return true; } private void delete(BeatmapSetInfo beatmap) { if (beatmap == null || beatmap.ID <= 0) return; dialogOverlay?.Push(new BeatmapDeleteDialog(beatmap)); } private void clearScores(BeatmapInfo beatmapInfo) { if (beatmapInfo == null || beatmapInfo.ID <= 0) return; dialogOverlay?.Push(new BeatmapClearScoresDialog(beatmapInfo, () => // schedule done here rather than inside the dialog as the dialog may fade out and never callback. Schedule(() => BeatmapDetails.Refresh()))); } public virtual bool OnPressed(KeyBindingPressEvent<GlobalAction> e) { if (e.Repeat) return false; if (!this.IsCurrentScreen()) return false; switch (e.Action) { case GlobalAction.Select: FinaliseSelection(); return true; } return false; } public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e) { } protected override bool OnKeyDown(KeyDownEvent e) { if (e.Repeat) return false; switch (e.Key) { case Key.Delete: if (e.ShiftPressed) { if (!Beatmap.IsDefault) delete(Beatmap.Value.BeatmapSetInfo); return true; } break; } return base.OnKeyDown(e); } private class VerticalMaskingContainer : Container { private const float panel_overflow = 1.2f; protected override Container<Drawable> Content { get; } public VerticalMaskingContainer() { RelativeSizeAxes = Axes.Both; Masking = true; Anchor = Anchor.Centre; Origin = Anchor.Centre; Width = panel_overflow; // avoid horizontal masking so the panels don't clip when screen stack is pushed. InternalChild = Content = new Container { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Width = 1 / panel_overflow, }; } } private class ResetScrollContainer : Container { private readonly Action onHoverAction; public ResetScrollContainer(Action onHoverAction) { this.onHoverAction = onHoverAction; } protected override bool OnHover(HoverEvent e) { onHoverAction?.Invoke(); return base.OnHover(e); } } } }
// 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.IO; using System.IO.Compression; using System.Net.Http.Headers; using System.Runtime.InteropServices; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { internal static class WinHttpResponseParser { private const string EncodingNameDeflate = "DEFLATE"; private const string EncodingNameGzip = "GZIP"; public static HttpResponseMessage CreateResponseMessage( WinHttpRequestState state, bool doManualDecompressionCheck) { HttpRequestMessage request = state.RequestMessage; SafeWinHttpHandle requestHandle = state.RequestHandle; CookieUsePolicy cookieUsePolicy = state.Handler.CookieUsePolicy; CookieContainer cookieContainer = state.Handler.CookieContainer; var response = new HttpResponseMessage(); bool stripEncodingHeaders = false; // Create a single buffer to use for all subsequent WinHttpQueryHeaders string interop calls. // This buffer is the length needed for WINHTTP_QUERY_RAW_HEADERS_CRLF, which includes the status line // and all headers separated by CRLF, so it should be large enough for any individual status line or header queries. int bufferLength = GetResponseHeaderCharBufferLength(requestHandle, Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF); char[] buffer = new char[bufferLength]; // Get HTTP version, status code, reason phrase from the response headers. if (IsResponseHttp2(requestHandle)) { response.Version = WinHttpHandler.HttpVersion20; } else { int versionLength = GetResponseHeader(requestHandle, Interop.WinHttp.WINHTTP_QUERY_VERSION, buffer); response.Version = CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase("HTTP/1.1", buffer, 0, versionLength) ? HttpVersion.Version11 : CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase("HTTP/1.0", buffer, 0, versionLength) ? HttpVersion.Version10 : WinHttpHandler.HttpVersionUnknown; } response.StatusCode = (HttpStatusCode)GetResponseHeaderNumberInfo( requestHandle, Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE); int reasonPhraseLength = GetResponseHeader(requestHandle, Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT, buffer); response.ReasonPhrase = reasonPhraseLength > 0 ? GetReasonPhrase(response.StatusCode, buffer, reasonPhraseLength) : string.Empty; // Create response stream and wrap it in a StreamContent object. var responseStream = new WinHttpResponseStream(requestHandle, state); state.RequestHandle = null; // ownership successfully transfered to WinHttpResponseStram. Stream decompressedStream = responseStream; if (doManualDecompressionCheck) { int contentEncodingStartIndex = 0; int contentEncodingLength = GetResponseHeader( requestHandle, Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING, buffer); CharArrayHelpers.Trim(buffer, ref contentEncodingStartIndex, ref contentEncodingLength); if (contentEncodingLength > 0) { if (CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase( EncodingNameGzip, buffer, contentEncodingStartIndex, contentEncodingLength)) { decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress); stripEncodingHeaders = true; } else if (CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase( EncodingNameDeflate, buffer, contentEncodingStartIndex, contentEncodingLength)) { decompressedStream = new DeflateStream(responseStream, CompressionMode.Decompress); stripEncodingHeaders = true; } } } #if HTTP_DLL var content = new StreamContent(decompressedStream, state.CancellationToken); #else // TODO: Issue https://github.com/dotnet/corefx/issues/9071 // We'd like to be able to pass state.CancellationToken into the StreamContent so that its // SerializeToStreamAsync method can use it, but that ctor isn't public, nor is there a // SerializeToStreamAsync override that takes a CancellationToken. var content = new StreamContent(decompressedStream); #endif response.Content = content; response.RequestMessage = request; // Parse raw response headers and place them into response message. ParseResponseHeaders(requestHandle, response, buffer, stripEncodingHeaders); if (response.RequestMessage.Method != HttpMethod.Head) { state.ExpectedBytesToRead = response.Content.Headers.ContentLength; } return response; } /// <summary> /// Returns the first header or throws if the header isn't found. /// </summary> public static uint GetResponseHeaderNumberInfo(SafeWinHttpHandle requestHandle, uint infoLevel) { uint result = 0; uint resultSize = sizeof(uint); if (!Interop.WinHttp.WinHttpQueryHeaders( requestHandle, infoLevel | Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER, Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX, ref result, ref resultSize, IntPtr.Zero)) { WinHttpException.ThrowExceptionUsingLastError(); } return result; } public unsafe static bool GetResponseHeader( SafeWinHttpHandle requestHandle, uint infoLevel, ref char[] buffer, ref uint index, out string headerValue) { const int StackLimit = 128; Debug.Assert(buffer == null || (buffer != null && buffer.Length > StackLimit)); int bufferLength; uint originalIndex = index; if (buffer == null) { bufferLength = StackLimit; char* pBuffer = stackalloc char[bufferLength]; if (QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index)) { headerValue = new string(pBuffer, 0, bufferLength); return true; } } else { bufferLength = buffer.Length; fixed (char* pBuffer = buffer) { if (QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index)) { headerValue = new string(pBuffer, 0, bufferLength); return true; } } } int lastError = Marshal.GetLastWin32Error(); if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND) { headerValue = null; return false; } if (lastError == Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER) { // WinHttpQueryHeaders may advance the index even when it fails due to insufficient buffer, // so we set the index back to its original value so we can retry retrieving the same // index again with a larger buffer. index = originalIndex; buffer = new char[bufferLength]; return GetResponseHeader(requestHandle, infoLevel, ref buffer, ref index, out headerValue); } throw WinHttpException.CreateExceptionUsingError(lastError); } /// <summary> /// Fills the buffer with the header value and returns the length, or returns 0 if the header isn't found. /// </summary> private unsafe static int GetResponseHeader(SafeWinHttpHandle requestHandle, uint infoLevel, char[] buffer) { Debug.Assert(buffer != null, "buffer must not be null."); Debug.Assert(buffer.Length > 0, "buffer must not be empty."); int bufferLength = buffer.Length; uint index = 0; fixed (char* pBuffer = buffer) { if (!QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index)) { int lastError = Marshal.GetLastWin32Error(); if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND) { return 0; } Debug.Assert(lastError != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER, "buffer must be of sufficient size."); throw WinHttpException.CreateExceptionUsingError(lastError); } } return bufferLength; } /// <summary> /// Returns the size of the char array buffer. /// </summary> private unsafe static int GetResponseHeaderCharBufferLength(SafeWinHttpHandle requestHandle, uint infoLevel) { char* buffer = null; int bufferLength = 0; uint index = 0; if (!QueryHeaders(requestHandle, infoLevel, buffer, ref bufferLength, ref index)) { int lastError = Marshal.GetLastWin32Error(); Debug.Assert(lastError != Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND); if (lastError != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER) { throw WinHttpException.CreateExceptionUsingError(lastError); } } return bufferLength; } private unsafe static bool QueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, char* buffer, ref int bufferLength, ref uint index) { Debug.Assert(bufferLength >= 0, "bufferLength must not be negative."); // Convert the char buffer length to the length in bytes. uint bufferLengthInBytes = (uint)bufferLength * sizeof(char); // The WinHttpQueryHeaders buffer length is in bytes, // but the API actually returns Unicode characters. bool result = Interop.WinHttp.WinHttpQueryHeaders( requestHandle, infoLevel, Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX, new IntPtr(buffer), ref bufferLengthInBytes, ref index); // Convert the byte buffer length back to the length in chars. bufferLength = (int)bufferLengthInBytes / sizeof(char); return result; } private static string GetReasonPhrase(HttpStatusCode statusCode, char[] buffer, int bufferLength) { CharArrayHelpers.DebugAssertArrayInputs(buffer, 0, bufferLength); Debug.Assert(bufferLength > 0); // If it's a known reason phrase, use the known reason phrase instead of allocating a new string. string knownReasonPhrase = HttpStatusDescription.Get(statusCode); return (knownReasonPhrase != null && CharArrayHelpers.EqualsOrdinal(knownReasonPhrase, buffer, 0, bufferLength)) ? knownReasonPhrase : new string(buffer, 0, bufferLength); } private static void ParseResponseHeaders( SafeWinHttpHandle requestHandle, HttpResponseMessage response, char[] buffer, bool stripEncodingHeaders) { HttpResponseHeaders responseHeaders = response.Headers; HttpContentHeaders contentHeaders = response.Content.Headers; int bufferLength = GetResponseHeader( requestHandle, Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF, buffer); var reader = new WinHttpResponseHeaderReader(buffer, 0, bufferLength); // Skip the first line which contains status code, etc. information that we already parsed. reader.ReadLine(); // Parse the array of headers and split them between Content headers and Response headers. string headerName; string headerValue; while (reader.ReadHeader(out headerName, out headerValue)) { if (!responseHeaders.TryAddWithoutValidation(headerName, headerValue)) { if (stripEncodingHeaders) { // Remove Content-Length and Content-Encoding headers if we are // decompressing the response stream in the handler (due to // WINHTTP not supporting it in a particular downlevel platform). // This matches the behavior of WINHTTP when it does decompression itself. if (string.Equals(HttpKnownHeaderNames.ContentLength, headerName, StringComparison.OrdinalIgnoreCase) || string.Equals(HttpKnownHeaderNames.ContentEncoding, headerName, StringComparison.OrdinalIgnoreCase)) { continue; } } // TODO: Issue #2165. Should we log if there is an error here? contentHeaders.TryAddWithoutValidation(headerName, headerValue); } } } private static bool IsResponseHttp2(SafeWinHttpHandle requestHandle) { uint data = 0; uint dataSize = sizeof(uint); if (Interop.WinHttp.WinHttpQueryOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_HTTP_PROTOCOL_USED, ref data, ref dataSize)) { if ((data & Interop.WinHttp.WINHTTP_PROTOCOL_FLAG_HTTP2) != 0) { WinHttpTraceHelper.Trace("WinHttpHandler.IsResponseHttp2: return true"); return true; } } return false; } } }
/* Copyright(c) 2009, Stefan Simek Copyright(c) 2016, Vladyslav Taranov 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.Text; using NUnit.Framework; using TriAxis.RunSharp; namespace TriAxis.RunSharp.Tests { [TestFixture] public class _09_IndexedProperties : TestBase { [Test] public void TestGenIndexedProperty() { TestingFacade.GetTestsForGenerator(GenIndexedProperty, @">>> GEN TriAxis.RunSharp.Tests.09_IndexedProperties.GenIndexedProperty === RUN TriAxis.RunSharp.Tests.09_IndexedProperties.GenIndexedProperty PeneloPe PiPer Picked a Peck of Pickled PePPers. How many Pickled PePPers did PeneloPe PiPer Pick? <<< END TriAxis.RunSharp.Tests.09_IndexedProperties.GenIndexedProperty ").RunAll(); } // example based on the MSDN Indexed Properties Sample (indexedproperty.cs) public static void GenIndexedProperty(AssemblyGen ag) { var st = ag.StaticFactory; var exp = ag.ExpressionFactory; CodeGen g; ITypeMapper m = ag.TypeMapper; TypeGen Document = ag.Public.Class("Document"); { FieldGen TextArray = Document.Private.Field(typeof(char[]), "TextArray"); // The text of the document. // Type allowing the document to be viewed like an array of words: TypeGen WordCollection = Document.Public.Class("WordCollection"); { FieldGen document = WordCollection.ReadOnly.Field(Document, "document"); // The containing document var document_TextArray = document.Field("TextArray", m); // example of a saved expression - it is always re-evaluated when used g = WordCollection.Internal.Constructor().Parameter(Document, "d"); { g.Assign(document, g.Arg("d")); } // Helper function -- search character array "text", starting at // character "begin", for word number "wordCount." Returns false // if there are less than wordCount words.Sets "start" and // length" to the position and length of the word within text: g = WordCollection.Private.Method(typeof(bool), "GetWord") .Parameter(typeof(char[]), "text") .Parameter(typeof(int), "begin") .Parameter(typeof(int), "wordCount") .Out.Parameter(typeof(int), "start") .Out.Parameter(typeof(int), "length") ; { ContextualOperand text = g.Arg("text"), begin = g.Arg("begin"), wordCount = g.Arg("wordCount"), start = g.Arg("start"), length = g.Arg("length"); var end = g.Local(text.ArrayLength()); var count = g.Local(0); var inWord = g.Local(-1); g.Assign(start, length.Assign(0)); var i = g.Local(); g.For(i.Assign(begin), i <= end, i.Increment()); { var isLetter = g.Local(i < end && st.Invoke(typeof(char), "IsLetterOrDigit", text[i])); g.If(inWord >= 0); { g.If(!isLetter); { g.If(count.PostIncrement() == wordCount); { g.Assign(start, inWord); g.Assign(length, i - inWord); g.Return(true); } g.End(); g.Assign(inWord, -1); } g.End(); } g.Else(); { g.If(isLetter); { g.Assign(inWord, i); } g.End(); } g.End(); } g.End(); g.Return(false); } // Indexer to get and set words of the containing document: PropertyGen Item = WordCollection.Public.Indexer(typeof(string)).Index(typeof(int), "index"); { g = Item.Getter(); { var index = g.Arg("index"); var start = g.Local(0); var length = g.Local(0); g.If(g.This().Invoke("GetWord", document_TextArray, 0, index, start.Ref(), length.Ref())); { g.Return(exp.New(typeof(string), document_TextArray, start, length)); } g.Else(); { g.Throw(exp.New(typeof(IndexOutOfRangeException))); } g.End(); } g = Item.Setter(); { var index = g.Arg("index"); var value = g.PropertyValue(); var start = g.Local(0); var length = g.Local(0); g.If(g.This().Invoke("GetWord", document_TextArray, 0, index, start.Ref(), length.Ref())); { // Replace the word at start/length with the // string "value": g.If(length == value.Property("Length")); { g.Invoke(typeof(Array), "Copy", value.Invoke("ToCharArray"), 0, document_TextArray, start, length); } g.Else(); { var newText = g.Local(exp.NewArray(typeof(char), document_TextArray.ArrayLength() + value.Property("Length") - length)); g.Invoke(typeof(Array), "Copy", document_TextArray, 0, newText, 0, start); g.Invoke(typeof(Array), "Copy", value.Invoke("ToCharArray"), 0, newText, start, value.Property("Length")); g.Invoke(typeof(Array), "Copy", document_TextArray, start + length, newText, start + value.Property("Length"), document_TextArray.ArrayLength() - start - length); g.Assign(document_TextArray, newText); } g.End(); } g.Else(); { g.Throw(exp.New(typeof(IndexOutOfRangeException))); } g.End(); } } // Get the count of words in the containing document: g = WordCollection.Public.Property(typeof(int), "Count").Getter(); { ContextualOperand count = g.Local(0), start = g.Local(0), length = g.Local(0); g.While(g.This().Invoke("GetWord", document_TextArray, start + length, 0, start.Ref(), length.Ref())); { g.Increment(count); } g.End(); g.Return(count); } } // Type allowing the document to be viewed like an "array" // of characters: TypeGen CharacterCollection = Document.Public.Class("CharacterCollection"); { FieldGen document = CharacterCollection.ReadOnly.Field(Document, "document"); // The containing document var document_TextArray = document.Field("TextArray", m); g = CharacterCollection.Internal.Constructor().Parameter(Document, "d"); { g.Assign(document, g.Arg("d")); } // Indexer to get and set characters in the containing document: PropertyGen Item = CharacterCollection.Public.Indexer(typeof(char)).Index(typeof(int), "index"); { g = Item.Getter(); { g.Return(document_TextArray[g.Arg("index")]); } g = Item.Setter(); { g.Assign(document_TextArray[g.Arg("index")], g.PropertyValue()); } } // Get the count of characters in the containing document: g = CharacterCollection.Public.Property(typeof(int), "Count").Getter(); { g.Return(document_TextArray.ArrayLength()); } } // Because the types of the fields have indexers, // these fields appear as "indexed properties": FieldGen Words = Document.Public.ReadOnly.Field(WordCollection, "Words"); FieldGen Characters = Document.Public.ReadOnly.Field(CharacterCollection, "Characters"); g = Document.Public.Constructor().Parameter(typeof(string), "initialText"); { g.Assign(TextArray, g.Arg("initialText").Invoke("ToCharArray")); g.Assign(Words, exp.New(WordCollection, g.This())); g.Assign(Characters, exp.New(CharacterCollection, g.This())); } g = Document.Public.Property(typeof(string), "Text").Getter(); { g.Return(exp.New(typeof(string), TextArray)); } } TypeGen Test = ag.Class("Test"); { g = Test.Public.Static.Method(typeof(void), "Main"); { var d = g.Local(exp.New(Document, "peter piper picked a peck of pickled peppers. How many pickled peppers did peter piper pick?")); // Change word "peter" to "penelope": var i = g.Local(); g.For(i.Assign(0), i < d.Field("Words").Property("Count"), i.Increment()); { g.If(d.Field("Words")[i] == "peter"); { g.Assign(d.Field("Words")[i], "penelope"); } g.End(); } g.End(); // Change character "p" to "P" g.For(i.Assign(0), i < d.Field("Characters").Property("Count"), i.Increment()); { g.If(d.Field("Characters")[i] == 'p'); { g.Assign(d.Field("Characters")[i], 'P'); } g.End(); } g.End(); g.WriteLine(d.Property("Text")); } } } } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Net; using System.Web; using System.IO; using System.Collections; using System.Collections.Specialized; using System.Diagnostics; using log4net; using FluorineFx.Util; using FluorineFx.Collections; using FluorineFx.Messaging; using FluorineFx.Messaging.Config; using FluorineFx.Messaging.Messages; using FluorineFx.Messaging.Endpoints; using FluorineFx.Messaging.Rtmp; using FluorineFx.Messaging.Adapter; using FluorineFx.Messaging.Rtmp.Service; using FluorineFx.Messaging.Api; using FluorineFx.Context; using FluorineFx.Configuration; namespace FluorineFx.Messaging.Endpoints { /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> internal class RtmpEndpoint : EndpointBase { private static readonly ILog log = LogManager.GetLogger(typeof(RtmpEndpoint)); //static object _objLock = new object(); public static string Slash = "/"; RtmpServer _rtmpServer; public RtmpEndpoint(MessageBroker messageBroker, ChannelDefinition channelDefinition) : base(messageBroker, channelDefinition) { } public override void Start() { try { if( log.IsInfoEnabled ) log.Info(__Res.GetString(__Res.RtmpEndpoint_Start)); //Each Application has its own Scope hierarchy and the root scope is WebScope. //There's a global scope that aims to provide common resource sharing across Applications namely GlobalScope. //The GlobalScope is the parent of all WebScopes. //Other scopes in between are all instances of Scope. Each scope takes a name. //The GlobalScope is named "default". //The WebScope is named per Application context name. //The Scope is named per path name. IGlobalScope globalScope = GetMessageBroker().GlobalScope; string baseDirectory; if (FluorineContext.Current != null) baseDirectory = Path.Combine(FluorineContext.Current.ApplicationBaseDirectory, "apps"); else baseDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "apps"); if (Directory.Exists(baseDirectory)) { foreach (string appDirectory in Directory.GetDirectories(baseDirectory)) { DirectoryInfo directoryInfo = new DirectoryInfo(appDirectory); string appName = directoryInfo.Name; string appConfigFile = Path.Combine(appDirectory, "app.config"); ApplicationConfiguration configuration = ApplicationConfiguration.Load(appConfigFile); WebScope scope = new WebScope(this, globalScope, configuration); // Create context for the WebScope and initialize ScopeContext scopeContext = new ScopeContext("/" + appName, globalScope.Context.ClientRegistry, globalScope.Context.ScopeResolver, globalScope.Context.ServiceInvoker, null); // Store context in scope scope.Context = scopeContext; // ApplicationAdapter IFlexFactory factory = GetMessageBroker().GetFactory(configuration.ApplicationHandler.Factory); FactoryInstance factoryInstance = factory.CreateFactoryInstance(this.Id, null); if (factoryInstance == null) { string msg = string.Format("Missing factory {0}", configuration.ApplicationHandler.Factory); log.Fatal(msg); throw new NotSupportedException(msg); } factoryInstance.Source = configuration.ApplicationHandler.Type; object applicationHandlerInstance = factoryInstance.Lookup(); IScopeHandler scopeHandler = applicationHandlerInstance as IScopeHandler; if (scopeHandler == null) { log.Error(__Res.GetString(__Res.Type_InitError, configuration.ApplicationHandler.Type)); throw new TypeInitializationException(configuration.ApplicationHandler.Type, null); } scope.Handler = scopeHandler; // Make available as "/<directoryName>" and allow access from all hosts scope.SetContextPath("/" + appName); // Register WebScope in server scope.Register(); } } _rtmpServer = new RtmpServer(this); UriBase uri = this.ChannelDefinition.GetUri(); if (uri.Protocol == "http" || uri.Protocol == "https") { log.Info(string.Format("Rtmp endpoint was not started, specified protocol: {0}", uri.Protocol)); return; } int port = 1935; if (uri.Port != null && uri.Port != string.Empty) { try { port = System.Convert.ToInt32(uri.Port); } catch (FormatException ex) { log.Error("Invalid port", ex); return; } } if( log.IsInfoEnabled ) log.Info(__Res.GetString(__Res.RtmpEndpoint_Starting, port.ToString())); IPEndPoint ipEndPoint; if (this.ChannelDefinition.Properties.BindAddress != null) { IPAddress ipAddress = IPAddress.Parse(this.ChannelDefinition.Properties.BindAddress); ipEndPoint = new IPEndPoint(ipAddress, port); } else ipEndPoint = new IPEndPoint(IPAddress.Any, port); _rtmpServer.AddListener(ipEndPoint); _rtmpServer.OnError += new ErrorHandler(OnError); _rtmpServer.Start(); if( log.IsInfoEnabled ) log.Info(__Res.GetString(__Res.RtmpEndpoint_Started)); } catch(Exception ex) { if( log.IsFatalEnabled ) log.Fatal("RtmpEndpoint failed", ex); } } public override void Stop() { try { if( log.IsInfoEnabled ) log.Info(__Res.GetString(__Res.RtmpEndpoint_Stopping)); if (_rtmpServer != null) { _rtmpServer.Stop(); _rtmpServer.OnError -= new ErrorHandler(OnError); _rtmpServer.Dispose(); _rtmpServer = null; } if( log.IsInfoEnabled ) log.Info(__Res.GetString(__Res.RtmpEndpoint_Stopped)); } catch(Exception ex) { if( log.IsFatalEnabled ) log.Fatal(__Res.GetString(__Res.RtmpEndpoint_Failed), ex); } } public override void Push(IMessage message, MessageClient messageClient) { /* IMessageConnection messageConnection = messageClient.MessageConnection; Debug.Assert(messageConnection != null); if (messageConnection != null) messageConnection.Push(message, messageClient); */ ISession session = messageClient.Session; System.Diagnostics.Debug.Assert(session != null); session.Push(message, messageClient); } private void OnError(object sender, ServerErrorEventArgs e) { System.Diagnostics.Debug.WriteLine(e.Exception.Message); if( log.IsErrorEnabled ) log.Error(__Res.GetString(__Res.RtmpEndpoint_Error), e.Exception); } /// <summary> /// This property supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public override int ClientLeaseTime { get { int timeout = this.GetMessageBroker().FlexClientSettings.TimeoutMinutes; return timeout; } } } }
// // 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 System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations for operating on service tier advisors. /// Contains operations to: Retrieve. /// </summary> internal partial class ServiceTierAdvisorOperations : IServiceOperations<SqlManagementClient>, IServiceTierAdvisorOperations { /// <summary> /// Initializes a new instance of the ServiceTierAdvisorOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ServiceTierAdvisorOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Returns information about a service tier advisor. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of server. /// </param> /// <param name='databaseName'> /// Required. The name of database. /// </param> /// <param name='serviceTierAdvisorName'> /// Required. The name of service tier advisor. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a get service tier advisor request. /// </returns> public async Task<ServiceTierAdvisorGetResponse> GetAsync(string resourceGroupName, string serverName, string databaseName, string serviceTierAdvisorName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } if (serviceTierAdvisorName == null) { throw new ArgumentNullException("serviceTierAdvisorName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("serviceTierAdvisorName", serviceTierAdvisorName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/serviceTierAdvisors/"; url = url + Uri.EscapeDataString(serviceTierAdvisorName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServiceTierAdvisorGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceTierAdvisorGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ServiceTierAdvisor serviceTierAdvisorInstance = new ServiceTierAdvisor(); result.ServiceTierAdvisor = serviceTierAdvisorInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServiceTierAdvisorProperties propertiesInstance = new ServiceTierAdvisorProperties(); serviceTierAdvisorInstance.Properties = propertiesInstance; JToken observationPeriodStartValue = propertiesValue["observationPeriodStart"]; if (observationPeriodStartValue != null && observationPeriodStartValue.Type != JTokenType.Null) { DateTime observationPeriodStartInstance = ((DateTime)observationPeriodStartValue); propertiesInstance.ObservationPeriodStart = observationPeriodStartInstance; } JToken observationPeriodEndValue = propertiesValue["observationPeriodEnd"]; if (observationPeriodEndValue != null && observationPeriodEndValue.Type != JTokenType.Null) { DateTime observationPeriodEndInstance = ((DateTime)observationPeriodEndValue); propertiesInstance.ObservationPeriodEnd = observationPeriodEndInstance; } JToken activeTimeRatioValue = propertiesValue["activeTimeRatio"]; if (activeTimeRatioValue != null && activeTimeRatioValue.Type != JTokenType.Null) { double activeTimeRatioInstance = ((double)activeTimeRatioValue); propertiesInstance.ActiveTimeRatio = activeTimeRatioInstance; } JToken minDtuValue = propertiesValue["minDtu"]; if (minDtuValue != null && minDtuValue.Type != JTokenType.Null) { double minDtuInstance = ((double)minDtuValue); propertiesInstance.MinDtu = minDtuInstance; } JToken avgDtuValue = propertiesValue["avgDtu"]; if (avgDtuValue != null && avgDtuValue.Type != JTokenType.Null) { double avgDtuInstance = ((double)avgDtuValue); propertiesInstance.AvgDtu = avgDtuInstance; } JToken maxDtuValue = propertiesValue["maxDtu"]; if (maxDtuValue != null && maxDtuValue.Type != JTokenType.Null) { double maxDtuInstance = ((double)maxDtuValue); propertiesInstance.MaxDtu = maxDtuInstance; } JToken maxSizeInGBValue = propertiesValue["maxSizeInGB"]; if (maxSizeInGBValue != null && maxSizeInGBValue.Type != JTokenType.Null) { double maxSizeInGBInstance = ((double)maxSizeInGBValue); propertiesInstance.MaxSizeInGB = maxSizeInGBInstance; } JToken serviceLevelObjectiveUsageMetricsArray = propertiesValue["serviceLevelObjectiveUsageMetrics"]; if (serviceLevelObjectiveUsageMetricsArray != null && serviceLevelObjectiveUsageMetricsArray.Type != JTokenType.Null) { foreach (JToken serviceLevelObjectiveUsageMetricsValue in ((JArray)serviceLevelObjectiveUsageMetricsArray)) { SloUsageMetric sloUsageMetricInstance = new SloUsageMetric(); propertiesInstance.ServiceLevelObjectiveUsageMetrics.Add(sloUsageMetricInstance); JToken serviceLevelObjectiveValue = serviceLevelObjectiveUsageMetricsValue["serviceLevelObjective"]; if (serviceLevelObjectiveValue != null && serviceLevelObjectiveValue.Type != JTokenType.Null) { string serviceLevelObjectiveInstance = ((string)serviceLevelObjectiveValue); sloUsageMetricInstance.ServiceLevelObjective = serviceLevelObjectiveInstance; } JToken serviceLevelObjectiveIdValue = serviceLevelObjectiveUsageMetricsValue["serviceLevelObjectiveId"]; if (serviceLevelObjectiveIdValue != null && serviceLevelObjectiveIdValue.Type != JTokenType.Null) { Guid serviceLevelObjectiveIdInstance = Guid.Parse(((string)serviceLevelObjectiveIdValue)); sloUsageMetricInstance.ServiceLevelObjectiveId = serviceLevelObjectiveIdInstance; } JToken inRangeTimeRatioValue = serviceLevelObjectiveUsageMetricsValue["inRangeTimeRatio"]; if (inRangeTimeRatioValue != null && inRangeTimeRatioValue.Type != JTokenType.Null) { double inRangeTimeRatioInstance = ((double)inRangeTimeRatioValue); sloUsageMetricInstance.InRangeTimeRatio = inRangeTimeRatioInstance; } JToken idValue = serviceLevelObjectiveUsageMetricsValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); sloUsageMetricInstance.Id = idInstance; } JToken nameValue = serviceLevelObjectiveUsageMetricsValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); sloUsageMetricInstance.Name = nameInstance; } JToken typeValue = serviceLevelObjectiveUsageMetricsValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); sloUsageMetricInstance.Type = typeInstance; } JToken locationValue = serviceLevelObjectiveUsageMetricsValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); sloUsageMetricInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)serviceLevelObjectiveUsageMetricsValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); sloUsageMetricInstance.Tags.Add(tagsKey, tagsValue); } } } } JToken currentServiceLevelObjectiveValue = propertiesValue["currentServiceLevelObjective"]; if (currentServiceLevelObjectiveValue != null && currentServiceLevelObjectiveValue.Type != JTokenType.Null) { string currentServiceLevelObjectiveInstance = ((string)currentServiceLevelObjectiveValue); propertiesInstance.CurrentServiceLevelObjective = currentServiceLevelObjectiveInstance; } JToken currentServiceLevelObjectiveIdValue = propertiesValue["currentServiceLevelObjectiveId"]; if (currentServiceLevelObjectiveIdValue != null && currentServiceLevelObjectiveIdValue.Type != JTokenType.Null) { Guid currentServiceLevelObjectiveIdInstance = Guid.Parse(((string)currentServiceLevelObjectiveIdValue)); propertiesInstance.CurrentServiceLevelObjectiveId = currentServiceLevelObjectiveIdInstance; } JToken usageBasedRecommendationServiceLevelObjectiveValue = propertiesValue["usageBasedRecommendationServiceLevelObjective"]; if (usageBasedRecommendationServiceLevelObjectiveValue != null && usageBasedRecommendationServiceLevelObjectiveValue.Type != JTokenType.Null) { string usageBasedRecommendationServiceLevelObjectiveInstance = ((string)usageBasedRecommendationServiceLevelObjectiveValue); propertiesInstance.UsageBasedRecommendationServiceLevelObjective = usageBasedRecommendationServiceLevelObjectiveInstance; } JToken usageBasedRecommendationServiceLevelObjectiveIdValue = propertiesValue["usageBasedRecommendationServiceLevelObjectiveId"]; if (usageBasedRecommendationServiceLevelObjectiveIdValue != null && usageBasedRecommendationServiceLevelObjectiveIdValue.Type != JTokenType.Null) { Guid usageBasedRecommendationServiceLevelObjectiveIdInstance = Guid.Parse(((string)usageBasedRecommendationServiceLevelObjectiveIdValue)); propertiesInstance.UsageBasedRecommendationServiceLevelObjectiveId = usageBasedRecommendationServiceLevelObjectiveIdInstance; } JToken databaseSizeBasedRecommendationServiceLevelObjectiveValue = propertiesValue["databaseSizeBasedRecommendationServiceLevelObjective"]; if (databaseSizeBasedRecommendationServiceLevelObjectiveValue != null && databaseSizeBasedRecommendationServiceLevelObjectiveValue.Type != JTokenType.Null) { string databaseSizeBasedRecommendationServiceLevelObjectiveInstance = ((string)databaseSizeBasedRecommendationServiceLevelObjectiveValue); propertiesInstance.DatabaseSizeBasedRecommendationServiceLevelObjective = databaseSizeBasedRecommendationServiceLevelObjectiveInstance; } JToken databaseSizeBasedRecommendationServiceLevelObjectiveIdValue = propertiesValue["databaseSizeBasedRecommendationServiceLevelObjectiveId"]; if (databaseSizeBasedRecommendationServiceLevelObjectiveIdValue != null && databaseSizeBasedRecommendationServiceLevelObjectiveIdValue.Type != JTokenType.Null) { Guid databaseSizeBasedRecommendationServiceLevelObjectiveIdInstance = Guid.Parse(((string)databaseSizeBasedRecommendationServiceLevelObjectiveIdValue)); propertiesInstance.DatabaseSizeBasedRecommendationServiceLevelObjectiveId = databaseSizeBasedRecommendationServiceLevelObjectiveIdInstance; } JToken disasterPlanBasedRecommendationServiceLevelObjectiveValue = propertiesValue["disasterPlanBasedRecommendationServiceLevelObjective"]; if (disasterPlanBasedRecommendationServiceLevelObjectiveValue != null && disasterPlanBasedRecommendationServiceLevelObjectiveValue.Type != JTokenType.Null) { string disasterPlanBasedRecommendationServiceLevelObjectiveInstance = ((string)disasterPlanBasedRecommendationServiceLevelObjectiveValue); propertiesInstance.DisasterPlanBasedRecommendationServiceLevelObjective = disasterPlanBasedRecommendationServiceLevelObjectiveInstance; } JToken disasterPlanBasedRecommendationServiceLevelObjectiveIdValue = propertiesValue["disasterPlanBasedRecommendationServiceLevelObjectiveId"]; if (disasterPlanBasedRecommendationServiceLevelObjectiveIdValue != null && disasterPlanBasedRecommendationServiceLevelObjectiveIdValue.Type != JTokenType.Null) { Guid disasterPlanBasedRecommendationServiceLevelObjectiveIdInstance = Guid.Parse(((string)disasterPlanBasedRecommendationServiceLevelObjectiveIdValue)); propertiesInstance.DisasterPlanBasedRecommendationServiceLevelObjectiveId = disasterPlanBasedRecommendationServiceLevelObjectiveIdInstance; } JToken overallRecommendationServiceLevelObjectiveValue = propertiesValue["overallRecommendationServiceLevelObjective"]; if (overallRecommendationServiceLevelObjectiveValue != null && overallRecommendationServiceLevelObjectiveValue.Type != JTokenType.Null) { string overallRecommendationServiceLevelObjectiveInstance = ((string)overallRecommendationServiceLevelObjectiveValue); propertiesInstance.OverallRecommendationServiceLevelObjective = overallRecommendationServiceLevelObjectiveInstance; } JToken overallRecommendationServiceLevelObjectiveIdValue = propertiesValue["overallRecommendationServiceLevelObjectiveId"]; if (overallRecommendationServiceLevelObjectiveIdValue != null && overallRecommendationServiceLevelObjectiveIdValue.Type != JTokenType.Null) { Guid overallRecommendationServiceLevelObjectiveIdInstance = Guid.Parse(((string)overallRecommendationServiceLevelObjectiveIdValue)); propertiesInstance.OverallRecommendationServiceLevelObjectiveId = overallRecommendationServiceLevelObjectiveIdInstance; } JToken confidenceValue = propertiesValue["confidence"]; if (confidenceValue != null && confidenceValue.Type != JTokenType.Null) { double confidenceInstance = ((double)confidenceValue); propertiesInstance.Confidence = confidenceInstance; } } JToken idValue2 = responseDoc["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); serviceTierAdvisorInstance.Id = idInstance2; } JToken nameValue2 = responseDoc["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); serviceTierAdvisorInstance.Name = nameInstance2; } JToken typeValue2 = responseDoc["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); serviceTierAdvisorInstance.Type = typeInstance2; } JToken locationValue2 = responseDoc["location"]; if (locationValue2 != null && locationValue2.Type != JTokenType.Null) { string locationInstance2 = ((string)locationValue2); serviceTierAdvisorInstance.Location = locationInstance2; } JToken tagsSequenceElement2 = ((JToken)responseDoc["tags"]); if (tagsSequenceElement2 != null && tagsSequenceElement2.Type != JTokenType.Null) { foreach (JProperty property2 in tagsSequenceElement2) { string tagsKey2 = ((string)property2.Name); string tagsValue2 = ((string)property2.Value); serviceTierAdvisorInstance.Tags.Add(tagsKey2, tagsValue2); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns information about service tier advisors for specified /// database. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of server. /// </param> /// <param name='databaseName'> /// Required. The name of database. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a list service tier advisor request. /// </returns> public async Task<ServiceTierAdvisorListResponse> ListAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/serviceTierAdvisors"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServiceTierAdvisorListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceTierAdvisorListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ServiceTierAdvisor serviceTierAdvisorInstance = new ServiceTierAdvisor(); result.ServiceTierAdvisors.Add(serviceTierAdvisorInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServiceTierAdvisorProperties propertiesInstance = new ServiceTierAdvisorProperties(); serviceTierAdvisorInstance.Properties = propertiesInstance; JToken observationPeriodStartValue = propertiesValue["observationPeriodStart"]; if (observationPeriodStartValue != null && observationPeriodStartValue.Type != JTokenType.Null) { DateTime observationPeriodStartInstance = ((DateTime)observationPeriodStartValue); propertiesInstance.ObservationPeriodStart = observationPeriodStartInstance; } JToken observationPeriodEndValue = propertiesValue["observationPeriodEnd"]; if (observationPeriodEndValue != null && observationPeriodEndValue.Type != JTokenType.Null) { DateTime observationPeriodEndInstance = ((DateTime)observationPeriodEndValue); propertiesInstance.ObservationPeriodEnd = observationPeriodEndInstance; } JToken activeTimeRatioValue = propertiesValue["activeTimeRatio"]; if (activeTimeRatioValue != null && activeTimeRatioValue.Type != JTokenType.Null) { double activeTimeRatioInstance = ((double)activeTimeRatioValue); propertiesInstance.ActiveTimeRatio = activeTimeRatioInstance; } JToken minDtuValue = propertiesValue["minDtu"]; if (minDtuValue != null && minDtuValue.Type != JTokenType.Null) { double minDtuInstance = ((double)minDtuValue); propertiesInstance.MinDtu = minDtuInstance; } JToken avgDtuValue = propertiesValue["avgDtu"]; if (avgDtuValue != null && avgDtuValue.Type != JTokenType.Null) { double avgDtuInstance = ((double)avgDtuValue); propertiesInstance.AvgDtu = avgDtuInstance; } JToken maxDtuValue = propertiesValue["maxDtu"]; if (maxDtuValue != null && maxDtuValue.Type != JTokenType.Null) { double maxDtuInstance = ((double)maxDtuValue); propertiesInstance.MaxDtu = maxDtuInstance; } JToken maxSizeInGBValue = propertiesValue["maxSizeInGB"]; if (maxSizeInGBValue != null && maxSizeInGBValue.Type != JTokenType.Null) { double maxSizeInGBInstance = ((double)maxSizeInGBValue); propertiesInstance.MaxSizeInGB = maxSizeInGBInstance; } JToken serviceLevelObjectiveUsageMetricsArray = propertiesValue["serviceLevelObjectiveUsageMetrics"]; if (serviceLevelObjectiveUsageMetricsArray != null && serviceLevelObjectiveUsageMetricsArray.Type != JTokenType.Null) { foreach (JToken serviceLevelObjectiveUsageMetricsValue in ((JArray)serviceLevelObjectiveUsageMetricsArray)) { SloUsageMetric sloUsageMetricInstance = new SloUsageMetric(); propertiesInstance.ServiceLevelObjectiveUsageMetrics.Add(sloUsageMetricInstance); JToken serviceLevelObjectiveValue = serviceLevelObjectiveUsageMetricsValue["serviceLevelObjective"]; if (serviceLevelObjectiveValue != null && serviceLevelObjectiveValue.Type != JTokenType.Null) { string serviceLevelObjectiveInstance = ((string)serviceLevelObjectiveValue); sloUsageMetricInstance.ServiceLevelObjective = serviceLevelObjectiveInstance; } JToken serviceLevelObjectiveIdValue = serviceLevelObjectiveUsageMetricsValue["serviceLevelObjectiveId"]; if (serviceLevelObjectiveIdValue != null && serviceLevelObjectiveIdValue.Type != JTokenType.Null) { Guid serviceLevelObjectiveIdInstance = Guid.Parse(((string)serviceLevelObjectiveIdValue)); sloUsageMetricInstance.ServiceLevelObjectiveId = serviceLevelObjectiveIdInstance; } JToken inRangeTimeRatioValue = serviceLevelObjectiveUsageMetricsValue["inRangeTimeRatio"]; if (inRangeTimeRatioValue != null && inRangeTimeRatioValue.Type != JTokenType.Null) { double inRangeTimeRatioInstance = ((double)inRangeTimeRatioValue); sloUsageMetricInstance.InRangeTimeRatio = inRangeTimeRatioInstance; } JToken idValue = serviceLevelObjectiveUsageMetricsValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); sloUsageMetricInstance.Id = idInstance; } JToken nameValue = serviceLevelObjectiveUsageMetricsValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); sloUsageMetricInstance.Name = nameInstance; } JToken typeValue = serviceLevelObjectiveUsageMetricsValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); sloUsageMetricInstance.Type = typeInstance; } JToken locationValue = serviceLevelObjectiveUsageMetricsValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); sloUsageMetricInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)serviceLevelObjectiveUsageMetricsValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); sloUsageMetricInstance.Tags.Add(tagsKey, tagsValue); } } } } JToken currentServiceLevelObjectiveValue = propertiesValue["currentServiceLevelObjective"]; if (currentServiceLevelObjectiveValue != null && currentServiceLevelObjectiveValue.Type != JTokenType.Null) { string currentServiceLevelObjectiveInstance = ((string)currentServiceLevelObjectiveValue); propertiesInstance.CurrentServiceLevelObjective = currentServiceLevelObjectiveInstance; } JToken currentServiceLevelObjectiveIdValue = propertiesValue["currentServiceLevelObjectiveId"]; if (currentServiceLevelObjectiveIdValue != null && currentServiceLevelObjectiveIdValue.Type != JTokenType.Null) { Guid currentServiceLevelObjectiveIdInstance = Guid.Parse(((string)currentServiceLevelObjectiveIdValue)); propertiesInstance.CurrentServiceLevelObjectiveId = currentServiceLevelObjectiveIdInstance; } JToken usageBasedRecommendationServiceLevelObjectiveValue = propertiesValue["usageBasedRecommendationServiceLevelObjective"]; if (usageBasedRecommendationServiceLevelObjectiveValue != null && usageBasedRecommendationServiceLevelObjectiveValue.Type != JTokenType.Null) { string usageBasedRecommendationServiceLevelObjectiveInstance = ((string)usageBasedRecommendationServiceLevelObjectiveValue); propertiesInstance.UsageBasedRecommendationServiceLevelObjective = usageBasedRecommendationServiceLevelObjectiveInstance; } JToken usageBasedRecommendationServiceLevelObjectiveIdValue = propertiesValue["usageBasedRecommendationServiceLevelObjectiveId"]; if (usageBasedRecommendationServiceLevelObjectiveIdValue != null && usageBasedRecommendationServiceLevelObjectiveIdValue.Type != JTokenType.Null) { Guid usageBasedRecommendationServiceLevelObjectiveIdInstance = Guid.Parse(((string)usageBasedRecommendationServiceLevelObjectiveIdValue)); propertiesInstance.UsageBasedRecommendationServiceLevelObjectiveId = usageBasedRecommendationServiceLevelObjectiveIdInstance; } JToken databaseSizeBasedRecommendationServiceLevelObjectiveValue = propertiesValue["databaseSizeBasedRecommendationServiceLevelObjective"]; if (databaseSizeBasedRecommendationServiceLevelObjectiveValue != null && databaseSizeBasedRecommendationServiceLevelObjectiveValue.Type != JTokenType.Null) { string databaseSizeBasedRecommendationServiceLevelObjectiveInstance = ((string)databaseSizeBasedRecommendationServiceLevelObjectiveValue); propertiesInstance.DatabaseSizeBasedRecommendationServiceLevelObjective = databaseSizeBasedRecommendationServiceLevelObjectiveInstance; } JToken databaseSizeBasedRecommendationServiceLevelObjectiveIdValue = propertiesValue["databaseSizeBasedRecommendationServiceLevelObjectiveId"]; if (databaseSizeBasedRecommendationServiceLevelObjectiveIdValue != null && databaseSizeBasedRecommendationServiceLevelObjectiveIdValue.Type != JTokenType.Null) { Guid databaseSizeBasedRecommendationServiceLevelObjectiveIdInstance = Guid.Parse(((string)databaseSizeBasedRecommendationServiceLevelObjectiveIdValue)); propertiesInstance.DatabaseSizeBasedRecommendationServiceLevelObjectiveId = databaseSizeBasedRecommendationServiceLevelObjectiveIdInstance; } JToken disasterPlanBasedRecommendationServiceLevelObjectiveValue = propertiesValue["disasterPlanBasedRecommendationServiceLevelObjective"]; if (disasterPlanBasedRecommendationServiceLevelObjectiveValue != null && disasterPlanBasedRecommendationServiceLevelObjectiveValue.Type != JTokenType.Null) { string disasterPlanBasedRecommendationServiceLevelObjectiveInstance = ((string)disasterPlanBasedRecommendationServiceLevelObjectiveValue); propertiesInstance.DisasterPlanBasedRecommendationServiceLevelObjective = disasterPlanBasedRecommendationServiceLevelObjectiveInstance; } JToken disasterPlanBasedRecommendationServiceLevelObjectiveIdValue = propertiesValue["disasterPlanBasedRecommendationServiceLevelObjectiveId"]; if (disasterPlanBasedRecommendationServiceLevelObjectiveIdValue != null && disasterPlanBasedRecommendationServiceLevelObjectiveIdValue.Type != JTokenType.Null) { Guid disasterPlanBasedRecommendationServiceLevelObjectiveIdInstance = Guid.Parse(((string)disasterPlanBasedRecommendationServiceLevelObjectiveIdValue)); propertiesInstance.DisasterPlanBasedRecommendationServiceLevelObjectiveId = disasterPlanBasedRecommendationServiceLevelObjectiveIdInstance; } JToken overallRecommendationServiceLevelObjectiveValue = propertiesValue["overallRecommendationServiceLevelObjective"]; if (overallRecommendationServiceLevelObjectiveValue != null && overallRecommendationServiceLevelObjectiveValue.Type != JTokenType.Null) { string overallRecommendationServiceLevelObjectiveInstance = ((string)overallRecommendationServiceLevelObjectiveValue); propertiesInstance.OverallRecommendationServiceLevelObjective = overallRecommendationServiceLevelObjectiveInstance; } JToken overallRecommendationServiceLevelObjectiveIdValue = propertiesValue["overallRecommendationServiceLevelObjectiveId"]; if (overallRecommendationServiceLevelObjectiveIdValue != null && overallRecommendationServiceLevelObjectiveIdValue.Type != JTokenType.Null) { Guid overallRecommendationServiceLevelObjectiveIdInstance = Guid.Parse(((string)overallRecommendationServiceLevelObjectiveIdValue)); propertiesInstance.OverallRecommendationServiceLevelObjectiveId = overallRecommendationServiceLevelObjectiveIdInstance; } JToken confidenceValue = propertiesValue["confidence"]; if (confidenceValue != null && confidenceValue.Type != JTokenType.Null) { double confidenceInstance = ((double)confidenceValue); propertiesInstance.Confidence = confidenceInstance; } } JToken idValue2 = valueValue["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); serviceTierAdvisorInstance.Id = idInstance2; } JToken nameValue2 = valueValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); serviceTierAdvisorInstance.Name = nameInstance2; } JToken typeValue2 = valueValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); serviceTierAdvisorInstance.Type = typeInstance2; } JToken locationValue2 = valueValue["location"]; if (locationValue2 != null && locationValue2.Type != JTokenType.Null) { string locationInstance2 = ((string)locationValue2); serviceTierAdvisorInstance.Location = locationInstance2; } JToken tagsSequenceElement2 = ((JToken)valueValue["tags"]); if (tagsSequenceElement2 != null && tagsSequenceElement2.Type != JTokenType.Null) { foreach (JProperty property2 in tagsSequenceElement2) { string tagsKey2 = ((string)property2.Name); string tagsValue2 = ((string)property2.Value); serviceTierAdvisorInstance.Tags.Add(tagsKey2, tagsValue2); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * 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 MemberCanBeProtected.Global // ReSharper disable UnassignedField.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global namespace Apache.Ignite.Core.Tests { using System; using System.Collections; using System.Collections.Generic; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Lifecycle beans test. /// </summary> public class LifecycleTest { /** Configuration: without Java beans. */ private const string CfgNoBeans = "Config/Lifecycle/lifecycle-no-beans.xml"; /** Configuration: with Java beans. */ private const string CfgBeans = "Config/Lifecycle//lifecycle-beans.xml"; /** Whether to throw an error on lifecycle event. */ internal static bool ThrowErr; /** Events: before start. */ internal static IList<Event> BeforeStartEvts; /** Events: after start. */ internal static IList<Event> AfterStartEvts; /** Events: before stop. */ internal static IList<Event> BeforeStopEvts; /** Events: after stop. */ internal static IList<Event> AfterStopEvts; /// <summary> /// Set up routine. /// </summary> [SetUp] public void SetUp() { ThrowErr = false; BeforeStartEvts = new List<Event>(); AfterStartEvts = new List<Event>(); BeforeStopEvts = new List<Event>(); AfterStopEvts = new List<Event>(); } /// <summary> /// Tear down routine. /// </summary> [TearDown] public void TearDown() { Ignition.StopAll(true); } /// <summary> /// Test without Java beans. /// </summary> [Test] public void TestWithoutBeans() { // 1. Test start events. IIgnite grid = Start(CfgNoBeans); Assert.AreEqual(2, grid.GetConfiguration().LifecycleHandlers.Count); Assert.AreEqual(2, BeforeStartEvts.Count); CheckEvent(BeforeStartEvts[0], null, null, 0, null); CheckEvent(BeforeStartEvts[1], null, null, 0, null); Assert.AreEqual(2, AfterStartEvts.Count); CheckEvent(AfterStartEvts[0], grid, grid, 0, null); CheckEvent(AfterStartEvts[1], grid, grid, 0, null); // 2. Test stop events. var stoppingCnt = 0; var stoppedCnt = 0; grid.Stopping += (sender, args) => { stoppingCnt++; }; grid.Stopped += (sender, args) => { stoppedCnt++; }; Ignition.Stop(grid.Name, false); Assert.AreEqual(1, stoppingCnt); Assert.AreEqual(1, stoppedCnt); Assert.AreEqual(2, BeforeStartEvts.Count); Assert.AreEqual(2, AfterStartEvts.Count); Assert.AreEqual(2, BeforeStopEvts.Count); CheckEvent(BeforeStopEvts[0], grid, grid, 0, null); CheckEvent(BeforeStopEvts[1], grid, grid, 0, null); Assert.AreEqual(2, AfterStopEvts.Count); CheckEvent(AfterStopEvts[0], grid, grid, 0, null); CheckEvent(AfterStopEvts[1], grid, grid, 0, null); } /// <summary> /// Test with Java beans. /// </summary> [Test] public void TestWithBeans() { // 1. Test .Net start events. IIgnite grid = Start(CfgBeans); Assert.AreEqual(2, grid.GetConfiguration().LifecycleHandlers.Count); Assert.AreEqual(4, BeforeStartEvts.Count); CheckEvent(BeforeStartEvts[0], null, null, 0, null); CheckEvent(BeforeStartEvts[1], null, null, 1, "1"); CheckEvent(BeforeStartEvts[2], null, null, 0, null); CheckEvent(BeforeStartEvts[3], null, null, 0, null); Assert.AreEqual(4, AfterStartEvts.Count); CheckEvent(AfterStartEvts[0], grid, grid, 0, null); CheckEvent(AfterStartEvts[1], grid, grid, 1, "1"); CheckEvent(AfterStartEvts[2], grid, grid, 0, null); CheckEvent(AfterStartEvts[3], grid, grid, 0, null); // 2. Test Java start events. var res = grid.GetCompute().ExecuteJavaTask<IList>( "org.apache.ignite.platform.lifecycle.PlatformJavaLifecycleTask", null); Assert.AreEqual(2, res.Count); Assert.AreEqual(3, res[0]); Assert.AreEqual(3, res[1]); // 3. Test .Net stop events. Ignition.Stop(grid.Name, false); Assert.AreEqual(4, BeforeStartEvts.Count); Assert.AreEqual(4, AfterStartEvts.Count); Assert.AreEqual(4, BeforeStopEvts.Count); CheckEvent(BeforeStopEvts[0], grid, grid, 0, null); CheckEvent(BeforeStopEvts[1], grid, grid, 1, "1"); CheckEvent(BeforeStopEvts[2], grid, grid, 0, null); CheckEvent(BeforeStopEvts[3], grid, grid, 0, null); Assert.AreEqual(4, AfterStopEvts.Count); CheckEvent(AfterStopEvts[0], grid, grid, 0, null); CheckEvent(AfterStopEvts[1], grid, grid, 1, "1"); CheckEvent(AfterStopEvts[2], grid, grid, 0, null); CheckEvent(AfterStopEvts[3], grid, grid, 0, null); } /// <summary> /// Test behavior when error is thrown from lifecycle beans. /// </summary> [Test] public void TestError() { ThrowErr = true; var ex = Assert.Throws<IgniteException>(() => Start(CfgNoBeans)); Assert.AreEqual("Lifecycle exception.", ex.Message); } /// <summary> /// Start grid. /// </summary> /// <param name="cfgPath">Spring configuration path.</param> /// <returns>Grid.</returns> private static IIgnite Start(string cfgPath) { return Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SpringConfigUrl = cfgPath, LifecycleHandlers = new List<ILifecycleHandler> {new Bean(), new Bean()} }); } /// <summary> /// Check event. /// </summary> /// <param name="evt">Event.</param> /// <param name="expGrid1">Expected grid 1.</param> /// <param name="expGrid2">Expected grid 2.</param> /// <param name="expProp1">Expected property 1.</param> /// <param name="expProp2">Expected property 2.</param> private static void CheckEvent(Event evt, IIgnite expGrid1, IIgnite expGrid2, int expProp1, string expProp2) { Assert.AreEqual(expGrid1, evt.Grid1); Assert.AreEqual(expGrid2, evt.Grid2); Assert.AreEqual(expProp1, evt.Prop1); Assert.AreEqual(expProp2, evt.Prop2); } } public abstract class AbstractBean { [InstanceResource] public IIgnite Grid1; public int Property1 { get; set; } } public class Bean : AbstractBean, ILifecycleHandler { [InstanceResource] public IIgnite Grid2; public string Property2 { get; set; } /** <inheritDoc /> */ public void OnLifecycleEvent(LifecycleEventType evtType) { if (LifecycleTest.ThrowErr) throw new Exception("Lifecycle exception."); Event evt = new Event { Grid1 = Grid1, Grid2 = Grid2, Prop1 = Property1, Prop2 = Property2 }; switch (evtType) { case LifecycleEventType.BeforeNodeStart: LifecycleTest.BeforeStartEvts.Add(evt); break; case LifecycleEventType.AfterNodeStart: LifecycleTest.AfterStartEvts.Add(evt); break; case LifecycleEventType.BeforeNodeStop: LifecycleTest.BeforeStopEvts.Add(evt); break; case LifecycleEventType.AfterNodeStop: LifecycleTest.AfterStopEvts.Add(evt); break; } } } public class Event { public IIgnite Grid1; public IIgnite Grid2; public int Prop1; public string Prop2; } }
// This file contains general utilities to aid in development. // Classes here generally shouldn't be exposed publicly since // they're not particular to any library functionality. // Because the classes here are internal, it's likely this file // might be included in multiple assemblies. namespace Standard { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Threading; /// <summary> /// A static class for retail validated assertions. /// Instead of breaking into the debugger an exception is thrown. /// </summary> internal static class Verify { /// <summary> /// Ensure that the current thread's apartment state is what's expected. /// </summary> /// <param name="requiredState"> /// The required apartment state for the current thread. /// </param> /// <param name="message"> /// The message string for the exception to be thrown if the state is invalid. /// </param> /// <exception cref="InvalidOperationException"> /// Thrown if the calling thread's apartment state is not the same as the requiredState. /// </exception> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void IsApartmentState(ApartmentState requiredState, string message) { if (Thread.CurrentThread.GetApartmentState() != requiredState) { Assert.Fail(); throw new InvalidOperationException(message); } } /// <summary> /// Ensure that an argument is neither null nor empty. /// </summary> /// <param name="value">The string to validate.</param> /// <param name="name">The name of the parameter that will be presented if an exception is thrown.</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Performance", "CA1820:TestForEmptyStringsUsingStringLength")] [DebuggerStepThrough] public static void IsNeitherNullNorEmpty(string value, string name) { // catch caller errors, mixing up the parameters. Name should never be empty. Assert.IsNeitherNullNorEmpty(name); // Notice that ArgumentNullException and ArgumentException take the parameters in opposite order :P const string errorMessage = "The parameter can not be either null or empty."; if (null == value) { Assert.Fail(); throw new ArgumentNullException(name, errorMessage); } if ("" == value) { Assert.Fail(); throw new ArgumentException(errorMessage, name); } } /// <summary> /// Ensure that an argument is neither null nor does it consist only of whitespace. /// </summary> /// <param name="value">The string to validate.</param> /// <param name="name">The name of the parameter that will be presented if an exception is thrown.</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Performance", "CA1820:TestForEmptyStringsUsingStringLength")] [DebuggerStepThrough] public static void IsNeitherNullNorWhitespace(string value, string name) { // catch caller errors, mixing up the parameters. Name should never be empty. Assert.IsNeitherNullNorEmpty(name); // Notice that ArgumentNullException and ArgumentException take the parameters in opposite order :P const string errorMessage = "The parameter can not be either null or empty or consist only of white space characters."; if (null == value) { Assert.Fail(); throw new ArgumentNullException(name, errorMessage); } if ("" == value.Trim()) { Assert.Fail(); throw new ArgumentException(errorMessage, name); } } /// <summary>Verifies that an argument is not null.</summary> /// <typeparam name="T">Type of the object to validate. Must be a class.</typeparam> /// <param name="obj">The object to validate.</param> /// <param name="name">The name of the parameter that will be presented if an exception is thrown.</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void IsNotDefault<T>(T obj, string name) where T : struct { if (default(T).Equals(obj)) { Assert.Fail(); throw new ArgumentException("The parameter must not be the default value.", name); } } /// <summary>Verifies that an argument is not null.</summary> /// <typeparam name="T">Type of the object to validate. Must be a class.</typeparam> /// <param name="obj">The object to validate.</param> /// <param name="name">The name of the parameter that will be presented if an exception is thrown.</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void IsNotNull<T>(T obj, string name) where T : class { if (null == obj) { Assert.Fail(); throw new ArgumentNullException(name); } } /// <summary>Verifies that an argument is null.</summary> /// <typeparam name="T">Type of the object to validate. Must be a class.</typeparam> /// <param name="obj">The object to validate.</param> /// <param name="name">The name of the parameter that will be presented if an exception is thrown.</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void IsNull<T>(T obj, string name) where T : class { if (null != obj) { Assert.Fail(); throw new ArgumentException("The parameter must be null.", name); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void PropertyIsNotNull<T>(T obj, string name) where T : class { if (null == obj) { Assert.Fail(); throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "The property {0} cannot be null at this time.", name)); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void PropertyIsNull<T>(T obj, string name) where T : class { if (null != obj) { Assert.Fail(); throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "The property {0} must be null at this time.", name)); } } /// <summary> /// Verifies the specified statement is true. Throws an ArgumentException if it's not. /// </summary> /// <param name="statement">The statement to be verified as true.</param> /// <param name="name">Name of the parameter to include in the ArgumentException.</param> /// <param name="message">The message to include in the ArgumentException.</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void IsTrue(bool statement, string name, string message = null) { if (!statement) { Assert.Fail(); throw new ArgumentException(message ?? "", name); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void IsFalse(bool statement, string name, string message = null) { if (statement) { Assert.Fail(); throw new ArgumentException(message ?? "", name); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void AreEqual<T>(T expected, T actual, string parameterName, string message) { if (null == expected) { // Two nulls are considered equal, regardless of type semantics. if (null != actual && !actual.Equals(expected)) { Assert.Fail(); throw new ArgumentException(message, parameterName); } } else if (!expected.Equals(actual)) { Assert.Fail(); throw new ArgumentException(message, parameterName); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void AreNotEqual<T>(T notExpected, T actual, string parameterName, string message) { if (null == notExpected) { // Two nulls are considered equal, regardless of type semantics. if (null == actual || actual.Equals(notExpected)) { Assert.Fail(); throw new ArgumentException(message, parameterName); } } else if (notExpected.Equals(actual)) { Assert.Fail(); throw new ArgumentException(message, parameterName); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void UriIsAbsolute(Uri uri, string parameterName) { Verify.IsNotNull(uri, parameterName); if (!uri.IsAbsoluteUri) { Assert.Fail(); throw new ArgumentException("The URI must be absolute.", parameterName); } } /// <summary> /// Verifies that the specified value is within the expected range. The assertion fails if it isn't. /// </summary> /// <param name="lowerBoundInclusive">The lower bound inclusive value.</param> /// <param name="value">The value to verify.</param> /// <param name="upperBoundExclusive">The upper bound exclusive value.</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void BoundedInteger(int lowerBoundInclusive, int value, int upperBoundExclusive, string parameterName) { if (value < lowerBoundInclusive || value >= upperBoundExclusive) { Assert.Fail(); throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The integer value must be bounded with [{0}, {1})", lowerBoundInclusive, upperBoundExclusive), parameterName); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void BoundedDoubleInc(double lowerBoundInclusive, double value, double upperBoundInclusive, string message, string parameter) { if (value < lowerBoundInclusive || value > upperBoundInclusive) { Assert.Fail(); throw new ArgumentException(message, parameter); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void TypeSupportsInterface(Type type, Type interfaceType, string parameterName) { Assert.IsNeitherNullNorEmpty(parameterName); Verify.IsNotNull(type, "type"); Verify.IsNotNull(interfaceType, "interfaceType"); if (type.GetInterface(interfaceType.Name) == null) { Assert.Fail(); throw new ArgumentException("The type of this parameter does not support a required interface", parameterName); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] public static void FileExists(string filePath, string parameterName) { Verify.IsNeitherNullNorEmpty(filePath, parameterName); if (!File.Exists(filePath)) { Assert.Fail(); throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "No file exists at \"{0}\"", filePath), parameterName); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DebuggerStepThrough] internal static void ImplementsInterface(object parameter, Type interfaceType, string parameterName) { Assert.IsNotNull(parameter); Assert.IsNotNull(interfaceType); Assert.IsTrue(interfaceType.IsInterface); bool isImplemented = false; foreach (var ifaceType in parameter.GetType().GetInterfaces()) { if (ifaceType == interfaceType) { isImplemented = true; break; } } if (!isImplemented) { Assert.Fail(); throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The parameter must implement interface {0}.", interfaceType.ToString()), parameterName); } } } }
//------------------------------------------------------------------------------ // <copyright file="etwprovider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Globalization; using System.Runtime.InteropServices; using System.ComponentModel; using System.Threading; using System.Security; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.Eventing { public class EventProvider : IDisposable { [SecurityCritical] private UnsafeNativeMethods.EtwEnableCallback _etwCallback; // Trace Callback function private long _regHandle; // Trace Registration Handle private byte _level; // Tracing Level private long _anyKeywordMask; // Trace Enable Flags private long _allKeywordMask; // Match all keyword private int _enabled; // Enabled flag from Trace callback private Guid _providerId; // Control Guid private int _disposed; // when 1, provider has unregister [ThreadStatic] private static WriteEventErrorCode t_returnCode; // thread slot to keep last error [ThreadStatic] private static Guid t_activityId; private const int s_basicTypeAllocationBufferSize = 16; private const int s_etwMaxNumberArguments = 32; private const int s_etwAPIMaxStringCount = 8; private const int s_maxEventDataDescriptors = 128; private const int s_traceEventMaximumSize = 65482; private const int s_traceEventMaximumStringSize = 32724; [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public enum WriteEventErrorCode : int { //check mapping to runtime codes NoError = 0, NoFreeBuffers = 1, EventTooBig = 2 } [StructLayout(LayoutKind.Explicit, Size = 16)] private struct EventData { [FieldOffset(0)] internal ulong DataPointer; [FieldOffset(8)] internal uint Size; [FieldOffset(12)] internal int Reserved; } private enum ActivityControl : uint { EVENT_ACTIVITY_CTRL_GET_ID = 1, EVENT_ACTIVITY_CTRL_SET_ID = 2, EVENT_ACTIVITY_CTRL_CREATE_ID = 3, EVENT_ACTIVITY_CTRL_GET_SET_ID = 4, EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5 } /// <summary> /// Constructor for EventProvider class. /// </summary> /// <param name="providerGuid"> /// Unique GUID among all trace sources running on a system /// </param> [SecuritySafeCritical] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")] public EventProvider(Guid providerGuid) { _providerId = providerGuid; // // EtwRegister the ProviderId with ETW // EtwRegister(); } /// <summary> /// This method registers the controlGuid of this class with ETW. /// We need to be running on Vista or above. If not an /// PlatformNotSupported exception will be thrown. /// If for some reason the ETW EtwRegister call failed /// a NotSupported exception will be thrown. /// </summary> [System.Security.SecurityCritical] private unsafe void EtwRegister() { uint status; _etwCallback = new UnsafeNativeMethods.EtwEnableCallback(EtwEnableCallBack); status = UnsafeNativeMethods.EventRegister(ref _providerId, _etwCallback, null, ref _regHandle); if (status != 0) { throw new Win32Exception((int)status); } } // // implement Dispose Pattern to early deregister from ETW insted of waiting for // the finalizer to call deregistration. // Once the user is done with the provider it needs to call Close() or Dispose() // If neither are called the finalizer will unregister the provider anyway // public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecuritySafeCritical] protected virtual void Dispose(bool disposing) { // // explicit cleanup is done by calling Dispose with true from // Dispose() or Close(). The disposing argument is ignored because there // are no unmanaged resources. // The finalizer calls Dispose with false. // // // check if the object has been already disposed // if (_disposed == 1) return; if (Interlocked.Exchange(ref _disposed, 1) != 0) { // somebody is already disposing the provider return; } // // Disables Tracing in the provider, then unregister // _enabled = 0; Deregister(); } /// <summary> /// This method deregisters the controlGuid of this class with ETW. /// /// </summary> public virtual void Close() { Dispose(); } ~EventProvider() { Dispose(false); } /// <summary> /// This method un-registers from ETW. /// </summary> [System.Security.SecurityCritical] private unsafe void Deregister() { // // Unregister from ETW using the RegHandle saved from // the register call. // if (_regHandle != 0) { UnsafeNativeMethods.EventUnregister(_regHandle); _regHandle = 0; } } [System.Security.SecurityCritical] private unsafe void EtwEnableCallBack( [In] ref System.Guid sourceId, [In] int isEnabled, [In] byte setLevel, [In] long anyKeyword, [In] long allKeyword, [In] void* filterData, [In] void* callbackContext ) { _enabled = isEnabled; _level = setLevel; _anyKeywordMask = anyKeyword; _allKeywordMask = allKeyword; return; } /// <summary> /// IsEnabled, method used to test if provider is enabled /// </summary> public bool IsEnabled() { return (_enabled != 0) ? true : false; } /// <summary> /// IsEnabled, method used to test if event is enabled /// </summary> /// <param name="level"> /// Level to test /// </param> /// <param name="keywords"> /// Keyword to test /// </param> public bool IsEnabled(byte level, long keywords) { // // If not enabled at all, return false. // if (_enabled == 0) { return false; } // This also covers the case of Level == 0. if ((level <= _level) || (_level == 0)) { // // Check if Keyword is enabled // if ((keywords == 0) || (((keywords & _anyKeywordMask) != 0) && ((keywords & _allKeywordMask) == _allKeywordMask))) { return true; } } return false; } public static WriteEventErrorCode GetLastWriteEventError() { return t_returnCode; } // // Helper function to set the last error on the thread // private static void SetLastError(int error) { switch (error) { case UnsafeNativeMethods.ERROR_ARITHMETIC_OVERFLOW: case UnsafeNativeMethods.ERROR_MORE_DATA: t_returnCode = WriteEventErrorCode.EventTooBig; break; case UnsafeNativeMethods.ERROR_NOT_ENOUGH_MEMORY: t_returnCode = WriteEventErrorCode.NoFreeBuffers; break; } } [System.Security.SecurityCritical] private static unsafe string EncodeObject(ref object data, EventData* dataDescriptor, byte* dataBuffer) /*++ Routine Description: This routine is used by WriteEvent to unbox the object type and to fill the passed in ETW data descriptor. Arguments: data - argument to be decoded dataDescriptor - pointer to the descriptor to be filled dataBuffer - storage buffer for storing user data, needed because cant get the address of the object Return Value: null if the object is a basic type other than string. String otherwise --*/ { dataDescriptor->Reserved = 0; string sRet = data as string; if (sRet != null) { dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); return sRet; } if (data == null) { dataDescriptor->Size = 0; dataDescriptor->DataPointer = 0; } else if (data is IntPtr) { dataDescriptor->Size = (uint)sizeof(IntPtr); IntPtr* intptrPtr = (IntPtr*)dataBuffer; *intptrPtr = (IntPtr)data; dataDescriptor->DataPointer = (ulong)intptrPtr; } else if (data is int) { dataDescriptor->Size = (uint)sizeof(int); int* intptrPtr = (int*)dataBuffer; *intptrPtr = (int)data; dataDescriptor->DataPointer = (ulong)intptrPtr; } else if (data is long) { dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = (long)data; dataDescriptor->DataPointer = (ulong)longptr; } else if (data is uint) { dataDescriptor->Size = (uint)sizeof(uint); uint* uintptr = (uint*)dataBuffer; *uintptr = (uint)data; dataDescriptor->DataPointer = (ulong)uintptr; } else if (data is UInt64) { dataDescriptor->Size = (uint)sizeof(ulong); UInt64* ulongptr = (ulong*)dataBuffer; *ulongptr = (ulong)data; dataDescriptor->DataPointer = (ulong)ulongptr; } else if (data is char) { dataDescriptor->Size = (uint)sizeof(char); char* charptr = (char*)dataBuffer; *charptr = (char)data; dataDescriptor->DataPointer = (ulong)charptr; } else if (data is byte) { dataDescriptor->Size = (uint)sizeof(byte); byte* byteptr = (byte*)dataBuffer; *byteptr = (byte)data; dataDescriptor->DataPointer = (ulong)byteptr; } else if (data is short) { dataDescriptor->Size = (uint)sizeof(short); short* shortptr = (short*)dataBuffer; *shortptr = (short)data; dataDescriptor->DataPointer = (ulong)shortptr; } else if (data is sbyte) { dataDescriptor->Size = (uint)sizeof(sbyte); sbyte* sbyteptr = (sbyte*)dataBuffer; *sbyteptr = (sbyte)data; dataDescriptor->DataPointer = (ulong)sbyteptr; } else if (data is ushort) { dataDescriptor->Size = (uint)sizeof(ushort); ushort* ushortptr = (ushort*)dataBuffer; *ushortptr = (ushort)data; dataDescriptor->DataPointer = (ulong)ushortptr; } else if (data is float) { dataDescriptor->Size = (uint)sizeof(float); float* floatptr = (float*)dataBuffer; *floatptr = (float)data; dataDescriptor->DataPointer = (ulong)floatptr; } else if (data is double) { dataDescriptor->Size = (uint)sizeof(double); double* doubleptr = (double*)dataBuffer; *doubleptr = (double)data; dataDescriptor->DataPointer = (ulong)doubleptr; } else if (data is bool) { dataDescriptor->Size = (uint)sizeof(bool); bool* boolptr = (bool*)dataBuffer; *boolptr = (bool)data; dataDescriptor->DataPointer = (ulong)boolptr; } else if (data is Guid) { dataDescriptor->Size = (uint)sizeof(Guid); Guid* guidptr = (Guid*)dataBuffer; *guidptr = (Guid)data; dataDescriptor->DataPointer = (ulong)guidptr; } else if (data is decimal) { dataDescriptor->Size = (uint)sizeof(decimal); decimal* decimalptr = (decimal*)dataBuffer; *decimalptr = (decimal)data; dataDescriptor->DataPointer = (ulong)decimalptr; } else if (data is Boolean) { dataDescriptor->Size = (uint)sizeof(Boolean); Boolean* booleanptr = (Boolean*)dataBuffer; *booleanptr = (Boolean)data; dataDescriptor->DataPointer = (ulong)booleanptr; } else { //To our eyes, everything else is a just a string sRet = data.ToString(); dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); return sRet; } return null; } /// <summary> /// WriteMessageEvent, method to write a string with level and Keyword. /// The activity ID will be propagated only if the call stays on the same native thread as SetActivityId(). /// </summary> /// <param name="eventMessage"> /// Message to write /// </param> /// <param name="eventLevel"> /// Level to test /// </param> /// <param name="eventKeywords"> /// Keyword to test /// </param> [System.Security.SecurityCritical] public bool WriteMessageEvent(string eventMessage, byte eventLevel, long eventKeywords) { int status = 0; if (eventMessage == null) { throw new ArgumentNullException("eventMessage"); } if (IsEnabled(eventLevel, eventKeywords)) { if (eventMessage.Length > s_traceEventMaximumStringSize) { t_returnCode = WriteEventErrorCode.EventTooBig; return false; } unsafe { fixed (char* pdata = eventMessage) { status = (int)UnsafeNativeMethods.EventWriteString(_regHandle, eventLevel, eventKeywords, pdata); } if (status != 0) { SetLastError(status); return false; } } } return true; } /// <summary> /// WriteMessageEvent, method to write a string with level=0 and Keyword=0 /// The activity ID will be propagated only if the call stays on the same native thread as SetActivityId(). /// </summary> /// <param name="eventMessage"> /// Message to log /// </param> public bool WriteMessageEvent(string eventMessage) { return WriteMessageEvent(eventMessage, 0, 0); } /// <summary> /// WriteEvent method to write parameters with event schema properties /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="eventPayload"> /// </param> public bool WriteEvent(ref EventDescriptor eventDescriptor, params object[] eventPayload) { return WriteTransferEvent(ref eventDescriptor, Guid.Empty, eventPayload); } /// <summary> /// WriteEvent, method to write a string with event schema properties /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="data"> /// string to log. /// </param> [System.Security.SecurityCritical] [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public bool WriteEvent(ref EventDescriptor eventDescriptor, string data) { uint status = 0; if (data == null) { throw new ArgumentNullException("dataString"); } if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { if (data.Length > s_traceEventMaximumStringSize) { t_returnCode = WriteEventErrorCode.EventTooBig; return false; } EventData userData; userData.Size = (uint)((data.Length + 1) * 2); userData.Reserved = 0; unsafe { fixed (char* pdata = data) { Guid activityId = GetActivityId(); userData.DataPointer = (ulong)pdata; status = UnsafeNativeMethods.EventWriteTransfer(_regHandle, ref eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, null, 1, &userData); } } } if (status != 0) { SetLastError((int)status); return false; } return true; } /// <summary> /// WriteEvent, method to be used by generated code on a derived class /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="dataCount"> /// number of event descriptors /// </param> /// <param name="data"> /// pointer do the event data /// </param> [System.Security.SecurityCritical] protected bool WriteEvent(ref EventDescriptor eventDescriptor, int dataCount, IntPtr data) { uint status = 0; unsafe { Guid activityId = GetActivityId(); status = UnsafeNativeMethods.EventWriteTransfer( _regHandle, ref eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, null, (uint)dataCount, (void*)data); } if (status != 0) { SetLastError((int)status); return false; } return true; } /// <summary> /// WriteTransferEvent, method to write a parameters with event schema properties /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="relatedActivityId"> /// </param> /// <param name="eventPayload"> /// </param> [System.Security.SecurityCritical] public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid relatedActivityId, params object[] eventPayload) { uint status = 0; if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { Guid activityId = GetActivityId(); unsafe { int argCount = 0; EventData* userDataPtr = null; if ((eventPayload != null) && (eventPayload.Length != 0)) { argCount = eventPayload.Length; if (argCount > s_etwMaxNumberArguments) { // //too many arguments to log // throw new ArgumentOutOfRangeException("eventPayload", string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_MaxArgExceeded, s_etwMaxNumberArguments)); } uint totalEventSize = 0; int index; int stringIndex = 0; int[] stringPosition = new int[s_etwAPIMaxStringCount]; //used to keep the position of strings in the eventPayload parameter string[] dataString = new string[s_etwAPIMaxStringCount]; // string arrays from the eventPayload parameter EventData* userData = stackalloc EventData[argCount]; // allocation for the data descriptors userDataPtr = (EventData*)userData; byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * argCount]; // 16 byte for unboxing non-string argument byte* currentBuffer = dataBuffer; // // The loop below goes through all the arguments and fills in the data // descriptors. For strings save the location in the dataString array. // Calculates the total size of the event by adding the data descriptor // size value set in EncodeObjec method. // for (index = 0; index < eventPayload.Length; index++) { string isString; isString = EncodeObject(ref eventPayload[index], userDataPtr, currentBuffer); currentBuffer += s_basicTypeAllocationBufferSize; totalEventSize += userDataPtr->Size; userDataPtr++; if (isString != null) { if (stringIndex < s_etwAPIMaxStringCount) { dataString[stringIndex] = isString; stringPosition[stringIndex] = index; stringIndex++; } else { throw new ArgumentOutOfRangeException("eventPayload", string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_MaxStringsExceeded, s_etwAPIMaxStringCount)); } } } if (totalEventSize > s_traceEventMaximumSize) { t_returnCode = WriteEventErrorCode.EventTooBig; return false; } fixed (char* v0 = dataString[0], v1 = dataString[1], v2 = dataString[2], v3 = dataString[3], v4 = dataString[4], v5 = dataString[5], v6 = dataString[6], v7 = dataString[7]) { userDataPtr = (EventData*)userData; if (dataString[0] != null) { userDataPtr[stringPosition[0]].DataPointer = (ulong)v0; } if (dataString[1] != null) { userDataPtr[stringPosition[1]].DataPointer = (ulong)v1; } if (dataString[2] != null) { userDataPtr[stringPosition[2]].DataPointer = (ulong)v2; } if (dataString[3] != null) { userDataPtr[stringPosition[3]].DataPointer = (ulong)v3; } if (dataString[4] != null) { userDataPtr[stringPosition[4]].DataPointer = (ulong)v4; } if (dataString[5] != null) { userDataPtr[stringPosition[5]].DataPointer = (ulong)v5; } if (dataString[6] != null) { userDataPtr[stringPosition[6]].DataPointer = (ulong)v6; } if (dataString[7] != null) { userDataPtr[stringPosition[7]].DataPointer = (ulong)v7; } } } status = UnsafeNativeMethods.EventWriteTransfer(_regHandle, ref eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, (relatedActivityId == Guid.Empty) ? null : &relatedActivityId, (uint)argCount, userDataPtr); } } if (status != 0) { SetLastError((int)status); return false; } return true; } [System.Security.SecurityCritical] protected bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid relatedActivityId, int dataCount, IntPtr data) { uint status = 0; Guid activityId = GetActivityId(); unsafe { status = UnsafeNativeMethods.EventWriteTransfer( _regHandle, ref eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, &relatedActivityId, (uint)dataCount, (void*)data); } if (status != 0) { SetLastError((int)status); return false; } return true; } [System.Security.SecurityCritical] private static Guid GetActivityId() { return t_activityId; } [System.Security.SecurityCritical] public static void SetActivityId(ref Guid id) { t_activityId = id; UnsafeNativeMethods.EventActivityIdControl((int)ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID, ref id); } [System.Security.SecurityCritical] public static Guid CreateActivityId() { Guid newId = new Guid(); UnsafeNativeMethods.EventActivityIdControl((int)ActivityControl.EVENT_ACTIVITY_CTRL_CREATE_ID, ref newId); return newId; } } }
//To enable RUNUO 2.0 compatibility, simply comment out the next line (#define); //#define RUNUO_1 using System; using System.Security; using System.Security.Cryptography; using System.Net; using System.Collections; using System.Text; using System.IO; using Server; namespace Server.ServerSeasons { public static class SeasonTracker { private static int LoadedCount = 0; private static int SavedCount = 0; private static MD5CryptoServiceProvider m_MD5HashProvider; private static byte[] m_MD5HashBuffer; public static string MD5Hash(string plainText) { if (m_MD5HashProvider == null) m_MD5HashProvider = new MD5CryptoServiceProvider(); if (m_MD5HashBuffer == null) m_MD5HashBuffer = new byte[256]; int length = Encoding.ASCII.GetBytes(plainText, 0, plainText.Length > 256 ? 256 : plainText.Length, m_MD5HashBuffer, 0); byte[] hashed = m_MD5HashProvider.ComputeHash(m_MD5HashBuffer, 0, length); return BitConverter.ToString(hashed); } /// <summary> /// Configuration Events /// </summary> public static void Configure() { EventSink.ServerStarted += new ServerStartedEventHandler(OnLoad); EventSink.WorldSave += new WorldSaveEventHandler(OnSave); } /// <summary> /// Serialize /// </summary> /// <param name="e"></param> private static void OnSave(WorldSaveEventArgs e) { string CurRegion = ""; try { if (Directory.Exists("Saves/Regions/Seasons/")) Directory.Delete("Saves/Regions/Seasons/", true); foreach (Region r in Region.Regions) { if (r != null) { if (!(r is ISeasons)) continue; if (r.GetType().IsAbstract || !r.GetType().IsSubclassOf(typeof(Region))) continue; CurRegion = r.Name; if (!Directory.Exists("Saves/Regions/Seasons/" + r.Map + "/")) Directory.CreateDirectory("Saves/Regions/Seasons/" + r.Map + "/"); string name = "(" + r.Name + ")"; string nameTmp = ""; #if(RUNUO_1) if( r.Coords != null ) { for( int i = 0; i < r.Coords.Count; ++i ) { object obj = r.Coords[i]; if( obj is Rectangle3D ) { Rectangle3D r3d = ( Rectangle3D )obj; nameTmp += r3d.ToString( ); } else if( obj is Rectangle2D ) { Rectangle2D r2d = ( Rectangle2D )obj; nameTmp += r2d.ToString( ); } } name += "(" + MD5Hash( nameTmp ) + ")"; } if( name == null || name == "" || name.Length == 0 ) { name += "(" + r.UId + ")"; } #else if (r.Area != null) { for (int i = 0; i < r.Area.Length; ++i) { Rectangle3D r3d = r.Area[i]; nameTmp += r3d.ToString(); } name += "(" + MD5Hash(nameTmp) + ")"; } #endif try { GenericWriter writer = new BinaryFileWriter(Path.Combine("Saves/Regions/Seasons/" + r.Map + "/", name + ".bin"), true); Season season = ((ISeasons)r).Season; writer.Write((int)season); SavedCount++; writer.Close(); } catch (Exception ex1) { Console.WriteLine("[SeasonTracker] Serialize: ({0})", CurRegion); Console.WriteLine(ex1.ToString()); } } } } catch (Exception ex2) { Console.WriteLine("[SeasonTracker] OnSave: ({0})", CurRegion); Console.WriteLine(ex2.ToString()); } Console.WriteLine("[SeasonTracker] Saved {0} Region Seasons!", SavedCount); SavedCount = 0; } /// <summary> /// Deserialize /// </summary> private static void OnLoad() { string CurRegion = ""; try { foreach (Region r in Region.Regions) { if (r != null) { if (!(r is ISeasons)) continue; if (r.GetType().IsAbstract || !r.GetType().IsSubclassOf(typeof(Region))) continue; CurRegion = r.Name; if (!Directory.Exists("Saves/Regions/Seasons/" + r.Map + "/")) Directory.CreateDirectory("Saves/Regions/Seasons/" + r.Map + "/"); string name = "(" + r.Name + ")"; string nameTmp = ""; #if(RUNUO_1) if (r.Coords != null) { for (int i = 0; i < r.Coords.Count; ++i) { object obj = r.Coords[i]; if (obj is Rectangle3D) { Rectangle3D r3d = (Rectangle3D)obj; nameTmp += r3d.ToString(); } else if (obj is Rectangle2D) { Rectangle2D r2d = (Rectangle2D)obj; nameTmp += r2d.ToString(); } } name += "(" + MD5Hash(nameTmp) + ")"; } if (name == null || name == "" || name.Length == 0) { name += "(" + r.UId + ")"; } #else if (r.Area != null) { for (int i = 0; i < r.Area.Length; ++i) { Rectangle3D r3d = r.Area[i]; nameTmp += r3d.ToString(); } name += "(" + MD5Hash(nameTmp) + ")"; } #endif if (!File.Exists(Path.Combine("Saves/Regions/Seasons/" + r.Map + "/", name + ".bin"))) return; using (FileStream bin = new FileStream(Path.Combine("Saves/Regions/Seasons/" + r.Map + "/", name + ".bin"), FileMode.Open, FileAccess.Read, FileShare.Read)) { try { GenericReader reader = new BinaryFileReader(new BinaryReader(bin)); Season season = (Season)reader.ReadInt(); ((ISeasons)r).Season = season; LoadedCount++; } catch (Exception ex1) { Console.WriteLine("[SeasonTracker] Deserialize: ({0})", CurRegion); Console.WriteLine(ex1.ToString()); } } } } } catch (Exception ex2) { Console.WriteLine("[SeasonTracker] OnLoad: ({0})", CurRegion); Console.WriteLine(ex2.ToString()); } Console.WriteLine("[SeasonTracker] Tracking {0} Regions' Seasons...", LoadedCount); LoadedCount = 0; } } }
#region References using System; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestR.Desktop; using TestR.Web; using TestR.Web.Browsers; using TestR.Web.Elements; #endregion namespace TestR.Tests.Web { [TestClass] public class BrowserTests { #region Constructors static BrowserTests() { DefaultTimeout = TimeSpan.FromMilliseconds(2000); TestSite = "https://testr.local"; } #endregion #region Properties public static bool CleanupBrowsers { get; set; } public static TimeSpan DefaultTimeout { get; set; } public static string TestSite { get; } #endregion #region Methods [TestMethod] public void AngularInputTrigger() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Angular.html"); var email = browser.First<TextInput>("email"); email.SendInput("user", true); var expected = "ng-valid-parse ng-untouched ng-scope ng-invalid ng-not-empty ng-dirty ng-invalid-email ng-valid-required".Split(' '); var actual = email.GetAttributeValue("class", true).Split(' '); TestHelper.AreEqual("user", email.Text); TestHelper.AreEqual(expected, actual); email.SendInput("@domain.com"); expected = "ng-valid-parse ng-untouched ng-scope ng-not-empty ng-dirty ng-valid-required ng-valid ng-valid-email".Split(' '); actual = email.GetAttributeValue("class", true).Split(' '); TestHelper.AreEqual("user@domain.com", email.Text); TestHelper.AreEqual(expected, actual); }); } [TestMethod] public void AngularNewElementCount() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Angular.html"); var span = browser.First<Span>("items-length"); var button = browser.First<Button>("addItem"); button.Click(); var count = 0; var result = span.Wait(x => { count++; var text = ((Span) x).Text; return text == "1"; }); Assert.IsTrue(count > 1, "We should have tested text more than once."); Assert.IsTrue(result, "The count never incremented to 1."); }); } [TestMethod] public void AngularNewElements() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Angular.html"); var elementCount = browser.Descendants().Count(); var button = browser.First<Button>("addItem"); button.Click(); var newItem = browser.FirstOrDefault("items-0"); Assert.IsNotNull(newItem, "Never found the new item."); Assert.AreEqual(elementCount + 1, browser.Descendants().Count()); elementCount = browser.Descendants().Count(); button.Click(); newItem = browser.FirstOrDefault("items-1"); Assert.IsNotNull(newItem, "Never found the new item."); Assert.AreEqual(elementCount + 1, browser.Descendants().Count()); }); } [TestMethod] public void AngularSetTextInputs() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Angular.html#!/form"); Assert.AreEqual("true", browser.First<Button>("saveButton").Disabled); browser.First<TextInput>("pageTitle").Text = "Hello World"; Assert.AreEqual("Hello World", browser.First<TextInput>("pageTitle").Text); browser.First<TextArea>("pageText").Text = "The quick brown fox jumps over the lazy dog's back."; Assert.AreEqual("The quick brown fox jumps over the lazy dog's back.", browser.First<TextArea>("pageText").Text); Assert.AreEqual("false", browser.First<Button>("saveButton").Disabled); }); } [TestMethod] public void AngularSwitchPageByNavigateTo() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Angular.html#!/"); Assert.AreEqual(TestSite + "/Angular.html#!/", browser.Uri); Assert.IsTrue(browser.Contains("addItem")); Assert.IsTrue(browser.Contains("anotherPageLink")); browser.NavigateTo(TestSite + "/Angular.html#!/anotherPage"); Assert.AreEqual(TestSite + "/Angular.html#!/anotherPage", browser.Uri); Assert.IsFalse(browser.Contains("addItem")); Assert.IsTrue(browser.Contains("pageLink")); browser.NavigateTo(TestSite + "/Angular.html#!/"); Assert.AreEqual(TestSite + "/Angular.html#!/", browser.Uri); Assert.IsTrue(browser.Contains("addItem")); Assert.IsTrue(browser.Contains("anotherPageLink")); }); } [ClassCleanup] public static void ClassCleanup() { if (CleanupBrowsers) { Browser.CloseBrowsers(); } } [ClassInitialize] public static void ClassInitialize(TestContext context) { if (CleanupBrowsers) { Browser.CloseBrowsers(); } } [TestMethod] public void ClickButton() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); Assert.AreEqual("Text Area's \"Quotes\" Data", browser.First<TextArea>("textarea").Text); browser.First("button").Click(); Assert.AreEqual("button", browser.First<TextArea>("textarea").Text); browser.NavigateTo(TestSite + "/vue.html"); Assert.AreEqual("", browser.First<Division>("error").Text); browser.First<Button>("click").Click(); Assert.AreEqual("click", browser.First<Division>("error").Text); }); } [TestMethod] public void ClickButtonByName() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); browser.First(x => x.Name == "buttonByName").Click(); var textArea = browser.First<TextArea>("textarea"); Assert.AreEqual("buttonByName", textArea.Text); }); } [TestMethod] public void ClickCheckbox() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); foreach (var element in browser.Descendants<CheckBox>()) { element.Click(); Assert.IsTrue(element.Checked); element.Click(); Assert.IsFalse(element.Checked); } }); } [TestMethod] public void ClickInputButton() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); browser.First<Button>("inputButton").Click(); var textArea = browser.First<TextArea>("textarea"); Assert.AreEqual("inputButton", textArea.Text); }); } [TestMethod] public void ClickLink() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); browser.First("link").Click(); var textArea = browser.First<TextArea>("textarea"); Assert.AreEqual("link", textArea.Text); }); } [TestMethod] public void ClickRadioButton() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); Assert.IsFalse(browser.Descendants<RadioButton>().Any(x => x.Checked)); foreach (var element in browser.Descendants<RadioButton>()) { element.Click(); Assert.IsTrue(element.Checked); Assert.IsTrue(browser.Descendants<RadioButton>().Where(x => x.Id == element.Id).All(x => x.Checked)); Assert.IsTrue(browser.Descendants<RadioButton>().Where(x => x.Id != element.Id).All(x => !x.Checked)); } }); } [TestMethod] public void Close() { ForAllBrowsers(browser => { Assert.IsFalse(browser.IsClosed, "The browser should not be closed."); browser.Close(); Assert.IsTrue(browser.IsClosed, "The browser should be closed but was not."); }); } [TestMethod] public void DeepDescendants() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/relationships.html"); Assert.AreEqual(4043, browser.Descendants().Count()); foreach (var e in browser.Descendants()) { Console.WriteLine(e.Id); } }); } [TestMethod] public void DetectAngularJavaScriptLibrary() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Angular.html#!/"); Assert.IsTrue(browser.JavascriptLibraries.Contains(JavaScriptLibrary.Angular)); }); } [TestMethod] public void DetectBootstrap2JavaScriptLibrary() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Bootstrap2.html"); Assert.IsTrue(browser.JavascriptLibraries.Contains(JavaScriptLibrary.Bootstrap2)); }); } [TestMethod] public void DetectBootstrap3JavaScriptLibrary() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Bootstrap3.html"); Assert.IsTrue(browser.JavascriptLibraries.Contains(JavaScriptLibrary.Bootstrap3)); }); } [TestMethod] public void DetectJQueryJavaScriptLibrary() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/JQuery.html"); Assert.IsTrue(browser.JavascriptLibraries.Contains(JavaScriptLibrary.JQuery)); }); } [TestMethod] public void DetectMomentJavaScriptLibrary() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Moment.html"); Assert.IsTrue(browser.JavascriptLibraries.Contains(JavaScriptLibrary.Moment)); }); } [TestMethod] public void DetectNoJavaScriptLibrary() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Inputs.html"); Assert.AreEqual(0, browser.JavascriptLibraries.Count()); }); } [TestMethod] public void DetectVueJavaScriptLibrary() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Vue.html"); Assert.IsTrue(browser.JavascriptLibraries.Contains(JavaScriptLibrary.Vue)); }); } [TestMethod] public void ElementChildren() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/relationships.html"); Assert.AreEqual(4043, browser.Descendants().Count()); var children = browser.First("parent1div").Children; var expected = new[] { "child1div", "child2span", "child3br", "child4input" }; Assert.AreEqual(4, children.Count); TestHelper.AreEqual(expected.ToList(), children.Select(x => x.Id).ToList()); }); } [TestMethod] public void ElementParent() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/relationships.html"); var element = browser.First("child1div").Parent; Assert.AreEqual("parent1div", element.Id); }); } [TestMethod] public void Enabled() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); Assert.AreEqual(true, browser.First<Button>("button").Enabled); Assert.AreEqual(false, browser.First<Button>("button2").Enabled); }); } [TestMethod] public void EnumerateDivisions() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var elements = browser.Descendants<Division>().ToList(); Assert.AreEqual(2, elements.Count()); foreach (var division in elements) { division.Highlight(true); } }); } [TestMethod] public void EnumerateHeaders() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var elements = browser.Descendants<Header>().ToList(); Assert.AreEqual(6, elements.Count()); foreach (var header in elements) { header.Text = "Header!"; } }); } [TestMethod] public void FilterElementByTextElements() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); var inputs = browser.Descendants<TextInput>().ToList(); // Old IE treats input types of Date, Month, Week as "Text" which increases input count. //var expected = browser.BrowserType == BrowserType.InternetExplorer ? 11 : 8; Assert.AreEqual(8, inputs.Count); }); } [TestMethod] public void FindElementByClass() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var elements = browser.Descendants() .Cast<WebElement>() .Where(x => x.Class.Contains("red")); Assert.AreEqual(1, elements.Count()); }); } [TestMethod] public void FindElementByClassByValueAccessor() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var elements = browser.Descendants() .Cast<WebElement>().Where(x => x["class"].Contains("red")); Assert.AreEqual(1, elements.Count()); }); } [TestMethod] public void FindElementByClassProperty() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var elements = browser.Descendants<Link>().Where(x => x.Class == "bold"); Assert.AreEqual(1, elements.Count()); }); } [TestMethod] public void FindElementByDataAttribute() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var link = browser.Descendants(x => x["data-test"] == "testAnchor").FirstOrDefault(); Assert.IsNotNull(link, "Failed to find the link by data attribute."); Assert.AreEqual(link.Id, "a1"); }); } [TestMethod] public void FindHeadersByText() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var elements = browser.Descendants<Header>().Where(x => x.Text.Contains("Header")); Assert.AreEqual(6, elements.Count()); }); } [TestMethod] public void FindSpanElementByText() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var elements = browser.Descendants<Span>(x => x.Text == "SPAN with ID of 1"); Assert.AreEqual(1, elements.Count()); }); } [TestMethod] public void FindTextInputsByText() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var elements = browser.Descendants<TextInput>().Where(x => x.Text == "Hello World"); Assert.AreEqual(1, elements.Count()); }); } [TestMethod] public void Focus() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); var expected = browser.Descendants<TextInput>().Last(); expected.Focus(); Assert.IsNotNull(browser.ActiveElement, "There should be an active element."); Assert.AreEqual(expected.Id, browser.ActiveElement.Id); }); } [TestMethod] public void FocusEvent() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var expected = browser.First<TextInput>("text"); expected.Focus(); Assert.IsNotNull(browser.ActiveElement, "There should be an active element."); Assert.AreEqual(expected.Id, browser.ActiveElement.Id); Assert.AreEqual("focused", expected.Text); }); } [TestMethod] public void ForAllBrowserExceptions() { Browser.CloseBrowsers(); try { ForAllBrowsers(x => throw new Exception(x.BrowserType.ToString())); } catch (AggregateException ex) { Assert.AreEqual(2, ex.InnerExceptions.Count); Assert.AreEqual("Test failed using Chrome.", ex.InnerExceptions[0].Message); Assert.AreEqual("Test failed using Edge.", ex.InnerExceptions[1].Message); //Assert.AreEqual("Test failed using Firefox.", ex.InnerExceptions[2].Message); } catch (Exception ex) { Assert.Fail("Invalid exception: " + ex.GetType().FullName); } } [TestMethod] public void ForAllBrowserShouldTimeoutFast() { try { ForAllBrowsers(x => Thread.Sleep(5000), timeout: 1000); } catch (Exception ex) { Assert.AreEqual("ForAllBrowsers has timed out.", ex.Message); } } [TestMethod] public void FormWithSubInputsWithNamesOfFormAttributeNames() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/forms.html"); Assert.AreEqual(10, browser.Descendants().Count()); Assert.AreEqual(10, browser.Descendants<WebElement>().Count()); var form = browser.First<Form>("form"); Assert.AreEqual("form", form.Id); Assert.AreEqual("form", form.Name); Assert.AreEqual("form", form.TagName); Assert.AreEqual("form", form.GetAttributeValue("id", true)); var input = browser.First<TextInput>("id"); Assert.AreEqual("id", input.Id); Assert.AreEqual("id", input.Name); Assert.AreEqual("input", input.TagName); Assert.AreEqual("id", input.GetAttributeValue("id", true)); input = browser.First<TextInput>("name"); Assert.AreEqual("name", input.Id); Assert.AreEqual("name", input.Name); Assert.AreEqual("input", input.TagName); Assert.AreEqual("name", input.GetAttributeValue("id", true)); }); } [TestMethod] public void FormWithSubInputsWithNamesOfFormAttributeNamesButMainFormHasNoId() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/forms2.html"); Assert.AreEqual(10, browser.Descendants().Count()); Assert.AreEqual(10, browser.Descendants<WebElement>().Count()); var form = browser.First<Form>("form"); Assert.AreEqual("form", form.Name); Assert.AreEqual("form", form.TagName); var input = browser.First<TextInput>("id"); Assert.AreEqual("id", input.Id); Assert.AreEqual("id", input.Name); Assert.AreEqual("input", input.TagName); Assert.AreEqual("id", input.GetAttributeValue("id", true)); input = browser.First<TextInput>("name"); Assert.AreEqual("name", input.Id); Assert.AreEqual("name", input.Name); Assert.AreEqual("input", input.TagName); Assert.AreEqual("name", input.GetAttributeValue("id", true)); }); } [TestMethod] public void GetAndSetHtml() { ForAllBrowsers(browser => { var guid = Guid.NewGuid().ToString(); browser.NavigateTo(TestSite + "/main.html"); var button = browser.FirstOrDefault<Button>("button"); Assert.IsNotNull(button); var actual = browser.GetHtml(); Assert.IsFalse(actual.Contains(guid)); var expected = $"<html><head><link href=\"https://testr.local/Content/testr.css\" rel=\"stylesheet\"></head><body>{guid}</body></html>"; browser.SetHtml(expected); actual = browser.GetHtml(); actual.Dump(); Assert.AreEqual(expected, actual); }); } [TestMethod] public void GetAndSetHtmlForElement() { ForAllBrowsers(browser => { var guid = Guid.NewGuid().ToString(); var input = $"Special characters like \", ', \0, \", \n, \r, \r\n, <, >, should not break html... however &amp; must be already encoded! \n{guid}"; browser.NavigateTo(TestSite + "/main.html"); var body = browser.FirstOrDefault<Body>(); Assert.IsNotNull(body); var original = body.GetHtml(); body.SetHtml(input); var actual = body.GetHtml(); Assert.AreNotEqual(original, actual); Assert.IsTrue(actual.Contains(guid)); }); } [TestMethod] public void GetAndSetHtmlOfCodeBlock() { ForAllBrowsers(browser => { var guid = Guid.NewGuid().ToString(); browser.NavigateTo(TestSite + "/main.html"); var button = browser.FirstOrDefault<Button>("button"); Assert.IsNotNull(button); var actual = browser.GetHtml(); Assert.IsFalse(actual.Contains(guid)); var expected = $"<html>\r\n<head>\r\n\t<link href=\"https://testr.local/Content/testr.css\" rel=\"stylesheet\">\r\n</head>\r\n<body>\r\n\t{guid}\r\n<pre><code>\r\naoeu\r\nblah\r\n\r\n\'testing\'\r\n</code></pre>\r\n</body>\r\n</html>"; browser.SetHtml(expected); actual = browser.GetHtml(); Assert.IsTrue(actual.Contains(guid)); }); } [TestMethod] public void GetAndSetHtmlOnAboutBlankPage() { ForAllBrowsers(browser => { browser.NavigateTo("about:blank"); var actual = browser.GetHtml(); Assert.IsTrue(actual == "<html id=\"testR-1\"><head id=\"testR-2\"></head><body id=\"testR-3\"></body></html>" || actual == ""); var guid = Guid.NewGuid().ToString(); var expected = $"<html><head><link href=\"https://testr.local/Content/testr.css\" rel=\"stylesheet\"></head><body>{guid}</body></html>"; browser.SetHtml(expected); Assert.AreEqual(expected, browser.GetHtml()); guid = Guid.NewGuid().ToString(); expected = $"<html><head></head><body>{guid}</body></html>"; browser.SetHtml(expected); Assert.AreEqual(expected, browser.GetHtml()); }); } [TestMethod] public void GetAndSetStyle() { ForAllBrowsers(browser => //ForEachBrowser(browser => { browser.NavigateTo(TestSite + "/invalid.html"); var span1 = browser.FirstOrDefault<WebElement>("span1"); Assert.IsNotNull(span1); Assert.AreEqual("", span1.Style); Assert.AreEqual("", span1.GetAttributeValue("Style", true)); span1.Style = "color: red"; var actual = span1.GetStyleAttributeValue("color", true); Assert.AreEqual("red", actual); Assert.IsTrue(span1.GetAttributeValue("Style", true).Contains("color: red")); var input1 = browser.FirstOrDefault<WebElement>("input1"); Assert.IsNotNull(input1); Assert.AreEqual("", input1.Style); Assert.AreEqual("", input1.GetAttributeValue("Style", true)); input1.Style = "color: red"; actual = input1.GetStyleAttributeValue("color", true); Assert.AreEqual("red", actual); Assert.IsTrue(input1.GetAttributeValue("Style", true).Contains("color: red")); }); } [TestMethod] public void GetElementByNameIndex() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var actual = browser.First(x => x.Name == "inputName").Name; Assert.AreEqual("inputName", actual); }); } [TestMethod] public void GetNextSibling() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Angular.html#!/"); var items = browser.First<Division>("items"); Assert.AreEqual(0, items.Children.Count); browser.First<Button>("addItem").Click().Click(); var result = items.Wait(x => x.Refresh().Children.Count >= 2); Assert.IsTrue(result, "Should have had two items."); Assert.AreEqual(2, items.Children.Count); var item0 = items.First("items-0"); var item1 = item0.GetNextSibling(); Assert.IsNotNull(item1, "Failed to find sibling."); Assert.AreEqual("items-1", item1.Id); }); } [TestMethod] public void GetPreviousSibling() { ForEachBrowser(browser => { browser.NavigateTo(TestSite + "/Angular.html#!/"); var items = browser.First<Division>("items"); Assert.AreEqual(0, items.Children.Count); browser.First<Button>("addItem").Click().Click(); var result = items.Wait(x => x.Refresh().Children.Count >= 2); Assert.IsTrue(result, "Should have had two items."); Assert.AreEqual(2, items.Children.Count); var item1 = items.First("items-1"); var item0 = item1.GetPreviousSibling(); Assert.AreEqual("items-0", item0.Id); }); } [TestMethod] public void HighlightAllElements() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var elements = browser.OfType<WebElement>(); foreach (var element in elements) { var originalColor = element.GetStyleAttributeValue("background-color"); element.Highlight(true); Assert.AreEqual("yellow", element.GetStyleAttributeValue("background-color")); element.Highlight(false); Assert.AreEqual(originalColor, element.GetStyleAttributeValue("background-color")); } }); } [TestMethod] public void HighlightElement() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); var inputElements = browser.Descendants<WebElement>(t => t.TagName == "input").ToList(); foreach (var element in inputElements) { var originalColor = element.GetStyleAttributeValue("background-color"); element.Highlight(true); Assert.AreEqual("yellow", element.GetStyleAttributeValue("background-color")); element.Highlight(false); Assert.AreEqual(originalColor, element.GetStyleAttributeValue("background-color")); } }); } [TestMethod] public void IframesShouldHaveAccess() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/iframe.html"); browser.First<TextInput>("id").SendInput("hello", true); var frame = browser.First("frame"); var email = frame.First<TextInput>("email"); email.SendInput("world", true); Assert.AreEqual("world", email.Text); Assert.AreEqual("world", email.GetAttributeValue("value")); }); } [TestMethod] public void InternetOfBing() { ForAllBrowsers(browser => { browser.NavigateTo("https://www.bing.com"); browser.Descendants().ToList().Count.Dump(); browser.FirstOrDefault("sb_form_q").SendInput("Bobby Cannon Epic Coders"); browser.FirstOrDefault("sb_form_go").Click(); browser.WaitForComplete(); }); } [TestMethod] public void Location() { ForEachBrowser(browser => { browser.NavigateTo("about:blank"); browser.NavigateTo(TestSite + "/main.html"); var button = browser.First("button"); button.Location.Dump(); button.LeftClick(); var result = Utility.Wait(() => "button".Equals(browser.First<TextArea>("textarea").Text), 5000, 100); Assert.IsTrue(result, "The text should have been button but was not."); }); } [TestMethod] public void MiddleClickButton() { ForEachBrowser(browser => { browser.NavigateTo(TestSite + "/main.html"); var button = browser.First("button"); button.MiddleClick(); browser.WaitForComplete(150); // Middle click may not click but does set focus. Assert.IsTrue(button.Focused); Input.Mouse.LeftButtonClick(button.Location); }); } [TestMethod] public void NavigateThenRunJavascript() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var actual = browser.ExecuteScript("TestR.runScript('document.toString()')"); Assert.IsTrue(actual.Contains("undefined")); actual = browser.ExecuteScript("document.title"); Assert.AreEqual("Index", actual); }); } [TestMethod] public void NavigateTo() { ForAllBrowsers(browser => { var expected = TestSite + "/main.html"; browser.NavigateTo(expected); Assert.AreEqual(expected, browser.Uri.ToLower()); }); } [TestMethod] public void NavigateToFromHttpToHttps() { ForAllBrowsers(browser => { var expected = TestSite.Replace("https://", "http://") + "/main.html"; Assert.IsFalse(expected.StartsWith("https://")); browser.NavigateTo(expected); Assert.IsTrue(browser.Uri.StartsWith("https://")); Assert.AreEqual($"{TestSite}/main.html", browser.Uri.ToLower()); }); } [TestMethod] public void NavigateToFromHttpToHttpsWhenAlreadyOnExpectedUri() { ForAllBrowsers(browser => { browser.NavigateTo($"{TestSite}/main.html"); var expected = TestSite.Replace("https://", "http://") + "/main.html"; Assert.IsFalse(expected.StartsWith("https://")); browser.NavigateTo(expected); Assert.IsTrue(browser.Uri.StartsWith("https://")); Assert.AreEqual($"{TestSite}/main.html", browser.Uri.ToLower()); }); } [TestMethod] public void NavigateToSameUri() { ForAllBrowsers(browser => { var expected = TestSite + "/main.html"; browser.NavigateTo(expected); browser.NavigateTo(expected); browser.NavigateTo(expected); Assert.AreEqual(expected, browser.Uri.ToLower()); }); } [TestMethod] public void NavigateToSameUriWithEndingForwardSlash() { ForAllBrowsers(browser => { var expected = TestSite + "/"; browser.NavigateTo(expected); browser.NavigateTo(expected); browser.NavigateTo(expected); Assert.AreEqual($"{expected}", browser.Uri.ToLower()); }); } [TestMethod] public void NavigateToWithDifferentFinalUri() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Angular.html"); Assert.AreEqual(TestSite + "/Angular.html#!/", browser.Uri); }); } [TestMethod] public void RawHtml() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Jquery.html"); var test = browser.RawHtml.Trim(); Assert.IsTrue(test.StartsWith("<html")); Assert.IsTrue(test.EndsWith("</html>")); }); } [TestMethod] public void RedirectByLink() { ForAllBrowsers(browser => { var expected = TestSite + "/main.html"; browser.NavigateTo(expected); Assert.AreEqual(expected, browser.Uri.ToLower()); // Redirect by the link. browser.First<Link>("redirectLink").Click(); browser.WaitForNavigation(TestSite + "/Inputs.html"); expected = TestSite + "/inputs.html"; Assert.AreEqual(expected, browser.Uri.ToLower()); }); } [TestMethod] public void RedirectByLinkWithoutProvidingExpectedUri() { ForAllBrowsers(browser => { var expected = TestSite + "/main.html"; browser.NavigateTo(expected); Assert.AreEqual(expected, browser.Uri.ToLower()); // Redirect by the link. browser.First<Link>("redirectLink").Click(); browser.WaitForNavigation(); expected = TestSite + "/inputs.html"; Assert.AreEqual(expected, browser.Uri.ToLower()); }); } [TestMethod] public void RedirectByScript() { ForAllBrowsers(browser => { var expected = TestSite + "/main.html"; browser.NavigateTo(expected); Assert.AreEqual(expected, browser.Uri.ToLower()); Assert.IsNotNull(browser.First("link"), "Failed to find the link element."); // Redirect by a script. browser.ExecuteScript("window.location.href = 'inputs.html'"); browser.WaitForNavigation(TestSite + "/inputs.html"); expected = TestSite + "/inputs.html"; Assert.AreEqual(expected, browser.Uri.ToLower()); }); } [TestMethod] public void RedirectByScriptWithoutProvidedExpectedUri() { ForAllBrowsers(browser => { var expected = TestSite + "/main.html"; browser.NavigateTo(expected); Assert.AreEqual(expected, browser.Uri.ToLower()); Assert.IsNotNull(browser.First("link"), "Failed to find the link element."); // Redirect by a script. browser.ExecuteScript("setTimeout(function() {window.location.href = 'inputs.html'}, 1000)"); browser.WaitForNavigation(); expected = TestSite + "/inputs.html"; Assert.AreEqual(expected, browser.Uri.ToLower()); }); } [TestMethod] public void Refresh() { ForAllBrowsers(browser => { var expected = TestSite + "/angular.html"; browser.NavigateTo(expected); Assert.AreEqual(33, browser.Descendants().Count()); browser.First("addItem").Click(); Assert.AreEqual(33, browser.Descendants().Count()); var result = browser.Wait(x => { x.Refresh(); return x.Descendants().Count() == 34; }); Assert.IsTrue(result, "The count never incremented."); }); } [TestMethod] public void RightClickButton() { ForEachBrowser(browser => { browser.NavigateTo(TestSite + "/main.html"); var button = browser.First("button"); button.RightClick(); var actual = browser.First<TextArea>("textarea").Text; Assert.AreEqual("Text Area's \"Quotes\" Data", actual); var location = button.Location; button.Focus(); location.Dump(); Input.Mouse.MoveTo(location.X + 60, location.Y + 22); Thread.Sleep(1000); // had to add "pane" as a valid option because FF uses a custom control now. var result = Utility.Wait(() => DesktopElement.FromCursor()?.TypeName.Equals("menu item", StringComparison.OrdinalIgnoreCase) == true || DesktopElement.FromCursor()?.TypeName.Equals("pane", StringComparison.OrdinalIgnoreCase) == true, 1000, 50); Assert.IsTrue(result, "Failed to find menu."); Input.Mouse.LeftButtonClick(button.Location); }); } [TestMethod] public void ScrollIntoView() { ForEachBrowser(browser => { var location = browser.Location; var size = browser.Size; try { browser.NavigateTo(TestSite + "/main.html"); browser.MoveWindow(0, 0, 400, 300); browser.BringToFront(); var button = browser.First<WebElement>("button"); button.ScrollIntoView(); Assert.IsTrue(button.Location.X < 120, $"x:{button.Location.X} should be less than 100."); Assert.IsTrue(button.Location.Y < 120, $"y:{button.Location.Y} should be less than 100."); } finally { browser.MoveWindow(location, size); } }, resizeBrowsers: false); } [TestMethod] public void SelectSelectedOption() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var select = browser.First<Select>("select"); Assert.AreEqual("2", select.Value); Assert.AreEqual("2", select.SelectedOption.Value); Assert.AreEqual("Two", select.SelectedOption.Text); }); } [TestMethod] public void SendInputAllInputs() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); foreach (var input in browser.Descendants<TextInput>()) { if (input.Id == "number") { input.SendInput("100"); Assert.AreEqual("100", input.Text); } else { input.SendInput(input.Id); Assert.AreEqual(input.Id, input.Text); } } foreach (var input in browser.Descendants<TextArea>()) { input.SendInput(input.Id); Assert.AreEqual(input.Id, input.Text); } }); } [TestMethod] public void SendInputAppendInput() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); var input = browser.First<TextInput>("text"); input.Value = "foo"; input.SendInput("bar"); Assert.AreEqual("foobar", input.Value); }); } [TestMethod] public void SendInputPasswordInput() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); var input = browser.First<TextInput>("password"); input.SendInput("password", true); Assert.AreEqual("password", input.Value); }); } [TestMethod] public void SendInputSelectInput() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var select = browser.First<Select>("select"); select.SendInput("O"); Assert.AreEqual("One", select.Text); Assert.AreEqual("1", select.Value); }); } [TestMethod] public void SendInputSetInput() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); var input = browser.First<TextInput>("text"); input.Value = "foo"; input.SendInput("bar", true); Assert.AreEqual("bar", input.Value); }); } [TestMethod] public void SendInputUsingKeyboard() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); var input = browser.First("text"); input.SendInput("bar"); Assert.AreEqual("bar", ((TextInput) input).Value); }); } [TestMethod] public void SendInputWithNewLine() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); var input = browser.First<TextArea>("textarea"); input.SendInput("first\r\nsecond"); Assert.AreEqual("first\nsecond", input.Text); }); } [TestMethod] public void SetButtonText() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); browser.First<Button>("button").Text = "Hello"; var actual = browser.First<Button>("button").GetAttributeValue("textContent", true); Assert.AreEqual("Hello", actual); }); } [TestMethod] public void SetInputButtonText() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); browser.First<Button>("inputButton").Text = "Hello"; var actual = browser.First<Button>("inputButton").GetAttributeValue("value", true); Assert.AreEqual("Hello", actual); }); } [TestMethod] public void SetSelectText() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var select = browser.First<Select>("select"); select.Text = "One"; Assert.AreEqual("One", select.Text); Assert.AreEqual("1", select.Value); var text = browser.First<TextInput>("text"); Assert.AreEqual("1", text.Value); }); } [TestMethod] public void SetTextAllInputs() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); foreach (var input in browser.Descendants<TextInput>()) { if (input.Id == "number") { input.Text = "100"; Assert.AreEqual("100", input.Text); } else { input.Text = input.Id; Assert.AreEqual(input.Id, input.Text); } } foreach (var input in browser.Descendants<TextArea>()) { input.Text = input.Id; Assert.AreEqual(input.Id, input.Text); } }); } [TestMethod] public void SetTextWithNewLine() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); var input = browser.First<TextArea>("textarea"); input.Text = "first\r\nsecond"; Assert.AreEqual("first\nsecond", input.Text); }); } [TestMethod] public void SetThenGetHtmlOnAboutBlankPage() { ForAllBrowsers(browser => { browser.SetHtml("aoeu"); Assert.IsTrue(browser.GetHtml().Contains("aoeu")); var guid = Guid.NewGuid().ToString(); guid.Dump(); var body = $"{guid}"; var input = $"<html><head><link href=\"https://testr.local/Content/testr.css\" rel=\"stylesheet\"></head><body>{body}</body></html>"; browser.SetHtml(input); var actual = browser.GetHtml(); actual.Dump(); Assert.IsTrue(actual.Contains(guid)); }); } [TestMethod] public void SetThenGetHtmlOnAboutBlankPageMoreCharacters() { ForAllBrowsers(browser => { browser.NavigateTo("about:blank"); browser.SetHtml("aoeu"); Assert.IsTrue(browser.GetHtml().Contains("aoeu")); var guid = Guid.NewGuid().ToString(); guid.Dump(); var body = $"Special characters like \", ', \0, \", \n, \r, \r\n, <, >, should not break html... however &amp; must be already encoded! \n{guid}"; var input = $"<html><head><link href=\"https://testr.local/Content/testr.css\" rel=\"stylesheet\"></head><body>{body}</body></html>"; browser.SetHtml(input); var actual = browser.GetHtml(); actual.Dump(); Assert.IsTrue(actual.Contains(guid)); }); } [TestMethod] public void SetThenGetHtmlOnAboutBlankPageWithAllCharacters() { ForAllBrowsers(browser => { browser.NavigateTo("about:blank"); if (browser is Firefox) { return; } var buffer = new byte[255]; for (var i = 0; i < buffer.Length; i++) { buffer[i] = (byte) i; } var data = Encoding.UTF8.GetString(buffer).Replace("&", "&amp;"); data.ToLiteral().Dump(); var guid = Guid.NewGuid().ToString(); guid.Dump(); var body = $"Special characters like \", ', \0, \", \n, \r, \r\n, <, >, should not break html... however &amp; must be already encoded! \n{data}\n{guid}"; var input = $"<html><head><link href=\"https://testr.local/Content/testr.css\" rel=\"stylesheet\"></head><body>{body}</body></html>"; browser.SetHtml(input); var actual = browser.GetHtml(); actual.Dump(); Assert.IsTrue(actual.Contains(guid)); }); } [TestMethod] public void SetThenGetHtmlOnAboutBlankPageWithRandomCharacters() { ForAllBrowsers(browser => { browser.NavigateTo("about:blank"); if (browser is Firefox) { return; } var buffer = new byte[32]; RandomNumberGenerator.Create().GetBytes(buffer); var data = Encoding.UTF8.GetString(buffer); data.ToLiteral().Dump(); var guid = Guid.NewGuid().ToString(); guid.Dump(); var body = $"Special characters like \", ', \0, \", \n, \r, \r\n, <, >, should not break html... however &amp; must be already encoded! \n{data}\n{guid}"; var input = $"<html><head><link href=\"https://testr.local/Content/testr.css\" rel=\"stylesheet\"></head><body>{body}</body></html>"; browser.SetHtml(input); var actual = browser.GetHtml(); actual.Dump(); Assert.IsTrue(actual.Contains(guid)); }); } [TestMethod] public void SetValueWithNewLine() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/inputs.html"); var input = browser.First<TextArea>("textarea"); input.Value = "first\r\nsecond"; Assert.AreEqual("first\nsecond", input.Value); }); } [TestMethod] public void TestContentForInputText() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/TextContent.html"); var element = browser.First<TextInput>("inputText1"); Assert.AreEqual(element.Text, "inputText1"); }); } [TestMethod] public void TextAreaValue() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/main.html"); var element = browser.First<TextArea>("textarea"); Assert.AreEqual(element.Text, "Text Area's \"Quotes\" Data"); element.Text = "\"Text Area's \"Quote's\" Data\""; Assert.AreEqual(element.Text, "\"Text Area's \"Quote's\" Data\""); }); } [TestMethod] public void TextContentForDiv() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/TextContent.html"); var element = browser.First<Division>("div1"); Assert.AreEqual(element.Text, "\n\t\t\tDiv - Span\n\t\t\tOther Text\n\t\t"); }); } [TestMethod] public void TextContentForDivWithChildren() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/TextContent.html"); var element = browser.First<Division>("div2"); Assert.AreEqual(element.Text, "\n\t\t\tHeader One\n\t\t\tHeader Two\n\t\t\tHeader Three\n\t\t\tHeader Four\n\t\t\tHeader Five\n\t\t"); }); } [TestMethod] public void TextContentForHeader1() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/TextContent.html"); var element = browser.First<Header>("h1"); Assert.AreEqual(element.Text, "Header One"); }); } [TestMethod] public void TextContentForHeader2() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/TextContent.html"); var element = browser.First<Header>("h2"); Assert.AreEqual(element.Text, "Header Two"); }); } [TestMethod] public void TextContentForHeader3() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/TextContent.html"); var element = browser.First<Header>("h3"); Assert.AreEqual(element.Text, "Header Three"); }); } [TestMethod] public void TextContentForHeader4() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/TextContent.html"); var element = browser.First<Header>("h4"); Assert.AreEqual(element.Text, "Header Four"); }); } [TestMethod] public void TextContentForHeader5() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/TextContent.html"); var element = browser.First<Header>("h5"); Assert.AreEqual(element.Text, "Header Five"); }); } [TestMethod] public void VueInputTrigger() { ForAllBrowsers(browser => { browser.NavigateTo(TestSite + "/Vue.html"); Assert.AreEqual(false, browser.First<Button>("submit").Enabled); browser.First<TextInput>("emailAddress").SendInput("user"); var expected = "user"; var actual = browser.First<WebElement>("emailAddressLabel").GetHtml(); Assert.AreEqual(expected, actual); expected = "keydown: 117(u)<br>keypress: 117(u)<br>keyup: 117(u)<br>keydown: 115(s)<br>keypress: 115(s)<br>keyup: 115(s)<br>keydown: 101(e)<br>keypress: 101(e)<br>keyup: 101(e)<br>keydown: 114(r)<br>keypress: 114(r)<br>keyup: 114(r)<br>"; actual = browser.First<WebElement>("log").GetHtml(); Assert.AreEqual(expected, actual); Assert.AreEqual(true, browser.First<Button>("submit").Enabled); }); } [TestMethod] public void WebElementRefresh() { ForAllBrowsers(browser => { browser.Timeout = DefaultTimeout; browser.NavigateTo(TestSite + "/Angular.html#!/"); var items = browser.First<Division>("items"); Assert.AreEqual(0, items.Children.Count); browser.First<Button>("addItem").Click(); var result = items.Wait(x => x.Refresh().Children.Count == 1); Assert.IsTrue(result, "Items was not added"); Assert.AreEqual(1, items.Children.Count); Assert.AreEqual("items-0", items.Children[0].Id); }); } private void ForAllBrowsers(Action<Browser> action, BrowserType browserTypes = BrowserType.Chrome | BrowserType.Edge, bool resizeBrowsers = true, bool useSecondaryMonitor = false, int? timeout = null) { CleanupBrowsers = false; browserTypes.ForAllBrowsers(action, useSecondaryMonitor, resizeBrowsers, BrowserResizeType.LeftSideBySide, timeout ?? (int) DefaultTimeout.TotalMilliseconds); } private void ForEachBrowser(Action<Browser> action, BrowserType browserTypes = BrowserType.Chrome | BrowserType.Edge, bool resizeBrowsers = true, bool useSecondaryMonitor = false) { CleanupBrowsers = false; browserTypes.ForEachBrowser(action, useSecondaryMonitor, resizeBrowsers, BrowserResizeType.LeftSideBySide); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using ModestTree; using UnityEngine; using Random = UnityEngine.Random; namespace Zenject.Asteroids { public class AsteroidManager : ITickable, IFixedTickable { readonly List<Asteroid> _asteroids = new List<Asteroid>(); readonly Queue<AsteroidAttributes> _cachedAttributes = new Queue<AsteroidAttributes>(); readonly Settings _settings; readonly Asteroid.Factory _asteroidFactory; readonly LevelHelper _level; float _timeToNextSpawn; float _timeIntervalBetweenSpawns; bool _started; [InjectOptional] bool _autoSpawn = true; public AsteroidManager( Settings settings, Asteroid.Factory asteroidFactory, LevelHelper level) { _settings = settings; _timeIntervalBetweenSpawns = _settings.maxSpawnTime / (_settings.maxSpawns - _settings.startingSpawns); _timeToNextSpawn = _timeIntervalBetweenSpawns; _asteroidFactory = asteroidFactory; _level = level; } public IEnumerable<Asteroid> Asteroids { get { return _asteroids; } } public void Start() { Assert.That(!_started); _started = true; ResetAll(); GenerateRandomAttributes(); for (int i = 0; i < _settings.startingSpawns; i++) { SpawnNext(); } } // Generate the full list of size and speeds so that we can maintain an approximate average // this way we don't get wildly different difficulties each time the game is run // For example, if we just chose speed randomly each time we spawned an asteroid, in some // cases that might result in the first set of asteroids all going at max speed, or min speed void GenerateRandomAttributes() { Assert.That(_cachedAttributes.Count == 0); var speedTotal = 0.0f; var sizeTotal = 0.0f; for (int i = 0; i < _settings.maxSpawns; i++) { var sizePx = Random.Range(0.0f, 1.0f); var speed = Random.Range(_settings.minSpeed, _settings.maxSpeed); _cachedAttributes.Enqueue(new AsteroidAttributes { SizePx = sizePx, InitialSpeed = speed }); speedTotal += speed; sizeTotal += sizePx; } var desiredAverageSpeed = (_settings.minSpeed + _settings.maxSpeed) * 0.5f; var desiredAverageSize = 0.5f; var averageSize = sizeTotal / _settings.maxSpawns; var averageSpeed = speedTotal / _settings.maxSpawns; var speedScaleFactor = desiredAverageSpeed / averageSpeed; var sizeScaleFactor = desiredAverageSize / averageSize; foreach (var attributes in _cachedAttributes) { attributes.SizePx *= sizeScaleFactor; attributes.InitialSpeed *= speedScaleFactor; } Assert.That(Mathf.Approximately(_cachedAttributes.Average(x => x.InitialSpeed), desiredAverageSpeed)); Assert.That(Mathf.Approximately(_cachedAttributes.Average(x => x.SizePx), desiredAverageSize)); } void ResetAll() { foreach (var asteroid in _asteroids) { GameObject.Destroy(asteroid.gameObject); } _asteroids.Clear(); _cachedAttributes.Clear(); } public void Stop() { Assert.That(_started); _started = false; } public void FixedTick() { for (int i = 0; i < _asteroids.Count; i++) { _asteroids[i].FixedTick(); } } public void Tick() { for (int i = 0; i < _asteroids.Count; i++) { _asteroids[i].Tick(); } if (_started && _autoSpawn) { _timeToNextSpawn -= Time.deltaTime; if (_timeToNextSpawn < 0 && _asteroids.Count < _settings.maxSpawns) { _timeToNextSpawn = _timeIntervalBetweenSpawns; SpawnNext(); } } } public void SpawnNext() { var asteroid = _asteroidFactory.Create(); var attributes = _cachedAttributes.Dequeue(); asteroid.Scale = Mathf.Lerp(_settings.minScale, _settings.maxScale, attributes.SizePx); asteroid.Mass = Mathf.Lerp(_settings.minMass, _settings.maxMass, attributes.SizePx); asteroid.Position = GetRandomStartPosition(asteroid.Scale); asteroid.Velocity = GetRandomDirection() * attributes.InitialSpeed; _asteroids.Add(asteroid); } Vector3 GetRandomDirection() { var theta = Random.Range(0, Mathf.PI * 2.0f); return new Vector3(Mathf.Cos(theta), Mathf.Sin(theta), 0); } Vector3 GetRandomStartPosition(float scale) { var side = (Side)Random.Range(0, (int)Side.Count); var rand = Random.Range(0.0f, 1.0f); switch (side) { case Side.Top: { return new Vector3(_level.Left + rand * _level.Width, _level.Top + scale, 0); } case Side.Bottom: { return new Vector3(_level.Left + rand * _level.Width, _level.Bottom - scale, 0); } case Side.Right: { return new Vector3(_level.Right + scale, _level.Bottom + rand * _level.Height, 0); } case Side.Left: { return new Vector3(_level.Left - scale, _level.Bottom + rand * _level.Height, 0); } } throw Assert.CreateException(); } enum Side { Top, Bottom, Left, Right, Count } [Serializable] public class Settings { public float minSpeed; public float maxSpeed; public float minScale; public float maxScale; public int startingSpawns; public int maxSpawns; public float maxSpawnTime; public float maxMass; public float minMass; } class AsteroidAttributes { public float SizePx; public float InitialSpeed; } } }
using System; using System.Collections.Generic; namespace YMR.ComplexBody.Core.GeometryUtility { /// <summary> /// Summary description for Class1. /// </summary> public class CPolygonShape { private CPoint2D[] m_aInputVertices; private CPoint2D[] m_aUpdatedPolygonVertices; private List<CPoint2D[]> m_alEars = new List<CPoint2D[]>(); private CPoint2D[][] m_aPolygons; public int NumberOfPolygons { get { return m_aPolygons.Length; } } public CPoint2D[] Polygons(int index) { if (index< m_aPolygons.Length) return m_aPolygons[index]; else return null; } public CPolygonShape(CPoint2D[] vertices) { int nVertices=vertices.Length; if (nVertices < 3) return; //initalize the 2D points m_aInputVertices=new CPoint2D[nVertices]; for (int i=0; i<nVertices; i++) m_aInputVertices[i] =vertices[i]; //make a working copy, m_aUpdatedPolygonVertices are //in count clock direction from user view SetUpdatedPolygonVertices(); } /**************************************************** To fill m_aUpdatedPolygonVertices array with input array. m_aUpdatedPolygonVertices is a working array that will be updated when an ear is cut till m_aUpdatedPolygonVertices makes triangle (a convex polygon). ******************************************************/ private void SetUpdatedPolygonVertices() { int nVertices=m_aInputVertices.Length; m_aUpdatedPolygonVertices=new CPoint2D[nVertices]; for (int i=0; i< nVertices; i++) m_aUpdatedPolygonVertices[i] =m_aInputVertices[i]; //m_aUpdatedPolygonVertices should be in count clock wise if (CPolygon.PointsDirection(m_aUpdatedPolygonVertices) ==PolygonDirection.Clockwise) CPolygon.ReversePointsDirection(m_aUpdatedPolygonVertices); } /********************************************************** To check the Pt is in the Triangle or not. If the Pt is in the line or is a vertex, then return true. If the Pt is out of the Triangle, then return false. This method is used for triangle only. ***********************************************************/ private bool TriangleContainsPoint(CPoint2D[] trianglePts, CPoint2D pt) { if (trianglePts.Length!=3) return false; for (int i=trianglePts.GetLowerBound(0); i<trianglePts.GetUpperBound(0); i++) { if (pt.EqualsPoint(trianglePts[i])) return true; } bool bIn=false; CLineSegment line0=new CLineSegment(trianglePts[0],trianglePts[1]); CLineSegment line1=new CLineSegment(trianglePts[1],trianglePts[2]); CLineSegment line2=new CLineSegment(trianglePts[2],trianglePts[0]); if (pt.InLine(line0)||pt.InLine(line1) ||pt.InLine(line2)) bIn=true; else //point is not in the lines { double dblArea0=CPolygon.PolygonArea(new CPoint2D[] {trianglePts[0],trianglePts[1], pt}); double dblArea1=CPolygon.PolygonArea(new CPoint2D[] {trianglePts[1],trianglePts[2], pt}); double dblArea2=CPolygon.PolygonArea(new CPoint2D[] {trianglePts[2],trianglePts[0], pt}); if (dblArea0>0) { if ((dblArea1 >0) &&(dblArea2>0)) bIn=true; } else if (dblArea0<0) { if ((dblArea1 < 0) && (dblArea2< 0)) bIn=true; } } return bIn; } /**************************************************************** To check whether the Vertex is an ear or not based updated Polygon vertices ref. www-cgrl.cs.mcgill.ca/~godfried/teaching/cg-projects/97/Ian /algorithm1.html If it is an ear, return true, If it is not an ear, return false; *****************************************************************/ private bool IsEarOfUpdatedPolygon(CPoint2D vertex ) { CPolygon polygon=new CPolygon(m_aUpdatedPolygonVertices); if (polygon.PolygonVertex(vertex)) { bool bEar=true; if (polygon.PolygonVertexType(vertex)==VertexType.ConvexPoint) { CPoint2D pi=vertex; CPoint2D pj=polygon.PreviousPoint(vertex); //previous vertex CPoint2D pk=polygon.NextPoint(vertex);//next vertex for (int i=m_aUpdatedPolygonVertices.GetLowerBound(0); i<m_aUpdatedPolygonVertices.GetUpperBound(0); i++) { CPoint2D pt = m_aUpdatedPolygonVertices[i]; if ( !(pt.EqualsPoint(pi)|| pt.EqualsPoint(pj)||pt.EqualsPoint(pk))) { if (TriangleContainsPoint(new CPoint2D[] {pj, pi, pk}, pt)) bEar=false; } } } //ThePolygon.getVertexType(Vertex)=ConvexPt else //concave point bEar=false; //not an ear/ return bEar; } else //not a polygon vertex; { //ERROR! return false; } } /**************************************************** Set up m_aPolygons: add ears and been cut Polygon togather ****************************************************/ private void SetPolygons() { int nPolygon=m_alEars.Count + 1; //ears plus updated polygon m_aPolygons=new CPoint2D[nPolygon][]; for (int i=0; i<nPolygon-1; i++) //add ears { CPoint2D[] points=(CPoint2D[])m_alEars[i]; m_aPolygons[i]=new CPoint2D[3]; //3 vertices each ear m_aPolygons[i][0]=points[0]; m_aPolygons[i][1]=points[1]; m_aPolygons[i][2]=points[2]; } //add UpdatedPolygon: m_aPolygons[nPolygon-1]=new CPoint2D[m_aUpdatedPolygonVertices.Length]; for (int i=0; i<m_aUpdatedPolygonVertices.Length;i++) { m_aPolygons[nPolygon-1][i] = m_aUpdatedPolygonVertices[i]; } } /******************************************************** To update m_aUpdatedPolygonVertices: Take out Vertex from m_aUpdatedPolygonVertices array, add 3 points to the m_aEars **********************************************************/ private void UpdatePolygonVertices(CPoint2D vertex) { List<CPoint2D> alTempPts = new List<CPoint2D>(); for (int i=0; i< m_aUpdatedPolygonVertices.Length; i++) { if (vertex.EqualsPoint( m_aUpdatedPolygonVertices[i])) //add 3 pts to FEars { CPolygon polygon=new CPolygon(m_aUpdatedPolygonVertices); CPoint2D pti = vertex; CPoint2D ptj = polygon.PreviousPoint(vertex); //previous point CPoint2D ptk = polygon.NextPoint(vertex); //next point CPoint2D[] aEar=new CPoint2D[3]; //3 vertices of each ear aEar[0]=ptj; aEar[1]=pti; aEar[2]=ptk; m_alEars.Add(aEar); } else { alTempPts.Add(m_aUpdatedPolygonVertices[i]); } //not equal points } if (m_aUpdatedPolygonVertices.Length - alTempPts.Count==1) { int nLength=m_aUpdatedPolygonVertices.Length; m_aUpdatedPolygonVertices=new CPoint2D[nLength-1]; for (int i=0; i<alTempPts.Count; i++) m_aUpdatedPolygonVertices[i]=(CPoint2D)alTempPts[i]; } } /******************************************************* To cut an ear from polygon to make ears and an updated polygon: *******************************************************/ public void CutEar() { CPolygon polygon=new CPolygon(m_aUpdatedPolygonVertices); bool bFinish=false; //if (polygon.GetPolygonType()==PolygonType.Convex) //don't have to cut ear // bFinish=true; if (m_aUpdatedPolygonVertices.Length==3) //triangle, don't have to cut ear bFinish=true; CPoint2D pt=new CPoint2D(); int maxCicles = m_aInputVertices.Length * m_aInputVertices.Length; // YMR - Just in case... int cicle = 0; while (bFinish==false && cicle++ < maxCicles) //UpdatedPolygon { int i=0; bool bNotFound=true; while (bNotFound && (i<m_aUpdatedPolygonVertices.Length)) //loop till find an ear { pt=m_aUpdatedPolygonVertices[i]; if (IsEarOfUpdatedPolygon(pt)) bNotFound=false; //got one, pt is an ear else i++; } //bNotFount //An ear found:} if (pt !=null) UpdatePolygonVertices(pt); polygon=new CPolygon(m_aUpdatedPolygonVertices); //if ((polygon.GetPolygonType()==PolygonType.Convex) // && (m_aUpdatedPolygonVertices.Length==3)) if (m_aUpdatedPolygonVertices.Length==3) bFinish=true; } //bFinish=false SetPolygons(); } } }
using System.Collections.Generic; using Esprima.Ast; using Jint.Native; using Jint.Native.Iterator; using Jint.Native.Object; using Jint.Runtime.Descriptors; using Jint.Runtime.Environments; using Jint.Runtime.Interpreter.Expressions; using Jint.Runtime.References; namespace Jint.Runtime.Interpreter.Statements { /// <summary> /// https://tc39.es/ecma262/#sec-for-in-and-for-of-statements /// </summary> internal sealed class JintForInForOfStatement : JintStatement<Statement> { private readonly Node _leftNode; private readonly Statement _forBody; private readonly Expression _rightExpression; private readonly IterationKind _iterationKind; private JintStatement _body; private JintExpression _expr; private BindingPattern _assignmentPattern; private JintExpression _right; private List<string> _tdzNames; private bool _destructuring; private LhsKind _lhsKind; public JintForInForOfStatement(ForInStatement statement) : base(statement) { _leftNode = statement.Left; _rightExpression = statement.Right; _forBody = statement.Body; _iterationKind = IterationKind.Enumerate; } public JintForInForOfStatement(ForOfStatement statement) : base(statement) { _leftNode = statement.Left; _rightExpression = statement.Right; _forBody = statement.Body; _iterationKind = IterationKind.Iterate; } protected override void Initialize(EvaluationContext context) { _lhsKind = LhsKind.Assignment; var engine = context.Engine; if (_leftNode is VariableDeclaration variableDeclaration) { _lhsKind = variableDeclaration.Kind == VariableDeclarationKind.Var ? LhsKind.VarBinding : LhsKind.LexicalBinding; var variableDeclarationDeclaration = variableDeclaration.Declarations[0]; var id = variableDeclarationDeclaration.Id; if (_lhsKind == LhsKind.LexicalBinding) { _tdzNames = new List<string>(1); id.GetBoundNames(_tdzNames); } if (id is BindingPattern bindingPattern) { _destructuring = true; _assignmentPattern = bindingPattern; } else { var identifier = (Identifier) id; _expr = new JintIdentifierExpression(identifier); } } else if (_leftNode is BindingPattern bindingPattern) { _destructuring = true; _assignmentPattern = bindingPattern; } else if (_leftNode is MemberExpression memberExpression) { _expr = new JintMemberExpression(memberExpression); } else { _expr = new JintIdentifierExpression((Identifier) _leftNode); } _body = Build(_forBody); _right = JintExpression.Build(engine, _rightExpression); } protected override Completion ExecuteInternal(EvaluationContext context) { if (!HeadEvaluation(context, out var keyResult)) { return new Completion(CompletionType.Normal, JsValue.Undefined, null, Location); } return BodyEvaluation(context, _expr, _body, keyResult, IterationKind.Enumerate, _lhsKind); } /// <summary> /// https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofheadevaluation-tdznames-expr-iterationkind /// </summary> private bool HeadEvaluation(EvaluationContext context, out IteratorInstance result) { var engine = context.Engine; var oldEnv = engine.ExecutionContext.LexicalEnvironment; var tdz = JintEnvironment.NewDeclarativeEnvironment(engine, oldEnv); if (_tdzNames != null) { var TDZEnvRec = tdz; foreach (var name in _tdzNames) { TDZEnvRec.CreateMutableBinding(name); } } engine.UpdateLexicalEnvironment(tdz); var exprValue = _right.GetValue(context).Value; engine.UpdateLexicalEnvironment(oldEnv); if (_iterationKind == IterationKind.Enumerate) { if (exprValue.IsNullOrUndefined()) { result = null; return false; } var obj = TypeConverter.ToObject(engine.Realm, exprValue); result = new ObjectKeyVisitor(engine, obj); } else { result = exprValue as IteratorInstance ?? exprValue.GetIterator(engine.Realm); } return true; } /// <summary> /// https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset /// </summary> private Completion BodyEvaluation( EvaluationContext context, JintExpression lhs, JintStatement stmt, IteratorInstance iteratorRecord, IterationKind iterationKind, LhsKind lhsKind, IteratorKind iteratorKind = IteratorKind.Sync) { var engine = context.Engine; var oldEnv = engine.ExecutionContext.LexicalEnvironment; var v = Undefined.Instance; var destructuring = _destructuring; string lhsName = null; var completionType = CompletionType.Normal; var close = false; try { while (true) { EnvironmentRecord iterationEnv = null; if (!iteratorRecord.TryIteratorStep(out var nextResult)) { close = true; return new Completion(CompletionType.Normal, v, null, Location); } if (iteratorKind == IteratorKind.Async) { // nextResult = await nextResult; ExceptionHelper.ThrowNotImplementedException("await"); } var nextValue = nextResult.Get(CommonProperties.Value); close = true; var lhsRef = new ExpressionResult(); if (lhsKind != LhsKind.LexicalBinding) { if (!destructuring) { lhsRef = lhs.Evaluate(context); } } else { iterationEnv = JintEnvironment.NewDeclarativeEnvironment(engine, oldEnv); if (_tdzNames != null) { BindingInstantiation(iterationEnv); } engine.UpdateLexicalEnvironment(iterationEnv); if (!destructuring) { var identifier = (Identifier) ((VariableDeclaration) _leftNode).Declarations[0].Id; lhsName ??= identifier.Name; lhsRef = new ExpressionResult(ExpressionCompletionType.Normal, engine.ResolveBinding(lhsName), identifier.Location); } } var status = new Completion(); if (!destructuring) { if (lhsRef.IsAbrupt()) { close = true; status = new Completion(lhsRef); } else if (lhsKind == LhsKind.LexicalBinding) { ((Reference) lhsRef.Value).InitializeReferencedBinding(nextValue); } else { engine.PutValue((Reference) lhsRef.Value, nextValue); } } else { status = BindingPatternAssignmentExpression.ProcessPatterns( context, _assignmentPattern, nextValue, iterationEnv, checkObjectPatternPropertyReference: _lhsKind != LhsKind.VarBinding); if (lhsKind == LhsKind.Assignment) { // DestructuringAssignmentEvaluation of assignmentPattern using nextValue as the argument. } else if (lhsKind == LhsKind.VarBinding) { // BindingInitialization for lhs passing nextValue and undefined as the arguments. } else { // BindingInitialization for lhs passing nextValue and iterationEnv as arguments } } if (status.IsAbrupt()) { engine.UpdateLexicalEnvironment(oldEnv); if (_iterationKind == IterationKind.AsyncIterate) { iteratorRecord.Close(status.Type); return status; } if (iterationKind == IterationKind.Enumerate) { return status; } iteratorRecord.Close(status.Type); return status; } var result = stmt.Execute(context); engine.UpdateLexicalEnvironment(oldEnv); if (!ReferenceEquals(result.Value, null)) { v = result.Value; } if (result.Type == CompletionType.Break && (result.Target == null || result.Target == _statement?.LabelSet?.Name)) { completionType = CompletionType.Normal; return new Completion(CompletionType.Normal, v, null, Location); } if (result.Type != CompletionType.Continue || (result.Target != null && result.Target != _statement?.LabelSet?.Name)) { completionType = result.Type; if (result.IsAbrupt()) { close = true; return result; } } } } catch { completionType = CompletionType.Throw; throw; } finally { if (close) { try { iteratorRecord.Close(completionType); } catch { // if we already have and exception, use it if (completionType != CompletionType.Throw) { throw; } } } engine.UpdateLexicalEnvironment(oldEnv); } } private void BindingInstantiation(EnvironmentRecord environment) { var envRec = (DeclarativeEnvironmentRecord) environment; var variableDeclaration = (VariableDeclaration) _leftNode; var boundNames = new List<string>(); variableDeclaration.GetBoundNames(boundNames); for (var i = 0; i < boundNames.Count; i++) { var name = boundNames[i]; if (variableDeclaration.Kind == VariableDeclarationKind.Const) { envRec.CreateImmutableBinding(name, strict: true); } else { envRec.CreateMutableBinding(name, canBeDeleted: false); } } } private enum LhsKind { Assignment, VarBinding, LexicalBinding } private enum IteratorKind { Sync, Async } private enum IterationKind { Enumerate, Iterate, AsyncIterate } private sealed class ObjectKeyVisitor : IteratorInstance { public ObjectKeyVisitor(Engine engine, ObjectInstance obj) : base(engine, CreateEnumerator(obj)) { } private static IEnumerable<JsValue> CreateEnumerator(ObjectInstance obj) { var visited = new HashSet<JsValue>(); foreach (var key in obj.GetOwnPropertyKeys(Types.String)) { var desc = obj.GetOwnProperty(key); if (desc != PropertyDescriptor.Undefined) { visited.Add(key); if (desc.Enumerable) { yield return key; } } } if (obj.Prototype is null) { yield break; } foreach (var protoKey in CreateEnumerator(obj.Prototype)) { if (!visited.Contains(protoKey)) { yield return protoKey; } } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using Microsoft.Protocols.TestTools.StackSdk.Messages; using System.Globalization; namespace Microsoft.Protocols.TestTools { /// <summary> /// An auxiliary class for implementing abstract identifier bindings. /// </summary> /// <typeparam name="Target">The target type to which the abstract identifier is bound.</typeparam> public class IdentifierBinding<Target> { Dictionary<int, Target> forwardMap = new Dictionary<int,Target>(); Dictionary<Target, int> backwardMap = new Dictionary<Target,int>(); IRuntimeHost host; int maxIdUsed; private readonly object identifierBindingLock = new object(); /// <summary> /// Constructs an identifier binding instance. /// A test site must be passed so that the binding can generate assertions and log entries. /// </summary> /// <param name="host">The message runtime host.</param> public IdentifierBinding(IRuntimeHost host) { this.host = host; } /// <summary> /// Constructs an identifier binding instance. /// Only use when no test site is needed. /// </summary> public IdentifierBinding() { } /// <summary> /// Resets the identifier binding. /// This method clears all previous definitions. /// </summary> public void Reset() { lock (identifierBindingLock) { forwardMap.Clear(); backwardMap.Clear(); maxIdUsed = 0; } } /// <summary> /// Binds the given identifier to the given target. /// If the identifier is already mapped to a different target, /// or if the target is already mapped to a different identifier, /// an assertion failure is raised on the test site. /// </summary> /// <param name="id">The identifier</param> /// <param name="target">The target</param> public void Bind(int id, Target target) { lock (identifierBindingLock) { Target oldTarget; int oldId; if (forwardMap.TryGetValue(id, out oldTarget)) { if (!Object.Equals(oldTarget, target)) { if (host != null) { host.Assert(false, "failed binding identifier '{0}' to '{1}': identifier already bound to '{2}'", id, target, oldTarget); } else Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "failed binding identifier '{0}' to '{1}': identifier already bound to '{2}'", id, target, oldTarget)); } } else { forwardMap[id] = target; if (id > maxIdUsed) maxIdUsed = id; } if (backwardMap.TryGetValue(target, out oldId)) { if (id != oldId) { if (host != null) { host.Assert(false, "failed binding identifier '{0}' to '{1}': target already uses identifier '{2}'", id, target, oldId); } else Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "failed binding identifier '{0}' to '{1}': target already uses identifier '{2}'", id, target, oldId)); } } else backwardMap[target] = id; } } /// <summary> /// Unbinds the given identifier. /// This method does nothing if the identifier is not bound. /// </summary> /// <param name="id">The identifier</param> public void Unbind(int id) { lock (identifierBindingLock) { Target oldTarget; if (forwardMap.TryGetValue(id, out oldTarget)) { forwardMap.Remove(id); backwardMap.Remove(oldTarget); } } } /// <summary> /// Gets the identifier which is associated with the given target. /// An assertion failure is raised on test site if the target has no binding. /// </summary> /// <param name="target">The target</param> /// <returns>The identifier of the target</returns> public int GetIdentifier(Target target) { lock (identifierBindingLock) { int id = 0; if (!backwardMap.TryGetValue(target, out id)) { if (host != null) { host.Assert(false, "failed resolving target '{0}': not bound to identifier", target); } else Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "failed resolving target '{0}': not bound to identifier", target)); } return id; } } /// <summary> /// Gets the identifier associated with the given target, or creates a new identifier /// if target not bound. /// </summary> /// <param name="target">The target</param> /// <returns>The identifier of the target</returns> public int GetOrCreateIdentifier(Target target) { lock (identifierBindingLock) { if (!IsTargetBound(target)) Bind(this.GetUnusedIdentifier(), target); return GetIdentifier(target); } } /// <summary> /// Gets the target which is associated with the given identifier. /// An assertion failure is raised on test site if the identifier has no binding. /// </summary> /// <param name="id">The identifier</param> /// <returns>The target</returns> public Target GetTarget(int id) { lock (identifierBindingLock) { Target t = default(Target); if (!forwardMap.TryGetValue(id, out t)) { if (host != null) { host.Assert(false, "failed resolving identifier '{0}': not bound to target", id); } else Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "failed resolving identifier '{0}': not bound to target", id)); } return t; } } /// <summary> /// Checks if the identifier is bound. /// </summary> /// <param name="id">The identifier</param> /// <returns>Returns true if the identifier is bound.</returns> public bool IsIdentifierBound(int id) { lock (identifierBindingLock) { return forwardMap.ContainsKey(id); } } /// <summary> /// Checks if the target is bound. /// </summary> /// <param name="target">The target</param> /// <returns>Returns true if the target is bound.</returns> public bool IsTargetBound(Target target) { lock (identifierBindingLock) { return backwardMap.ContainsKey(target); } } /// <summary> /// Gets a value for an identifier which is not used in the binding. /// This method can be used for creating a new binding. /// </summary> /// <returns>Returns the unused identifier</returns> // The following suppression is adopted because the method GetUnusedIdentifier() performs a conversion of maxIdUsed field. // In this case, method is preferable to property. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public int GetUnusedIdentifier() { lock (identifierBindingLock) { return maxIdUsed + 1; } } /// <summary> /// Gets the current binding as a dictionary. /// </summary> public IDictionary<int, Target> Dictionary { get { return forwardMap; } } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Engagement Channel Type Feed ///<para>SObject Name: EngagementChannelTypeFeed</para> ///<para>Custom Object: False</para> ///</summary> public class SfEngagementChannelTypeFeed : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "EngagementChannelTypeFeed"; } } ///<summary> /// Feed Item ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Parent ID /// <para>Name: ParentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "parentId")] [Updateable(false), Createable(false)] public string ParentId { get; set; } ///<summary> /// ReferenceTo: EngagementChannelType /// <para>RelationshipName: Parent</para> ///</summary> [JsonProperty(PropertyName = "parent")] [Updateable(false), Createable(false)] public SfEngagementChannelType Parent { get; set; } ///<summary> /// Feed Item Type /// <para>Name: Type</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "type")] [Updateable(false), Createable(false)] public string Type { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Comment Count /// <para>Name: CommentCount</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "commentCount")] [Updateable(false), Createable(false)] public int? CommentCount { get; set; } ///<summary> /// Like Count /// <para>Name: LikeCount</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "likeCount")] [Updateable(false), Createable(false)] public int? LikeCount { get; set; } ///<summary> /// Title /// <para>Name: Title</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "title")] [Updateable(false), Createable(false)] public string Title { get; set; } ///<summary> /// Body /// <para>Name: Body</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "body")] [Updateable(false), Createable(false)] public string Body { get; set; } ///<summary> /// Link Url /// <para>Name: LinkUrl</para> /// <para>SF Type: url</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "linkUrl")] [Updateable(false), Createable(false)] public string LinkUrl { get; set; } ///<summary> /// Is Rich Text /// <para>Name: IsRichText</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isRichText")] [Updateable(false), Createable(false)] public bool? IsRichText { get; set; } ///<summary> /// Related Record ID /// <para>Name: RelatedRecordId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "relatedRecordId")] [Updateable(false), Createable(false)] public string RelatedRecordId { get; set; } ///<summary> /// InsertedBy ID /// <para>Name: InsertedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "insertedById")] [Updateable(false), Createable(false)] public string InsertedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: InsertedBy</para> ///</summary> [JsonProperty(PropertyName = "insertedBy")] [Updateable(false), Createable(false)] public SfUser InsertedBy { get; set; } ///<summary> /// Best Comment ID /// <para>Name: BestCommentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "bestCommentId")] [Updateable(false), Createable(false)] public string BestCommentId { get; set; } ///<summary> /// ReferenceTo: FeedComment /// <para>RelationshipName: BestComment</para> ///</summary> [JsonProperty(PropertyName = "bestComment")] [Updateable(false), Createable(false)] public SfFeedComment BestComment { get; set; } } }
#region Apache License // // 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. // #endregion // .NET Compact Framework 1.0 has no support for System.Web.Mail // SSCLI 1.0 has no support for System.Web.Mail #if !NETCF && !SSCLI using System; using System.IO; #if NET_2_0 || NET_3_5 || NET_4_0 using System.Net.Mail; #else using System.Web.Mail; #endif using log4net.Layout; using log4net.Core; using log4net.Util; namespace log4net.Appender { /// <summary> /// Send an e-mail when a specific logging event occurs, typically on errors /// or fatal errors. /// </summary> /// <remarks> /// <para> /// The number of logging events delivered in this e-mail depend on /// the value of <see cref="BufferingAppenderSkeleton.BufferSize"/> option. The /// <see cref="SmtpAppender"/> keeps only the last /// <see cref="BufferingAppenderSkeleton.BufferSize"/> logging events in its /// cyclic buffer. This keeps memory requirements at a reasonable level while /// still delivering useful application context. /// </para> /// <note type="caution"> /// Authentication and setting the server Port are only available on the MS .NET 1.1 runtime. /// For these features to be enabled you need to ensure that you are using a version of /// the log4net assembly that is built against the MS .NET 1.1 framework and that you are /// running the your application on the MS .NET 1.1 runtime. On all other platforms only sending /// unauthenticated messages to a server listening on port 25 (the default) is supported. /// </note> /// <para> /// Authentication is supported by setting the <see cref="Authentication"/> property to /// either <see cref="SmtpAuthentication.Basic"/> or <see cref="SmtpAuthentication.Ntlm"/>. /// If using <see cref="SmtpAuthentication.Basic"/> authentication then the <see cref="Username"/> /// and <see cref="Password"/> properties must also be set. /// </para> /// <para> /// To set the SMTP server port use the <see cref="Port"/> property. The default port is 25. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class SmtpAppender : BufferingAppenderSkeleton { #region Public Instance Constructors /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para> /// Default constructor /// </para> /// </remarks> public SmtpAppender() { } #endregion // Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets a semicolon-delimited list of recipient e-mail addresses. /// </summary> /// <value> /// <para> /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// </para> /// <para> /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// </para> /// </value> /// <remarks> /// <para> /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// </para> /// <para> /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// </para> /// </remarks> public string To { get { return m_to; } set { m_to = value; } } /// <summary> /// Gets or sets a semicolon-delimited list of recipient e-mail addresses /// that will be carbon copied. /// </summary> /// <value> /// <para> /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// </para> /// <para> /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// </para> /// </value> /// <remarks> /// <para> /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// </para> /// <para> /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// </para> /// </remarks> public string Cc { get { return m_cc; } set { m_cc = value; } } /// <summary> /// Gets or sets a semicolon-delimited list of recipient e-mail addresses /// that will be blind carbon copied. /// </summary> /// <value> /// A semicolon-delimited list of e-mail addresses. /// </value> /// <remarks> /// <para> /// A semicolon-delimited list of recipient e-mail addresses. /// </para> /// </remarks> public string Bcc { get { return m_bcc; } set { m_bcc = value; } } /// <summary> /// Gets or sets the e-mail address of the sender. /// </summary> /// <value> /// The e-mail address of the sender. /// </value> /// <remarks> /// <para> /// The e-mail address of the sender. /// </para> /// </remarks> public string From { get { return m_from; } set { m_from = value; } } /// <summary> /// Gets or sets the subject line of the e-mail message. /// </summary> /// <value> /// The subject line of the e-mail message. /// </value> /// <remarks> /// <para> /// The subject line of the e-mail message. /// </para> /// </remarks> public string Subject { get { return m_subject; } set { m_subject = value; } } /// <summary> /// Gets or sets the name of the SMTP relay mail server to use to send /// the e-mail messages. /// </summary> /// <value> /// The name of the e-mail relay server. If SmtpServer is not set, the /// name of the local SMTP server is used. /// </value> /// <remarks> /// <para> /// The name of the e-mail relay server. If SmtpServer is not set, the /// name of the local SMTP server is used. /// </para> /// </remarks> public string SmtpHost { get { return m_smtpHost; } set { m_smtpHost = value; } } /// <summary> /// Obsolete /// </summary> /// <remarks> /// Use the BufferingAppenderSkeleton Fix methods instead /// </remarks> /// <remarks> /// <para> /// Obsolete property. /// </para> /// </remarks> [Obsolete("Use the BufferingAppenderSkeleton Fix methods")] public bool LocationInfo { get { return false; } set { ; } } /// <summary> /// The mode to use to authentication with the SMTP server /// </summary> /// <remarks> /// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note> /// <para> /// Valid Authentication mode values are: <see cref="SmtpAuthentication.None"/>, /// <see cref="SmtpAuthentication.Basic"/>, and <see cref="SmtpAuthentication.Ntlm"/>. /// The default value is <see cref="SmtpAuthentication.None"/>. When using /// <see cref="SmtpAuthentication.Basic"/> you must specify the <see cref="Username"/> /// and <see cref="Password"/> to use to authenticate. /// When using <see cref="SmtpAuthentication.Ntlm"/> the Windows credentials for the current /// thread, if impersonating, or the process will be used to authenticate. /// </para> /// </remarks> public SmtpAuthentication Authentication { get { return m_authentication; } set { m_authentication = value; } } /// <summary> /// The username to use to authenticate with the SMTP server /// </summary> /// <remarks> /// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note> /// <para> /// A <see cref="Username"/> and <see cref="Password"/> must be specified when /// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>, /// otherwise the username will be ignored. /// </para> /// </remarks> public string Username { get { return m_username; } set { m_username = value; } } /// <summary> /// The password to use to authenticate with the SMTP server /// </summary> /// <remarks> /// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note> /// <para> /// A <see cref="Username"/> and <see cref="Password"/> must be specified when /// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>, /// otherwise the password will be ignored. /// </para> /// </remarks> public string Password { get { return m_password; } set { m_password = value; } } /// <summary> /// The port on which the SMTP server is listening /// </summary> /// <remarks> /// <note type="caution">Server Port is only available on the MS .NET 1.1 runtime.</note> /// <para> /// The port on which the SMTP server is listening. The default /// port is <c>25</c>. The Port can only be changed when running on /// the MS .NET 1.1 runtime. /// </para> /// </remarks> public int Port { get { return m_port; } set { m_port = value; } } /// <summary> /// Gets or sets the priority of the e-mail message /// </summary> /// <value> /// One of the <see cref="MailPriority"/> values. /// </value> /// <remarks> /// <para> /// Sets the priority of the e-mails generated by this /// appender. The default priority is <see cref="MailPriority.Normal"/>. /// </para> /// <para> /// If you are using this appender to report errors then /// you may want to set the priority to <see cref="MailPriority.High"/>. /// </para> /// </remarks> public MailPriority Priority { get { return m_mailPriority; } set { m_mailPriority = value; } } #if NET_2_0 || NET_3_5 || NET_4_0 /// <summary> /// Enable or disable use of SSL when sending e-mail message /// </summary> /// <remarks> /// This is available on MS .NET 2.0 runtime and higher /// </remarks> public bool EnableSsl { get { return m_enableSsl; } set { m_enableSsl = value; } } /// <summary> /// Gets or sets the reply-to e-mail address. /// </summary> /// <remarks> /// This is available on MS .NET 2.0 runtime and higher /// </remarks> public string ReplyTo { get { return m_replyTo; } set { m_replyTo = value; } } #endif #endregion // Public Instance Properties #region Override implementation of BufferingAppenderSkeleton /// <summary> /// Sends the contents of the cyclic buffer as an e-mail message. /// </summary> /// <param name="events">The logging events to send.</param> override protected void SendBuffer(LoggingEvent[] events) { // Note: this code already owns the monitor for this // appender. This frees us from needing to synchronize again. try { StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); string t = Layout.Header; if (t != null) { writer.Write(t); } for(int i = 0; i < events.Length; i++) { // Render the event and append the text to the buffer RenderLoggingEvent(writer, events[i]); } t = Layout.Footer; if (t != null) { writer.Write(t); } SendEmail(writer.ToString()); } catch(Exception e) { ErrorHandler.Error("Error occurred while sending e-mail notification.", e); } } #endregion // Override implementation of BufferingAppenderSkeleton #region Override implementation of AppenderSkeleton /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } #endregion // Override implementation of AppenderSkeleton #region Protected Methods /// <summary> /// Send the email message /// </summary> /// <param name="messageBody">the body text to include in the mail</param> virtual protected void SendEmail(string messageBody) { #if NET_2_0 || NET_3_5 || NET_4_0 // .NET 2.0 has a new API for SMTP email System.Net.Mail // This API supports credentials and multiple hosts correctly. // The old API is deprecated. // Create and configure the smtp client SmtpClient smtpClient = new SmtpClient(); if (!String.IsNullOrEmpty(m_smtpHost)) { smtpClient.Host = m_smtpHost; } smtpClient.Port = m_port; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.EnableSsl = m_enableSsl; if (m_authentication == SmtpAuthentication.Basic) { // Perform basic authentication smtpClient.Credentials = new System.Net.NetworkCredential(m_username, m_password); } else if (m_authentication == SmtpAuthentication.Ntlm) { // Perform integrated authentication (NTLM) smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; } using (MailMessage mailMessage = new MailMessage()) { mailMessage.Body = messageBody; mailMessage.From = new MailAddress(m_from); mailMessage.To.Add(m_to); if (!String.IsNullOrEmpty(m_cc)) { mailMessage.CC.Add(m_cc); } if (!String.IsNullOrEmpty(m_bcc)) { mailMessage.Bcc.Add(m_bcc); } if (!String.IsNullOrEmpty(m_replyTo)) { // .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete: // 'ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202' #if !NET_4_0 mailMessage.ReplyTo = new MailAddress(m_replyTo); #else mailMessage.ReplyToList.Add(new MailAddress(m_replyTo)); #endif } mailMessage.Subject = m_subject; mailMessage.Priority = m_mailPriority; // TODO: Consider using SendAsync to send the message without blocking. This would be a change in // behaviour compared to .NET 1.x. We would need a SendCompletedCallback to log errors. smtpClient.Send(mailMessage); } #else // .NET 1.x uses the System.Web.Mail API for sending Mail MailMessage mailMessage = new MailMessage(); mailMessage.Body = messageBody; mailMessage.From = m_from; mailMessage.To = m_to; if (m_cc != null && m_cc.Length > 0) { mailMessage.Cc = m_cc; } if (m_bcc != null && m_bcc.Length > 0) { mailMessage.Bcc = m_bcc; } mailMessage.Subject = m_subject; mailMessage.Priority = m_mailPriority; #if NET_1_1 // The Fields property on the MailMessage allows the CDO properties to be set directly. // This property is only available on .NET Framework 1.1 and the implementation must understand // the CDO properties. For details of the fields available in CDO see: // // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_configuration_coclass.asp // try { if (m_authentication == SmtpAuthentication.Basic) { // Perform basic authentication mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1); mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", m_username); mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", m_password); } else if (m_authentication == SmtpAuthentication.Ntlm) { // Perform integrated authentication (NTLM) mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 2); } // Set the port if not the default value if (m_port != 25) { mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", m_port); } } catch(MissingMethodException missingMethodException) { // If we were compiled against .NET 1.1 but are running against .NET 1.0 then // we will get a MissingMethodException when accessing the MailMessage.Fields property. ErrorHandler.Error("SmtpAppender: Authentication and server Port are only supported when running on the MS .NET 1.1 framework", missingMethodException); } #else if (m_authentication != SmtpAuthentication.None) { ErrorHandler.Error("SmtpAppender: Authentication is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net"); } if (m_port != 25) { ErrorHandler.Error("SmtpAppender: Server Port is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net"); } #endif // if NET_1_1 if (m_smtpHost != null && m_smtpHost.Length > 0) { SmtpMail.SmtpServer = m_smtpHost; } SmtpMail.Send(mailMessage); #endif // if NET_2_0 } #endregion // Protected Methods #region Private Instance Fields private string m_to; private string m_cc; private string m_bcc; private string m_from; private string m_subject; private string m_smtpHost; // authentication fields private SmtpAuthentication m_authentication = SmtpAuthentication.None; private string m_username; private string m_password; // server port, default port 25 private int m_port = 25; private MailPriority m_mailPriority = MailPriority.Normal; #if NET_2_0 || NET_3_5 || NET_4_0 private bool m_enableSsl = false; private string m_replyTo; #endif #endregion // Private Instance Fields #region SmtpAuthentication Enum /// <summary> /// Values for the <see cref="SmtpAppender.Authentication"/> property. /// </summary> /// <remarks> /// <para> /// SMTP authentication modes. /// </para> /// </remarks> public enum SmtpAuthentication { /// <summary> /// No authentication /// </summary> None, /// <summary> /// Basic authentication. /// </summary> /// <remarks> /// Requires a username and password to be supplied /// </remarks> Basic, /// <summary> /// Integrated authentication /// </summary> /// <remarks> /// Uses the Windows credentials from the current thread or process to authenticate. /// </remarks> Ntlm } #endregion // SmtpAuthentication Enum } } #endif // !NETCF && !SSCLI
/* * Application.cs - Implementation of the * "System.Windows.Forms.Application" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Windows.Forms { using Microsoft.Win32; using System.Globalization; using System.Threading; using System.Reflection; using System.IO; using System.Drawing.Toolkit; #if CONFIG_FRAMEWORK_2_0 && !CONFIG_COMPACT_FORMS using System.Windows.Forms.VisualStyles; #endif // CONFIG_FRAMEWORK_2_0 && !CONFIG_COMPACT_FORMS public sealed class Application { // Internal state. private static Request requests; private static Request lastRequest; // Cannot instantiate this class. private Application() {} #if !CONFIG_COMPACT_FORMS // Internal state. [ThreadStatic] private static InputLanguage inputLanguage; private static String safeTopLevelCaptionFormat = "{0}"; #if CONFIG_FRAMEWORK_2_0 // The application wide default for the UseCompatibleTextRendering. internal static bool useCompatibleTextRendering = true; // The last value to which the UseWaitCursor of this application was set. private static bool useWaitCursor = false; // The application wide unhandled exception mode. internal static UnhandledExceptionMode unhandledExceptionMode = UnhandledExceptionMode.Automatic; // The application wide visual style state. internal static VisualStyleState visualStyleState = VisualStyleState.ClientAndNonClientAreasEnabled; #endif // CONFIG_FRAMEWORK_2_0 // Determine if it is possible to quit this application. public static bool AllowQuit { get { // Returns false for applet usage, which we don't have yet. return true; } } #if CONFIG_WIN32_SPECIFICS // Get a registry key for a data path. private static RegistryKey GetAppDataRegistry(RegistryKey hive) { String key = "Software\\" + CompanyName + "\\" + ProductName + "\\" + ProductVersion; return hive.CreateSubKey(key); } // Get the common registry key for data shared between all users. public static RegistryKey CommonAppDataRegistry { get { return GetAppDataRegistry(Registry.LocalMachine); } } #endif #if !ECMA_COMPAT // Get a data path based on a special folder name. private static String GetAppDataPath(Environment.SpecialFolder folder) { String path = Environment.GetFolderPath(folder); path += Path.DirectorySeparatorChar.ToString() + CompanyName + Path.DirectorySeparatorChar.ToString() + ProductName + Path.DirectorySeparatorChar.ToString() + ProductVersion; if(!Directory.Exists(path)) { Directory.CreateDirectory(path); } return path; } // Get the common data path for data shared between all users. public static String CommonAppDataPath { get { return GetAppDataPath (Environment.SpecialFolder.CommonApplicationData); } } // Get the local user application data path. public static String LocalUserAppDataPath { get { return GetAppDataPath (Environment.SpecialFolder.LocalApplicationData); } } // Get the user application data path. public static String UserAppDataPath { get { return GetAppDataPath (Environment.SpecialFolder.ApplicationData); } } // Get the company name for this application public static String CompanyName { get { Assembly assembly = Assembly.GetEntryAssembly(); Object[] attrs = assembly.GetCustomAttributes (typeof(AssemblyCompanyAttribute), false); if(attrs != null && attrs.Length > 0) { return ((AssemblyCompanyAttribute)(attrs[0])).Company; } return assembly.GetName().Name; } } // Get the product name associated with this application. public static String ProductName { get { Assembly assembly = Assembly.GetEntryAssembly(); Object[] attrs = assembly.GetCustomAttributes (typeof(AssemblyProductAttribute), false); if(attrs != null && attrs.Length > 0) { return ((AssemblyProductAttribute)(attrs[0])).Product; } return assembly.GetName().Name; } } // Get the product version associated with this application. public static String ProductVersion { get { Assembly assembly = Assembly.GetEntryAssembly(); Object[] attrs = assembly.GetCustomAttributes (typeof(AssemblyInformationalVersionAttribute), false); if(attrs != null && attrs.Length > 0) { return ((AssemblyInformationalVersionAttribute) (attrs[0])).InformationalVersion; } return assembly.GetName().Version.ToString(); } } #endif // !ECMA_COMPAT // Get or set the culture for the current thread. public static CultureInfo CurrentCulture { get { return CultureInfo.CurrentCulture; } set { #if !ECMA_COMPAT Thread.CurrentThread.CurrentCulture = value; #endif } } // Get or set the input language for the current thread. public static InputLanguage CurrentInputLanguage { get { return inputLanguage; } set { inputLanguage = value; } } // Get the executable path for this application. public static String ExecutablePath { get { return (Environment.GetCommandLineArgs())[0]; } } // Determine if a message loop exists on this thread. public static bool MessageLoop { get { return true; } } // Get or set the top-level warning caption format. public static String SafeTopLevelCaptionFormat { get { return safeTopLevelCaptionFormat; } set { safeTopLevelCaptionFormat = value; } } // Get the startup path for the executable. public static String StartupPath { get { return Path.GetDirectoryName(ExecutablePath); } } #if CONFIG_WIN32_SPECIFICS // Get the registry key for user-specific data. public static RegistryKey UserAppDataRegistry { get { return GetAppDataRegistry(Registry.CurrentUser); } } #endif // Add a message filter. public static void AddMessageFilter(IMessageFilter value) { // We don't use message filters in this implementation. } // Enable Windows XP visual styles. public static void EnableVisualStyles() { // Not used in this implementation. } // Exit the message loop on the current thread and close all windows. public static void ExitThread() { // We only allow one message loop in this implementation, // so "ExitThread" is the same as "Exit". Exit(); } #if !ECMA_COMPAT // Initialize OLE on the current thread. public static ApartmentState OleRequired() { // Not used in this implementation. return ApartmentState.Unknown; } #endif // Raise the thread exception event. public static void OnThreadException(Exception t) { if(ThreadException != null) { ThreadException(null, new ThreadExceptionEventArgs(t)); } } // Remove a message filter. public static void RemoveMessageFilter(IMessageFilter value) { // We don't use message filters in this implementation. } #if CONFIG_FRAMEWORK_2_0 // Run any filters for the message. // Returns true if filters processed the message and false otherwise [TODO] public static bool FilterMessage(Message message) { return false; } // Get a read only collection of all currently open forms in this application. [TODO] public static FormCollection OpenForms { get { return null; } } // Raise the Idle event public static void RaiseIdle(EventArgs e) { if(Idle != null) { Idle(null, e); } } // Register a callback to for checking if messages are still processed. // The MessageLoop property will return false if SWF is not processing messages. [TODO] public static void RegisterMessageLoop(MessageLoopCallback callback) { } public static bool RenderWithVisualStyles { get { // No visual styles are used. return false; } } // Shut down and restart the application. // Throws a NotSupportedException if it's no SWF application. [TODO] public static void Restart() { throw new NotSupportedException(); } // Suspend or hibernate the system or requests the system to do so. // if force is true the system will be suspended immediately otherwise // a suspend request is sent to every app. // If disableWakeEvent is true the power state will not be restored on a // wake event. // Returns true if the system is being suspended, otherwise false. [TODO] public static bool SetSuspendState(PowerState state, bool force, bool disableWakeEvent) { return false; } // Instruct the application how to handle unhandled exceptions. // This function must be called before the first window is created // otherwise an InvalidOperationException will be thrown. [TODO] public static void SetUnhandledExceptionMode(UnhandledExceptionMode mode) { unhandledExceptionMode = mode; } // Instruct the application how to handle unhandled exceptions. // This version allows the mode to be set thread specific. // This function must be called before the first window is created // otherwise an InvalidOperationException will be thrown. [TODO] public static void SetUnhandledExceptionMode(UnhandledExceptionMode mode, bool threadScope) { if(!threadScope) { unhandledExceptionMode = mode; } } // Set the application wide default for the UseCompatibleTextRendering. // This function must be called before the first window is created // otherwise an InvalidOperationException will be thrown. [TODO] public static void SetCompatibleTextRenderingDefault(bool defaultValue) { useCompatibleTextRendering = defaultValue; } // Set or reset the UseWaitCursor for all windows in this application. [TODO] public static bool UseWaitCursor { get { return useWaitCursor; } set { if(useWaitCursor != value) { // TODO // Apply the property change to all open windows useWaitCursor = value; } } } // Get or set the visual style state used. public static VisualStyleState VisualStyleState { get { return visualStyleState; } set { visualStyleState = value; } } // Event that occurs when the application is about to enter a modal state. public static event EventHandler EnterThreadModal; // Event that occurs when the application is about to leave a modal state. public static event EventHandler LeaveThreadModal; #endif // CONFIG_FRAMEWORK_2_0 // Event that is raised when the application is about to exit. public static event EventHandler ApplicationExit; // Event that is raised when the message loop is entering the idle state. public static event EventHandler Idle; // Event that is raised for an untrapped thread exception. public static event ThreadExceptionEventHandler ThreadException; // Event that is raised when the current thread is about to exit. public static event EventHandler ThreadExit; #endif // !CONFIG_COMPACT_FORMS // The thread that is running the main message loop. private static Thread mainThread; // Process all events that are currently in the message queue. public static void DoEvents() { bool isMainThread; Thread thread = Thread.CurrentThread; Request request; // Determine if we are the main thread. lock(typeof(Application)) { isMainThread = (mainThread == thread); } // Process pending events. if(isMainThread) { ToolkitManager.Toolkit.ProcessEvents(false); } // Process requests that were sent via "SendRequest". while((request = NextRequest(thread, false)) != null) { request.Execute(); } } // Tell the application to exit. public static void Exit() { lock(typeof(Application)) { if(mainThread != null || Thread.CurrentThread == null) { ToolkitManager.Toolkit.Quit(); } } } // Exit from the current thread when the main form closes. private static void ContextExit(Object sender, EventArgs e) { #if !CONFIG_COMPACT_FORMS ExitThread(); #else Exit(); #endif } // Inner version of "Run". In this implementation we only allow a // message loop to be running on one of the threads. private static void RunMessageLoop(ApplicationContext context) { Form mainForm = context.MainForm; EventHandler handler; Request request; Thread thread = Thread.CurrentThread; bool isMainThread; // Connect the context's ThreadExit event to our "ExitThread". handler = new EventHandler(ContextExit); context.ThreadExit += handler; // Show the main form on-screen. if(mainForm != null) { mainForm.Show(); mainForm.SelectNextControl (null, true, true, true, false); Form.activeForm = mainForm; } // Make sure that we are the only message loop. lock(typeof(Application)) { if(mainThread != null) { isMainThread = false; } else { mainThread = thread; isMainThread = true; } } // Run the main message processing loop. if(isMainThread) { IToolkit toolkit = ToolkitManager.Toolkit; try { for(;;) { try { // Process events in the queue. if(!toolkit.ProcessEvents(false)) { #if !CONFIG_COMPACT_FORMS // There were no events, so raise "Idle". if(Idle != null) { Idle(null, EventArgs.Empty); } #endif // Block until an event, or quit, arrives. if(!toolkit.ProcessEvents(true)) { break; } } // Process requests sent via "SendRequest". while((request = NextRequest(thread, false)) != null) { request.Execute(); } } catch( Exception e ) { Application.OnThreadException( e ); } } } finally { // Reset the "mainThread" variable because there // is no message loop any more. lock(typeof(Application)) { mainThread = null; } } } else { // This is not the main thread, so only process // requests that were sent via "SendRequest". while((request = NextRequest(thread, true)) != null) { request.Execute(); } } // Disconnect from the context's "ThreadExit" event. context.ThreadExit -= handler; Form.activeForm = null; #if !CONFIG_COMPACT_FORMS // Raise the "ThreadExit" event. if(ThreadExit != null) { ThreadExit(null, EventArgs.Empty); } // Raise the "ApplicationExit" event. if(ApplicationExit != null) { ApplicationExit(null, EventArgs.Empty); } #endif } // Run an inner message loop until the dialog result is set on a form. internal static void InnerMessageLoop(Form form) { Request request; Thread thread = Thread.CurrentThread; bool isMainThread; bool resetMainThread; // Determine if we are running on the main thread or not. lock(typeof(Application)) { if(mainThread == null) { // The main message loop hasn't started yet. // This might happen with MessageBox dialogs. mainThread = thread; isMainThread = true; resetMainThread = true; } else { isMainThread = (mainThread == thread); resetMainThread = false; } } // Run the main message processing loop. if(isMainThread) { IToolkit toolkit = ToolkitManager.Toolkit; try { while(!(form.dialogResultIsSet) && form.Visible) { // Process events in the queue. if(!toolkit.ProcessEvents(false)) { #if !CONFIG_COMPACT_FORMS // There were no events, so raise "Idle". if(Idle != null) { Idle(null, EventArgs.Empty); } #endif // Block until an event, or quit, arrives. if(!toolkit.ProcessEvents(true)) { break; } } // Process requests sent via "SendRequest". while((request = NextRequest(thread, false)) != null) { request.Execute(); } } } finally { // Reset the "mainThread" variable because there // is no message loop any more. lock(typeof(Application)) { if(resetMainThread) { mainThread = null; } } } } else { // This is not the main thread, so only process // requests that were sent via "SendRequest". while(!(form.dialogResultIsSet) && form.Visible) { if((request = NextRequest(thread, true)) != null) { request.Execute(); } else { break; } } } } // Make the specified form visible and run the main loop. // The loop will exit when "Exit" is called. public static void Run(Form mainForm) { RunMessageLoop(new ApplicationContext(mainForm)); } #if !CONFIG_COMPACT_FORMS // Run the main message loop on this thread. public static void Run() { RunMessageLoop(new ApplicationContext()); } // Run the main message loop for an application context. public static void Run(ApplicationContext context) { if(context == null) { context = new ApplicationContext(); } RunMessageLoop(context); } #endif // !CONFIG_COMPACT_FORMS // Information about a request to be executed in a specific thread. // This is used to help implement the "Control.Invoke" method. internal abstract class Request { public Request next; public Thread thread; // Execute the request. public abstract void Execute(); }; // class Request // Send a request to a particular thread's message queue. internal static void SendRequest(Request request, Thread thread) { Object obj = typeof(Application); request.thread = thread; lock(obj) { // Add the request to the queue. request.next = null; if(requests != null) { lastRequest.next = request; } else { requests = request; } lastRequest = request; // Wake up all threads that are blocking in "NextRequest". Monitor.PulseAll(obj); // Wake up the thread that will receive the request, // as it may be blocking inside "ProcessEvents". ToolkitManager.Toolkit.Wakeup(thread); } } // Get the next pending request for a particular thread. private static Request NextRequest(Thread thread, bool block) { Object obj = typeof(Application); Request request, prev; lock(obj) { for(;;) { // See if there is a request on the queue for us. prev = null; request = requests; while(request != null) { if(request.thread == thread) { if(prev != null) { prev.next = request.next; } else { requests = request.next; } if(request.next == null) { lastRequest = prev; } else { request.next = null; } break; } prev = request; request = request.next; } // Bail out if we got something or we aren't blocking. if(request != null || !block) { break; } // Wait to be signalled by "SendRequest". Monitor.Wait(obj); } } return request; } }; // class Application }; // namespace System.Windows.Forms
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // 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 PdfSharp.Internal; #if GDI using System.Drawing; using System.Drawing.Drawing2D; using GdiPen = System.Drawing.Pen; #endif #if WPF using System.Windows; using System.Windows.Media; using WpfPen =System.Windows.Media.Pen; using WpfBrush =System.Windows.Media.Brush; #endif #if UWP #endif namespace PdfSharp.Drawing { // TODO Free GDI objects (pens, brushes, ...) automatically without IDisposable. /// <summary> /// Defines an object used to draw lines and curves. /// </summary> public sealed class XPen { /// <summary> /// Initializes a new instance of the <see cref="XPen"/> class. /// </summary> public XPen(XColor color) : this(color, 1, false) { } /// <summary> /// Initializes a new instance of the <see cref="XPen"/> class. /// </summary> public XPen(XColor color, double width) : this(color, width, false) { } internal XPen(XColor color, double width, bool immutable) { _color = color; _width = width; _lineJoin = XLineJoin.Miter; _lineCap = XLineCap.Flat; _dashStyle = XDashStyle.Solid; _dashOffset = 0f; _immutable = immutable; } /// <summary> /// Initializes a new instance of the <see cref="XPen"/> class. /// </summary> public XPen(XPen pen) { _color = pen._color; _width = pen._width; _lineJoin = pen._lineJoin; _lineCap = pen._lineCap; _dashStyle = pen._dashStyle; _dashOffset = pen._dashOffset; _dashPattern = pen._dashPattern; if (_dashPattern != null) _dashPattern = (double[])_dashPattern.Clone(); } /// <summary> /// Clones this instance. /// </summary> public XPen Clone() { return new XPen(this); } /// <summary> /// Gets or sets the color. /// </summary> public XColor Color { get { return _color; } set { if (_immutable) throw new ArgumentException(PSSR.CannotChangeImmutableObject("XPen")); _dirty = _dirty || _color != value; _color = value; } } internal XColor _color; /// <summary> /// Gets or sets the width. /// </summary> public double Width { get { return _width; } set { if (_immutable) throw new ArgumentException(PSSR.CannotChangeImmutableObject("XPen")); _dirty = _dirty || _width != value; _width = value; } } internal double _width; /// <summary> /// Gets or sets the line join. /// </summary> public XLineJoin LineJoin { get { return _lineJoin; } set { if (_immutable) throw new ArgumentException(PSSR.CannotChangeImmutableObject("XPen")); _dirty = _dirty || _lineJoin != value; _lineJoin = value; } } internal XLineJoin _lineJoin; /// <summary> /// Gets or sets the line cap. /// </summary> public XLineCap LineCap { get { return _lineCap; } set { if (_immutable) throw new ArgumentException(PSSR.CannotChangeImmutableObject("XPen")); _dirty = _dirty || _lineCap != value; _lineCap = value; } } internal XLineCap _lineCap; /// <summary> /// Gets or sets the miter limit. /// </summary> public double MiterLimit { get { return _miterLimit; } set { if (_immutable) throw new ArgumentException(PSSR.CannotChangeImmutableObject("XPen")); _dirty = _dirty || _miterLimit != value; _miterLimit = value; } } internal double _miterLimit; /// <summary> /// Gets or sets the dash style. /// </summary> public XDashStyle DashStyle { get { return _dashStyle; } set { if (_immutable) throw new ArgumentException(PSSR.CannotChangeImmutableObject("XPen")); _dirty = _dirty || _dashStyle != value; _dashStyle = value; } } internal XDashStyle _dashStyle; /// <summary> /// Gets or sets the dash offset. /// </summary> public double DashOffset { get { return _dashOffset; } set { if (_immutable) throw new ArgumentException(PSSR.CannotChangeImmutableObject("XPen")); _dirty = _dirty || _dashOffset != value; _dashOffset = value; } } internal double _dashOffset; /// <summary> /// Gets or sets the dash pattern. /// </summary> public double[] DashPattern { get { if (_dashPattern == null) _dashPattern = new double[0]; return _dashPattern; } set { if (_immutable) throw new ArgumentException(PSSR.CannotChangeImmutableObject("XPen")); int length = value.Length; //if (length == 0) // throw new ArgumentException("Dash pattern array must not be empty."); for (int idx = 0; idx < length; idx++) { if (value[idx] <= 0) throw new ArgumentException("Dash pattern value must greater than zero."); } _dirty = true; _dashStyle = XDashStyle.Custom; _dashPattern = (double[])value.Clone(); } } internal double[] _dashPattern; /// <summary> /// Gets or sets a value indicating whether the pen enables overprint when used in a PDF document. /// Experimental, takes effect only on CMYK color mode. /// </summary> public bool Overprint { get { return _overprint; } set { if (_immutable) throw new ArgumentException(PSSR.CannotChangeImmutableObject("XPen")); _overprint = value; } } internal bool _overprint; #if GDI #if UseGdiObjects /// <summary> /// Implicit conversion from Pen to XPen /// </summary> public static implicit operator XPen(Pen pen) { XPen xpen; try { Lock.EnterGdiPlus(); switch (pen.PenType) { case PenType.SolidColor: xpen = new XPen(pen.Color, pen.Width); xpen.LineJoin = (XLineJoin)pen.LineJoin; xpen.DashStyle = (XDashStyle)pen.DashStyle; xpen._miterLimit = pen.MiterLimit; break; default: throw new NotImplementedException("Pen type not supported by PDFsharp."); } // Bug fixed by drice2@ageone.de if (pen.DashStyle == System.Drawing.Drawing2D.DashStyle.Custom) { int length = pen.DashPattern.Length; double[] pattern = new double[length]; for (int idx = 0; idx < length; idx++) pattern[idx] = pen.DashPattern[idx]; xpen.DashPattern = pattern; xpen._dashOffset = pen.DashOffset; } } finally { Lock.ExitGdiPlus(); } return xpen; } #endif internal System.Drawing.Pen RealizeGdiPen() { if (_dirty) { if (_gdiPen == null) _gdiPen = new System.Drawing.Pen(_color.ToGdiColor(), (float)_width); else { _gdiPen.Color = _color.ToGdiColor(); _gdiPen.Width = (float)_width; } LineCap lineCap = XConvert.ToLineCap(_lineCap); _gdiPen.StartCap = lineCap; _gdiPen.EndCap = lineCap; _gdiPen.LineJoin = XConvert.ToLineJoin(_lineJoin); _gdiPen.DashOffset = (float)_dashOffset; if (_dashStyle == XDashStyle.Custom) { int len = _dashPattern == null ? 0 : _dashPattern.Length; float[] pattern = new float[len]; for (int idx = 0; idx < len; idx++) pattern[idx] = (float)_dashPattern[idx]; _gdiPen.DashPattern = pattern; } else _gdiPen.DashStyle = (System.Drawing.Drawing2D.DashStyle)_dashStyle; } return _gdiPen; } #endif #if WPF internal WpfPen RealizeWpfPen() { #if !SILVERLIGHT if (_dirty || !_dirty) // TODOWPF: XPen is frozen by design, WPF Pen can change { //if (_wpfPen == null) _wpfPen = new WpfPen(new SolidColorBrush(_color.ToWpfColor()), _width); //else //{ // _wpfPen.Brush = new SolidColorBrush(_color.ToWpfColor()); // _wpfPen.Thickness = _width; //} PenLineCap lineCap = XConvert.ToPenLineCap(_lineCap); _wpfPen.StartLineCap = lineCap; _wpfPen.EndLineCap = lineCap; _wpfPen.LineJoin = XConvert.ToPenLineJoin(_lineJoin); if (_dashStyle == XDashStyle.Custom) { // TODOWPF: does not work in all cases _wpfPen.DashStyle = new System.Windows.Media.DashStyle(_dashPattern, _dashOffset); } else { switch (_dashStyle) { case XDashStyle.Solid: _wpfPen.DashStyle = DashStyles.Solid; break; case XDashStyle.Dash: //_wpfPen.DashStyle = DashStyles.Dash; _wpfPen.DashStyle = new System.Windows.Media.DashStyle(new double[] { 2, 2 }, 0); break; case XDashStyle.Dot: //_wpfPen.DashStyle = DashStyles.Dot; _wpfPen.DashStyle = new System.Windows.Media.DashStyle(new double[] { 0, 2 }, 1.5); break; case XDashStyle.DashDot: //_wpfPen.DashStyle = DashStyles.DashDot; _wpfPen.DashStyle = new System.Windows.Media.DashStyle(new double[] { 2, 2, 0, 2 }, 0); break; case XDashStyle.DashDotDot: //_wpfPen.DashStyle = DashStyles.DashDotDot; _wpfPen.DashStyle = new System.Windows.Media.DashStyle(new double[] { 2, 2, 0, 2, 0, 2 }, 0); break; } } } #else _wpfPen = new System.Windows.Media.Pen(); _wpfPen.Brush = new SolidColorBrush(_color.ToWpfColor()); _wpfPen.Thickness = _width; #endif return _wpfPen; } #endif bool _dirty = true; readonly bool _immutable; #if GDI GdiPen _gdiPen; #endif #if WPF WpfPen _wpfPen; #endif } }
using System; using System.Collections.Generic; using System.Xml.Linq; using De.Osthus.Ambeth.Collections; using De.Osthus.Ambeth.Config; using De.Osthus.Ambeth.Ioc.Annotation; using De.Osthus.Ambeth.Log; using De.Osthus.Ambeth.Merge; using De.Osthus.Ambeth.Util; using De.Osthus.Ambeth.Util.Xml; namespace De.Osthus.Ambeth.Orm { public class OrmXmlReaderLegathy : IOrmXmlReader { [LogInstance] public ILogger Log { private get; set; } [Property(ServiceConfigurationConstants.IndependentMetaData, DefaultValue = "false")] public virtual bool IndependentMetaData { protected get; set; } [Autowired] public IProxyHelper ProxyHelper { protected get; set; } [Autowired] public IXmlConfigUtil XmlConfigUtil { protected get; set; } public ISet<IEntityConfig> LoadFromDocument(XDocument doc) { ISet<IEntityConfig> entities = new CHashSet<IEntityConfig>(); LoadFromDocument(doc, entities, entities); return entities; } public void LoadFromDocument(XDocument doc, ISet<IEntityConfig> localEntities, ISet<IEntityConfig> externalEntities) { List<XElement> entityNodes = new List<XElement>(); IMap<String,IList<XElement>> childrenMap = XmlConfigUtil.ChildrenToElementMap(doc.Root); if (childrenMap.ContainsKey(XmlConstants.ENTITY.LocalName)) { entityNodes.AddRange(childrenMap.Get(XmlConstants.ENTITY.LocalName)); } for (int i = entityNodes.Count; i-- > 0; ) { XElement entityNode = entityNodes[i]; EntityConfig entityConfig = ReadEntityConfig(entityNode); if (localEntities.Contains(entityConfig) || externalEntities.Contains(entityConfig)) { throw new Exception("Duplicate orm configuration for entity '" + entityConfig.EntityType.Name + "'"); } if (entityConfig.Local) { localEntities.Add(entityConfig); } else { externalEntities.Add(entityConfig); } } } protected EntityConfig ReadEntityConfig(XElement entityTag) { String entityTypeName = XmlConfigUtil.GetRequiredAttribute(entityTag, XmlConstants.CLASS); try { Type entityType = XmlConfigUtil.GetTypeForName(entityTypeName); Type realType = ProxyHelper.GetRealType(entityType); EntityConfig entityConfig = new EntityConfig(entityType, realType); bool localEntity = !XmlConfigUtil.GetAttribute(entityTag, XmlConstants.TYPE).Equals(XmlConstants.EXTERN.LocalName); entityConfig.Local = localEntity; IMap<String, IList<XElement>> attributeMap = null; IMap<String, IList<XElement>> entityDefs = XmlConfigUtil.ChildrenToElementMap(entityTag); if (entityDefs.ContainsKey(XmlConstants.TABLE.LocalName)) { String specifiedTableName = XmlConfigUtil.GetRequiredAttribute(entityDefs.Get(XmlConstants.TABLE.LocalName)[0], XmlConstants.NAME); entityConfig.TableName = specifiedTableName; } if (entityDefs.ContainsKey(XmlConstants.PERMISSION_GROUP.LocalName)) { String permissionGroupName = XmlConfigUtil.GetRequiredAttribute(entityDefs.Get(XmlConstants.PERMISSION_GROUP.LocalName)[0], XmlConstants.NAME); entityConfig.PermissionGroupName = permissionGroupName; } if (entityDefs.ContainsKey(XmlConstants.SEQ.LocalName)) { String sequenceName = XmlConfigUtil.GetRequiredAttribute(entityDefs.Get(XmlConstants.SEQ.LocalName)[0], XmlConstants.NAME); entityConfig.SequenceName = sequenceName; } if (entityDefs.ContainsKey(XmlConstants.ATTR.LocalName)) { attributeMap = XmlConfigUtil.ChildrenToElementMap(entityDefs.Get(XmlConstants.ATTR.LocalName)[0]); } bool versionRequired = true; if (attributeMap != null) { if (attributeMap.ContainsKey(XmlConstants.ID.LocalName)) { XElement idElement = attributeMap.Get(XmlConstants.ID.LocalName)[0]; MemberConfig idMemberConfig = ReadMemberConfig(idElement); entityConfig.IdMemberConfig = idMemberConfig; } else if (!localEntity) { throw new Exception("ID member name has to be set on external entities"); } if (attributeMap.ContainsKey(XmlConstants.VERSION.LocalName)) { XElement versionElement = attributeMap.Get(XmlConstants.VERSION.LocalName)[0]; versionRequired = XmlConfigUtil.AttributeIsTrue(versionElement, XmlConstants.WITHOUT); if (versionRequired) { MemberConfig versionMemberConfig = ReadMemberConfig(versionElement); entityConfig.VersionMemberConfig = versionMemberConfig; } } else if (!localEntity) { throw new Exception("Version member name has to be set on external entities"); } if (attributeMap.ContainsKey(XmlConstants.BASIC.LocalName)) { IList<XElement> basicAttrs = attributeMap.Get(XmlConstants.BASIC.LocalName); for (int j = basicAttrs.Count; j-- > 0; ) { XElement memberElement = basicAttrs[j]; MemberConfig memberConfig = ReadMemberConfig(memberElement); entityConfig.AddMemberConfig(memberConfig); } } if (attributeMap.ContainsKey(XmlConstants.TO_ONE.LocalName)) { IList<XElement> toOneAttrs = attributeMap.Get(XmlConstants.TO_ONE.LocalName); for (int j = toOneAttrs.Count; j-- > 0; ) { XElement toOneElement = toOneAttrs[j]; RelationConfigLegathy relationConfig = ReadRelationConfig(toOneElement, localEntity, true); entityConfig.AddRelationConfig(relationConfig); } } if (attributeMap.ContainsKey(XmlConstants.TO_MANY.LocalName)) { IList<XElement> toManyAttrs = attributeMap.Get(XmlConstants.TO_MANY.LocalName); for (int j = toManyAttrs.Count; j-- > 0; ) { XElement toManyElement = toManyAttrs[j]; RelationConfigLegathy relationConfig = ReadRelationConfig(toManyElement, localEntity, false); entityConfig.AddRelationConfig(relationConfig); } } if (attributeMap.ContainsKey(XmlConstants.IGNORE.LocalName)) { IList<XElement> ignoreAttrs = attributeMap.Get(XmlConstants.IGNORE.LocalName); for (int j = ignoreAttrs.Count; j-- > 0; ) { XElement ignoreElement = ignoreAttrs[j]; MemberConfig memberConfig = ReadMemberConfig(ignoreElement); memberConfig.Ignore = true; entityConfig.AddMemberConfig(memberConfig); } } } entityConfig.VersionRequired = versionRequired; return entityConfig; } catch (Exception e) { throw new Exception("Error occured while processing mapping for entity: " + entityTypeName, e); } } protected MemberConfig ReadMemberConfig(XElement memberElement) { String memberName = XmlConfigUtil.GetRequiredAttribute(memberElement, XmlConstants.NAME, true); String columnName = null; XElement columnElement = XmlConfigUtil.GetChildUnique(memberElement, XmlConstants.COLUMN); if (columnElement != null) { columnName = XmlConfigUtil.GetRequiredAttribute(columnElement, XmlConstants.NAME); } MemberConfig memberConfig = new MemberConfig(memberName, columnName); bool alternateId = XmlConfigUtil.AttributeIsTrue(memberElement, XmlConstants.ALT_ID); memberConfig.AlternateId = alternateId; return memberConfig; } protected RelationConfigLegathy ReadRelationConfig(XElement relationElement, bool localEntity, bool toOne) { String relationName = XmlConfigUtil.GetRequiredAttribute(relationElement, XmlConstants.NAME, true); try { RelationConfigLegathy relationConfig = new RelationConfigLegathy(relationName, toOne); String linkedEntityName = XmlConfigUtil.GetRequiredAttribute(relationElement, XmlConstants.TARGET_ENTITY); Type linkedEntityType = XmlConfigUtil.GetTypeForName(linkedEntityName); relationConfig.LinkedEntityType = linkedEntityType; bool doDelete = XmlConfigUtil.AttributeIsTrue(relationElement, XmlConstants.DO_DELETE); relationConfig.DoDelete = doDelete; bool mayDelete = XmlConfigUtil.AttributeIsTrue(relationElement, XmlConstants.MAY_DELETE); relationConfig.MayDelete = mayDelete; if (localEntity) { XElement joinTableTag = XmlConfigUtil.GetChildUnique(relationElement, XmlConstants.JOIN_TABLE); if (joinTableTag == null) { String constraintName = XmlConfigUtil.GetAttribute(relationElement, XmlConstants.CONSTRAINT_NAME); if (constraintName.Length == 0 && !IndependentMetaData) { throw new ArgumentException("Either nested element '" + XmlConstants.JOIN_TABLE + "' or attribute '" + XmlConstants.CONSTRAINT_NAME + "' required to map link"); } relationConfig.ConstraintName = constraintName; } else { String joinTableName = XmlConfigUtil.GetRequiredAttribute(joinTableTag, XmlConstants.NAME); relationConfig.JoinTableName = joinTableName; String fromFieldName = XmlConfigUtil.GetChildElementAttribute(joinTableTag, XmlConstants.JOIN_COLUMN, XmlConstants.NAME, "Join column name has to be set exactly once"); relationConfig.FromFieldName = fromFieldName; String toFieldName = XmlConfigUtil.GetChildElementAttribute(joinTableTag, XmlConstants.INV_JOIN_COLUMN, XmlConstants.NAME, null); relationConfig.ToFieldName = toFieldName; String toAttributeName = XmlConfigUtil.GetChildElementAttribute(joinTableTag, XmlConstants.INV_JOIN_ATTR, XmlConstants.NAME, null); toAttributeName = StringConversionHelper.UpperCaseFirst(toAttributeName); relationConfig.ToAttributeName = toAttributeName; if (toFieldName == null && toAttributeName == null) { throw new ArgumentException("Inverse join column or attribute name has to be set"); } } } return relationConfig; } catch (Exception e) { throw new Exception("Error occured while processing relation '" + relationName + "'", e); } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // 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 Jaroslaw Kowalski 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. // namespace NLog.UnitTests.Config { using System; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.IO; using MyExtensionNamespace; using NLog.Common; using NLog.Config; using NLog.Filters; using NLog.Layouts; using NLog.Targets; using Xunit; public class ExtensionTests : NLogTestBase { private string extensionAssemblyName1 = "SampleExtensions"; private string extensionAssemblyFullPath1 = Path.GetFullPath("SampleExtensions.dll"); private string GetExtensionAssemblyFullPath() { #if NETSTANDARD Assert.NotNull(typeof(FooLayout)); return typeof(FooLayout).GetTypeInfo().Assembly.Location; #else return extensionAssemblyFullPath1; #endif } [Fact] public void ExtensionTest1() { Assert.NotNull(typeof(FooLayout)); var configuration = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add assemblyFile='" + GetExtensionAssemblyFullPath() + @"' /> </extensions> <targets> <target name='t' type='MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Ignore' /> </filters> </logger> </rules> </nlog>").LogFactory.Configuration; Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(1, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); } [Fact] public void ExtensionTest2() { var configuration = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add assembly='" + extensionAssemblyName1 + @"' /> </extensions> <targets> <target name='t' type='MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Ignore' /> <when condition='myrandom(10)==3' action='Log' /> </filters> </logger> </rules> </nlog>").LogFactory.Configuration; Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(2, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); var cbf = configuration.LoggingRules[0].Filters[1] as ConditionBasedFilter; Assert.NotNull(cbf); Assert.Equal("(myrandom(10) == 3)", cbf.Condition.ToString()); } [Fact] public void ExtensionWithPrefixTest() { var configuration = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add prefix='myprefix' assemblyFile='" + GetExtensionAssemblyFullPath() + @"' /> </extensions> <targets> <target name='t' type='myprefix.MyTarget' /> <target name='d1' type='Debug' layout='${myprefix.foo}' /> <target name='d2' type='Debug'> <layout type='myprefix.FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <myprefix.whenFoo x='44' action='Ignore' /> </filters> </logger> </rules> </nlog>").LogFactory.Configuration; Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(1, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); } [Fact] public void ExtensionTest4() { Assert.NotNull(typeof(FooLayout)); var configuration = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' /> <add type='" + typeof(FooLayout).AssemblyQualifiedName + @"' /> <add type='" + typeof(FooLayoutRenderer).AssemblyQualifiedName + @"' /> <add type='" + typeof(WhenFooFilter).AssemblyQualifiedName + @"' /> </extensions> <targets> <target name='t' type='MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Ignore' /> </filters> </logger> </rules> </nlog>").LogFactory.Configuration; Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(1, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); } [Fact] public void ExtensionTest_extensions_not_top_and_used() { Assert.NotNull(typeof(FooLayout)); var configuration = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='t' type='MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Ignore' /> </filters> </logger> </rules> <extensions> <add assemblyFile='" + GetExtensionAssemblyFullPath() + @"' /> </extensions> </nlog>").LogFactory.Configuration; Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(1, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); } [Fact] public void ExtensionShouldThrowNLogConfiguratonExceptionWhenRegisteringInvalidType() { var configXml = @" <nlog throwConfigExceptions='true'> <extensions> <add type='some_type_that_doesnt_exist'/> </extensions> </nlog>"; Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configXml)); } [Fact] public void ExtensionShouldThrowNLogConfiguratonExceptionWhenRegisteringInvalidAssembly() { var configXml = @" <nlog throwConfigExceptions='true'> <extensions> <add assembly='some_assembly_that_doesnt_exist'/> </extensions> </nlog>"; Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configXml)); } [Fact] public void ExtensionShouldThrowNLogConfiguratonExceptionWhenRegisteringInvalidAssemblyFile() { var configXml = @" <nlog throwConfigExceptions='true'> <extensions> <add assemblyfile='some_file_that_doesnt_exist'/> </extensions> </nlog>"; Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configXml)); } [Fact] public void ExtensionShouldNotThrowWhenRegisteringInvalidTypeIfThrowConfigExceptionsFalse() { var configXml = @" <nlog throwConfigExceptions='false'> <extensions> <add type='some_type_that_doesnt_exist'/> <add assembly='NLog'/> </extensions> </nlog>"; XmlLoggingConfiguration.CreateFromXmlString(configXml); } [Fact] public void ExtensionShouldNotThrowWhenRegisteringInvalidAssemblyIfThrowConfigExceptionsFalse() { var configXml = @" <nlog throwConfigExceptions='false'> <extensions> <add assembly='some_assembly_that_doesnt_exist'/> </extensions> </nlog>"; XmlLoggingConfiguration.CreateFromXmlString(configXml); } [Fact] public void ExtensionShouldNotThrowWhenRegisteringInvalidAssemblyFileIfThrowConfigExceptionsFalse() { var configXml = @" <nlog throwConfigExceptions='false'> <extensions> <add assemblyfile='some_file_that_doesnt_exist'/> </extensions> </nlog>"; XmlLoggingConfiguration.CreateFromXmlString(configXml); } [Fact] public void CustomXmlNamespaceTest() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true' xmlns:foo='http://bar'> <targets> <target name='d' type='foo:Debug' /> </targets> </nlog>"); var d1Target = (DebugTarget)configuration.FindTargetByName("d"); Assert.NotNull(d1Target); } [Fact] public void Extension_should_be_auto_loaded_when_following_NLog_dll_format() { var fileLocations = ConfigurationItemFactory.GetAutoLoadingFileLocations().ToArray(); Assert.NotEmpty(fileLocations); Assert.NotNull(fileLocations[0].Key); Assert.NotNull(fileLocations[0].Value); // Primary search location is NLog-assembly Assert.Equal(fileLocations.Length, fileLocations.Select(f => f.Key).Distinct().Count()); var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true' autoLoadExtensions='true'> <targets> <target name='t' type='AutoLoadTarget' /> </targets> <rules> <logger name='*' writeTo='t' /> </rules> </nlog>").LogFactory; var autoLoadedTarget = logFactory.Configuration.FindTargetByName("t"); Assert.Equal("NLogAutloadExtension.AutoLoadTarget", autoLoadedTarget.GetType().ToString()); } [Fact] public void ExtensionTypeWithAssemblyNameCanLoad() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='t' type='AutoLoadTarget, NLogAutoLoadExtension' /> </targets> <rules> <logger name='*' writeTo='t' /> </rules> </nlog>").LogFactory; var autoLoadedTarget = logFactory.Configuration.FindTargetByName("t"); Assert.Equal("NLogAutloadExtension.AutoLoadTarget", autoLoadedTarget.GetType().ToString()); } [Theory] [InlineData(true)] [InlineData(false)] public void Extension_loading_could_be_canceled(bool cancel) { ConfigurationItemFactory.Default = null; EventHandler<AssemblyLoadingEventArgs> onAssemblyLoading = (sender, e) => { if (e.Assembly.FullName.Contains("NLogAutoLoadExtension")) { e.Cancel = cancel; } }; try { ConfigurationItemFactory.AssemblyLoading += onAssemblyLoading; using(new NoThrowNLogExceptions()) { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='false' autoLoadExtensions='true'> <targets> <target name='t' type='AutoLoadTarget' /> </targets> <rules> <logger name='*' writeTo='t' /> </rules> </nlog>").LogFactory; var autoLoadedTarget = logFactory.Configuration.FindTargetByName("t"); if (cancel) { Assert.Null(autoLoadedTarget); } else { Assert.Equal("NLogAutloadExtension.AutoLoadTarget", autoLoadedTarget.GetType().ToString()); } } } finally { //cleanup ConfigurationItemFactory.AssemblyLoading -= onAssemblyLoading; } } [Fact] public void Extensions_NLogPackageLoader_should_beCalled() { try { var writer = new StringWriter(); InternalLogger.LogWriter = writer; InternalLogger.LogLevel = LogLevel.Debug; var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add assembly='PackageLoaderTestAssembly' /> </extensions> </nlog>"); var logs = writer.ToString(); Assert.Contains("Preload successfully invoked for 'LoaderTestInternal.NLogPackageLoader'", logs); Assert.Contains("Preload successfully invoked for 'LoaderTestPublic.NLogPackageLoader'", logs); Assert.Contains("Preload successfully invoked for 'LoaderTestPrivateNestedStatic.SomeType+NLogPackageLoader'", logs); Assert.Contains("Preload successfully invoked for 'LoaderTestPrivateNested.SomeType+NLogPackageLoader'", logs); //4 times successful Assert.Equal(4, Regex.Matches(logs, Regex.Escape("Preload successfully invoked for '")).Count); } finally { InternalLogger.Reset(); } } [Fact] public void ImplicitConversionOperatorTest() { var config = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <extensions> <add assemblyFile='" + GetExtensionAssemblyFullPath() + @"' /> </extensions> <targets> <target name='myTarget' type='MyTarget' layout='123' /> </targets> <rules> <logger name='*' level='Debug' writeTo='myTarget' /> </rules> </nlog>"); var target = config.FindTargetByName<MyTarget>("myTarget"); Assert.NotNull(target); Assert.Equal(123, target.Layout.X); } [Fact] public void LoadExtensionFromAppDomain() { try { // ...\NLog\tests\NLog.UnitTests\bin\Debug\netcoreapp2.0\nlog.dll var nlogDirectory = new DirectoryInfo(ConfigurationItemFactory.GetAutoLoadingFileLocations().First().Key); var configurationDirectory = nlogDirectory.Parent; var testsDirectory = configurationDirectory.Parent.Parent.Parent; var manuallyLoadedAssemblyPath = Path.Combine(testsDirectory.FullName, "ManuallyLoadedExtension", "bin", configurationDirectory.Name, #if NETSTANDARD "netstandard2.0", #elif NET35 || NET40 || NET45 "net461", #else nlogDirectory.Name, #endif "ManuallyLoadedExtension.dll"); Assembly.LoadFrom(manuallyLoadedAssemblyPath); InternalLogger.LogLevel = LogLevel.Trace; var writer = new StringWriter(); InternalLogger.LogWriter = writer; var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <extensions> <add assembly='ManuallyLoadedExtension' /> </extensions> <targets> <target name='t' type='ManuallyLoadedTarget' /> </targets> </nlog>"); // We get Exception for normal Assembly-Load only in net452. #if !NETSTANDARD && !MONO var logs = writer.ToString(); Assert.Contains("Try find 'ManuallyLoadedExtension' in current domain", logs); #endif // Was AssemblyLoad successful? var autoLoadedTarget = configuration.FindTargetByName("t"); Assert.Equal("ManuallyLoadedExtension.ManuallyLoadedTarget", autoLoadedTarget.GetType().FullName); } finally { InternalLogger.Reset(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Holds the result of a diff between two trees. /// <para>Changes at the granularity of the file can be obtained through the different sub-collections <see cref="Added"/>, <see cref="Deleted"/> and <see cref="Modified"/>.</para> /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class TreeChanges : IEnumerable<TreeEntryChanges> { private readonly IDictionary<FilePath, TreeEntryChanges> changes = new Dictionary<FilePath, TreeEntryChanges>(); private readonly List<TreeEntryChanges> added = new List<TreeEntryChanges>(); private readonly List<TreeEntryChanges> deleted = new List<TreeEntryChanges>(); private readonly List<TreeEntryChanges> modified = new List<TreeEntryChanges>(); private readonly List<TreeEntryChanges> typeChanged = new List<TreeEntryChanges>(); private int linesAdded; private int linesDeleted; private readonly IDictionary<ChangeKind, Action<TreeChanges, TreeEntryChanges>> fileDispatcher = Build(); private readonly StringBuilder fullPatchBuilder = new StringBuilder(); private static readonly Comparison<TreeEntryChanges> ordinalComparer = (one, other) => string.CompareOrdinal(one.Path, other.Path); private static IDictionary<ChangeKind, Action<TreeChanges, TreeEntryChanges>> Build() { return new Dictionary<ChangeKind, Action<TreeChanges, TreeEntryChanges>> { { ChangeKind.Modified, (de, d) => de.modified.Add(d) }, { ChangeKind.Deleted, (de, d) => de.deleted.Add(d) }, { ChangeKind.Added, (de, d) => de.added.Add(d) }, { ChangeKind.TypeChanged, (de, d) => de.typeChanged.Add(d) }, }; } /// <summary> /// Needed for mocking purposes. /// </summary> protected TreeChanges() { } internal TreeChanges(DiffListSafeHandle diff) { Proxy.git_diff_print_patch(diff, PrintCallBack); added.Sort(ordinalComparer); deleted.Sort(ordinalComparer); modified.Sort(ordinalComparer); } private int PrintCallBack(GitDiffDelta delta, GitDiffRange range, GitDiffLineOrigin lineorigin, IntPtr content, UIntPtr contentlen, IntPtr payload) { string formattedoutput = Utf8Marshaler.FromNative(content, (int)contentlen); TreeEntryChanges currentChange = AddFileChange(delta, lineorigin); AddLineChange(currentChange, lineorigin); currentChange.AppendToPatch(formattedoutput); fullPatchBuilder.Append(formattedoutput); return 0; } private void AddLineChange(Changes currentChange, GitDiffLineOrigin lineOrigin) { switch (lineOrigin) { case GitDiffLineOrigin.GIT_DIFF_LINE_ADDITION: linesAdded++; currentChange.LinesAdded++; break; case GitDiffLineOrigin.GIT_DIFF_LINE_DELETION: linesDeleted++; currentChange.LinesDeleted++; break; } } private TreeEntryChanges AddFileChange(GitDiffDelta delta, GitDiffLineOrigin lineorigin) { var newFilePath = FilePathMarshaler.FromNative(delta.NewFile.Path); if (lineorigin != GitDiffLineOrigin.GIT_DIFF_LINE_FILE_HDR) return this[newFilePath]; var oldFilePath = FilePathMarshaler.FromNative(delta.OldFile.Path); var newMode = (Mode)delta.NewFile.Mode; var oldMode = (Mode)delta.OldFile.Mode; var newOid = new ObjectId(delta.NewFile.Oid); var oldOid = new ObjectId(delta.OldFile.Oid); if (delta.Status == ChangeKind.Untracked) { delta.Status = ChangeKind.Added; } var diffFile = new TreeEntryChanges(newFilePath, newMode, newOid, delta.Status, oldFilePath, oldMode, oldOid, delta.IsBinary()); fileDispatcher[delta.Status](this, diffFile); changes.Add(newFilePath, diffFile); return diffFile; } #region IEnumerable<Tag> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref = "IEnumerator{T}" /> object that can be used to iterate through the collection.</returns> public virtual IEnumerator<TreeEntryChanges> GetEnumerator() { return changes.Values.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref = "IEnumerator" /> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion /// <summary> /// Gets the <see cref = "TreeEntryChanges"/> corresponding to the specified <paramref name = "path"/>. /// </summary> public virtual TreeEntryChanges this[string path] { get { return this[(FilePath)path]; } } private TreeEntryChanges this[FilePath path] { get { TreeEntryChanges treeEntryChanges; if (changes.TryGetValue(path, out treeEntryChanges)) { return treeEntryChanges; } return null; } } /// <summary> /// List of <see cref = "TreeEntryChanges"/> that have been been added. /// </summary> public virtual IEnumerable<TreeEntryChanges> Added { get { return added; } } /// <summary> /// List of <see cref = "TreeEntryChanges"/> that have been deleted. /// </summary> public virtual IEnumerable<TreeEntryChanges> Deleted { get { return deleted; } } /// <summary> /// List of <see cref = "TreeEntryChanges"/> that have been modified. /// </summary> public virtual IEnumerable<TreeEntryChanges> Modified { get { return modified; } } /// <summary> /// List of <see cref = "TreeEntryChanges"/> which type have been changed. /// </summary> public virtual IEnumerable<TreeEntryChanges> TypeChanged { get { return typeChanged; } } /// <summary> /// The total number of lines added in this diff. /// </summary> public virtual int LinesAdded { get { return linesAdded; } } /// <summary> /// The total number of lines added in this diff. /// </summary> public virtual int LinesDeleted { get { return linesDeleted; } } /// <summary> /// The full patch file of this diff. /// </summary> public virtual string Patch { get { return fullPatchBuilder.ToString(); } } private string DebuggerDisplay { get { return string.Format(CultureInfo.InvariantCulture, "+{0} ~{2} -{1} \u00B1{3}", Added.Count(), Deleted.Count(), Modified.Count(), TypeChanged.Count()); } } } }
// 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.Runtime; using System.Runtime.InteropServices; using System.Text; namespace System.Security { // SecureString attempts to provide a defense-in-depth solution. // // On Windows, this is done with several mechanisms: // 1. keeping the data in unmanaged memory so that copies of it aren't implicitly made by the GC moving it around // 2. zero'ing out that unmanaged memory so that the string is reliably removed from memory when done with it // 3. encrypting the data while it's not being used (it's unencrypted to manipulate and use it) // // On Unix, we do 1 and 2, but we don't do 3 as there's no CryptProtectData equivalent. public sealed partial class SecureString { private UnmanagedBuffer _buffer; internal SecureString(SecureString str) { // Allocate enough space to store the provided string EnsureCapacity(str._decryptedLength); _decryptedLength = str._decryptedLength; // Copy the string into the newly allocated space if (_decryptedLength > 0) { UnmanagedBuffer.Copy(str._buffer, _buffer, (ulong)(str._decryptedLength * sizeof(char))); } } private unsafe void InitializeSecureString(char* value, int length) { // Allocate enough space to store the provided string EnsureCapacity(length); _decryptedLength = length; if (length == 0) { return; } // Copy the string into the newly allocated space byte* ptr = null; try { _buffer.AcquirePointer(ref ptr); Buffer.MemoryCopy(value, ptr, _buffer.ByteLength, (ulong)(length * sizeof(char))); } finally { if (ptr != null) { _buffer.ReleasePointer(); } } } private void DisposeCore() { if (_buffer != null && !_buffer.IsInvalid) { _buffer.Dispose(); _buffer = null; } } private void EnsureNotDisposed() { if (_buffer == null) { throw new ObjectDisposedException(GetType().Name); } } private void ClearCore() { _decryptedLength = 0; _buffer.Clear(); } private unsafe void AppendCharCore(char c) { // Make sure we have enough space for the new character, then write it at the end. EnsureCapacity(_decryptedLength + 1); _buffer.Write((ulong)(_decryptedLength * sizeof(char)), c); _decryptedLength++; } private unsafe void InsertAtCore(int index, char c) { // Make sure we have enough space for the new character, then shift all of the characters above it and insert it. EnsureCapacity(_decryptedLength + 1); byte* ptr = null; try { _buffer.AcquirePointer(ref ptr); ptr += index * sizeof(char); long bytesToShift = (_decryptedLength - index) * sizeof(char); Buffer.MemoryCopy(ptr, ptr + sizeof(char), bytesToShift, bytesToShift); *((char*)ptr) = c; ++_decryptedLength; } finally { if (ptr != null) { _buffer.ReleasePointer(); } } } private unsafe void RemoveAtCore(int index) { // Shift down all values above the specified index, then null out the empty space at the end. byte* ptr = null; try { _buffer.AcquirePointer(ref ptr); ptr += index * sizeof(char); long bytesToShift = (_decryptedLength - index - 1) * sizeof(char); Buffer.MemoryCopy(ptr + sizeof(char), ptr, bytesToShift, bytesToShift); *((char*)(ptr + bytesToShift)) = (char)0; --_decryptedLength; } finally { if (ptr != null) { _buffer.ReleasePointer(); } } } private void SetAtCore(int index, char c) { // Overwrite the character at the specified index _buffer.Write((ulong)(index * sizeof(char)), c); } internal unsafe IntPtr MarshalToBSTR() { int length = _decryptedLength; IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; byte* bufferPtr = null; try { _buffer.AcquirePointer(ref bufferPtr); int resultByteLength = (length + 1) * sizeof(char); ptr = PInvokeMarshal.AllocBSTR(length); Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char)); result = ptr; } finally { // If we failed for any reason, free the new buffer if (result == IntPtr.Zero && ptr != IntPtr.Zero) { RuntimeImports.RhZeroMemory(ptr, (UIntPtr)(length * sizeof(char))); PInvokeMarshal.FreeBSTR(ptr); } if (bufferPtr != null) { _buffer.ReleasePointer(); } } return result; } internal unsafe IntPtr MarshalToStringCore(bool globalAlloc, bool unicode) { int length = _decryptedLength; byte* bufferPtr = null; IntPtr stringPtr = IntPtr.Zero, result = IntPtr.Zero; try { _buffer.AcquirePointer(ref bufferPtr); if (unicode) { int resultLength = (length + 1) * sizeof(char); stringPtr = globalAlloc ? Marshal.AllocHGlobal(resultLength) : Marshal.AllocCoTaskMem(resultLength); Buffer.MemoryCopy( source: bufferPtr, destination: (byte*)stringPtr.ToPointer(), destinationSizeInBytes: resultLength, sourceBytesToCopy: length * sizeof(char)); *(length + (char*)stringPtr) = '\0'; } else { int resultLength = Encoding.UTF8.GetByteCount((char*)bufferPtr, length) + 1; stringPtr = globalAlloc ? Marshal.AllocHGlobal(resultLength) : Marshal.AllocCoTaskMem(resultLength); int encodedLength = Encoding.UTF8.GetBytes((char*)bufferPtr, length, (byte*)stringPtr, resultLength); Debug.Assert(encodedLength + 1 == resultLength, $"Expected encoded length to match result, got {encodedLength} != {resultLength}"); *(resultLength - 1 + (byte*)stringPtr) = 0; } result = stringPtr; } finally { // If there was a failure, such that result isn't initialized, // release the string if we had one. if (stringPtr != IntPtr.Zero && result == IntPtr.Zero) { RuntimeImports.RhZeroMemory(stringPtr, (UIntPtr)(length * sizeof(char))); MarshalFree(stringPtr, globalAlloc); } if (bufferPtr != null) { _buffer.ReleasePointer(); } } return result; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private void EnsureCapacity(int capacity) { // Make sure the requested capacity doesn't exceed SecureString's defined limit if (capacity > MaxLength) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity); } // If we already have enough space allocated, we're done if (_buffer != null && (capacity * sizeof(char)) <= (int)_buffer.ByteLength) { return; } // We need more space, so allocate a new buffer, copy all our data into it, // and then swap the new for the old. UnmanagedBuffer newBuffer = UnmanagedBuffer.Allocate(capacity * sizeof(char)); if (_buffer != null) { UnmanagedBuffer.Copy(_buffer, newBuffer, _buffer.ByteLength); _buffer.Dispose(); } _buffer = newBuffer; } /// <summary>SafeBuffer for managing memory meant to be kept confidential.</summary> private sealed class UnmanagedBuffer : SafeBuffer { internal UnmanagedBuffer() : base(true) { } internal static UnmanagedBuffer Allocate(int bytes) { Debug.Assert(bytes >= 0); UnmanagedBuffer buffer = new UnmanagedBuffer(); buffer.SetHandle(Marshal.AllocHGlobal(bytes)); buffer.Initialize((ulong)bytes); return buffer; } internal unsafe void Clear() { byte* ptr = null; try { AcquirePointer(ref ptr); RuntimeImports.RhZeroMemory((IntPtr)ptr, (UIntPtr)ByteLength); } finally { if (ptr != null) { ReleasePointer(); } } } internal static unsafe void Copy(UnmanagedBuffer source, UnmanagedBuffer destination, ulong bytesLength) { if (bytesLength == 0) { return; } byte* srcPtr = null, dstPtr = null; try { source.AcquirePointer(ref srcPtr); destination.AcquirePointer(ref dstPtr); Buffer.MemoryCopy(srcPtr, dstPtr, destination.ByteLength, bytesLength); } finally { if (dstPtr != null) { destination.ReleasePointer(); } if (srcPtr != null) { source.ReleasePointer(); } } } protected override unsafe bool ReleaseHandle() { Marshal.FreeHGlobal(handle); return true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.IO; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using Microsoft.DotNet.RemoteExecutor; using Xunit; using System.Tests; namespace System.Data.Tests { public class DataTableReadXmlSchemaTest { private DataSet CreateTestSet() { var ds = new DataSet(); ds.Tables.Add("Table1"); ds.Tables.Add("Table2"); ds.Tables[0].Columns.Add("Column1_1"); ds.Tables[0].Columns.Add("Column1_2"); ds.Tables[0].Columns.Add("Column1_3"); ds.Tables[1].Columns.Add("Column2_1"); ds.Tables[1].Columns.Add("Column2_2"); ds.Tables[1].Columns.Add("Column2_3"); ds.Tables[0].Rows.Add(new object[] { "ppp", "www", "xxx" }); ds.Relations.Add("Rel1", ds.Tables[0].Columns[2], ds.Tables[1].Columns[0]); return ds; } [Fact] public void SuspiciousDataSetElement() { string schema = @"<?xml version='1.0'?> <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:attribute name='foo' type='xsd:string'/> <xsd:attribute name='bar' type='xsd:string'/> <xsd:complexType name='attRef'> <xsd:attribute name='att1' type='xsd:int'/> <xsd:attribute name='att2' type='xsd:string'/> </xsd:complexType> <xsd:element name='doc'> <xsd:complexType> <xsd:choice> <xsd:element name='elem' type='attRef'/> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>"; var ds = new DataSet(); ds.Tables.Add(new DataTable("elem")); ds.Tables[0].ReadXmlSchema(new StringReader(schema)); DataSetAssertion.AssertDataTable("table", ds.Tables[0], "elem", 2, 0, 0, 0, 0, 0); } [Fact] public void UnusedComplexTypesIgnored() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' id='hoge'> <xs:element name='Root'> <xs:complexType> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Orphan' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:schema>"; AssertExtensions.Throws<ArgumentException>(null, () => { var ds = new DataSet(); ds.Tables.Add(new DataTable("Root")); ds.Tables.Add(new DataTable("unusedType")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataSetAssertion.AssertDataTable("dt", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); // Here "unusedType" table is never imported. ds.Tables[1].ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void IsDataSetAndTypeIgnored() { string xsbase = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' type='unusedType' msdata:IsDataSet='{0}'> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:schema>"; AssertExtensions.Throws<ArgumentException>(null, () => { // When explicit msdata:IsDataSet value is "false", then // treat as usual. string xs = string.Format(xsbase, "false"); var ds = new DataSet(); ds.Tables.Add(new DataTable("Root")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataSetAssertion.AssertDataTable("dt", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); // Even if a global element uses a complexType, it will be // ignored if the element has msdata:IsDataSet='true' xs = string.Format(xsbase, "true"); ds = new DataSet(); ds.Tables.Add(new DataTable("Root")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void NestedReferenceNotAllowed() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' type='unusedType' msdata:IsDataSet='true'> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> <xs:element name='Foo'> <xs:complexType> <xs:sequence> <xs:element ref='Root' /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; AssertExtensions.Throws<ArgumentException>(null, () => { // DataSet element cannot be converted into a DataTable. // (i.e. cannot be referenced in any other elements) var ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void LocaleOnRootWithoutIsDataSet() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' msdata:Locale='ja-JP'> <xs:complexType> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> <xs:attribute name='Attr' type='xs:integer' /> </xs:complexType> </xs:element> </xs:schema>"; var ds = new DataSet(); ds.Tables.Add("Root"); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataTable dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("dt", dt, "Root", 2, 0, 0, 0, 0, 0); Assert.Equal("ja-JP", dt.Locale.Name); // DataTable's Locale comes from msdata:Locale DataSetAssertion.AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); DataSetAssertion.AssertDataColumn("col2", dt.Columns[1], "Child", false, false, 0, 1, "Child", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); } [Fact] public void PrefixedTargetNS() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:x='urn:foo' targetNamespace='urn:foo' elementFormDefault='qualified'> <xs:element name='DS' msdata:IsDataSet='true'> <xs:complexType> <xs:choice> <xs:element ref='x:R1' /> <xs:element ref='x:R2' /> </xs:choice> </xs:complexType> <xs:key name='key'> <xs:selector xpath='./any/string_is_OK/x:R1'/> <xs:field xpath='x:Child2'/> </xs:key> <xs:keyref name='kref' refer='x:key'> <xs:selector xpath='.//x:R2'/> <xs:field xpath='x:Child2'/> </xs:keyref> </xs:element> <xs:element name='R3' type='x:RootType' /> <xs:complexType name='extracted'> <xs:choice> <xs:element ref='x:R1' /> <xs:element ref='x:R2' /> </xs:choice> </xs:complexType> <xs:element name='R1' type='x:RootType'> <xs:unique name='Rkey'> <xs:selector xpath='.//x:Child1'/> <xs:field xpath='.'/> </xs:unique> <xs:keyref name='Rkref' refer='x:Rkey'> <xs:selector xpath='.//x:Child2'/> <xs:field xpath='.'/> </xs:keyref> </xs:element> <xs:element name='R2' type='x:RootType'> </xs:element> <xs:complexType name='RootType'> <xs:choice> <xs:element name='Child1' type='xs:string'> </xs:element> <xs:element name='Child2' type='xs:string' /> </xs:choice> <xs:attribute name='Attr' type='xs:integer' /> </xs:complexType> </xs:schema>"; // No prefixes on tables and columns var ds = new DataSet(); ds.Tables.Add(new DataTable("R3")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataTable dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("R3", dt, "R3", 3, 0, 0, 0, 0, 0); DataSetAssertion.AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); } private void ReadTest1Check(DataSet ds) { DataSetAssertion.AssertDataSet("dataset", ds, "NewDataSet", 2, 1); DataSetAssertion.AssertDataTable("tbl1", ds.Tables[0], "Table1", 3, 0, 0, 1, 1, 0); DataSetAssertion.AssertDataTable("tbl2", ds.Tables[1], "Table2", 3, 0, 1, 0, 1, 0); DataRelation rel = ds.Relations[0]; DataSetAssertion.AssertDataRelation("rel", rel, "Rel1", false, new string[] { "Column1_3" }, new string[] { "Column2_1" }, true, true); DataSetAssertion.AssertUniqueConstraint("uc", rel.ParentKeyConstraint, "Constraint1", false, new string[] { "Column1_3" }); DataSetAssertion.AssertForeignKeyConstraint("fk", rel.ChildKeyConstraint, "Rel1", AcceptRejectRule.None, Rule.Cascade, Rule.Cascade, new string[] { "Column2_1" }, new string[] { "Column1_3" }); } [Fact] public void TestSampleFileSimpleTables() { var ds = new DataSet(); ds.Tables.Add(new DataTable("foo")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='foo' type='ct' /> <xs:complexType name='ct'> <xs:simpleContent> <xs:extension base='xs:integer'> <xs:attribute name='attr' /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:schema>")); DataSetAssertion.AssertDataSet("005", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("tab", dt, "foo", 2, 0, 0, 0, 0, 0); DataSetAssertion.AssertDataColumn("attr", dt.Columns[0], "attr", true, false, 0, 1, "attr", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); DataSetAssertion.AssertDataColumn("text", dt.Columns[1], "foo_text", false, false, 0, 1, "foo_text", MappingType.SimpleContent, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); ds = new DataSet(); ds.Tables.Add(new DataTable("foo")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='foo' type='st' /> <xs:complexType name='st'> <xs:attribute name='att1' /> <xs:attribute name='att2' type='xs:int' default='2' /> </xs:complexType> </xs:schema>")); DataSetAssertion.AssertDataSet("006", ds, "NewDataSet", 1, 0); dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("tab", dt, "foo", 2, 0, 0, 0, 0, 0); DataSetAssertion.AssertDataColumn("att1", dt.Columns["att1"], "att1", true, false, 0, 1, "att1", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, /*0*/-1, string.Empty, false, false); DataSetAssertion.AssertDataColumn("att2", dt.Columns["att2"], "att2", true, false, 0, 1, "att2", MappingType.Attribute, typeof(int), 2, string.Empty, -1, string.Empty, /*1*/-1, string.Empty, false, false); } [Fact] public void TestSampleFileComplexTables3() { var ds = new DataSet(); ds.Tables.Add(new DataTable("e")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<!-- Modified w3ctests attQ014.xsd --> <xsd:schema xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" targetNamespace=""http://xsdtesting"" xmlns:x=""http://xsdtesting""> <xsd:element name=""root""> <xsd:complexType> <xsd:sequence> <xsd:element name=""e""> <xsd:complexType> <xsd:simpleContent> <xsd:extension base=""xsd:decimal""> <xsd:attribute name=""a"" type=""xsd:string""/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>")); DataTable dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("root", dt, "e", 2, 0, 0, 0, 0, 0); DataSetAssertion.AssertDataColumn("attr", dt.Columns[0], "a", true, false, 0, 1, "a", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); DataSetAssertion.AssertDataColumn("simple", dt.Columns[1], "e_text", false, false, 0, 1, "e_text", MappingType.SimpleContent, typeof(decimal), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); } [Fact] public void TestSampleFileXPath() { var ds = new DataSet(); ds.Tables.Add(new DataTable("Track")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <xs:schema targetNamespace=""http://neurosaudio.com/Tracks.xsd"" xmlns=""http://neurosaudio.com/Tracks.xsd"" xmlns:mstns=""http://neurosaudio.com/Tracks.xsd"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"" elementFormDefault=""qualified"" id=""Tracks""> <xs:element name=""Tracks""> <xs:complexType> <xs:sequence> <xs:element name=""Track"" minOccurs=""0"" maxOccurs=""unbounded""> <xs:complexType> <xs:sequence> <xs:element name=""Title"" type=""xs:string"" /> <xs:element name=""Artist"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Album"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Performer"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Sequence"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Genre"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Comment"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Year"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Duration"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Path"" type=""xs:string"" /> <xs:element name=""DevicePath"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""FileSize"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Source"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""FlashStatus"" type=""xs:unsignedInt"" /> <xs:element name=""HDStatus"" type=""xs:unsignedInt"" /> </xs:sequence> <xs:attribute name=""ID"" type=""xs:unsignedInt"" msdata:AutoIncrement=""true"" msdata:AutoIncrementSeed=""1"" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <xs:key name=""TrackPK"" msdata:PrimaryKey=""true""> <xs:selector xpath="".//mstns:Track"" /> <xs:field xpath=""@ID"" /> </xs:key> </xs:element> </xs:schema>")); } [Fact] public void ReadConstraints() { const string Schema = @"<?xml version=""1.0"" encoding=""utf-8""?> <xs:schema id=""NewDataSet"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <xs:element name=""NewDataSet"" msdata:IsDataSet=""true"" msdata:Locale=""en-US""> <xs:complexType> <xs:choice maxOccurs=""unbounded""> <xs:element name=""Table1""> <xs:complexType> <xs:sequence> <xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name=""Table2""> <xs:complexType> <xs:sequence> <xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> <xs:unique name=""Constraint1""> <xs:selector xpath="".//Table1"" /> <xs:field xpath=""col1"" /> </xs:unique> <xs:keyref name=""fk1"" refer=""Constraint1"" msdata:ConstraintOnly=""true""> <xs:selector xpath="".//Table2"" /> <xs:field xpath=""col1"" /> </xs:keyref> </xs:element> </xs:schema>"; var ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables.Add(new DataTable()); ds.Tables[0].ReadXmlSchema(new StringReader(Schema)); ds.Tables[1].ReadXmlSchema(new StringReader(Schema)); Assert.Equal(0, ds.Relations.Count); Assert.Equal(1, ds.Tables[0].Constraints.Count); Assert.Equal(0, ds.Tables[1].Constraints.Count); Assert.Equal("Constraint1", ds.Tables[0].Constraints[0].ConstraintName); } [Fact] public void XsdSchemaSerializationIgnoresLocale() { var serializer = new BinaryFormatter(); var table = new DataTable(); table.Columns.Add(new DataColumn("RowID", typeof(int)) { AutoIncrement = true, AutoIncrementSeed = -1, // These lines produce attributes within the schema portion of the underlying XML representation of the DataTable with the values "-1" and "-2". AutoIncrementStep = -2, }); table.Columns.Add("Value", typeof(string)); table.Rows.Add(1, "Test"); table.Rows.Add(2, "Data"); var buffer = new MemoryStream(); using (new ThreadCultureChange(new CultureInfo("en-US") { NumberFormat = new NumberFormatInfo() { NegativeSign = "()" } })) { // Before serializing, update the culture to use a weird negative number format. This test is ensuring that this is ignored. serializer.Serialize(buffer, table); } // The raw serialized data now contains an embedded XML schema. We need to verify that this embedded schema used "-1" for the numeric value // negative 1, instead of "()1" as indicated by the current culture. string rawSerializedData = System.Text.Encoding.ASCII.GetString(buffer.ToArray()); const string SchemaStartTag = "<xs:schema"; const string SchemaEndTag = "</xs:schema>"; int schemaStart = rawSerializedData.IndexOf(SchemaStartTag); int schemaEnd = rawSerializedData.IndexOf(SchemaEndTag); Assert.True(schemaStart >= 0); Assert.True(schemaEnd > schemaStart); Assert.True(rawSerializedData.IndexOf("<xs:schema", schemaStart + 1) < 0); schemaEnd += SchemaEndTag.Length; string rawSchemaXML = rawSerializedData.Substring( startIndex: schemaStart, length: schemaEnd - schemaStart); Assert.Contains(@"AutoIncrementSeed=""-1""", rawSchemaXML); Assert.Contains(@"AutoIncrementStep=""-2""", rawSchemaXML); Assert.DoesNotContain("()1", rawSchemaXML); Assert.DoesNotContain("()2", rawSchemaXML); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework does not yet have the fix for this bug")] public void XsdSchemaDeserializationIgnoresLocale() { var serializer = new BinaryFormatter(); /* Test data generator: var table = new DataTable(); table.Columns.Add(new DataColumn("RowID", typeof(int)) { AutoIncrement = true, AutoIncrementSeed = -1, // These lines produce attributes within the schema portion of the underlying XML representation of the DataTable with the value "-1". AutoIncrementStep = -2, }); table.Columns.Add("Value", typeof(string)); table.Rows.Add(1, "Test"); table.Rows.Add(2, "Data"); var buffer = new MemoryStream(); serializer.Serialize(buffer, table); This test data (binary serializer output) embeds the following XML schema: <?xml version="1.0" encoding="utf-16"?> <xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="Table1"> <xs:complexType> <xs:sequence> <xs:element name="RowID" msdata:AutoIncrement="true" msdata:AutoIncrementSeed="-1" msdata:AutoIncrementStep="-2" type="xs:int" msdata:targetNamespace="" minOccurs="0" /> <xs:element name="Value" type="xs:string" msdata:targetNamespace="" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="tmpDataSet" msdata:IsDataSet="true" msdata:MainDataTable="Table1" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded" /> </xs:complexType> </xs:element> </xs:schema> The bug being tested here is that the negative integer values in AutoInecrementSeed and AutoIncrementStep fail to parse because the deserialization code incorrectly uses the current culture instead of the invariant culture when parsing strings like "-1" and "-2". */ var buffer = new MemoryStream(new byte[] { 0,1,0,0,0,255,255,255,255,1,0,0,0,0,0,0,0,12,2,0,0,0,78,83,121,115,116,101,109,46,68,97,116,97,44,32,86,101,114,115,105,111,110,61,52,46,48,46,48,46,48,44,32,67,117, 108,116,117,114,101,61,110,101,117,116,114,97,108,44,32,80,117,98,108,105,99,75,101,121,84,111,107,101,110,61,98,55,55,97,53,99,53,54,49,57,51,52,101,48,56,57,5,1,0, 0,0,21,83,121,115,116,101,109,46,68,97,116,97,46,68,97,116,97,84,97,98,108,101,3,0,0,0,25,68,97,116,97,84,97,98,108,101,46,82,101,109,111,116,105,110,103,86,101,114, 115,105,111,110,9,88,109,108,83,99,104,101,109,97,11,88,109,108,68,105,102,102,71,114,97,109,3,1,1,14,83,121,115,116,101,109,46,86,101,114,115,105,111,110,2,0,0,0,9, 3,0,0,0,6,4,0,0,0,177,6,60,63,120,109,108,32,118,101,114,115,105,111,110,61,34,49,46,48,34,32,101,110,99,111,100,105,110,103,61,34,117,116,102,45,49,54,34,63,62,13, 10,60,120,115,58,115,99,104,101,109,97,32,120,109,108,110,115,61,34,34,32,120,109,108,110,115,58,120,115,61,34,104,116,116,112,58,47,47,119,119,119,46,119,51,46,111, 114,103,47,50,48,48,49,47,88,77,76,83,99,104,101,109,97,34,32,120,109,108,110,115,58,109,115,100,97,116,97,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105, 99,114,111,115,111,102,116,45,99,111,109,58,120,109,108,45,109,115,100,97,116,97,34,62,13,10,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34, 84,97,98,108,101,49,34,62,13,10,32,32,32,32,60,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,32,32,32,32,60,120,115,58,115,101,113,117,101,110, 99,101,62,13,10,32,32,32,32,32,32,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,82,111,119,73,68,34,32,109,115,100,97,116,97,58,65,117,116, 111,73,110,99,114,101,109,101,110,116,61,34,116,114,117,101,34,32,109,115,100,97,116,97,58,65,117,116,111,73,110,99,114,101,109,101,110,116,83,101,101,100,61,34,45, 49,34,32,109,115,100,97,116,97,58,65,117,116,111,73,110,99,114,101,109,101,110,116,83,116,101,112,61,34,45,50,34,32,116,121,112,101,61,34,120,115,58,105,110,116,34, 32,109,115,100,97,116,97,58,116,97,114,103,101,116,78,97,109,101,115,112,97,99,101,61,34,34,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,47,62,13,10,32,32,32, 32,32,32,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,86,97,108,117,101,34,32,116,121,112,101,61,34,120,115,58,115,116,114,105,110,103,34, 32,109,115,100,97,116,97,58,116,97,114,103,101,116,78,97,109,101,115,112,97,99,101,61,34,34,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,47,62,13,10,32,32,32, 32,32,32,60,47,120,115,58,115,101,113,117,101,110,99,101,62,13,10,32,32,32,32,60,47,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,60,47,120,115, 58,101,108,101,109,101,110,116,62,13,10,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,116,109,112,68,97,116,97,83,101,116,34,32,109,115,100, 97,116,97,58,73,115,68,97,116,97,83,101,116,61,34,116,114,117,101,34,32,109,115,100,97,116,97,58,77,97,105,110,68,97,116,97,84,97,98,108,101,61,34,84,97,98,108,101, 49,34,32,109,115,100,97,116,97,58,85,115,101,67,117,114,114,101,110,116,76,111,99,97,108,101,61,34,116,114,117,101,34,62,13,10,32,32,32,32,60,120,115,58,99,111,109, 112,108,101,120,84,121,112,101,62,13,10,32,32,32,32,32,32,60,120,115,58,99,104,111,105,99,101,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,109,97,120,79,99,99, 117,114,115,61,34,117,110,98,111,117,110,100,101,100,34,32,47,62,13,10,32,32,32,32,60,47,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,60,47, 120,115,58,101,108,101,109,101,110,116,62,13,10,60,47,120,115,58,115,99,104,101,109,97,62,6,5,0,0,0,221,3,60,100,105,102,102,103,114,58,100,105,102,102,103,114,97, 109,32,120,109,108,110,115,58,109,115,100,97,116,97,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105,99,114,111,115,111,102,116,45,99,111,109,58,120,109,108, 45,109,115,100,97,116,97,34,32,120,109,108,110,115,58,100,105,102,102,103,114,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105,99,114,111,115,111,102,116,45, 99,111,109,58,120,109,108,45,100,105,102,102,103,114,97,109,45,118,49,34,62,13,10,32,32,60,116,109,112,68,97,116,97,83,101,116,62,13,10,32,32,32,32,60,84,97,98,108, 101,49,32,100,105,102,102,103,114,58,105,100,61,34,84,97,98,108,101,49,49,34,32,109,115,100,97,116,97,58,114,111,119,79,114,100,101,114,61,34,48,34,32,100,105,102, 102,103,114,58,104,97,115,67,104,97,110,103,101,115,61,34,105,110,115,101,114,116,101,100,34,62,13,10,32,32,32,32,32,32,60,82,111,119,73,68,62,49,60,47,82,111,119,73, 68,62,13,10,32,32,32,32,32,32,60,86,97,108,117,101,62,84,101,115,116,60,47,86,97,108,117,101,62,13,10,32,32,32,32,60,47,84,97,98,108,101,49,62,13,10,32,32,32,32,60, 84,97,98,108,101,49,32,100,105,102,102,103,114,58,105,100,61,34,84,97,98,108,101,49,50,34,32,109,115,100,97,116,97,58,114,111,119,79,114,100,101,114,61,34,49,34,32, 100,105,102,102,103,114,58,104,97,115,67,104,97,110,103,101,115,61,34,105,110,115,101,114,116,101,100,34,62,13,10,32,32,32,32,32,32,60,82,111,119,73,68,62,50,60,47, 82,111,119,73,68,62,13,10,32,32,32,32,32,32,60,86,97,108,117,101,62,68,97,116,97,60,47,86,97,108,117,101,62,13,10,32,32,32,32,60,47,84,97,98,108,101,49,62,13,10,32, 32,60,47,116,109,112,68,97,116,97,83,101,116,62,13,10,60,47,100,105,102,102,103,114,58,100,105,102,102,103,114,97,109,62,4,3,0,0,0,14,83,121,115,116,101,109,46,86, 101,114,115,105,111,110,4,0,0,0,6,95,77,97,106,111,114,6,95,77,105,110,111,114,6,95,66,117,105,108,100,9,95,82,101,118,105,115,105,111,110,0,0,0,0,8,8,8,8,2,0,0,0,0, 0,0,0,255,255,255,255,255,255,255,255,11 }); DataTable table; using (new ThreadCultureChange(new CultureInfo("en-US") { NumberFormat = new NumberFormatInfo() { NegativeSign = "()" } })) { // Before deserializing, update the culture to use a weird negative number format. This test is ensuring that this is ignored. // The bug this test is testing would cause "-1" to no longer be treated as a valid representation of the value -1, instead // only accepting the string "()1". table = (DataTable)serializer.Deserialize(buffer); // BUG: System.Exception: "-1 is not a valid value for Int64." } } DataColumn rowIDColumn = table.Columns["RowID"]; Assert.Equal(-1, rowIDColumn.AutoIncrementSeed); Assert.Equal(-2, rowIDColumn.AutoIncrementStep); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "Exists to provide notification of when the full framework gets the bug fix, at which point the preceding test can be re-enabled")] public void XsdSchemaDeserializationOnFullFrameworkStillHasBug() { var serializer = new BinaryFormatter(); var buffer = new MemoryStream(new byte[] { 0,1,0,0,0,255,255,255,255,1,0,0,0,0,0,0,0,12,2,0,0,0,78,83,121,115,116,101,109,46,68,97,116,97,44,32,86,101,114,115,105,111,110,61,52,46,48,46,48,46,48,44,32,67,117, 108,116,117,114,101,61,110,101,117,116,114,97,108,44,32,80,117,98,108,105,99,75,101,121,84,111,107,101,110,61,98,55,55,97,53,99,53,54,49,57,51,52,101,48,56,57,5,1,0, 0,0,21,83,121,115,116,101,109,46,68,97,116,97,46,68,97,116,97,84,97,98,108,101,3,0,0,0,25,68,97,116,97,84,97,98,108,101,46,82,101,109,111,116,105,110,103,86,101,114, 115,105,111,110,9,88,109,108,83,99,104,101,109,97,11,88,109,108,68,105,102,102,71,114,97,109,3,1,1,14,83,121,115,116,101,109,46,86,101,114,115,105,111,110,2,0,0,0,9, 3,0,0,0,6,4,0,0,0,177,6,60,63,120,109,108,32,118,101,114,115,105,111,110,61,34,49,46,48,34,32,101,110,99,111,100,105,110,103,61,34,117,116,102,45,49,54,34,63,62,13, 10,60,120,115,58,115,99,104,101,109,97,32,120,109,108,110,115,61,34,34,32,120,109,108,110,115,58,120,115,61,34,104,116,116,112,58,47,47,119,119,119,46,119,51,46,111, 114,103,47,50,48,48,49,47,88,77,76,83,99,104,101,109,97,34,32,120,109,108,110,115,58,109,115,100,97,116,97,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105, 99,114,111,115,111,102,116,45,99,111,109,58,120,109,108,45,109,115,100,97,116,97,34,62,13,10,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34, 84,97,98,108,101,49,34,62,13,10,32,32,32,32,60,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,32,32,32,32,60,120,115,58,115,101,113,117,101,110, 99,101,62,13,10,32,32,32,32,32,32,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,82,111,119,73,68,34,32,109,115,100,97,116,97,58,65,117,116, 111,73,110,99,114,101,109,101,110,116,61,34,116,114,117,101,34,32,109,115,100,97,116,97,58,65,117,116,111,73,110,99,114,101,109,101,110,116,83,101,101,100,61,34,45, 49,34,32,109,115,100,97,116,97,58,65,117,116,111,73,110,99,114,101,109,101,110,116,83,116,101,112,61,34,45,50,34,32,116,121,112,101,61,34,120,115,58,105,110,116,34, 32,109,115,100,97,116,97,58,116,97,114,103,101,116,78,97,109,101,115,112,97,99,101,61,34,34,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,47,62,13,10,32,32,32, 32,32,32,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,86,97,108,117,101,34,32,116,121,112,101,61,34,120,115,58,115,116,114,105,110,103,34, 32,109,115,100,97,116,97,58,116,97,114,103,101,116,78,97,109,101,115,112,97,99,101,61,34,34,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,47,62,13,10,32,32,32, 32,32,32,60,47,120,115,58,115,101,113,117,101,110,99,101,62,13,10,32,32,32,32,60,47,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,60,47,120,115, 58,101,108,101,109,101,110,116,62,13,10,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,116,109,112,68,97,116,97,83,101,116,34,32,109,115,100, 97,116,97,58,73,115,68,97,116,97,83,101,116,61,34,116,114,117,101,34,32,109,115,100,97,116,97,58,77,97,105,110,68,97,116,97,84,97,98,108,101,61,34,84,97,98,108,101, 49,34,32,109,115,100,97,116,97,58,85,115,101,67,117,114,114,101,110,116,76,111,99,97,108,101,61,34,116,114,117,101,34,62,13,10,32,32,32,32,60,120,115,58,99,111,109, 112,108,101,120,84,121,112,101,62,13,10,32,32,32,32,32,32,60,120,115,58,99,104,111,105,99,101,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,109,97,120,79,99,99, 117,114,115,61,34,117,110,98,111,117,110,100,101,100,34,32,47,62,13,10,32,32,32,32,60,47,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,60,47, 120,115,58,101,108,101,109,101,110,116,62,13,10,60,47,120,115,58,115,99,104,101,109,97,62,6,5,0,0,0,221,3,60,100,105,102,102,103,114,58,100,105,102,102,103,114,97, 109,32,120,109,108,110,115,58,109,115,100,97,116,97,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105,99,114,111,115,111,102,116,45,99,111,109,58,120,109,108, 45,109,115,100,97,116,97,34,32,120,109,108,110,115,58,100,105,102,102,103,114,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105,99,114,111,115,111,102,116,45, 99,111,109,58,120,109,108,45,100,105,102,102,103,114,97,109,45,118,49,34,62,13,10,32,32,60,116,109,112,68,97,116,97,83,101,116,62,13,10,32,32,32,32,60,84,97,98,108, 101,49,32,100,105,102,102,103,114,58,105,100,61,34,84,97,98,108,101,49,49,34,32,109,115,100,97,116,97,58,114,111,119,79,114,100,101,114,61,34,48,34,32,100,105,102, 102,103,114,58,104,97,115,67,104,97,110,103,101,115,61,34,105,110,115,101,114,116,101,100,34,62,13,10,32,32,32,32,32,32,60,82,111,119,73,68,62,49,60,47,82,111,119,73, 68,62,13,10,32,32,32,32,32,32,60,86,97,108,117,101,62,84,101,115,116,60,47,86,97,108,117,101,62,13,10,32,32,32,32,60,47,84,97,98,108,101,49,62,13,10,32,32,32,32,60, 84,97,98,108,101,49,32,100,105,102,102,103,114,58,105,100,61,34,84,97,98,108,101,49,50,34,32,109,115,100,97,116,97,58,114,111,119,79,114,100,101,114,61,34,49,34,32, 100,105,102,102,103,114,58,104,97,115,67,104,97,110,103,101,115,61,34,105,110,115,101,114,116,101,100,34,62,13,10,32,32,32,32,32,32,60,82,111,119,73,68,62,50,60,47, 82,111,119,73,68,62,13,10,32,32,32,32,32,32,60,86,97,108,117,101,62,68,97,116,97,60,47,86,97,108,117,101,62,13,10,32,32,32,32,60,47,84,97,98,108,101,49,62,13,10,32, 32,60,47,116,109,112,68,97,116,97,83,101,116,62,13,10,60,47,100,105,102,102,103,114,58,100,105,102,102,103,114,97,109,62,4,3,0,0,0,14,83,121,115,116,101,109,46,86, 101,114,115,105,111,110,4,0,0,0,6,95,77,97,106,111,114,6,95,77,105,110,111,114,6,95,66,117,105,108,100,9,95,82,101,118,105,115,105,111,110,0,0,0,0,8,8,8,8,2,0,0,0,0, 0,0,0,255,255,255,255,255,255,255,255,11 }); Exception exception; CultureInfo savedCulture = CultureInfo.CurrentCulture; try { exception = Assert.Throws<TargetInvocationException>(() => { // Before deserializing, update the culture to use a weird negative number format. The bug this test is testing causes "-1" to no // longer be treated as a valid representation of the value -1, instead only accepting the string "()1". CultureInfo.CurrentCulture = new CultureInfo("en-US") { NumberFormat = new NumberFormatInfo() { NegativeSign = "()" } }; serializer.Deserialize(buffer); // BUG: System.Exception: "-1 is not a valid value for Int64." }); } finally { CultureInfo.CurrentCulture = savedCulture; } Assert.IsAssignableFrom<FormatException>(exception.InnerException.InnerException); } } }
using System; using System.IO; using System.Net; using System.Threading; using NUnit.Framework; using ServiceStack.Common.Utils; using ServiceStack.Common.Web; using ServiceStack.Service; using ServiceStack.ServiceClient.Web; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints.Tests.Support.Host; using ServiceStack.WebHost.Endpoints.Tests.Support.Services; namespace ServiceStack.WebHost.Endpoints.Tests { [TestFixture] public class FileUploadTests { public const string ListeningOn = "http://localhost:8082/"; ExampleAppHostHttpListener appHost; [TestFixtureSetUp] public void TextFixtureSetUp() { try { appHost = new ExampleAppHostHttpListener(); appHost.Init(); appHost.Start(ListeningOn); } catch (Exception ex) { throw ex; } } [Test] [Explicit("Helps debugging when you need to find out WTF is going on")] public void Run_for_30secs() { Thread.Sleep(30000); } [TestFixtureTearDown] public void TestFixtureTearDown() { if (appHost != null) appHost.Dispose(); appHost = null; } public void AssertResponse<T>(HttpWebResponse response, Action<T> customAssert) { var contentType = response.ContentType; AssertResponse(response, contentType); var contents = new StreamReader(response.GetResponseStream()).ReadToEnd(); var result = DeserializeResult<T>(response, contents, contentType); customAssert(result); } private static T DeserializeResult<T>(WebResponse response, string contents, string contentType) { T result; switch (contentType) { case ContentType.Xml: result = XmlSerializer.DeserializeFromString<T>(contents); break; case ContentType.Json: case ContentType.Json + ContentType.Utf8Suffix: result = JsonSerializer.DeserializeFromString<T>(contents); break; case ContentType.Jsv: result = TypeSerializer.DeserializeFromString<T>(contents); break; default: throw new NotSupportedException(response.ContentType); } return result; } public void AssertResponse(HttpWebResponse response, string contentType) { var statusCode = (int)response.StatusCode; Assert.That(statusCode, Is.LessThan(400)); Assert.That(response.ContentType.StartsWith(contentType)); } [Test] public void Can_POST_upload_file() { var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); var webRequest = (HttpWebRequest)WebRequest.Create(ListeningOn + "/fileuploads"); webRequest.Accept = ContentType.Json; var webResponse = webRequest.UploadFile(uploadFile, MimeTypes.GetMimeType(uploadFile.Name)); AssertResponse<FileUploadResponse>((HttpWebResponse)webResponse, r => { var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd(); Assert.That(r.FileName, Is.EqualTo(uploadFile.Name)); Assert.That(r.ContentLength, Is.EqualTo(uploadFile.Length)); Assert.That(r.ContentType, Is.EqualTo(MimeTypes.GetMimeType(uploadFile.Name))); Assert.That(r.Contents, Is.EqualTo(expectedContents)); }); } [Test] public void Can_POST_upload_file_using_ServiceClient() { IServiceClient client = new JsonServiceClient(ListeningOn); var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); var response = client.PostFile<FileUploadResponse>( ListeningOn + "/fileuploads", uploadFile, MimeTypes.GetMimeType(uploadFile.Name)); var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd(); Assert.That(response.FileName, Is.EqualTo(uploadFile.Name)); Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length)); Assert.That(response.ContentType, Is.EqualTo(MimeTypes.GetMimeType(uploadFile.Name))); Assert.That(response.Contents, Is.EqualTo(expectedContents)); } [Test] public void Can_POST_upload_file_using_ServiceClient_with_request() { IServiceClient client = new JsonServiceClient(ListeningOn); var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); var request = new FileUpload{CustomerId = 123, CustomerName = "Foo"}; var response = client.PostFileWithRequest<FileUploadResponse>(ListeningOn + "/fileuploads", uploadFile, request); var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd(); Assert.That(response.FileName, Is.EqualTo(uploadFile.Name)); Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length)); Assert.That(response.Contents, Is.EqualTo(expectedContents)); Assert.That(response.CustomerName, Is.EqualTo("Foo")); Assert.That(response.CustomerId, Is.EqualTo(123)); } [Test] public void Can_handle_error_on_POST_upload_file_using_ServiceClient() { IServiceClient client = new JsonServiceClient(ListeningOn); var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); try { client.PostFile<FileUploadResponse>( ListeningOn + "/fileuploads/ThrowError", uploadFile, MimeTypes.GetMimeType(uploadFile.Name)); Assert.Fail("Upload Service should've thrown an error"); } catch (Exception ex) { var webEx = ex as WebServiceException; var response = (FileUploadResponse)webEx.ResponseDto; Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo(typeof(NotSupportedException).Name)); Assert.That(response.ResponseStatus.Message, Is.EqualTo("ThrowError")); } } [Test] public void Can_GET_upload_file() { var uploadedFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); var webRequest = (HttpWebRequest)WebRequest.Create(ListeningOn + "/fileuploads/TestExistingDir/upload.html"); var expectedContents = new StreamReader(uploadedFile.OpenRead()).ReadToEnd(); var webResponse = webRequest.GetResponse(); var actualContents = new StreamReader(webResponse.GetResponseStream()).ReadToEnd(); Assert.That(webResponse.ContentType, Is.EqualTo(MimeTypes.GetMimeType(uploadedFile.Name))); Assert.That(actualContents, Is.EqualTo(expectedContents)); } [Test] public void Can_POST_upload_file_and_apply_filter_using_ServiceClient() { try { var client = new JsonServiceClient(ListeningOn); var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); bool isFilterCalled = false; ServiceClientBase.HttpWebRequestFilter = request => { isFilterCalled = true; }; var response = client.PostFile<FileUploadResponse>( ListeningOn + "/fileuploads", uploadFile, MimeTypes.GetMimeType(uploadFile.Name)); var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd(); Assert.That(isFilterCalled); Assert.That(response.FileName, Is.EqualTo(uploadFile.Name)); Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length)); Assert.That(response.ContentType, Is.EqualTo(MimeTypes.GetMimeType(uploadFile.Name))); Assert.That(response.Contents, Is.EqualTo(expectedContents)); } finally { ServiceClientBase.HttpWebRequestFilter = null; //reset this to not cause side-effects } } [Test] public void Can_POST_upload_stream_using_ServiceClient() { try { var client = new JsonServiceClient(ListeningOn); using (var fileStream = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()).OpenRead()) { var fileName = "upload.html"; bool isFilterCalled = false; ServiceClientBase.HttpWebRequestFilter = request => { isFilterCalled = true; }; var response = client.PostFile<FileUploadResponse>( ListeningOn + "/fileuploads", fileStream, fileName, MimeTypes.GetMimeType(fileName)); fileStream.Position = 0; var expectedContents = new StreamReader(fileStream).ReadToEnd(); Assert.That(isFilterCalled); Assert.That(response.FileName, Is.EqualTo(fileName)); Assert.That(response.ContentLength, Is.EqualTo(fileStream.Length)); Assert.That(response.ContentType, Is.EqualTo(MimeTypes.GetMimeType(fileName))); Assert.That(response.Contents, Is.EqualTo(expectedContents)); } } finally { ServiceClientBase.HttpWebRequestFilter = null; //reset this to not cause side-effects } } } }
// ZipInputStream.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // HISTORY // 2010-05-25 Z-1663 Fixed exception when testing local header compressed size of -1 using System; using System.IO; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; #if !NETCF_1_0 using ICSharpCode.SharpZipLib.Encryption; #endif namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// This is an InflaterInputStream that reads the files baseInputStream an zip archive /// one after another. It has a special method to get the zip entry of /// the next file. The zip entry contains information about the file name /// size, compressed size, Crc, etc. /// It includes support for Stored and Deflated entries. /// <br/> /// <br/>Author of the original java version : Jochen Hoenicke /// </summary> /// /// <example> This sample shows how to read a zip file /// <code lang="C#"> /// using System; /// using System.Text; /// using System.IO; /// /// using ICSharpCode.SharpZipLib.Zip; /// /// class MainClass /// { /// public static void Main(string[] args) /// { /// using ( ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]))) { /// /// ZipEntry theEntry; /// const int size = 2048; /// byte[] data = new byte[2048]; /// /// while ((theEntry = s.GetNextEntry()) != null) { /// if ( entry.IsFile ) { /// Console.Write("Show contents (y/n) ?"); /// if (Console.ReadLine() == "y") { /// while (true) { /// size = s.Read(data, 0, data.Length); /// if (size > 0) { /// Console.Write(new ASCIIEncoding().GetString(data, 0, size)); /// } else { /// break; /// } /// } /// } /// } /// } /// } /// } /// } /// </code> /// </example> internal class ZipInputStream : InflaterInputStream { #region Instance Fields /// <summary> /// Delegate for reading bytes from a stream. /// </summary> delegate int ReadDataHandler(byte[] b, int offset, int length); /// <summary> /// The current reader this instance. /// </summary> ReadDataHandler internalReader; Crc32 crc = new Crc32(); ZipEntry entry; long size; int method; int flags; string password; #endregion #region Constructors /// <summary> /// Creates a new Zip input stream, for reading a zip archive. /// </summary> /// <param name="baseInputStream">The underlying <see cref="Stream"/> providing data.</param> public ZipInputStream(Stream baseInputStream) : base(baseInputStream, new Inflater(true)) { internalReader = new ReadDataHandler(ReadingNotAvailable); } /// <summary> /// Creates a new Zip input stream, for reading a zip archive. /// </summary> /// <param name="baseInputStream">The underlying <see cref="Stream"/> providing data.</param> /// <param name="bufferSize">Size of the buffer.</param> public ZipInputStream( Stream baseInputStream, int bufferSize ) : base(baseInputStream, new Inflater(true), bufferSize) { internalReader = new ReadDataHandler(ReadingNotAvailable); } #endregion /// <summary> /// Optional password used for encryption when non-null /// </summary> /// <value>A password for all encrypted <see cref="ZipEntry">entries </see> in this <see cref="ZipInputStream"/></value> public string Password { get { return password; } set { password = value; } } /// <summary> /// Gets a value indicating if there is a current entry and it can be decompressed /// </summary> /// <remarks> /// The entry can only be decompressed if the library supports the zip features required to extract it. /// See the <see cref="ZipEntry.Version">ZipEntry Version</see> property for more details. /// </remarks> public bool CanDecompressEntry { get { return (entry != null) && entry.CanDecompress; } } /// <summary> /// Advances to the next entry in the archive /// </summary> /// <returns> /// The next <see cref="ZipEntry">entry</see> in the archive or null if there are no more entries. /// </returns> /// <remarks> /// If the previous entry is still open <see cref="CloseEntry">CloseEntry</see> is called. /// </remarks> /// <exception cref="InvalidOperationException"> /// Input stream is closed /// </exception> /// <exception cref="ZipException"> /// Password is not set, password is invalid, compression method is invalid, /// version required to extract is not supported /// </exception> public ZipEntry GetNextEntry() { if (crc == null) { throw new InvalidOperationException("Closed."); } if (entry != null) { CloseEntry(); } int header = inputBuffer.ReadLeInt(); if (header == ZipConstants.CentralHeaderSignature || header == ZipConstants.EndOfCentralDirectorySignature || header == ZipConstants.CentralHeaderDigitalSignature || header == ZipConstants.ArchiveExtraDataSignature || header == ZipConstants.Zip64CentralFileHeaderSignature) { // No more individual entries exist Close(); return null; } // -jr- 07-Dec-2003 Ignore spanning temporary signatures if found // Spanning signature is same as descriptor signature and is untested as yet. if ( (header == ZipConstants.SpanningTempSignature) || (header == ZipConstants.SpanningSignature) ) { header = inputBuffer.ReadLeInt(); } if (header != ZipConstants.LocalHeaderSignature) { throw new ZipException("Wrong Local header signature: 0x" + String.Format("{0:X}", header)); } short versionRequiredToExtract = (short)inputBuffer.ReadLeShort(); flags = inputBuffer.ReadLeShort(); method = inputBuffer.ReadLeShort(); uint dostime = (uint)inputBuffer.ReadLeInt(); int crc2 = inputBuffer.ReadLeInt(); csize = inputBuffer.ReadLeInt(); size = inputBuffer.ReadLeInt(); int nameLen = inputBuffer.ReadLeShort(); int extraLen = inputBuffer.ReadLeShort(); bool isCrypted = (flags & 1) == 1; byte[] buffer = new byte[nameLen]; inputBuffer.ReadRawBuffer(buffer); string name = ZipConstants.ConvertToStringExt(flags, buffer); entry = new ZipEntry(name, versionRequiredToExtract); entry.Flags = flags; entry.CompressionMethod = (CompressionMethod)method; if ((flags & 8) == 0) { entry.Crc = crc2 & 0xFFFFFFFFL; entry.Size = size & 0xFFFFFFFFL; entry.CompressedSize = csize & 0xFFFFFFFFL; entry.CryptoCheckValue = (byte)((crc2 >> 24) & 0xff); } else { // This allows for GNU, WinZip and possibly other archives, the PKZIP spec // says these values are zero under these circumstances. if (crc2 != 0) { entry.Crc = crc2 & 0xFFFFFFFFL; } if (size != 0) { entry.Size = size & 0xFFFFFFFFL; } if (csize != 0) { entry.CompressedSize = csize & 0xFFFFFFFFL; } entry.CryptoCheckValue = (byte)((dostime >> 8) & 0xff); } entry.DosTime = dostime; // If local header requires Zip64 is true then the extended header should contain // both values. // Handle extra data if present. This can set/alter some fields of the entry. if (extraLen > 0) { byte[] extra = new byte[extraLen]; inputBuffer.ReadRawBuffer(extra); entry.ExtraData = extra; } entry.ProcessExtraData(true); if ( entry.CompressedSize >= 0 ) { csize = entry.CompressedSize; } if ( entry.Size >= 0 ) { size = entry.Size; } if (method == (int)CompressionMethod.Stored && (!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CryptoHeaderSize != size))) { throw new ZipException("Stored, but compressed != uncompressed"); } // Determine how to handle reading of data if this is attempted. if (entry.IsCompressionMethodSupported()) { internalReader = new ReadDataHandler(InitialRead); } else { internalReader = new ReadDataHandler(ReadingNotSupported); } return entry; } /// <summary> /// Read data descriptor at the end of compressed data. /// </summary> void ReadDataDescriptor() { if (inputBuffer.ReadLeInt() != ZipConstants.DataDescriptorSignature) { throw new ZipException("Data descriptor signature not found"); } entry.Crc = inputBuffer.ReadLeInt() & 0xFFFFFFFFL; if ( entry.LocalHeaderRequiresZip64 ) { csize = inputBuffer.ReadLeLong(); size = inputBuffer.ReadLeLong(); } else { csize = inputBuffer.ReadLeInt(); size = inputBuffer.ReadLeInt(); } entry.CompressedSize = csize; entry.Size = size; } /// <summary> /// Complete cleanup as the final part of closing. /// </summary> /// <param name="testCrc">True if the crc value should be tested</param> void CompleteCloseEntry(bool testCrc) { StopDecrypting(); if ((flags & 8) != 0) { ReadDataDescriptor(); } size = 0; if ( testCrc && ((crc.Value & 0xFFFFFFFFL) != entry.Crc) && (entry.Crc != -1)) { throw new ZipException("CRC mismatch"); } crc.Reset(); if (method == (int)CompressionMethod.Deflated) { inf.Reset(); } entry = null; } /// <summary> /// Closes the current zip entry and moves to the next one. /// </summary> /// <exception cref="InvalidOperationException"> /// The stream is closed /// </exception> /// <exception cref="ZipException"> /// The Zip stream ends early /// </exception> public void CloseEntry() { if (crc == null) { throw new InvalidOperationException("Closed"); } if (entry == null) { return; } if (method == (int)CompressionMethod.Deflated) { if ((flags & 8) != 0) { // We don't know how much we must skip, read until end. byte[] tmp = new byte[4096]; // Read will close this entry while (Read(tmp, 0, tmp.Length) > 0) { } return; } csize -= inf.TotalIn; inputBuffer.Available += inf.RemainingInput; } if ( (inputBuffer.Available > csize) && (csize >= 0) ) { inputBuffer.Available = (int)((long)inputBuffer.Available - csize); } else { csize -= inputBuffer.Available; inputBuffer.Available = 0; while (csize != 0) { long skipped = base.Skip(csize); if (skipped <= 0) { throw new ZipException("Zip archive ends early."); } csize -= skipped; } } CompleteCloseEntry(false); } /// <summary> /// Returns 1 if there is an entry available /// Otherwise returns 0. /// </summary> public override int Available { get { return entry != null ? 1 : 0; } } /// <summary> /// Returns the current size that can be read from the current entry if available /// </summary> /// <exception cref="ZipException">Thrown if the entry size is not known.</exception> /// <exception cref="InvalidOperationException">Thrown if no entry is currently available.</exception> public override long Length { get { if ( entry != null ) { if ( entry.Size >= 0 ) { return entry.Size; } else { throw new ZipException("Length not available for the current entry"); } } else { throw new InvalidOperationException("No current entry"); } } } /// <summary> /// Reads a byte from the current zip entry. /// </summary> /// <returns> /// The byte or -1 if end of stream is reached. /// </returns> public override int ReadByte() { byte[] b = new byte[1]; if (Read(b, 0, 1) <= 0) { return -1; } return b[0] & 0xff; } /// <summary> /// Handle attempts to read by throwing an <see cref="InvalidOperationException"/>. /// </summary> /// <param name="destination">The destination array to store data in.</param> /// <param name="offset">The offset at which data read should be stored.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>Returns the number of bytes actually read.</returns> int ReadingNotAvailable(byte[] destination, int offset, int count) { throw new InvalidOperationException("Unable to read from this stream"); } /// <summary> /// Handle attempts to read from this entry by throwing an exception /// </summary> int ReadingNotSupported(byte[] destination, int offset, int count) { throw new ZipException("The compression method for this entry is not supported"); } /// <summary> /// Perform the initial read on an entry which may include /// reading encryption headers and setting up inflation. /// </summary> /// <param name="destination">The destination to fill with data read.</param> /// <param name="offset">The offset to start reading at.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>The actual number of bytes read.</returns> int InitialRead(byte[] destination, int offset, int count) { if ( !CanDecompressEntry ) { throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version.ToString() + ")"); } // Handle encryption if required. if (entry.IsCrypted) { #if NETCF_1_0 throw new ZipException("Encryption not supported for Compact Framework 1.0"); #else if (password == null) { throw new ZipException("No password set."); } // Generate and set crypto transform... PkzipClassicManaged managed = new PkzipClassicManaged(); byte[] key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(password)); inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null); byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize]; inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize); if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue) { throw new ZipException("Invalid password"); } if (csize >= ZipConstants.CryptoHeaderSize) { csize -= ZipConstants.CryptoHeaderSize; } else if ( (entry.Flags & (int)GeneralBitFlags.Descriptor) == 0 ) { throw new ZipException(string.Format("Entry compressed size {0} too small for encryption", csize)); } #endif } else { #if !NETCF_1_0 inputBuffer.CryptoTransform = null; #endif } if ((csize > 0) || ((flags & (int)GeneralBitFlags.Descriptor) != 0)) { if ((method == (int)CompressionMethod.Deflated) && (inputBuffer.Available > 0)) { inputBuffer.SetInflaterInput(inf); } internalReader = new ReadDataHandler(BodyRead); return BodyRead(destination, offset, count); } else { internalReader = new ReadDataHandler(ReadingNotAvailable); return 0; } } /// <summary> /// Read a block of bytes from the stream. /// </summary> /// <param name="buffer">The destination for the bytes.</param> /// <param name="offset">The index to start storing data.</param> /// <param name="count">The number of bytes to attempt to read.</param> /// <returns>Returns the number of bytes read.</returns> /// <remarks>Zero bytes read means end of stream.</remarks> public override int Read(byte[] buffer, int offset, int count) { if ( buffer == null ) { throw new ArgumentNullException("buffer"); } if ( offset < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); #endif } if ( count < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif } if ( (buffer.Length - offset) < count ) { throw new ArgumentException("Invalid offset/count combination"); } return internalReader(buffer, offset, count); } /// <summary> /// Reads a block of bytes from the current zip entry. /// </summary> /// <returns> /// The number of bytes read (this may be less than the length requested, even before the end of stream), or 0 on end of stream. /// </returns> /// <exception name="IOException"> /// An i/o error occured. /// </exception> /// <exception cref="ZipException"> /// The deflated stream is corrupted. /// </exception> /// <exception cref="InvalidOperationException"> /// The stream is not open. /// </exception> int BodyRead(byte[] buffer, int offset, int count) { if ( crc == null ) { throw new InvalidOperationException("Closed"); } if ( (entry == null) || (count <= 0) ) { return 0; } if ( offset + count > buffer.Length ) { throw new ArgumentException("Offset + count exceeds buffer size"); } bool finished = false; switch (method) { case (int)CompressionMethod.Deflated: count = base.Read(buffer, offset, count); if (count <= 0) { if (!inf.IsFinished) { throw new ZipException("Inflater not finished!"); } inputBuffer.Available = inf.RemainingInput; // A csize of -1 is from an unpatched local header if ((flags & 8) == 0 && (inf.TotalIn != csize && csize != 0xFFFFFFFF && csize != -1 || inf.TotalOut != size)) { throw new ZipException("Size mismatch: " + csize + ";" + size + " <-> " + inf.TotalIn + ";" + inf.TotalOut); } inf.Reset(); finished = true; } break; case (int)CompressionMethod.Stored: if ( (count > csize) && (csize >= 0) ) { count = (int)csize; } if ( count > 0 ) { count = inputBuffer.ReadClearTextBuffer(buffer, offset, count); if (count > 0) { csize -= count; size -= count; } } if (csize == 0) { finished = true; } else { if (count < 0) { throw new ZipException("EOF in stored block"); } } break; } if (count > 0) { crc.Update(buffer, offset, count); } if (finished) { CompleteCloseEntry(true); } return count; } /// <summary> /// Closes the zip input stream /// </summary> public override void Close() { internalReader = new ReadDataHandler(ReadingNotAvailable); crc = null; entry = null; base.Close(); } } }
using System; using System.IO; using GitVersion.MsBuild.Tests.Mocks; using GitVersionCore.Tests.Helpers; using Microsoft.Build.Framework; using NUnit.Framework; namespace GitVersion.MsBuild.Tests { [TestFixture] public class InvalidFileCheckerTests : TestBase { private string projectDirectory; private string projectFile; [SetUp] public void CreateTemporaryProject() { projectDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); projectFile = Path.Combine(projectDirectory, "Fake.csproj"); Directory.CreateDirectory(projectDirectory); File.Create(projectFile).Close(); } [TearDown] public void Cleanup() { Directory.Delete(projectDirectory, true); } [Test] public void VerifyIgnoreNonAssemblyInfoFile() { using (var writer = File.CreateText(Path.Combine(projectDirectory, "SomeOtherFile.cs"))) { writer.Write(@" using System; using System.Reflection; [assembly: AssemblyVersion(""1.0.0.0"")] "); } FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "SomeOtherFile.cs" } }, projectFile); } [Test] public void VerifyAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")] string attribute) { using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs"))) { writer.Write(@" using System; using System.Reflection; [assembly:{0}(""1.0.0.0"")] ", attribute); } var ex = Assert.Throws<WarningException>(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile), attribute); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.cs")); } [Test] public void VerifyUnformattedAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")] string attribute) { using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs"))) { writer.Write(@" using System; using System.Reflection; [ assembly : {0} ( ""1.0.0.0"")] ", attribute); } var ex = Assert.Throws<WarningException>(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile), attribute); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.cs")); } [Test] public void VerifyCommentWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs"))) { writer.Write(@" using System; using System.Reflection; //[assembly: {0}(""1.0.0.0"")] ", attribute); } FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile); } [Test] public void VerifyCommentWithNoNewLineAtEndWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs"))) { writer.Write(@" using System; using System.Reflection; //[assembly: {0}(""1.0.0.0"")]", attribute); } FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile); } [Test] public void VerifyStringWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs"))) { writer.Write(@" using System; using System.Reflection; public class Temp {{ static const string Foo = ""[assembly: {0}(""""1.0.0.0"""")]""; }} ", attribute); } FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile); } [Test] public void VerifyIdentifierWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs"))) { writer.Write(@" using System; using System.Reflection; public class {0} {{ }} ", attribute); } FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile); } [Test] public void VerifyAttributeFoundVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")] string attribute) { using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb"))) { writer.Write(@" Imports System Imports System.Reflection <Assembly:{0}(""1.0.0.0"")> ", attribute); } var ex = Assert.Throws<WarningException>(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile), attribute); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.vb")); } [Test] public void VerifyUnformattedAttributeFoundVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")] string attribute) { using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb"))) { writer.Write(@" Imports System Imports System.Reflection < Assembly : {0} ( ""1.0.0.0"")> ", attribute); } var ex = Assert.Throws<WarningException>(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile), attribute); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.vb")); } [Test] public void VerifyCommentWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb"))) { writer.Write(@" Imports System Imports System.Reflection '<Assembly: {0}(""1.0.0.0"")> ", attribute); } FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile); } [Test] public void VerifyCommentWithNoNewLineAtEndWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb"))) { writer.Write(@" Imports System Imports System.Reflection '<Assembly: {0}(""1.0.0.0"")>", attribute); } FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile); } [Test] public void VerifyStringWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb"))) { writer.Write(@" Imports System Imports System.Reflection Public Class Temp static const string Foo = ""<Assembly: {0}(""""1.0.0.0"""")>""; End Class ", attribute); } FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile); } [Test] public void VerifyIdentifierWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb"))) { writer.Write(@" Imports System Imports System.Reflection Public Class {0} End Class ", attribute); } FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile); } } }
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; namespace Firebase.Functions { /// <summary> /// FirebaseFunctions is a service that supports calling Google Cloud Functions. /// </summary> /// <remarks> /// FirebaseFunctions is a service that supports calling Google Cloud Functions. /// Pass a custom instance of /// <see cref="Firebase.FirebaseApp" /> /// to /// <see cref="GetInstance" /> /// which will use Auth and InstanceID from the app. /// . /// <p /> /// Otherwise, if you call /// <see cref="DefaultInstance" /> /// without a FirebaseApp, the /// FirebaseFunctions instance will initialize with the default /// <see cref="Firebase.FirebaseApp" /> /// obtainable from /// <see cref="FirebaseApp.DefaultInstance" />. /// </remarks> public sealed class FirebaseFunctions { // Dictionary of FirebaseFunctions instances indexed by a key FirebaseFunctionsInternal.InstanceKey. private static readonly Dictionary<string, FirebaseFunctions> functionsByInstanceKey = new Dictionary<string, FirebaseFunctions>(); // Proxy for the C++ firebase::functions::Functions object. private FirebaseFunctionsInternal functionsInternal; // Proxy for the C++ firebase::app:App object. private readonly FirebaseApp firebaseApp; // Key of this instance within functionsByInstanceKey. private string instanceKey; /// <summary> /// Construct a this instance associated with the specified app and region. /// </summary> /// <param name="functions">C# proxy for firebase::functions::Functions.</param> /// <param name="app">App the C# proxy functionsInternal was created from.</param> private FirebaseFunctions(FirebaseFunctionsInternal functions, FirebaseApp app, string region) { firebaseApp = app; firebaseApp.AppDisposed += OnAppDisposed; functionsInternal = functions; // As we know there is only one reference to the C++ firebase::functions::Functions object here // we'll let the proxy object take ownership so the C++ object can be deleted when the // proxy's Dispose() method is executed. functionsInternal.SetSwigCMemOwn(true); instanceKey = InstanceKey(app, region); } /// <summary> /// Remove the reference to this object from the functionsByInstanceKey dictionary. /// </summary> ~FirebaseFunctions() { Dispose(); } void OnAppDisposed(object sender, System.EventArgs eventArgs) { Dispose(); } // Remove the reference to this instance from functionsByInstanceKey and dispose the proxy. private void Dispose() { System.GC.SuppressFinalize(this); lock (functionsByInstanceKey) { if (functionsInternal == null) return; functionsByInstanceKey.Remove(instanceKey); functionsInternal.Dispose(); functionsInternal = null; firebaseApp.AppDisposed -= OnAppDisposed; } } /// <summary> /// Returns the /// <see cref="FirebaseFunctions" /> /// , initialized with the default /// <see cref="Firebase.FirebaseApp" /> /// . /// </summary> /// <value> /// a /// <see cref="FirebaseFunctions" /> /// instance. /// </value> public static FirebaseFunctions DefaultInstance { get { return GetInstance(FirebaseApp.DefaultInstance); } } /// <summary> /// The /// <see cref="Firebase.FirebaseApp" /> /// associated with this /// <see cref="FirebaseFunctions" /> /// instance. /// </summary> public FirebaseApp App { get { return firebaseApp; } } private static string InstanceKey(FirebaseApp app, string region) { return app.Name + "/" + region; } /// <summary> /// Returns the /// <see cref="FirebaseFunctions" /> /// , initialized with a custom /// <see cref="Firebase.FirebaseApp" /> /// </summary> /// <param name="app"> /// The custom /// <see cref="Firebase.FirebaseApp" /> /// used for initialization. /// </param> /// <returns> /// a /// <see cref="FirebaseFunctions" /> /// instance. /// </returns> public static FirebaseFunctions GetInstance(FirebaseApp app) { return GetInstance(app, "us-central1"); } /// <summary> /// Returns the /// <see cref="FirebaseFunctions" /> /// , initialized with the default <see cref="Firebase.FirebaseApp" />. /// </summary> /// <param name="region"> /// The region to call Cloud Functions in. /// </param> /// <returns> /// a /// <see cref="FirebaseFunctions" /> /// instance. /// </returns> public static FirebaseFunctions GetInstance(string region) { return GetInstance(FirebaseApp.DefaultInstance, region); } /// <summary> /// Returns the /// <see cref="FirebaseFunctions" /> /// , initialized with a custom /// <see cref="Firebase.FirebaseApp" /> /// and region. /// </summary> /// <param name="app"> /// The custom /// <see cref="Firebase.FirebaseApp" /> /// used for initialization. /// </param> /// <returns> /// a /// <see cref="FirebaseFunctions" /> /// instance. /// </returns> public static FirebaseFunctions GetInstance(FirebaseApp app, string region) { lock (functionsByInstanceKey) { var instanceKey = InstanceKey(app, region); FirebaseFunctions functions = null; if (functionsByInstanceKey.TryGetValue(instanceKey, out functions)) { if (functions != null) return functions; } app = app ?? FirebaseApp.DefaultInstance; InitResult initResult; FirebaseFunctionsInternal functionsInternal = FirebaseFunctionsInternal.GetInstanceInternal(app, region, out initResult); if (initResult != InitResult.Success) { throw new Firebase.InitializationException( initResult, Firebase.ErrorMessages.DllNotFoundExceptionErrorMessage); } else if (functionsInternal == null) { LogUtil.LogMessage(LogLevel.Warning, "Unable to create FirebaseFunctions."); return null; } functions = new FirebaseFunctions(functionsInternal, app, region); functionsByInstanceKey[instanceKey] = functions; return functions; } } // Throw a NullReferenceException if this proxy references a deleted object. private void ThrowIfNull() { if (functionsInternal == null || FirebaseFunctionsInternal.getCPtr(functionsInternal).Handle == System.IntPtr.Zero) { throw new System.NullReferenceException(); } } /// <summary> /// Creates a /// <see cref="HttpsCallableReference" /> /// given a name. /// </summary> public HttpsCallableReference GetHttpsCallable(string name) { ThrowIfNull(); return new HttpsCallableReference(this, functionsInternal.GetHttpsCallable(name)); } /// <summary> /// Sets an origin of a Cloud Functions Emulator instance to use. /// </summary> public void UseFunctionsEmulator(string origin) { ThrowIfNull(); functionsInternal.UseFunctionsEmulator(origin); } } }
// Copyright (c) 2012, Event Store LLP // 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 Event Store LLP 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.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; using EventStore.Common.Utils; using EventStore.Core.Util; using EventStore.Projections.Core.Messages; using EventStore.Projections.Core.Services.Processing; using EventStore.Projections.Core.v8; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Linq; namespace EventStore.Projections.Core.Services.v8 { public class V8ProjectionStateHandler : IProjectionStateHandler { private readonly PreludeScript _prelude; private readonly QueryScript _query; private List<EmittedEventEnvelope> _emittedEvents; private CheckpointTag _eventPosition; private bool _disposed; public V8ProjectionStateHandler( string preludeName, string querySource, Func<string, Tuple<string, string>> getModuleSource, Action<string> logger, Action<int, Action> cancelCallbackFactory) { var preludeSource = getModuleSource(preludeName); var prelude = new PreludeScript(preludeSource.Item1, preludeSource.Item2, getModuleSource, cancelCallbackFactory, logger); QueryScript query; try { query = new QueryScript(prelude, querySource, "POST-BODY"); query.Emit += QueryOnEmit; } catch { prelude.Dispose(); // clean up unmanaged resources if failed to create throw; } _prelude = prelude; _query = query; } [DataContract] public class EmittedEventJsonContract { [DataMember] public string streamId; [DataMember] public string eventName; [DataMember] public bool isJson; [DataMember] public string body; [DataMember] public Dictionary<string, JRaw> metadata; public ExtraMetaData GetExtraMetadata() { if (metadata == null) return null; return new ExtraMetaData(metadata); } } private void QueryOnEmit(string json) { EmittedEventJsonContract emittedEvent; try { emittedEvent = json.ParseJson<EmittedEventJsonContract>(); } catch (Exception ex) { throw new ArgumentException("Failed to deserialize emitted event JSON", ex); } if (_emittedEvents == null) _emittedEvents = new List<EmittedEventEnvelope>(); _emittedEvents.Add( new EmittedEventEnvelope( new EmittedDataEvent( emittedEvent.streamId, Guid.NewGuid(), emittedEvent.eventName, emittedEvent.isJson, emittedEvent.body, emittedEvent.GetExtraMetadata(), _eventPosition, expectedTag: null))); } private QuerySourcesDefinition GetQuerySourcesDefinition() { CheckDisposed(); var sourcesDefinition = _query.GetSourcesDefintion(); if (sourcesDefinition == null) throw new InvalidOperationException("Invalid query. No source definition."); return sourcesDefinition; } public void Load(string state) { CheckDisposed(); _query.SetState(state); } public void LoadShared(string state) { CheckDisposed(); _query.SetSharedState(state); } public void Initialize() { CheckDisposed(); _query.Initialize(); } public void InitializeShared() { CheckDisposed(); _query.InitializeShared(); } public string GetStatePartition( CheckpointTag eventPosition, string category, ResolvedEvent @event) { CheckDisposed(); if (@event == null) throw new ArgumentNullException("event"); var partition = _query.GetPartition( @event.Data.Trim(), // trimming data passed to a JS new string[] { @event.EventStreamId, @event.IsJson ? "1" : "", @event.EventType, category ?? "", @event.EventSequenceNumber.ToString(CultureInfo.InvariantCulture), @event.Metadata ?? "", @event.PositionMetadata ?? "" }); if (partition == "") return null; else return partition; } public string TransformCatalogEvent(CheckpointTag eventPosition, ResolvedEvent data) { CheckDisposed(); if (data == null) throw new ArgumentNullException("data"); return _query.TransformCatalogEvent( (data.Data ?? "").Trim(), // trimming data passed to a JS new[] { data.IsJson ? "1" : "", data.EventStreamId, data.EventType ?? "", "", data.EventSequenceNumber.ToString(CultureInfo.InvariantCulture), data.Metadata ?? "", data.PositionMetadata ?? "", data.EventStreamId, data.StreamMetadata ?? "" }); } public bool ProcessEvent( string partition, CheckpointTag eventPosition, string category, ResolvedEvent data, out string newState, out string newSharedState, out EmittedEventEnvelope[] emittedEvents) { CheckDisposed(); if (data == null) throw new ArgumentNullException("data"); _eventPosition = eventPosition; _emittedEvents = null; var newStates = _query.Push( data.Data.Trim(), // trimming data passed to a JS new[] { data.IsJson ? "1" : "", data.EventStreamId, data.EventType, category ?? "", data.EventSequenceNumber.ToString(CultureInfo.InvariantCulture), data.Metadata ?? "", data.PositionMetadata ?? "", partition, "" }); newState = newStates.Item1; newSharedState = newStates.Item2; /* try { if (!string.IsNullOrEmpty(newState)) { var jo = newState.ParseJson<JObject>(); } } catch (InvalidCastException) { Console.Error.WriteLine(newState); } catch (JsonException) { Console.Error.WriteLine(newState); }*/ emittedEvents = _emittedEvents == null ? null : _emittedEvents.ToArray(); return true; } public string TransformStateToResult() { CheckDisposed(); var result = _query.TransformStateToResult(); return result; } private void CheckDisposed() { if (_disposed) throw new InvalidOperationException("Disposed"); } public void Dispose() { _disposed = true; if (_query != null) _query.Dispose(); if (_prelude != null) _prelude.Dispose(); } public IQuerySources GetSourceDefinition() { return GetQuerySourcesDefinition(); } } }
// 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.IO; using System.Linq; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Audio.Sample; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Events; using osu.Framework.Logging; using osu.Framework.Screens; using osu.Framework.Threading; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Graphics.Containers; using osu.Game.IO.Archives; using osu.Game.Online.API; using osu.Game.Online.Spectator; using osu.Game.Overlays; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.UI; using osu.Game.Scoring; using osu.Game.Scoring.Legacy; using osu.Game.Screens.Ranking; using osu.Game.Skinning; using osu.Game.Users; using osuTK.Graphics; namespace osu.Game.Screens.Play { [Cached] [Cached(typeof(ISamplePlaybackDisabler))] public abstract class Player : ScreenWithBeatmapBackground, ISamplePlaybackDisabler, ILocalUserPlayInfo { /// <summary> /// The delay upon completion of the beatmap before displaying the results screen. /// </summary> public const double RESULTS_DISPLAY_DELAY = 1000.0; public override bool AllowBackButton => false; // handled by HoldForMenuButton protected override UserActivity InitialActivity => new UserActivity.InSoloGame(Beatmap.Value.BeatmapInfo, Ruleset.Value); public override float BackgroundParallaxAmount => 0.1f; public override bool HideOverlaysOnEnter => true; protected override OverlayActivation InitialOverlayActivationMode => OverlayActivation.UserTriggered; // We are managing our own adjustments (see OnEntering/OnExiting). public override bool? AllowTrackAdjustments => false; private readonly IBindable<bool> gameActive = new Bindable<bool>(true); private readonly Bindable<bool> samplePlaybackDisabled = new Bindable<bool>(); /// <summary> /// Whether gameplay should pause when the game window focus is lost. /// </summary> protected virtual bool PauseOnFocusLost => true; public Action RestartRequested; public bool HasFailed { get; private set; } private Bindable<bool> mouseWheelDisabled; private readonly Bindable<bool> storyboardReplacesBackground = new Bindable<bool>(); public IBindable<bool> LocalUserPlaying => localUserPlaying; private readonly Bindable<bool> localUserPlaying = new Bindable<bool>(); public int RestartCount; [Resolved] private ScoreManager scoreManager { get; set; } [Resolved] private IAPIProvider api { get; set; } [Resolved] private MusicController musicController { get; set; } [Resolved] private SpectatorClient spectatorClient { get; set; } public GameplayState GameplayState { get; private set; } private Ruleset ruleset; private Sample sampleRestart; public BreakOverlay BreakOverlay; /// <summary> /// Whether the gameplay is currently in a break. /// </summary> public readonly IBindable<bool> IsBreakTime = new BindableBool(); private BreakTracker breakTracker; private SkipOverlay skipIntroOverlay; private SkipOverlay skipOutroOverlay; protected ScoreProcessor ScoreProcessor { get; private set; } protected HealthProcessor HealthProcessor { get; private set; } protected DrawableRuleset DrawableRuleset { get; private set; } protected HUDOverlay HUDOverlay { get; private set; } public bool LoadedBeatmapSuccessfully => DrawableRuleset?.Objects.Any() == true; protected GameplayClockContainer GameplayClockContainer { get; private set; } public DimmableStoryboard DimmableStoryboard { get; private set; } /// <summary> /// Whether failing should be allowed. /// By default, this checks whether all selected mods allow failing. /// </summary> protected virtual bool CheckModsAllowFailure() => GameplayState.Mods.OfType<IApplicableFailOverride>().All(m => m.PerformFail()); public readonly PlayerConfiguration Configuration; protected Score Score { get; private set; } /// <summary> /// Create a new player instance. /// </summary> protected Player(PlayerConfiguration configuration = null) { Configuration = configuration ?? new PlayerConfiguration(); } private ScreenSuspensionHandler screenSuspension; private DependencyContainer dependencies; protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) => dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); protected override void LoadComplete() { base.LoadComplete(); if (!LoadedBeatmapSuccessfully) return; PrepareReplay(); ScoreProcessor.NewJudgement += result => ScoreProcessor.PopulateScore(Score.ScoreInfo); gameActive.BindValueChanged(_ => updatePauseOnFocusLostState(), true); } /// <summary> /// Run any recording / playback setup for replays. /// </summary> protected virtual void PrepareReplay() { DrawableRuleset.SetRecordTarget(Score); } [BackgroundDependencyLoader(true)] private void load(AudioManager audio, OsuConfigManager config, OsuGameBase game) { var gameplayMods = Mods.Value.Select(m => m.DeepClone()).ToArray(); if (Beatmap.Value is DummyWorkingBeatmap) return; IBeatmap playableBeatmap = loadPlayableBeatmap(gameplayMods); if (playableBeatmap == null) return; sampleRestart = audio.Samples.Get(@"Gameplay/restart"); mouseWheelDisabled = config.GetBindable<bool>(OsuSetting.MouseDisableWheel); if (game != null) gameActive.BindTo(game.IsActive); if (game is OsuGame osuGame) LocalUserPlaying.BindTo(osuGame.LocalUserPlaying); DrawableRuleset = ruleset.CreateDrawableRulesetWith(playableBeatmap, gameplayMods); dependencies.CacheAs(DrawableRuleset); ScoreProcessor = ruleset.CreateScoreProcessor(); ScoreProcessor.ApplyBeatmap(playableBeatmap); ScoreProcessor.Mods.Value = gameplayMods; dependencies.CacheAs(ScoreProcessor); HealthProcessor = ruleset.CreateHealthProcessor(playableBeatmap.HitObjects[0].StartTime); HealthProcessor.ApplyBeatmap(playableBeatmap); dependencies.CacheAs(HealthProcessor); if (!ScoreProcessor.Mode.Disabled) config.BindWith(OsuSetting.ScoreDisplayMode, ScoreProcessor.Mode); InternalChild = GameplayClockContainer = CreateGameplayClockContainer(Beatmap.Value, DrawableRuleset.GameplayStartTime); AddInternal(screenSuspension = new ScreenSuspensionHandler(GameplayClockContainer)); Score = CreateScore(playableBeatmap); // ensure the score is in a consistent state with the current player. Score.ScoreInfo.BeatmapInfo = Beatmap.Value.BeatmapInfo; Score.ScoreInfo.Ruleset = ruleset.RulesetInfo; if (ruleset.RulesetInfo.ID != null) Score.ScoreInfo.RulesetID = ruleset.RulesetInfo.ID.Value; Score.ScoreInfo.Mods = gameplayMods; dependencies.CacheAs(GameplayState = new GameplayState(playableBeatmap, ruleset, gameplayMods, Score)); var rulesetSkinProvider = new RulesetSkinProvidingContainer(ruleset, playableBeatmap, Beatmap.Value.Skin); // load the skinning hierarchy first. // this is intentionally done in two stages to ensure things are in a loaded state before exposing the ruleset to skin sources. GameplayClockContainer.Add(rulesetSkinProvider); rulesetSkinProvider.AddRange(new Drawable[] { failAnimationLayer = new FailAnimation(DrawableRuleset) { OnComplete = onFailComplete, Children = new[] { // underlay and gameplay should have access to the skinning sources. createUnderlayComponents(), createGameplayComponents(Beatmap.Value, playableBeatmap) } }, FailOverlay = new FailOverlay { OnRetry = Restart, OnQuit = () => PerformExit(true), }, new HotkeyExitOverlay { Action = () => { if (!this.IsCurrentScreen()) return; fadeOut(true); PerformExit(false); }, }, }); if (Configuration.AllowRestart) { rulesetSkinProvider.Add(new HotkeyRetryOverlay { Action = () => { if (!this.IsCurrentScreen()) return; fadeOut(true); Restart(); }, }); } // add the overlay components as a separate step as they proxy some elements from the above underlay/gameplay components. // also give the overlays the ruleset skin provider to allow rulesets to potentially override HUD elements (used to disable combo counters etc.) // we may want to limit this in the future to disallow rulesets from outright replacing elements the user expects to be there. failAnimationLayer.Add(createOverlayComponents(Beatmap.Value)); if (!DrawableRuleset.AllowGameplayOverlays) { HUDOverlay.ShowHud.Value = false; HUDOverlay.ShowHud.Disabled = true; BreakOverlay.Hide(); } DrawableRuleset.FrameStableClock.WaitingOnFrames.BindValueChanged(waiting => { if (waiting.NewValue) GameplayClockContainer.Stop(); else GameplayClockContainer.Start(); }); DrawableRuleset.IsPaused.BindValueChanged(paused => { updateGameplayState(); updateSampleDisabledState(); }); DrawableRuleset.FrameStableClock.IsCatchingUp.BindValueChanged(_ => updateSampleDisabledState()); DrawableRuleset.HasReplayLoaded.BindValueChanged(_ => updateGameplayState()); // bind clock into components that require it DrawableRuleset.IsPaused.BindTo(GameplayClockContainer.IsPaused); DrawableRuleset.NewResult += r => { HealthProcessor.ApplyResult(r); ScoreProcessor.ApplyResult(r); GameplayState.ApplyResult(r); }; DrawableRuleset.RevertResult += r => { HealthProcessor.RevertResult(r); ScoreProcessor.RevertResult(r); }; DimmableStoryboard.HasStoryboardEnded.ValueChanged += storyboardEnded => { if (storyboardEnded.NewValue) progressToResults(true); }; // Bind the judgement processors to ourselves ScoreProcessor.HasCompleted.BindValueChanged(scoreCompletionChanged); HealthProcessor.Failed += onFail; // Provide judgement processors to mods after they're loaded so that they're on the gameplay clock, // this is required for mods that apply transforms to these processors. ScoreProcessor.OnLoadComplete += _ => { foreach (var mod in gameplayMods.OfType<IApplicableToScoreProcessor>()) mod.ApplyToScoreProcessor(ScoreProcessor); }; HealthProcessor.OnLoadComplete += _ => { foreach (var mod in gameplayMods.OfType<IApplicableToHealthProcessor>()) mod.ApplyToHealthProcessor(HealthProcessor); }; IsBreakTime.BindTo(breakTracker.IsBreakTime); IsBreakTime.BindValueChanged(onBreakTimeChanged, true); } protected virtual GameplayClockContainer CreateGameplayClockContainer(WorkingBeatmap beatmap, double gameplayStart) => new MasterGameplayClockContainer(beatmap, gameplayStart); private Drawable createUnderlayComponents() => DimmableStoryboard = new DimmableStoryboard(Beatmap.Value.Storyboard) { RelativeSizeAxes = Axes.Both }; private Drawable createGameplayComponents(WorkingBeatmap working, IBeatmap playableBeatmap) => new ScalingContainer(ScalingMode.Gameplay) { Children = new Drawable[] { DrawableRuleset.With(r => r.FrameStableComponents.Children = new Drawable[] { ScoreProcessor, HealthProcessor, new ComboEffects(ScoreProcessor), breakTracker = new BreakTracker(DrawableRuleset.GameplayStartTime, ScoreProcessor) { Breaks = working.Beatmap.Breaks } }), } }; private Drawable createOverlayComponents(WorkingBeatmap working) { var container = new Container { RelativeSizeAxes = Axes.Both, Children = new[] { DimmableStoryboard.OverlayLayerContainer.CreateProxy(), BreakOverlay = new BreakOverlay(working.Beatmap.BeatmapInfo.LetterboxInBreaks, ScoreProcessor) { Clock = DrawableRuleset.FrameStableClock, ProcessCustomClock = false, Breaks = working.Beatmap.Breaks }, // display the cursor above some HUD elements. DrawableRuleset.Cursor?.CreateProxy() ?? new Container(), DrawableRuleset.ResumeOverlay?.CreateProxy() ?? new Container(), HUDOverlay = new HUDOverlay(DrawableRuleset, GameplayState.Mods) { HoldToQuit = { Action = () => PerformExit(true), IsPaused = { BindTarget = GameplayClockContainer.IsPaused } }, KeyCounter = { AlwaysVisible = { BindTarget = DrawableRuleset.HasReplayLoaded }, IsCounting = false }, Anchor = Anchor.Centre, Origin = Anchor.Centre }, skipIntroOverlay = new SkipOverlay(DrawableRuleset.GameplayStartTime) { RequestSkip = performUserRequestedSkip }, skipOutroOverlay = new SkipOverlay(Beatmap.Value.Storyboard.LatestEventTime ?? 0) { RequestSkip = () => progressToResults(false), Alpha = 0 }, PauseOverlay = new PauseOverlay { OnResume = Resume, Retries = RestartCount, OnRetry = Restart, OnQuit = () => PerformExit(true), }, }, }; if (!Configuration.AllowSkipping || !DrawableRuleset.AllowGameplayOverlays) { skipIntroOverlay.Expire(); skipOutroOverlay.Expire(); } if (GameplayClockContainer is MasterGameplayClockContainer master) HUDOverlay.PlayerSettingsOverlay.PlaybackSettings.UserPlaybackRate.BindTarget = master.UserPlaybackRate; return container; } private void onBreakTimeChanged(ValueChangedEvent<bool> isBreakTime) { updateGameplayState(); updatePauseOnFocusLostState(); HUDOverlay.KeyCounter.IsCounting = !isBreakTime.NewValue; } private void updateGameplayState() { bool inGameplay = !DrawableRuleset.HasReplayLoaded.Value && !DrawableRuleset.IsPaused.Value && !breakTracker.IsBreakTime.Value; OverlayActivationMode.Value = inGameplay ? OverlayActivation.Disabled : OverlayActivation.UserTriggered; localUserPlaying.Value = inGameplay; } private void updateSampleDisabledState() { samplePlaybackDisabled.Value = DrawableRuleset.FrameStableClock.IsCatchingUp.Value || GameplayClockContainer.GameplayClock.IsPaused.Value; } private void updatePauseOnFocusLostState() { if (!PauseOnFocusLost || !pausingSupportedByCurrentState || breakTracker.IsBreakTime.Value) return; if (gameActive.Value == false) { bool paused = Pause(); // if the initial pause could not be satisfied, the pause cooldown may be active. // reschedule the pause attempt until it can be achieved. if (!paused) Scheduler.AddOnce(updatePauseOnFocusLostState); } } private IBeatmap loadPlayableBeatmap(Mod[] gameplayMods) { IBeatmap playable; try { if (Beatmap.Value.Beatmap == null) throw new InvalidOperationException("Beatmap was not loaded"); var rulesetInfo = Ruleset.Value ?? Beatmap.Value.BeatmapInfo.Ruleset; ruleset = rulesetInfo.CreateInstance(); try { playable = Beatmap.Value.GetPlayableBeatmap(ruleset.RulesetInfo, gameplayMods); } catch (BeatmapInvalidForRulesetException) { // A playable beatmap may not be creatable with the user's preferred ruleset, so try using the beatmap's default ruleset rulesetInfo = Beatmap.Value.BeatmapInfo.Ruleset; ruleset = rulesetInfo.CreateInstance(); playable = Beatmap.Value.GetPlayableBeatmap(rulesetInfo, gameplayMods); } if (playable.HitObjects.Count == 0) { Logger.Log("Beatmap contains no hit objects!", level: LogLevel.Error); return null; } } catch (Exception e) { Logger.Error(e, "Could not load beatmap successfully!"); //couldn't load, hard abort! return null; } return playable; } /// <summary> /// Attempts to complete a user request to exit gameplay. /// </summary> /// <remarks> /// <list type="bullet"> /// <item>This should only be called in response to a user interaction. Exiting is not guaranteed.</item> /// <item>This will interrupt any pending progression to the results screen, even if the transition has begun.</item> /// </list> /// </remarks> /// <param name="showDialogFirst"> /// Whether the pause or fail dialog should be shown before performing an exit. /// If <see langword="true"/> and a dialog is not yet displayed, the exit will be blocked and the relevant dialog will display instead. /// </param> protected void PerformExit(bool showDialogFirst) { // if an exit has been requested, cancel any pending completion (the user has shown intention to exit). resultsDisplayDelegate?.Cancel(); // there is a chance that an exit request occurs after the transition to results has already started. // even in such a case, the user has shown intent, so forcefully return to this screen (to proceed with the upwards exit process). if (!this.IsCurrentScreen()) { ValidForResume = false; // in the potential case that this instance has already been exited, this is required to avoid a crash. if (this.GetChildScreen() != null) this.MakeCurrent(); return; } bool pauseOrFailDialogVisible = PauseOverlay.State.Value == Visibility.Visible || FailOverlay.State.Value == Visibility.Visible; if (showDialogFirst && !pauseOrFailDialogVisible) { // if the fail animation is currently in progress, accelerate it (it will show the pause dialog on completion). if (ValidForResume && HasFailed) { failAnimationLayer.FinishTransforms(true); return; } // even if this call has requested a dialog, there is a chance the current player mode doesn't support pausing. if (pausingSupportedByCurrentState) { // in the case a dialog needs to be shown, attempt to pause and show it. // this may fail (see internal checks in Pause()) but the fail cases are temporary, so don't fall through to Exit(). Pause(); return; } } // The actual exit is performed if // - the pause / fail dialog was not requested // - the pause / fail dialog was requested but is already displayed (user showing intention to exit). // - the pause / fail dialog was requested but couldn't be displayed due to the type or state of this Player instance. this.Exit(); } private void performUserRequestedSkip() { // user requested skip // disable sample playback to stop currently playing samples and perform skip samplePlaybackDisabled.Value = true; (GameplayClockContainer as MasterGameplayClockContainer)?.Skip(); // return samplePlaybackDisabled.Value to what is defined by the beatmap's current state updateSampleDisabledState(); } /// <summary> /// Seek to a specific time in gameplay. /// </summary> /// <param name="time">The destination time to seek to.</param> public void Seek(double time) => GameplayClockContainer.Seek(time); private ScheduledDelegate frameStablePlaybackResetDelegate; /// <summary> /// Seeks to a specific time in gameplay, bypassing frame stability. /// </summary> /// <remarks> /// Intermediate hitobject judgements may not be applied or reverted correctly during this seek. /// </remarks> /// <param name="time">The destination time to seek to.</param> internal void NonFrameStableSeek(double time) { if (frameStablePlaybackResetDelegate?.Cancelled == false && !frameStablePlaybackResetDelegate.Completed) frameStablePlaybackResetDelegate.RunTask(); bool wasFrameStable = DrawableRuleset.FrameStablePlayback; DrawableRuleset.FrameStablePlayback = false; Seek(time); // Delay resetting frame-stable playback for one frame to give the FrameStabilityContainer a chance to seek. frameStablePlaybackResetDelegate = ScheduleAfterChildren(() => DrawableRuleset.FrameStablePlayback = wasFrameStable); } /// <summary> /// Restart gameplay via a parent <see cref="PlayerLoader"/>. /// <remarks>This can be called from a child screen in order to trigger the restart process.</remarks> /// </summary> public void Restart() { if (!Configuration.AllowRestart) return; // at the point of restarting the track should either already be paused or the volume should be zero. // stopping here is to ensure music doesn't become audible after exiting back to PlayerLoader. musicController.Stop(); sampleRestart?.Play(); RestartRequested?.Invoke(); PerformExit(false); } /// <summary> /// This delegate, when set, means the results screen has been queued to appear. /// The display of the results screen may be delayed by any work being done in <see cref="PrepareScoreForResultsAsync"/>. /// </summary> /// <remarks> /// Once set, this can *only* be cancelled by rewinding, ie. if <see cref="JudgementProcessor.HasCompleted">ScoreProcessor.HasCompleted</see> becomes <see langword="false"/>. /// Even if the user requests an exit, it will forcefully proceed to the results screen (see special case in <see cref="OnExiting"/>). /// </remarks> private ScheduledDelegate resultsDisplayDelegate; /// <summary> /// A task which asynchronously prepares a completed score for display at results. /// This may include performing net requests or importing the score into the database, generally to ensure things are in a sane state for the play session. /// </summary> private Task<ScoreInfo> prepareScoreForDisplayTask; /// <summary> /// Handles changes in player state which may progress the completion of gameplay / this screen's lifetime. /// </summary> /// <exception cref="InvalidOperationException">Thrown if this method is called more than once without changing state.</exception> private void scoreCompletionChanged(ValueChangedEvent<bool> completed) { // If this player instance is in the middle of an exit, don't attempt any kind of state update. if (!this.IsCurrentScreen()) return; // Special case to handle rewinding post-completion. This is the only way already queued forward progress can be cancelled. // TODO: Investigate whether this can be moved to a RewindablePlayer subclass or similar. // Currently, even if this scenario is hit, prepareScoreForDisplay has already been queued (and potentially run). // In scenarios where rewinding is possible (replay, spectating) this is a non-issue as no submission/import work is done, // but it still doesn't feel right that this exists here. if (!completed.NewValue) { resultsDisplayDelegate?.Cancel(); resultsDisplayDelegate = null; ValidForResume = true; skipOutroOverlay.Hide(); return; } // Only show the completion screen if the player hasn't failed if (HealthProcessor.HasFailed) return; // Setting this early in the process means that even if something were to go wrong in the order of events following, there // is no chance that a user could return to the (already completed) Player instance from a child screen. ValidForResume = false; // Ensure we are not writing to the replay any more, as we are about to consume and store the score. DrawableRuleset.SetRecordTarget(null); if (!Configuration.ShowResults) return; prepareScoreForDisplayTask ??= Task.Run(prepareScoreForResults); bool storyboardHasOutro = DimmableStoryboard.ContentDisplayed && !DimmableStoryboard.HasStoryboardEnded.Value; if (storyboardHasOutro) { // if the current beatmap has a storyboard, the progression to results will be handled by the storyboard ending // or the user pressing the skip outro button. skipOutroOverlay.Show(); return; } progressToResults(true); } /// <summary> /// Asynchronously run score preparation operations (database import, online submission etc.). /// </summary> /// <returns>The final score.</returns> private async Task<ScoreInfo> prepareScoreForResults() { var scoreCopy = Score.DeepClone(); try { await PrepareScoreForResultsAsync(scoreCopy).ConfigureAwait(false); } catch (Exception ex) { Logger.Error(ex, @"Score preparation failed!"); } try { await ImportScore(scoreCopy).ConfigureAwait(false); } catch (Exception ex) { Logger.Error(ex, @"Score import failed!"); } return scoreCopy.ScoreInfo; } /// <summary> /// Queue the results screen for display. /// </summary> /// <remarks> /// A final display will only occur once all work is completed in <see cref="PrepareScoreForResultsAsync"/>. This means that even after calling this method, the results screen will never be shown until <see cref="JudgementProcessor.HasCompleted">ScoreProcessor.HasCompleted</see> becomes <see langword="true"/>. /// /// Calling this method multiple times will have no effect. /// </remarks> /// <param name="withDelay">Whether a minimum delay (<see cref="RESULTS_DISPLAY_DELAY"/>) should be added before the screen is displayed.</param> private void progressToResults(bool withDelay) { if (resultsDisplayDelegate != null) // Note that if progressToResults is called one withDelay=true and then withDelay=false, this no-delay timing will not be // accounted for. shouldn't be a huge concern (a user pressing the skip button after a results progression has already been queued // may take x00 more milliseconds than expected in the very rare edge case). // // If required we can handle this more correctly by rescheduling here. return; double delay = withDelay ? RESULTS_DISPLAY_DELAY : 0; resultsDisplayDelegate = new ScheduledDelegate(() => { if (prepareScoreForDisplayTask?.IsCompleted != true) // If the asynchronous preparation has not completed, keep repeating this delegate. return; resultsDisplayDelegate?.Cancel(); if (!this.IsCurrentScreen()) // This player instance may already be in the process of exiting. return; this.Push(CreateResults(prepareScoreForDisplayTask.Result)); }, Time.Current + delay, 50); Scheduler.Add(resultsDisplayDelegate); } protected override bool OnScroll(ScrollEvent e) => mouseWheelDisabled.Value && !GameplayClockContainer.IsPaused.Value; #region Fail Logic protected FailOverlay FailOverlay { get; private set; } private FailAnimation failAnimationLayer; private bool onFail() { if (!CheckModsAllowFailure()) return false; HasFailed = true; Score.ScoreInfo.Passed = false; // There is a chance that we could be in a paused state as the ruleset's internal clock (see FrameStabilityContainer) // could process an extra frame after the GameplayClock is stopped. // In such cases we want the fail state to precede a user triggered pause. if (PauseOverlay.State.Value == Visibility.Visible) PauseOverlay.Hide(); failAnimationLayer.Start(); if (GameplayState.Mods.OfType<IApplicableFailOverride>().Any(m => m.RestartOnFail)) Restart(); return true; } // Called back when the transform finishes private void onFailComplete() { GameplayClockContainer.Stop(); FailOverlay.Retries = RestartCount; FailOverlay.Show(); } #endregion #region Pause Logic public bool IsResuming { get; private set; } /// <summary> /// The amount of gameplay time after which a second pause is allowed. /// </summary> private const double pause_cooldown = 1000; protected PauseOverlay PauseOverlay { get; private set; } private double? lastPauseActionTime; protected bool PauseCooldownActive => lastPauseActionTime.HasValue && GameplayClockContainer.GameplayClock.CurrentTime < lastPauseActionTime + pause_cooldown; /// <summary> /// A set of conditionals which defines whether the current game state and configuration allows for /// pausing to be attempted via <see cref="Pause"/>. If false, the game should generally exit if a user pause /// is attempted. /// </summary> private bool pausingSupportedByCurrentState => // must pass basic screen conditions (beatmap loaded, instance allows pause) LoadedBeatmapSuccessfully && Configuration.AllowPause && ValidForResume // replays cannot be paused and exit immediately && !DrawableRuleset.HasReplayLoaded.Value // cannot pause if we are already in a fail state && !HasFailed; private bool canResume => // cannot resume from a non-paused state GameplayClockContainer.IsPaused.Value // cannot resume if we are already in a fail state && !HasFailed // already resuming && !IsResuming; public bool Pause() { if (!pausingSupportedByCurrentState) return false; if (!IsResuming && PauseCooldownActive) return false; if (IsResuming) { DrawableRuleset.CancelResume(); IsResuming = false; } GameplayClockContainer.Stop(); PauseOverlay.Show(); lastPauseActionTime = GameplayClockContainer.GameplayClock.CurrentTime; return true; } public void Resume() { if (!canResume) return; IsResuming = true; PauseOverlay.Hide(); // breaks and time-based conditions may allow instant resume. if (breakTracker.IsBreakTime.Value) completeResume(); else DrawableRuleset.RequestResume(completeResume); void completeResume() { GameplayClockContainer.Start(); IsResuming = false; } } #endregion #region Screen Logic public override void OnEntering(IScreen last) { base.OnEntering(last); if (!LoadedBeatmapSuccessfully) return; Alpha = 0; this .ScaleTo(0.7f) .ScaleTo(1, 750, Easing.OutQuint) .Delay(250) .FadeIn(250); ApplyToBackground(b => { b.IgnoreUserSettings.Value = false; b.BlurAmount.Value = 0; b.FadeColour(Color4.White, 250); // bind component bindables. b.IsBreakTime.BindTo(breakTracker.IsBreakTime); b.StoryboardReplacesBackground.BindTo(storyboardReplacesBackground); }); HUDOverlay.IsBreakTime.BindTo(breakTracker.IsBreakTime); DimmableStoryboard.IsBreakTime.BindTo(breakTracker.IsBreakTime); DimmableStoryboard.StoryboardReplacesBackground.BindTo(storyboardReplacesBackground); storyboardReplacesBackground.Value = Beatmap.Value.Storyboard.ReplacesBackground && Beatmap.Value.Storyboard.HasDrawable; foreach (var mod in GameplayState.Mods.OfType<IApplicableToPlayer>()) mod.ApplyToPlayer(this); foreach (var mod in GameplayState.Mods.OfType<IApplicableToHUD>()) mod.ApplyToHUD(HUDOverlay); // Our mods are local copies of the global mods so they need to be re-applied to the track. // This is done through the music controller (for now), because resetting speed adjustments on the beatmap track also removes adjustments provided by DrawableTrack. // Todo: In the future, player will receive in a track and will probably not have to worry about this... musicController.ResetTrackAdjustments(); foreach (var mod in GameplayState.Mods.OfType<IApplicableToTrack>()) mod.ApplyToTrack(musicController.CurrentTrack); updateGameplayState(); GameplayClockContainer.FadeInFromZero(750, Easing.OutQuint); StartGameplay(); } /// <summary> /// Called to trigger the starting of the gameplay clock and underlying gameplay. /// This will be called on entering the player screen once. A derived class may block the first call to this to delay the start of gameplay. /// </summary> protected virtual void StartGameplay() { if (GameplayClockContainer.GameplayClock.IsRunning) throw new InvalidOperationException($"{nameof(StartGameplay)} should not be called when the gameplay clock is already running"); GameplayClockContainer.Reset(); } public override void OnSuspending(IScreen next) { screenSuspension?.RemoveAndDisposeImmediately(); fadeOut(); base.OnSuspending(next); } public override bool OnExiting(IScreen next) { screenSuspension?.RemoveAndDisposeImmediately(); failAnimationLayer?.RemoveFilters(); // if arriving here and the results screen preparation task hasn't run, it's safe to say the user has not completed the beatmap. if (prepareScoreForDisplayTask == null) { Score.ScoreInfo.Passed = false; // potentially should be ScoreRank.F instead? this is the best alternative for now. Score.ScoreInfo.Rank = ScoreRank.D; } // EndPlaying() is typically called from ReplayRecorder.Dispose(). Disposal is currently asynchronous. // To resolve test failures, forcefully end playing synchronously when this screen exits. // Todo: Replace this with a more permanent solution once osu-framework has a synchronous cleanup method. spectatorClient.EndPlaying(); // GameplayClockContainer performs seeks / start / stop operations on the beatmap's track. // as we are no longer the current screen, we cannot guarantee the track is still usable. (GameplayClockContainer as MasterGameplayClockContainer)?.StopUsingBeatmapClock(); musicController.ResetTrackAdjustments(); fadeOut(); return base.OnExiting(next); } /// <summary> /// Creates the player's <see cref="Scoring.Score"/>. /// </summary> /// <param name="beatmap"></param> /// <returns>The <see cref="Scoring.Score"/>.</returns> protected virtual Score CreateScore(IBeatmap beatmap) => new Score { ScoreInfo = new ScoreInfo { User = api.LocalUser.Value }, }; /// <summary> /// Imports the player's <see cref="Scoring.Score"/> to the local database. /// </summary> /// <param name="score">The <see cref="Scoring.Score"/> to import.</param> /// <returns>The imported score.</returns> protected virtual async Task ImportScore(Score score) { // Replays are already populated and present in the game's database, so should not be re-imported. if (DrawableRuleset.ReplayScore != null) return; LegacyByteArrayReader replayReader; using (var stream = new MemoryStream()) { new LegacyScoreEncoder(score, GameplayState.Beatmap).Encode(stream); replayReader = new LegacyByteArrayReader(stream.ToArray(), "replay.osr"); } // For the time being, online ID responses are not really useful for anything. // In addition, the IDs provided via new (lazer) endpoints are based on a different autoincrement from legacy (stable) scores. // // Until we better define the server-side logic behind this, let's not store the online ID to avoid potential unique constraint // conflicts across various systems (ie. solo and multiplayer). long? onlineScoreId = score.ScoreInfo.OnlineScoreID; score.ScoreInfo.OnlineScoreID = null; await scoreManager.Import(score.ScoreInfo, replayReader).ConfigureAwait(false); // ... And restore the online ID for other processes to handle correctly (e.g. de-duplication for the results screen). score.ScoreInfo.OnlineScoreID = onlineScoreId; } /// <summary> /// Prepare the <see cref="Scoring.Score"/> for display at results. /// </summary> /// <param name="score">The <see cref="Scoring.Score"/> to prepare.</param> /// <returns>A task that prepares the provided score. On completion, the score is assumed to be ready for display.</returns> protected virtual Task PrepareScoreForResultsAsync(Score score) => Task.CompletedTask; /// <summary> /// Creates the <see cref="ResultsScreen"/> for a <see cref="ScoreInfo"/>. /// </summary> /// <param name="score">The <see cref="ScoreInfo"/> to be displayed in the results screen.</param> /// <returns>The <see cref="ResultsScreen"/>.</returns> protected virtual ResultsScreen CreateResults(ScoreInfo score) => new SoloResultsScreen(score, true); private void fadeOut(bool instant = false) { float fadeOutDuration = instant ? 0 : 250; this.FadeOut(fadeOutDuration); ApplyToBackground(b => b.IgnoreUserSettings.Value = true); storyboardReplacesBackground.Value = false; } #endregion IBindable<bool> ISamplePlaybackDisabler.SamplePlaybackDisabled => samplePlaybackDisabled; IBindable<bool> ILocalUserPlayInfo.IsPlaying => LocalUserPlaying; } }
//! \file ImageS25.cs //! \date Sat Apr 18 17:00:54 2015 //! \brief ShiinaRio S25 multi-image format. // // Copyright (C) 2015-2016 by morkt // // 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.ComponentModel.Composition; using System.IO; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Utility; namespace GameRes.Formats.ShiinaRio { internal class S25MetaData : ImageMetaData { public uint FirstOffset; public bool Incremental; } [Export(typeof(ImageFormat))] public class S25Format : ImageFormat { public override string Tag { get { return "S25"; } } public override string Description { get { return "ShiinaRio image format"; } } public override uint Signature { get { return 0x00353253; } } // 'S25' // in current implementation, only the first frame is returned. // per-frame access is provided by S25Opener class. public override ImageMetaData ReadMetaData (IBinaryStream file) { file.Position = 4; int count = file.ReadInt32(); if (count < 0 || count > 0xfffff) return null; uint first_offset = 0; for (int i = 0; i < count && 0 == first_offset; ++i) first_offset = file.ReadUInt32(); if (0 == first_offset) return null; file.Position = first_offset; var info = new S25MetaData(); info.Width = file.ReadUInt32(); info.Height = file.ReadUInt32(); info.OffsetX = file.ReadInt32(); info.OffsetY = file.ReadInt32(); info.FirstOffset = first_offset+0x14; info.Incremental = 0 != (file.ReadUInt32() & 0x80000000u); info.BPP = 32; return info; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { using (var reader = new Reader (stream, (S25MetaData)info, true)) return reader.Image; } public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("S25Format.Write not implemented"); } internal sealed class Reader : IImageDecoder { IBinaryStream m_input; int m_width; int m_height; uint m_origin; byte[] m_output; bool m_incremental; bool m_should_dispose; ImageMetaData m_info; ImageData m_image; public Stream Source { get { m_input.Position = 0; return m_input.AsStream; } } public ImageFormat SourceFormat { get { return null; } } public ImageMetaData Info { get { return m_info; } } public ImageData Image { get { if (null == m_image) { var pixels = Unpack(); m_image = ImageData.Create (m_info, PixelFormats.Bgra32, null, pixels); } return m_image; } } public byte[] Data { get { return m_output; } } public Reader (IBinaryStream file, S25MetaData info, bool leave_open = false) { m_width = (int)info.Width; m_height = (int)info.Height; m_output = new byte[m_width * m_height * 4]; m_input = file; m_origin = info.FirstOffset; m_incremental = info.Incremental; m_info = info; m_should_dispose = !leave_open; } public byte[] Unpack () { m_input.Position = m_origin; if (m_incremental) return UnpackIncremental(); var rows = new uint[m_height]; for (int i = 0; i < rows.Length; ++i) rows[i] = m_input.ReadUInt32(); var row_buffer = new byte[m_width]; int dst = 0; for (int y = 0; y < m_height && dst < m_output.Length; ++y) { uint row_pos = rows[y]; m_input.Position = row_pos; int row_length = m_input.ReadUInt16(); row_pos += 2; if (0 != (row_pos & 1)) { m_input.ReadByte(); --row_length; } if (row_buffer.Length < row_length) row_buffer = new byte[row_length]; m_input.Read (row_buffer, 0, row_length); dst = UnpackLine (row_buffer, dst); } return m_output; } void UpdateRepeatCount (Dictionary<uint, int> rows_count) { m_input.Position = 4; int count = m_input.ReadInt32(); var frames = new List<uint> (count); for (int i = 0; i < count; ++i) { var offset = m_input.ReadUInt32(); if (0 != offset) frames.Add (offset); } foreach (var offset in frames) { if (offset+0x14 == m_origin) continue; m_input.Position = offset+4; int height = m_input.ReadInt32(); m_input.Position = offset+0x14; for (int i = 0; i < height; ++i) { var row_offset = m_input.ReadUInt32(); if (rows_count.ContainsKey (row_offset)) ++rows_count[row_offset]; } } } byte[] UnpackIncremental () { var rows = new uint[m_height]; var rows_count = new Dictionary<uint, int> (m_height); for (int i = 0; i < rows.Length; ++i) { uint offset = m_input.ReadUInt32(); rows[i] = offset; if (rows_count.ContainsKey (offset)) ++rows_count[offset]; else rows_count[offset] = 1; } UpdateRepeatCount (rows_count); var input_rows = new Dictionary<uint, byte[]> (m_height); var input_lines = new byte[m_height][]; for (int y = 0; y < m_height; ++y) { uint row_pos = rows[y]; if (input_rows.ContainsKey (row_pos)) { input_lines[y] = input_rows[row_pos]; continue; } var row = ReadLine (row_pos, rows_count[row_pos]); input_rows[row_pos] = row; input_lines[y] = row; } int dst = 0; foreach (var line in input_lines) { dst = UnpackLine (line, dst); } return m_output; } int UnpackLine (byte[] line, int dst) { int row_pos = 0; for (int x = m_width; x > 0 && dst < m_output.Length && row_pos < line.Length; ) { if (0 != (row_pos & 1)) { ++row_pos; } int count = LittleEndian.ToUInt16 (line, row_pos); row_pos += 2; int method = count >> 13; int skip = (count >> 11) & 3; if (0 != skip) { row_pos += skip; } count &= 0x7ff; if (0 == count) { count = LittleEndian.ToInt32 (line, row_pos); row_pos += 4; } if (count > x) count = x; x -= count; byte b, g, r, a; switch (method) { case 2: for (int i = 0; i < count && row_pos < line.Length; ++i) { m_output[dst++] = line[row_pos++]; m_output[dst++] = line[row_pos++]; m_output[dst++] = line[row_pos++]; m_output[dst++] = 0xff; } break; case 3: b = line[row_pos++]; g = line[row_pos++]; r = line[row_pos++]; for (int i = 0; i < count; ++i) { m_output[dst++] = b; m_output[dst++] = g; m_output[dst++] = r; m_output[dst++] = 0xff; } break; case 4: for (int i = 0; i < count && row_pos < line.Length; ++i) { a = line[row_pos++]; m_output[dst++] = line[row_pos++]; m_output[dst++] = line[row_pos++]; m_output[dst++] = line[row_pos++]; m_output[dst++] = a; } break; case 5: a = line[row_pos++]; b = line[row_pos++]; g = line[row_pos++]; r = line[row_pos++]; for (int i = 0; i < count; ++i) { m_output[dst++] = b; m_output[dst++] = g; m_output[dst++] = r; m_output[dst++] = a; } break; default: dst += count * 4; break; } } return dst; } byte[] ReadLine (uint offset, int repeat) { m_input.Position = offset; int row_length = m_input.ReadUInt16(); if (0 != (offset & 1)) { m_input.ReadByte(); --row_length; } var row = new byte[row_length]; m_input.Read (row, 0, row.Length); int row_pos = 0; for (int x = m_width; x > 0; ) { if (0 != (row_pos & 1)) { ++row_pos; } int count = LittleEndian.ToUInt16 (row, row_pos); row_pos += 2; int method = count >> 13; int skip = (count >> 11) & 3; if (0 != skip) { row_pos += skip; } count &= 0x7ff; if (0 == count) { count = LittleEndian.ToInt32 (row, row_pos); row_pos += 4; } if (count < 0 || count > x) count = x; x -= count; switch (method) { case 2: for (int j = 0; j < repeat; ++j) { for (int i = 3; i < count*3 && row_pos+i < row.Length; ++i) { row[row_pos+i] += row[row_pos+i-3]; } } row_pos += count*3; break; case 3: row_pos += 3; break; case 4: for (int j = 0; j < repeat; ++j) { for (int i = 4; i < count*4 && row_pos+i < row.Length; ++i) { row[row_pos+i] += row[row_pos+i-4]; } } row_pos += count*4; break; case 5: row_pos += 4; break; default: break; } } return row; } #region IDisposable Members bool m_disposed = false; public void Dispose () { if (!m_disposed) { if (m_should_dispose) { m_input.Dispose(); } m_disposed = true; } GC.SuppressFinalize (this); } #endregion } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Holds the meta data of a <see cref="Tree"/>. /// </summary> public class TreeDefinition { private readonly Dictionary<string, TreeEntryDefinition> entries = new Dictionary<string, TreeEntryDefinition>(); private readonly Dictionary<string, TreeDefinition> unwrappedTrees = new Dictionary<string, TreeDefinition>(); /// <summary> /// Builds a <see cref="TreeDefinition"/> from an existing <see cref="Tree"/>. /// </summary> /// <param name="tree">The <see cref="Tree"/> to be processed.</param> /// <returns>A new <see cref="TreeDefinition"/> holding the meta data of the <paramref name="tree"/>.</returns> public static TreeDefinition From(Tree tree) { Ensure.ArgumentNotNull(tree, "tree"); var td = new TreeDefinition(); foreach (TreeEntry treeEntry in tree) { td.Add(treeEntry.Name, treeEntry); } return td; } /// <summary> /// Builds a <see cref="TreeDefinition"/> from a <see cref="Commit"/>'s <see cref="Tree"/>. /// </summary> /// <param name="commit">The <see cref="Commit"/> whose tree is to be processed</param> /// <returns>A new <see cref="TreeDefinition"/> holding the meta data of the <paramref name="commit"/>'s <see cref="Tree"/>.</returns> public static TreeDefinition From(Commit commit) { Ensure.ArgumentNotNull(commit, "commit"); return From(commit.Tree); } private void AddEntry(string targetTreeEntryName, TreeEntryDefinition treeEntryDefinition) { if (entries.ContainsKey(targetTreeEntryName)) { WrapTree(targetTreeEntryName, treeEntryDefinition); return; } entries.Add(targetTreeEntryName, treeEntryDefinition); } /// <summary> /// Removes a <see cref="TreeEntryDefinition"/> located the specified <paramref name="treeEntryPath"/> path. /// </summary> /// <param name="treeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition Remove(string treeEntryPath) { Ensure.ArgumentNotNullOrEmptyString(treeEntryPath, "treeEntryPath"); if (this[treeEntryPath] == null) { return this; } Tuple<string, string> segments = ExtractPosixLeadingSegment(treeEntryPath); if (segments.Item2 == null) { entries.Remove(segments.Item1); } if (!unwrappedTrees.ContainsKey(segments.Item1)) { return this; } if (segments.Item2 != null) { unwrappedTrees[segments.Item1].Remove(segments.Item2); } if (unwrappedTrees[segments.Item1].entries.Count == 0) { unwrappedTrees.Remove(segments.Item1); entries.Remove(segments.Item1); } return this; } /// <summary> /// Adds or replaces a <see cref="TreeEntryDefinition"/> at the specified <paramref name="targetTreeEntryPath"/> location. /// </summary> /// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <param name="treeEntryDefinition">The <see cref="TreeEntryDefinition"/> to be stored at the described location.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition Add(string targetTreeEntryPath, TreeEntryDefinition treeEntryDefinition) { Ensure.ArgumentNotNullOrEmptyString(targetTreeEntryPath, "targetTreeEntryPath"); Ensure.ArgumentNotNull(treeEntryDefinition, "treeEntryDefinition"); if (Path.IsPathRooted(targetTreeEntryPath)) { throw new ArgumentException("The provided path is an absolute path."); } if (treeEntryDefinition is TransientTreeTreeEntryDefinition) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "The {0} references a target which hasn't been created in the {1} yet. " + "This situation can occur when the target is a whole new {2} being created, or when an existing {2} is being updated because some of its children were added/removed.", typeof(TreeEntryDefinition).Name, typeof(ObjectDatabase).Name, typeof(Tree).Name)); } Tuple<string, string> segments = ExtractPosixLeadingSegment(targetTreeEntryPath); if (segments.Item2 != null) { TreeDefinition td = RetrieveOrBuildTreeDefinition(segments.Item1, true); td.Add(segments.Item2, treeEntryDefinition); } else { AddEntry(segments.Item1, treeEntryDefinition); } return this; } /// <summary> /// Adds or replaces a <see cref="TreeEntryDefinition"/>, built from the provided <see cref="TreeEntry"/>, at the specified <paramref name="targetTreeEntryPath"/> location. /// </summary> /// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <param name="treeEntry">The <see cref="TreeEntry"/> to be stored at the described location.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition Add(string targetTreeEntryPath, TreeEntry treeEntry) { Ensure.ArgumentNotNull(treeEntry, "treeEntry"); TreeEntryDefinition ted = TreeEntryDefinition.From(treeEntry); return Add(targetTreeEntryPath, ted); } /// <summary> /// Adds or replaces a <see cref="TreeEntryDefinition"/>, dynamically built from the provided <see cref="Blob"/>, at the specified <paramref name="targetTreeEntryPath"/> location. /// </summary> /// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <param name="blob">The <see cref="Blob"/> to be stored at the described location.</param> /// <param name="mode">The file related <see cref="Mode"/> attributes.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition Add(string targetTreeEntryPath, Blob blob, Mode mode) { Ensure.ArgumentNotNull(blob, "blob"); Ensure.ArgumentConformsTo(mode, m => m.HasAny(TreeEntryDefinition.BlobModes), "mode"); TreeEntryDefinition ted = TreeEntryDefinition.From(blob, mode); return Add(targetTreeEntryPath, ted); } /// <summary> /// Adds or replaces a <see cref="TreeEntryDefinition"/>, dynamically built from the content of the file, at the specified <paramref name="targetTreeEntryPath"/> location. /// </summary> /// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <param name="filePath">The path to the file from which a <see cref="Blob"/> will be built and stored at the described location. A relative path is allowed to be passed if the target /// <see cref="Repository"/> is a standard, non-bare, repository. The path will then be considered as a path relative to the root of the working directory.</param> /// <param name="mode">The file related <see cref="Mode"/> attributes.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition Add(string targetTreeEntryPath, string filePath, Mode mode) { Ensure.ArgumentNotNullOrEmptyString(filePath, "filePath"); TreeEntryDefinition ted = TreeEntryDefinition.TransientBlobFrom(filePath, mode); return Add(targetTreeEntryPath, ted); } /// <summary> /// Adds or replaces a <see cref="TreeEntryDefinition"/>, dynamically built from the provided <see cref="Tree"/>, at the specified <paramref name="targetTreeEntryPath"/> location. /// </summary> /// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <param name="tree">The <see cref="Tree"/> to be stored at the described location.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition Add(string targetTreeEntryPath, Tree tree) { Ensure.ArgumentNotNull(tree, "tree"); TreeEntryDefinition ted = TreeEntryDefinition.From(tree); return Add(targetTreeEntryPath, ted); } /// <summary> /// Adds or replaces a gitlink <see cref="TreeEntryDefinition"/> equivalent to <paramref name="submodule"/>. /// </summary> /// <param name="submodule">The <see cref="Submodule"/> to be linked.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition Add(Submodule submodule) { Ensure.ArgumentNotNull(submodule, "submodule"); return AddGitLink(submodule.Path, submodule.HeadCommitId); } /// <summary> /// Adds or replaces a gitlink <see cref="TreeEntryDefinition"/>, /// referencing the commit identified by <paramref name="objectId"/>, /// at the specified <paramref name="targetTreeEntryPath"/> location. /// </summary> /// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <param name="objectId">The <see cref="ObjectId"/> of the commit to be linked at the described location.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition AddGitLink(string targetTreeEntryPath, ObjectId objectId) { Ensure.ArgumentNotNull(objectId, "objectId"); var ted = TreeEntryDefinition.From(objectId); return Add(targetTreeEntryPath, ted); } private TreeDefinition RetrieveOrBuildTreeDefinition(string treeName, bool shouldOverWrite) { TreeDefinition td; if (unwrappedTrees.TryGetValue(treeName, out td)) { return td; } TreeEntryDefinition treeEntryDefinition; bool hasAnEntryBeenFound = entries.TryGetValue(treeName, out treeEntryDefinition); if (hasAnEntryBeenFound) { switch (treeEntryDefinition.TargetType) { case TreeEntryTargetType.Tree: td = From(treeEntryDefinition.Target as Tree); break; case TreeEntryTargetType.Blob: case TreeEntryTargetType.GitLink: if (shouldOverWrite) { td = new TreeDefinition(); break; } return null; default: throw new NotImplementedException(); } } else { if (!shouldOverWrite) { return null; } td = new TreeDefinition(); } entries[treeName] = new TransientTreeTreeEntryDefinition(); unwrappedTrees.Add(treeName, td); return td; } internal Tree Build(Repository repository) { WrapAllTreeDefinitions(repository); using (var builder = new TreeBuilder(repository)) { var builtTreeEntryDefinitions = new List<Tuple<string, TreeEntryDefinition>>(entries.Count); foreach (KeyValuePair<string, TreeEntryDefinition> kvp in entries) { string name = kvp.Key; TreeEntryDefinition ted = kvp.Value; var transient = ted as TransientBlobTreeEntryDefinition; if (transient == null) { builder.Insert(name, ted); continue; } Blob blob = transient.Builder(repository.ObjectDatabase); TreeEntryDefinition ted2 = TreeEntryDefinition.From(blob, ted.Mode); builtTreeEntryDefinitions.Add(new Tuple<string, TreeEntryDefinition>(name, ted2)); builder.Insert(name, ted2); } builtTreeEntryDefinitions.ForEach(t => entries[t.Item1] = t.Item2); ObjectId treeId = builder.Write(); var result = repository.Lookup<Tree>(treeId); if (result == null) { throw new LibGit2SharpException("Unable to read created tree"); } return result; } } private void WrapAllTreeDefinitions(Repository repository) { foreach (KeyValuePair<string, TreeDefinition> pair in unwrappedTrees) { Tree tree = pair.Value.Build(repository); entries[pair.Key] = TreeEntryDefinition.From(tree); } unwrappedTrees.Clear(); } private void WrapTree(string entryName, TreeEntryDefinition treeEntryDefinition) { entries[entryName] = treeEntryDefinition; unwrappedTrees.Remove(entryName); } /// <summary> /// Retrieves the <see cref="TreeEntryDefinition"/> located the specified <paramref name="treeEntryPath"/> path. /// </summary> /// <param name="treeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <returns>The found <see cref="TreeEntryDefinition"/> if any; null otherwise.</returns> public virtual TreeEntryDefinition this[string treeEntryPath] { get { Ensure.ArgumentNotNullOrEmptyString(treeEntryPath, "treeEntryPath"); Tuple<string, string> segments = ExtractPosixLeadingSegment(treeEntryPath); if (segments.Item2 != null) { TreeDefinition td = RetrieveOrBuildTreeDefinition(segments.Item1, false); return td == null ? null : td[segments.Item2]; } TreeEntryDefinition treeEntryDefinition; return !entries.TryGetValue(segments.Item1, out treeEntryDefinition) ? null : treeEntryDefinition; } } private static Tuple<string, string> ExtractPosixLeadingSegment(FilePath targetPath) { string[] segments = targetPath.Posix.Split(new[] { '/' }, 2); if (segments[0] == string.Empty || (segments.Length == 2 && (segments[1] == string.Empty || segments[1].StartsWith("/", StringComparison.Ordinal)))) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "'{0}' is not a valid path.", targetPath)); } return new Tuple<string, string>(segments[0], segments.Length == 2 ? segments[1] : null); } private class TreeBuilder : IDisposable { private readonly TreeBuilderSafeHandle handle; public TreeBuilder(Repository repo) { handle = Proxy.git_treebuilder_new(repo.Handle); } public void Insert(string name, TreeEntryDefinition treeEntryDefinition) { Proxy.git_treebuilder_insert(handle, name, treeEntryDefinition); } public ObjectId Write() { return Proxy.git_treebuilder_write(handle); } public void Dispose() { handle.SafeDispose(); } } } }
using System; using System.Collections.Generic; using Avalonia.Media.Imaging; using Avalonia.Platform; using Avalonia.Threading; using Avalonia.Visuals.Media.Imaging; namespace Avalonia.Media { public sealed class DrawingContext : IDisposable { private readonly bool _ownsImpl; private int _currentLevel; private static ThreadSafeObjectPool<Stack<PushedState>> StateStackPool { get; } = ThreadSafeObjectPool<Stack<PushedState>>.Default; private static ThreadSafeObjectPool<Stack<TransformContainer>> TransformStackPool { get; } = ThreadSafeObjectPool<Stack<TransformContainer>>.Default; private Stack<PushedState> _states = StateStackPool.Get(); private Stack<TransformContainer> _transformContainers = TransformStackPool.Get(); readonly struct TransformContainer { public readonly Matrix LocalTransform; public readonly Matrix ContainerTransform; public TransformContainer(Matrix localTransform, Matrix containerTransform) { LocalTransform = localTransform; ContainerTransform = containerTransform; } } public DrawingContext(IDrawingContextImpl impl) { PlatformImpl = impl; _ownsImpl = true; } public DrawingContext(IDrawingContextImpl impl, bool ownsImpl) { _ownsImpl = ownsImpl; PlatformImpl = impl; } public IDrawingContextImpl PlatformImpl { get; } private Matrix _currentTransform = Matrix.Identity; private Matrix _currentContainerTransform = Matrix.Identity; /// <summary> /// Gets the current transform of the drawing context. /// </summary> public Matrix CurrentTransform { get { return _currentTransform; } private set { _currentTransform = value; var transform = _currentTransform * _currentContainerTransform; PlatformImpl.Transform = transform; } } //HACK: This is a temporary hack that is used in the render loop //to update TransformedBounds property [Obsolete("HACK for render loop, don't use")] public Matrix CurrentContainerTransform => _currentContainerTransform; /// <summary> /// Draws a bitmap image. /// </summary> /// <param name="source">The bitmap image.</param> /// <param name="opacity">The opacity to draw with.</param> /// <param name="sourceRect">The rect in the image to draw.</param> /// <param name="destRect">The rect in the output to draw to.</param> /// <param name="bitmapInterpolationMode">The bitmap interpolation mode.</param> public void DrawImage(IBitmap source, double opacity, Rect sourceRect, Rect destRect, BitmapInterpolationMode bitmapInterpolationMode = default) { Contract.Requires<ArgumentNullException>(source != null); PlatformImpl.DrawImage(source.PlatformImpl, opacity, sourceRect, destRect, bitmapInterpolationMode); } /// <summary> /// Draws a line. /// </summary> /// <param name="pen">The stroke pen.</param> /// <param name="p1">The first point of the line.</param> /// <param name="p2">The second point of the line.</param> public void DrawLine(Pen pen, Point p1, Point p2) { if (PenIsVisible(pen)) { PlatformImpl.DrawLine(pen, p1, p2); } } /// <summary> /// Draws a geometry. /// </summary> /// <param name="brush">The fill brush.</param> /// <param name="pen">The stroke pen.</param> /// <param name="geometry">The geometry.</param> public void DrawGeometry(IBrush brush, Pen pen, Geometry geometry) { if (brush != null || PenIsVisible(pen)) { PlatformImpl.DrawGeometry(brush, pen, geometry.PlatformImpl); } } /// <summary> /// Draws the outline of a rectangle. /// </summary> /// <param name="pen">The pen.</param> /// <param name="rect">The rectangle bounds.</param> /// <param name="cornerRadius">The corner radius.</param> public void DrawRectangle(Pen pen, Rect rect, float cornerRadius = 0.0f) { if (PenIsVisible(pen)) { PlatformImpl.DrawRectangle(pen, rect, cornerRadius); } } /// <summary> /// Draws text. /// </summary> /// <param name="foreground">The foreground brush.</param> /// <param name="origin">The upper-left corner of the text.</param> /// <param name="text">The text.</param> public void DrawText(IBrush foreground, Point origin, FormattedText text) { Contract.Requires<ArgumentNullException>(text != null); if (foreground != null) { PlatformImpl.DrawText(foreground, origin, text.PlatformImpl); } } /// <summary> /// Draws a filled rectangle. /// </summary> /// <param name="brush">The brush.</param> /// <param name="rect">The rectangle bounds.</param> /// <param name="cornerRadius">The corner radius.</param> public void FillRectangle(IBrush brush, Rect rect, float cornerRadius = 0.0f) { if (brush != null && rect != Rect.Empty) { PlatformImpl.FillRectangle(brush, rect, cornerRadius); } } public readonly struct PushedState : IDisposable { private readonly int _level; private readonly DrawingContext _context; private readonly Matrix _matrix; private readonly PushedStateType _type; public enum PushedStateType { None, Matrix, Opacity, Clip, MatrixContainer, GeometryClip, OpacityMask } public PushedState(DrawingContext context, PushedStateType type, Matrix matrix = default(Matrix)) { _context = context; _type = type; _matrix = matrix; _level = context._currentLevel += 1; context._states.Push(this); } public void Dispose() { if (_type == PushedStateType.None) return; if (_context._currentLevel != _level) throw new InvalidOperationException("Wrong Push/Pop state order"); _context._currentLevel--; _context._states.Pop(); if (_type == PushedStateType.Matrix) _context.CurrentTransform = _matrix; else if (_type == PushedStateType.Clip) _context.PlatformImpl.PopClip(); else if (_type == PushedStateType.Opacity) _context.PlatformImpl.PopOpacity(); else if (_type == PushedStateType.GeometryClip) _context.PlatformImpl.PopGeometryClip(); else if (_type == PushedStateType.OpacityMask) _context.PlatformImpl.PopOpacityMask(); else if (_type == PushedStateType.MatrixContainer) { var cont = _context._transformContainers.Pop(); _context._currentContainerTransform = cont.ContainerTransform; _context.CurrentTransform = cont.LocalTransform; } } } /// <summary> /// Pushes a clip rectangle. /// </summary> /// <param name="clip">The clip rectangle.</param> /// <returns>A disposable used to undo the clip rectangle.</returns> public PushedState PushClip(Rect clip) { PlatformImpl.PushClip(clip); return new PushedState(this, PushedState.PushedStateType.Clip); } /// <summary> /// Pushes a clip geometry. /// </summary> /// <param name="clip">The clip geometry.</param> /// <returns>A disposable used to undo the clip geometry.</returns> public PushedState PushGeometryClip(Geometry clip) { Contract.Requires<ArgumentNullException>(clip != null); PlatformImpl.PushGeometryClip(clip.PlatformImpl); return new PushedState(this, PushedState.PushedStateType.GeometryClip); } /// <summary> /// Pushes an opacity value. /// </summary> /// <param name="opacity">The opacity.</param> /// <returns>A disposable used to undo the opacity.</returns> public PushedState PushOpacity(double opacity) //TODO: Eliminate platform-specific push opacity call { PlatformImpl.PushOpacity(opacity); return new PushedState(this, PushedState.PushedStateType.Opacity); } /// <summary> /// Pushes an opacity mask. /// </summary> /// <param name="mask">The opacity mask.</param> /// <param name="bounds"> /// The size of the brush's target area. TODO: Are we sure this is needed? /// </param> /// <returns>A disposable to undo the opacity mask.</returns> public PushedState PushOpacityMask(IBrush mask, Rect bounds) { PlatformImpl.PushOpacityMask(mask, bounds); return new PushedState(this, PushedState.PushedStateType.OpacityMask); } /// <summary> /// Pushes a matrix post-transformation. /// </summary> /// <param name="matrix">The matrix</param> /// <returns>A disposable used to undo the transformation.</returns> public PushedState PushPostTransform(Matrix matrix) => PushSetTransform(CurrentTransform * matrix); /// <summary> /// Pushes a matrix pre-transformation. /// </summary> /// <param name="matrix">The matrix</param> /// <returns>A disposable used to undo the transformation.</returns> public PushedState PushPreTransform(Matrix matrix) => PushSetTransform(matrix * CurrentTransform); /// <summary> /// Sets the current matrix transformation. /// </summary> /// <param name="matrix">The matrix</param> /// <returns>A disposable used to undo the transformation.</returns> PushedState PushSetTransform(Matrix matrix) { var oldMatrix = CurrentTransform; CurrentTransform = matrix; return new PushedState(this, PushedState.PushedStateType.Matrix, oldMatrix); } /// <summary> /// Pushes a new transform context. /// </summary> /// <returns>A disposable used to undo the transformation.</returns> public PushedState PushTransformContainer() { _transformContainers.Push(new TransformContainer(CurrentTransform, _currentContainerTransform)); _currentContainerTransform = CurrentTransform * _currentContainerTransform; _currentTransform = Matrix.Identity; return new PushedState(this, PushedState.PushedStateType.MatrixContainer); } /// <summary> /// Disposes of any resources held by the <see cref="DrawingContext"/>. /// </summary> public void Dispose() { while (_states.Count != 0) _states.Peek().Dispose(); StateStackPool.Return(_states); _states = null; if (_transformContainers.Count != 0) throw new InvalidOperationException("Transform container stack is non-empty"); TransformStackPool.Return(_transformContainers); _transformContainers = null; if (_ownsImpl) PlatformImpl.Dispose(); } private static bool PenIsVisible(Pen pen) { return pen?.Brush != null && pen.Thickness > 0; } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // 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 Rodrigo B. de Oliveira 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.Text.RegularExpressions; using System.Globalization; using System.IO; using System.Collections.Generic; namespace Boo.Lang.Compiler.Ast.Visitors { /// <summary> /// </summary> public class BooPrinterVisitor : TextEmitter { [Flags] public enum PrintOptions { None, PrintLocals = 1, WSA = 2, } public PrintOptions Options = PrintOptions.None; public BooPrinterVisitor(TextWriter writer) : base(writer) { } public BooPrinterVisitor(TextWriter writer, PrintOptions options) : this(writer) { this.Options = options; } public bool IsOptionSet(PrintOptions option) { return (option & Options) == option; } public void Print(CompileUnit ast) { OnCompileUnit(ast); } #region overridables public virtual void WriteKeyword(string text) { Write(text); } public virtual void WriteOperator(string text) { Write(text); } #endregion #region IAstVisitor Members override public void OnModule(Module m) { Visit(m.Namespace); if (m.Imports.Count > 0) { Visit(m.Imports); WriteLine(); } foreach (TypeMember member in m.Members) { Visit(member); WriteLine(); } if (null != m.Globals) Visit(m.Globals.Statements); foreach (Boo.Lang.Compiler.Ast.Attribute attribute in m.Attributes) WriteModuleAttribute(attribute); foreach (Boo.Lang.Compiler.Ast.Attribute attribute in m.AssemblyAttributes) WriteAssemblyAttribute(attribute); } private void WriteModuleAttribute(Attribute attribute) { WriteAttribute(attribute, "module: "); WriteLine(); } private void WriteAssemblyAttribute(Attribute attribute) { WriteAttribute(attribute, "assembly: "); WriteLine(); } override public void OnNamespaceDeclaration(NamespaceDeclaration node) { WriteKeyword("namespace"); WriteLine(" {0}", node.Name); WriteLine(); } static bool IsExtendedRE(string s) { return s.IndexOfAny(new char[] { ' ', '\t' }) > -1; } static bool CanBeRepresentedAsQualifiedName(string s) { foreach (char ch in s) if (!char.IsLetterOrDigit(ch) && ch != '_' && ch != '.') return false; return true; } override public void OnImport(Import p) { WriteKeyword("import"); Write(" {0}", p.Namespace); if (null != p.AssemblyReference) { WriteKeyword(" from "); var assemblyRef = p.AssemblyReference.Name; if (CanBeRepresentedAsQualifiedName(assemblyRef)) Write(assemblyRef); else WriteStringLiteral(assemblyRef); } if (null != p.Alias) { WriteKeyword(" as "); Write(p.Alias.Name); } WriteLine(); } public bool IsWhiteSpaceAgnostic { get { return IsOptionSet(PrintOptions.WSA); } } private void WritePass() { if (!IsWhiteSpaceAgnostic) { WriteIndented(); WriteKeyword("pass"); WriteLine(); } } private void WriteBlockStatements(Block b) { if (b.IsEmpty) { WritePass(); } else { Visit(b.Statements); } } public void WriteBlock(Block b) { BeginBlock(); WriteBlockStatements(b); EndBlock(); } private void BeginBlock() { Indent(); } private void EndBlock() { Dedent(); if (IsWhiteSpaceAgnostic) { WriteEnd(); } } private void WriteEnd() { WriteIndented(); WriteKeyword("end"); WriteLine(); } override public void OnAttribute(Attribute att) { WriteAttribute(att); } override public void OnClassDefinition(ClassDefinition c) { WriteTypeDefinition("class", c); } override public void OnStructDefinition(StructDefinition node) { WriteTypeDefinition("struct", node); } override public void OnInterfaceDefinition(InterfaceDefinition id) { WriteTypeDefinition("interface", id); } override public void OnEnumDefinition(EnumDefinition ed) { WriteTypeDefinition("enum", ed); } override public void OnEvent(Event node) { WriteAttributes(node.Attributes, true); WriteOptionalModifiers(node); WriteKeyword("event "); Write(node.Name); WriteTypeReference(node.Type); WriteLine(); } private static bool IsInterfaceMember(TypeMember node) { return node.ParentNode != null && node.ParentNode.NodeType == NodeType.InterfaceDefinition; } override public void OnField(Field f) { WriteAttributes(f.Attributes, true); WriteModifiers(f); Write(f.Name); WriteTypeReference(f.Type); if (null != f.Initializer) { WriteOperator(" = "); Visit(f.Initializer); } WriteLine(); } override public void OnExplicitMemberInfo(ExplicitMemberInfo node) { Visit(node.InterfaceType); Write("."); } override public void OnProperty(Property node) { bool interfaceMember = IsInterfaceMember(node); WriteAttributes(node.Attributes, true); WriteOptionalModifiers(node); WriteIndented(""); Visit(node.ExplicitInfo); Write(node.Name); if (node.Parameters.Count > 0) { WriteParameterList(node.Parameters, "[", "]"); } WriteTypeReference(node.Type); WriteLine(":"); BeginBlock(); WritePropertyAccessor(node.Getter, "get", interfaceMember); WritePropertyAccessor(node.Setter, "set", interfaceMember); EndBlock(); } private void WritePropertyAccessor(Method method, string name, bool interfaceMember) { if (null == method) return; WriteAttributes(method.Attributes, true); if (interfaceMember) { WriteIndented(); } else { WriteModifiers(method); } WriteKeyword(name); if (interfaceMember) { WriteLine(); } else { WriteLine(":"); WriteBlock(method.Body); } } override public void OnEnumMember(EnumMember node) { WriteAttributes(node.Attributes, true); WriteIndented(node.Name); if (null != node.Initializer) { WriteOperator(" = "); Visit(node.Initializer); } WriteLine(); } override public void OnConstructor(Constructor c) { OnMethod(c); } override public void OnDestructor(Destructor c) { OnMethod(c); } bool IsSimpleClosure(BlockExpression node) { switch (node.Body.Statements.Count) { case 0: return true; case 1: switch (node.Body.Statements[0].NodeType) { case NodeType.IfStatement: return false; case NodeType.WhileStatement: return false; case NodeType.ForStatement: return false; } return true; } return false; } override public void OnBlockExpression(BlockExpression node) { if (IsSimpleClosure(node)) { DisableNewLine(); Write("{ "); if (node.Parameters.Count > 0) { WriteCommaSeparatedList(node.Parameters); Write(" | "); } if (node.Body.IsEmpty) Write("return"); else Visit(node.Body.Statements); Write(" }"); EnableNewLine(); } else { WriteKeyword("def "); WriteParameterList(node.Parameters); WriteTypeReference(node.ReturnType); WriteLine(":"); WriteBlock(node.Body); } } void WriteCallableDefinitionHeader(string keyword, CallableDefinition node) { WriteAttributes(node.Attributes, true); WriteOptionalModifiers(node); WriteKeyword(keyword); IExplicitMember em = node as IExplicitMember; if (null != em) { Visit(em.ExplicitInfo); } Write(node.Name); if (node.GenericParameters.Count > 0) { WriteGenericParameterList(node.GenericParameters); } WriteParameterList(node.Parameters); if (node.ReturnTypeAttributes.Count > 0) { Write(" "); WriteAttributes(node.ReturnTypeAttributes, false); } WriteTypeReference(node.ReturnType); } private void WriteOptionalModifiers(TypeMember node) { if (IsInterfaceMember(node)) { WriteIndented(); } else { WriteModifiers(node); } } override public void OnCallableDefinition(CallableDefinition node) { WriteCallableDefinitionHeader("callable ", node); } override public void OnMethod(Method m) { if (m.IsRuntime) WriteImplementationComment("runtime"); WriteCallableDefinitionHeader("def ", m); if (IsInterfaceMember(m)) { WriteLine(); } else { WriteLine(":"); WriteLocals(m); WriteBlock(m.Body); } } private void WriteImplementationComment(string comment) { WriteIndented("// {0}", comment); WriteLine(); } public override void OnLocal(Local node) { WriteIndented("// Local {0}, {1}, PrivateScope: {2}", node.Name, node.Entity, node.PrivateScope); WriteLine(); } void WriteLocals(Method m) { if (!IsOptionSet(PrintOptions.PrintLocals)) return; Visit(m.Locals); } void WriteTypeReference(TypeReference t) { if (null != t) { WriteKeyword(" as "); Visit(t); } } override public void OnParameterDeclaration(ParameterDeclaration p) { WriteAttributes(p.Attributes, false); if (p.IsByRef) WriteKeyword("ref "); if (IsCallableTypeReferenceParameter(p)) { if (p.IsParamArray) Write("*"); Visit(p.Type); } else { Write(p.Name); WriteTypeReference(p.Type); } } private static bool IsCallableTypeReferenceParameter(ParameterDeclaration p) { var parentNode = p.ParentNode; return parentNode != null && parentNode.NodeType == NodeType.CallableTypeReference; } override public void OnGenericParameterDeclaration(GenericParameterDeclaration gp) { Write(gp.Name); if (gp.BaseTypes.Count > 0 || gp.Constraints != GenericParameterConstraints.None) { Write("("); WriteCommaSeparatedList(gp.BaseTypes); if (gp.Constraints != GenericParameterConstraints.None) { if (gp.BaseTypes.Count != 0) { Write(", "); } WriteGenericParameterConstraints(gp.Constraints); } Write(")"); } } private void WriteGenericParameterConstraints(GenericParameterConstraints constraints) { List<string> constraintStrings = new List<string>(); if ((constraints & GenericParameterConstraints.ReferenceType) != GenericParameterConstraints.None) { constraintStrings.Add("class"); } if ((constraints & GenericParameterConstraints.ValueType) != GenericParameterConstraints.None) { constraintStrings.Add("struct"); } if ((constraints & GenericParameterConstraints.Constructable) != GenericParameterConstraints.None) { constraintStrings.Add("constructor"); } Write(string.Join(", ", constraintStrings.ToArray())); } private KeyValuePair<T, string> CreateTranslation<T>(T value, string translation) { return new KeyValuePair<T, string>(value, translation); } override public void OnTypeofExpression(TypeofExpression node) { Write("typeof("); Visit(node.Type); Write(")"); } override public void OnSimpleTypeReference(SimpleTypeReference t) { Write(t.Name); } override public void OnGenericTypeReference(GenericTypeReference node) { OnSimpleTypeReference(node); WriteGenericArguments(node.GenericArguments); } override public void OnGenericTypeDefinitionReference(GenericTypeDefinitionReference node) { OnSimpleTypeReference(node); Write("[of *"); for (int i = 1; i < node.GenericPlaceholders; i++) { Write(", *"); } Write("]"); } override public void OnGenericReferenceExpression(GenericReferenceExpression node) { Visit(node.Target); WriteGenericArguments(node.GenericArguments); } void WriteGenericArguments(TypeReferenceCollection arguments) { Write("[of "); WriteCommaSeparatedList(arguments); Write("]"); } override public void OnArrayTypeReference(ArrayTypeReference t) { Write("("); Visit(t.ElementType); if (null != t.Rank && t.Rank.Value > 1) { Write(", "); t.Rank.Accept(this); } Write(")"); } override public void OnCallableTypeReference(CallableTypeReference node) { Write("callable("); WriteCommaSeparatedList(node.Parameters); Write(")"); WriteTypeReference(node.ReturnType); } override public void OnMemberReferenceExpression(MemberReferenceExpression e) { Visit(e.Target); Write("."); Write(e.Name); } override public void OnTryCastExpression(TryCastExpression e) { Write("("); Visit(e.Target); WriteTypeReference(e.Type); Write(")"); } override public void OnCastExpression(CastExpression node) { Write("("); Visit(node.Target); WriteKeyword(" cast "); Visit(node.Type); Write(")"); } override public void OnNullLiteralExpression(NullLiteralExpression node) { WriteKeyword("null"); } override public void OnSelfLiteralExpression(SelfLiteralExpression node) { WriteKeyword("self"); } override public void OnSuperLiteralExpression(SuperLiteralExpression node) { WriteKeyword("super"); } override public void OnTimeSpanLiteralExpression(TimeSpanLiteralExpression node) { WriteTimeSpanLiteral(node.Value, _writer); } override public void OnBoolLiteralExpression(BoolLiteralExpression node) { if (node.Value) { WriteKeyword("true"); } else { WriteKeyword("false"); } } override public void OnUnaryExpression(UnaryExpression node) { bool addParens = NeedParensAround(node) && !IsMethodInvocationArg(node); if (addParens) { Write("("); } bool postOperator = AstUtil.IsPostUnaryOperator(node.Operator); if (!postOperator) { WriteOperator(GetUnaryOperatorText(node.Operator)); } Visit(node.Operand); if (postOperator) { WriteOperator(GetUnaryOperatorText(node.Operator)); } if (addParens) { Write(")"); } } private bool IsMethodInvocationArg(UnaryExpression node) { MethodInvocationExpression parent = node.ParentNode as MethodInvocationExpression; return null != parent && node != parent.Target; } override public void OnConditionalExpression(ConditionalExpression e) { Write("("); Visit(e.TrueValue); WriteKeyword(" if "); Visit(e.Condition); WriteKeyword(" else "); Visit(e.FalseValue); Write(")"); } bool NeedParensAround(Expression e) { if (e.ParentNode == null) return false; switch (e.ParentNode.NodeType) { case NodeType.ExpressionStatement: case NodeType.MacroStatement: case NodeType.IfStatement: case NodeType.WhileStatement: case NodeType.UnlessStatement: return false; } return true; } override public void OnBinaryExpression(BinaryExpression e) { bool needsParens = NeedParensAround(e); if (needsParens) { Write("("); } Visit(e.Left); Write(" "); WriteOperator(GetBinaryOperatorText(e.Operator)); Write(" "); if (e.Operator == BinaryOperatorType.TypeTest) { // isa rhs is encoded in a typeof expression Visit(((TypeofExpression)e.Right).Type); } else { Visit(e.Right); } if (needsParens) { Write(")"); } } override public void OnRaiseStatement(RaiseStatement rs) { WriteIndented(); WriteKeyword("raise "); Visit(rs.Exception); Visit(rs.Modifier); WriteLine(); } override public void OnMethodInvocationExpression(MethodInvocationExpression e) { Visit(e.Target); Write("("); WriteCommaSeparatedList(e.Arguments); if (e.NamedArguments.Count > 0) { if (e.Arguments.Count > 0) { Write(", "); } WriteCommaSeparatedList(e.NamedArguments); } Write(")"); } override public void OnArrayLiteralExpression(ArrayLiteralExpression node) { WriteArray(node.Items, node.Type); } override public void OnListLiteralExpression(ListLiteralExpression node) { WriteDelimitedCommaSeparatedList("[", node.Items, "]"); } private void WriteDelimitedCommaSeparatedList(string opening, IEnumerable<Expression> list, string closing) { Write(opening); WriteCommaSeparatedList(list); Write(closing); } public override void OnCollectionInitializationExpression(CollectionInitializationExpression node) { Visit(node.Collection); Write(" "); if (node.Initializer is ListLiteralExpression) WriteDelimitedCommaSeparatedList("{ ", ((ListLiteralExpression) node.Initializer).Items, " }"); else Visit(node.Initializer); } override public void OnGeneratorExpression(GeneratorExpression node) { Write("("); Visit(node.Expression); WriteGeneratorExpressionBody(node); Write(")"); } void WriteGeneratorExpressionBody(GeneratorExpression node) { WriteKeyword(" for "); WriteCommaSeparatedList(node.Declarations); WriteKeyword(" in "); Visit(node.Iterator); Visit(node.Filter); } override public void OnExtendedGeneratorExpression(ExtendedGeneratorExpression node) { Write("("); Visit(node.Items[0].Expression); for (int i=0; i<node.Items.Count; ++i) { WriteGeneratorExpressionBody(node.Items[i]); } Write(")"); } override public void OnSlice(Slice node) { Visit(node.Begin); if (null != node.End || WasOmitted(node.Begin)) { Write(":"); } Visit(node.End); if (null != node.Step) { Write(":"); Visit(node.Step); } } override public void OnSlicingExpression(SlicingExpression node) { Visit(node.Target); Write("["); WriteCommaSeparatedList(node.Indices); Write("]"); } override public void OnHashLiteralExpression(HashLiteralExpression node) { Write("{"); if (node.Items.Count > 0) { Write(" "); WriteCommaSeparatedList(node.Items); Write(" "); } Write("}"); } override public void OnExpressionPair(ExpressionPair pair) { Visit(pair.First); Write(": "); Visit(pair.Second); } override public void OnRELiteralExpression(RELiteralExpression e) { if (IsExtendedRE(e.Value)) { Write("@"); } Write(e.Value); } override public void OnSpliceExpression(SpliceExpression e) { WriteSplicedExpression(e.Expression); } private void WriteSplicedExpression(Expression expression) { WriteOperator("$("); Visit(expression); WriteOperator(")"); } public override void OnStatementTypeMember(StatementTypeMember node) { WriteModifiers(node); Visit(node.Statement); } public override void OnSpliceTypeMember(SpliceTypeMember node) { WriteIndented(); Visit(node.TypeMember); WriteLine(); } public override void OnSpliceTypeDefinitionBody(SpliceTypeDefinitionBody node) { WriteIndented(); WriteSplicedExpression(node.Expression); WriteLine(); } override public void OnSpliceTypeReference(SpliceTypeReference node) { WriteSplicedExpression(node.Expression); } void WriteIndentedOperator(string op) { WriteIndented(); WriteOperator(op); } override public void OnQuasiquoteExpression(QuasiquoteExpression e) { WriteIndentedOperator("[|"); if (e.Node is Expression) { Write(" "); Visit(e.Node); Write(" "); WriteIndentedOperator("|]"); } else { WriteLine(); Indent(); Visit(e.Node); Dedent(); WriteIndentedOperator("|]"); WriteLine(); } } override public void OnStringLiteralExpression(StringLiteralExpression e) { if (e != null && e.Value != null) WriteStringLiteral(e.Value); else WriteKeyword("null"); } override public void OnCharLiteralExpression(CharLiteralExpression e) { WriteKeyword("char"); Write("("); WriteStringLiteral(e.Value); Write(")"); } override public void OnIntegerLiteralExpression(IntegerLiteralExpression e) { Write(e.Value.ToString()); if (e.IsLong) { Write("L"); } } override public void OnDoubleLiteralExpression(DoubleLiteralExpression e) { Write(e.Value.ToString("########0.0##########", CultureInfo.InvariantCulture)); if (e.IsSingle) { Write("F"); } } override public void OnReferenceExpression(ReferenceExpression node) { Write(node.Name); } override public void OnExpressionStatement(ExpressionStatement node) { WriteIndented(); Visit(node.Expression); Visit(node.Modifier); WriteLine(); } override public void OnExpressionInterpolationExpression(ExpressionInterpolationExpression node) { Write("\""); foreach (var arg in node.Expressions) { switch (arg.NodeType) { case NodeType.StringLiteralExpression: WriteStringLiteralContents(((StringLiteralExpression)arg).Value, _writer, false); break; case NodeType.ReferenceExpression: case NodeType.BinaryExpression: Write("$"); Visit(arg); break; default: Write("$("); Visit(arg); Write(")"); break; } } Write("\""); } override public void OnStatementModifier(StatementModifier sm) { Write(" "); WriteKeyword(sm.Type.ToString().ToLower()); Write(" "); Visit(sm.Condition); } override public void OnLabelStatement(LabelStatement node) { WriteIndented(":"); WriteLine(node.Name); } override public void OnGotoStatement(GotoStatement node) { WriteIndented(); WriteKeyword("goto "); Visit(node.Label); Visit(node.Modifier); WriteLine(); } override public void OnMacroStatement(MacroStatement node) { WriteIndented(node.Name); Write(" "); WriteCommaSeparatedList(node.Arguments); if (!node.Body.IsEmpty) { WriteLine(":"); WriteBlock(node.Body); } else { Visit(node.Modifier); WriteLine(); } } override public void OnForStatement(ForStatement fs) { WriteIndented(); WriteKeyword("for "); for (int i=0; i<fs.Declarations.Count; ++i) { if (i > 0) { Write(", "); } Visit(fs.Declarations[i]); } WriteKeyword(" in "); Visit(fs.Iterator); WriteLine(":"); WriteBlock(fs.Block); if(fs.OrBlock != null) { WriteIndented(); WriteKeyword("or:"); WriteLine(); WriteBlock(fs.OrBlock); } if(fs.ThenBlock != null) { WriteIndented(); WriteKeyword("then:"); WriteLine(); WriteBlock(fs.ThenBlock); } } override public void OnTryStatement(TryStatement node) { WriteIndented(); WriteKeyword("try:"); WriteLine(); Indent(); WriteBlockStatements(node.ProtectedBlock); Dedent(); Visit(node.ExceptionHandlers); if (null != node.FailureBlock) { WriteIndented(); WriteKeyword("failure:"); WriteLine(); Indent(); WriteBlockStatements(node.FailureBlock); Dedent(); } if (null != node.EnsureBlock) { WriteIndented(); WriteKeyword("ensure:"); WriteLine(); Indent(); WriteBlockStatements(node.EnsureBlock); Dedent(); } if(IsWhiteSpaceAgnostic) { WriteEnd(); } } override public void OnExceptionHandler(ExceptionHandler node) { WriteIndented(); WriteKeyword("except"); if ((node.Flags & ExceptionHandlerFlags.Untyped) == ExceptionHandlerFlags.None) { if((node.Flags & ExceptionHandlerFlags.Anonymous) == ExceptionHandlerFlags.None) { Write(" "); Visit(node.Declaration); } else { WriteTypeReference(node.Declaration.Type); } } else if((node.Flags & ExceptionHandlerFlags.Anonymous) == ExceptionHandlerFlags.None) { Write(" "); Write(node.Declaration.Name); } if((node.Flags & ExceptionHandlerFlags.Filter) == ExceptionHandlerFlags.Filter) { UnaryExpression unless = node.FilterCondition as UnaryExpression; if(unless != null && unless.Operator == UnaryOperatorType.LogicalNot) { WriteKeyword(" unless "); Visit(unless.Operand); } else { WriteKeyword(" if "); Visit(node.FilterCondition); } } WriteLine(":"); Indent(); WriteBlockStatements(node.Block); Dedent(); } override public void OnUnlessStatement(UnlessStatement node) { WriteConditionalBlock("unless", node.Condition, node.Block); } override public void OnBreakStatement(BreakStatement node) { WriteIndented(); WriteKeyword("break "); Visit(node.Modifier); WriteLine(); } override public void OnContinueStatement(ContinueStatement node) { WriteIndented(); WriteKeyword("continue "); Visit(node.Modifier); WriteLine(); } override public void OnYieldStatement(YieldStatement node) { WriteIndented(); WriteKeyword("yield "); Visit(node.Expression); Visit(node.Modifier); WriteLine(); } override public void OnWhileStatement(WhileStatement node) { WriteConditionalBlock("while", node.Condition, node.Block); if(node.OrBlock != null) { WriteIndented(); WriteKeyword("or:"); WriteLine(); WriteBlock(node.OrBlock); } if(node.ThenBlock != null) { WriteIndented(); WriteKeyword("then:"); WriteLine(); WriteBlock(node.ThenBlock); } } override public void OnIfStatement(IfStatement node) { WriteIfBlock("if ", node); Block elseBlock = WriteElifs(node); if (null != elseBlock) { WriteIndented(); WriteKeyword("else:"); WriteLine(); WriteBlock(elseBlock); } else { if (IsWhiteSpaceAgnostic) { WriteEnd(); } } } private Block WriteElifs(IfStatement node) { Block falseBlock = node.FalseBlock; while (IsElif(falseBlock)) { IfStatement stmt = (IfStatement) falseBlock.Statements[0]; WriteIfBlock("elif ", stmt); falseBlock = stmt.FalseBlock; } return falseBlock; } private void WriteIfBlock(string keyword, IfStatement ifs) { WriteIndented(); WriteKeyword(keyword); Visit(ifs.Condition); WriteLine(":"); Indent(); WriteBlockStatements(ifs.TrueBlock); Dedent(); } private static bool IsElif(Block block) { if (block == null) return false; if (block.Statements.Count != 1) return false; return block.Statements[0] is IfStatement; } override public void OnDeclarationStatement(DeclarationStatement d) { WriteIndented(); Visit(d.Declaration); if (null != d.Initializer) { WriteOperator(" = "); Visit(d.Initializer); } WriteLine(); } override public void OnDeclaration(Declaration d) { Write(d.Name); WriteTypeReference(d.Type); } override public void OnReturnStatement(ReturnStatement r) { WriteIndented(); WriteKeyword("return"); if (r.Expression != null || r.Modifier != null) Write(" "); Visit(r.Expression); Visit(r.Modifier); WriteLine(); } override public void OnUnpackStatement(UnpackStatement us) { WriteIndented(); for (int i=0; i<us.Declarations.Count; ++i) { if (i > 0) { Write(", "); } Visit(us.Declarations[i]); } WriteOperator(" = "); Visit(us.Expression); Visit(us.Modifier); WriteLine(); } #endregion public static string GetUnaryOperatorText(UnaryOperatorType op) { switch (op) { case UnaryOperatorType.Explode: { return "*"; } case UnaryOperatorType.PostIncrement: case UnaryOperatorType.Increment: return "++"; case UnaryOperatorType.PostDecrement: case UnaryOperatorType.Decrement: return "--"; case UnaryOperatorType.UnaryNegation: return "-"; case UnaryOperatorType.LogicalNot: return "not "; case UnaryOperatorType.OnesComplement: return "~"; case UnaryOperatorType.AddressOf: return "&"; case UnaryOperatorType.Indirection: return "*"; } throw new ArgumentException("op"); } public static string GetBinaryOperatorText(BinaryOperatorType op) { switch (op) { case BinaryOperatorType.Assign: return "="; case BinaryOperatorType.Match: return "=~"; case BinaryOperatorType.NotMatch: return "!~"; case BinaryOperatorType.Equality: return "=="; case BinaryOperatorType.Inequality: return "!="; case BinaryOperatorType.Addition: return "+"; case BinaryOperatorType.Exponentiation: return "**"; case BinaryOperatorType.InPlaceAddition: return "+="; case BinaryOperatorType.InPlaceBitwiseAnd: return "&="; case BinaryOperatorType.InPlaceBitwiseOr: return "|="; case BinaryOperatorType.InPlaceSubtraction: return "-="; case BinaryOperatorType.InPlaceMultiply: return "*="; case BinaryOperatorType.InPlaceModulus: return "%="; case BinaryOperatorType.InPlaceExclusiveOr: return "^="; case BinaryOperatorType.InPlaceDivision: return "/="; case BinaryOperatorType.Subtraction: return "-"; case BinaryOperatorType.Multiply: return "*"; case BinaryOperatorType.Division: return "/"; case BinaryOperatorType.GreaterThan: return ">"; case BinaryOperatorType.GreaterThanOrEqual: return ">="; case BinaryOperatorType.LessThan: return "<"; case BinaryOperatorType.LessThanOrEqual: return "<="; case BinaryOperatorType.Modulus: return "%"; case BinaryOperatorType.Member: return "in"; case BinaryOperatorType.NotMember: return "not in"; case BinaryOperatorType.ReferenceEquality: return "is"; case BinaryOperatorType.ReferenceInequality: return "is not"; case BinaryOperatorType.TypeTest: return "isa"; case BinaryOperatorType.Or: return "or"; case BinaryOperatorType.And: return "and"; case BinaryOperatorType.BitwiseOr: return "|"; case BinaryOperatorType.BitwiseAnd: return "&"; case BinaryOperatorType.ExclusiveOr: return "^"; case BinaryOperatorType.ShiftLeft: return "<<"; case BinaryOperatorType.ShiftRight: return ">>"; case BinaryOperatorType.InPlaceShiftLeft: return "<<="; case BinaryOperatorType.InPlaceShiftRight: return ">>="; } throw new NotImplementedException(op.ToString()); } public virtual void WriteStringLiteral(string text) { WriteStringLiteral(text, _writer); } public static void WriteTimeSpanLiteral(TimeSpan value, TextWriter writer) { double days = value.TotalDays; if (days >= 1) { writer.Write(days.ToString(CultureInfo.InvariantCulture) + "d"); } else { double hours = value.TotalHours; if (hours >= 1) { writer.Write(hours.ToString(CultureInfo.InvariantCulture) + "h"); } else { double minutes = value.TotalMinutes; if (minutes >= 1) { writer.Write(minutes.ToString(CultureInfo.InvariantCulture) + "m"); } else { double seconds = value.TotalSeconds; if (seconds >= 1) { writer.Write(seconds.ToString(CultureInfo.InvariantCulture) + "s"); } else { writer.Write(value.TotalMilliseconds.ToString(CultureInfo.InvariantCulture) + "ms"); } } } } } public static void WriteStringLiteral(string text, TextWriter writer) { writer.Write("'"); WriteStringLiteralContents(text, writer); writer.Write("'"); } public static void WriteStringLiteralContents(string text, TextWriter writer) { WriteStringLiteralContents(text, writer, true); } public static void WriteStringLiteralContents(string text, TextWriter writer, bool single) { foreach (char ch in text) { switch (ch) { case '\r': { writer.Write("\\r"); break; } case '\n': { writer.Write("\\n"); break; } case '\t': { writer.Write("\\t"); break; } case '\\': { writer.Write("\\\\"); break; } case '\a': { writer.Write(@"\a"); break; } case '\b': { writer.Write(@"\b"); break; } case '\f': { writer.Write(@"\f"); break; } case '\0': { writer.Write(@"\0"); break; } case '\'': { if (single) { writer.Write("\\'"); } else { writer.Write(ch); } break; } case '"': { if (!single) { writer.Write("\\\""); } else { writer.Write(ch); } break; } default: { writer.Write(ch); break; } } } } void WriteConditionalBlock(string keyword, Expression condition, Block block) { WriteIndented(); WriteKeyword(keyword + " "); Visit(condition); WriteLine(":"); WriteBlock(block); } void WriteParameterList(ParameterDeclarationCollection items) { WriteParameterList(items, "(", ")"); } void WriteParameterList(ParameterDeclarationCollection items, string st, string ed) { Write(st); int i = 0; foreach (ParameterDeclaration item in items) { if (i > 0) { Write(", "); } if (item.IsParamArray) { Write("*"); } Visit(item); ++i; } Write(ed); } void WriteGenericParameterList(GenericParameterDeclarationCollection items) { Write("[of "); WriteCommaSeparatedList(items); Write("]"); } void WriteAttribute(Attribute attribute) { WriteAttribute(attribute, null); } void WriteAttribute(Attribute attribute, string prefix) { WriteIndented("["); if (null != prefix) { Write(prefix); } Write(attribute.Name); if (attribute.Arguments.Count > 0 || attribute.NamedArguments.Count > 0) { Write("("); WriteCommaSeparatedList(attribute.Arguments); if (attribute.NamedArguments.Count > 0) { if (attribute.Arguments.Count > 0) { Write(", "); } WriteCommaSeparatedList(attribute.NamedArguments); } Write(")"); } Write("]"); } void WriteAttributes(AttributeCollection attributes, bool addNewLines) { foreach (Boo.Lang.Compiler.Ast.Attribute attribute in attributes) { Visit(attribute); if (addNewLines) { WriteLine(); } else { Write(" "); } } } void WriteModifiers(TypeMember member) { WriteIndented(); if (member.IsPartial) WriteKeyword("partial "); if (member.IsPublic) WriteKeyword("public "); else if (member.IsProtected) WriteKeyword("protected "); else if (member.IsPrivate) WriteKeyword("private "); else if (member.IsInternal) WriteKeyword("internal "); if (member.IsStatic) WriteKeyword("static "); else if (member.IsOverride) WriteKeyword("override "); else if (member.IsModifierSet(TypeMemberModifiers.Virtual)) WriteKeyword("virtual "); else if (member.IsModifierSet(TypeMemberModifiers.Abstract)) WriteKeyword("abstract "); if (member.IsFinal) WriteKeyword("final "); if (member.IsNew) WriteKeyword("new "); if (member.HasTransientModifier) WriteKeyword("transient "); } virtual protected void WriteTypeDefinition(string keyword, TypeDefinition td) { WriteAttributes(td.Attributes, true); WriteModifiers(td); WriteIndented(); WriteKeyword(keyword); Write(" "); var splice = td.ParentNode as SpliceTypeMember; if (splice != null) WriteSplicedExpression(splice.NameExpression); else Write(td.Name); if (td.GenericParameters.Count != 0) { WriteGenericParameterList(td.GenericParameters); } if (td.BaseTypes.Count > 0) { Write("("); WriteCommaSeparatedList<TypeReference>(td.BaseTypes); Write(")"); } WriteLine(":"); BeginBlock(); if (td.Members.Count > 0) { foreach (TypeMember member in td.Members) { WriteLine(); Visit(member); } } else { WritePass(); } EndBlock(); } bool WasOmitted(Expression node) { return null != node && NodeType.OmittedExpression == node.NodeType; } } }
/* * 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 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.Threading; using System.Collections.Generic; using System.Collections; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Scripting.LSLHttp { public class UrlData { public UUID hostID; public UUID itemID; public IScriptModule engine; public string url; public UUID urlcode; public List<UUID> requests; } public class RequestData { public UUID requestId; public AsyncHttpRequest polledRequest; public Dictionary<string, string> headers; public string body; public int responseCode; public string responseBody; public string contentType = "text/plain"; public bool requestDone; public int startTime; public string uri; } public class UrlModule : ISharedRegionModule, IUrlModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly Dictionary<string, UrlData> m_UrlMap = new Dictionary<string, UrlData>(); private readonly Dictionary<UUID, RequestData> m_RequestMap = new Dictionary<UUID, RequestData>(); private const int m_TotalUrls = 15000; private const int m_DefaultTimeout = 25 * 1000; // 25 sec timeout private uint https_port = 0; private IHttpServer m_HttpServer = null; private IHttpServer m_HttpsServer = null; public Type ReplaceableInterface { get { return null; } } public string Name { get { return "UrlModule"; } } public void Initialise(IConfigSource config) { bool ssl_enabled = config.Configs["Network"].GetBoolean("http_listener_ssl", false); if (ssl_enabled) https_port = (uint)config.Configs["Network"].GetInt("http_listener_sslport", ((int)ConfigSettings.DefaultRegionHttpPort + 1)); } public void PostInitialise() { } public void AddRegion(Scene scene) { if (m_HttpServer == null) { // There can only be one m_HttpServer = MainServer.Instance; // We can use the https if it is enabled if (https_port > 0) { m_HttpsServer = MainServer.GetHttpServer(https_port); } } scene.RegisterModuleInterface<IUrlModule>(this); scene.EventManager.OnScriptReset += OnScriptReset; } public void RegionLoaded(Scene scene) { /* IScriptModule[] scriptModules = scene.RequestModuleInterfaces<IScriptModule>(); foreach (IScriptModule scriptModule in scriptModules) { scriptModule.OnScriptRemoved += ScriptRemoved; scriptModule.OnObjectRemoved += ObjectRemoved; } */ } public void RemoveRegion(Scene scene) { } public void Close() { } public UUID RequestURL(IScriptModule engine, SceneObjectPart host, UUID itemID) { UUID urlcode = UUID.Random(); string url = String.Empty; lock (m_UrlMap) { if (m_UrlMap.Count >= m_TotalUrls) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } url = m_HttpServer.ServerURI + "/lslhttp/" + urlcode.ToString() + "/"; UrlData urlData = new UrlData { hostID = host.UUID, itemID = itemID, engine = engine, url = url, urlcode = urlcode, requests = new List<UUID>() }; m_UrlMap[url] = urlData; } string uri = "/lslhttp/" + urlcode.ToString() + "/"; m_HttpServer.AddStreamHandler(new AsyncRequestHandler("POST", uri, AsyncHttpRequest, "HTTP-IN-POST", "Http In Request Handler (Asynch)")); m_HttpServer.AddStreamHandler(new AsyncRequestHandler("GET", uri, AsyncHttpRequest, "HTTP-IN-GET", "Http In Request Handler (Asynch)")); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url }); return urlcode; } public UUID RequestSecureURL(IScriptModule engine, SceneObjectPart host, UUID itemID) { UUID urlcode = UUID.Random(); string url = String.Empty; if (m_HttpsServer == null) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } lock (m_UrlMap) { if (m_UrlMap.Count >= m_TotalUrls) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } url = m_HttpsServer.ServerURI + "/lslhttps/" + urlcode.ToString() + "/"; UrlData urlData = new UrlData { hostID = host.UUID, itemID = itemID, engine = engine, url = url, urlcode = urlcode, requests = new List<UUID>() }; m_UrlMap[url] = urlData; } string uri = "/lslhttps/" + urlcode.ToString() + "/"; m_HttpServer.AddStreamHandler(new AsyncRequestHandler("POST", uri, AsyncHttpRequest)); m_HttpServer.AddStreamHandler(new AsyncRequestHandler("GET", uri, AsyncHttpRequest)); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url }); return urlcode; } public void ReleaseURL(string url) { UrlData data; lock (m_UrlMap) { if (!m_UrlMap.TryGetValue(url, out data)) return; // Remove the URL so we dont accept any new requests RemoveUrl(data); m_UrlMap.Remove(url); } List<RequestData> requests = new List<RequestData>(); // Clean up existing requests lock (m_RequestMap) { foreach (UUID requestId in data.requests) { RequestData req; if (m_RequestMap.TryGetValue(requestId, out req)) requests.Add(req); } foreach (RequestData request in requests) { m_RequestMap.Remove(request.requestId); } } foreach (RequestData request in requests) { // Signal this request. A 404 will be returned request.polledRequest.SendResponse(ProcessEvents(request.polledRequest, false)); } } public void HttpContentType(UUID requestId, string content_type) { RequestData data; lock (m_RequestMap) { if (!m_RequestMap.TryGetValue(requestId, out data)) return; data.contentType = content_type; } } public void HttpResponse(UUID requestId, int status, string body) { RequestData data = null; lock (m_RequestMap) { if (!m_RequestMap.TryGetValue(requestId, out data)) return; } if (data != null) { data.responseCode = status; data.responseBody = body; data.requestDone = true; data.polledRequest.SendResponse(ProcessEvents(data.polledRequest, false)); } } public string GetHttpHeader(UUID requestId, string header) { RequestData data; lock (m_RequestMap) { if (!m_RequestMap.TryGetValue(requestId, out data)) return String.Empty; string value; if (!data.headers.TryGetValue(header, out value)) return (String.Empty); else return value; } } public int GetFreeUrls() { return m_TotalUrls - m_UrlMap.Count; } private void OnScriptReset(uint localID, UUID itemID) { ScriptRemoved(itemID); } public void ScriptRemoved(UUID itemID) { List<UrlData> removeURLs = new List<UrlData>(); lock (m_UrlMap) { foreach (UrlData url in m_UrlMap.Values) { if (url.itemID == itemID) { RemoveUrl(url); removeURLs.Add(url); } } foreach (UrlData data in removeURLs) { m_UrlMap.Remove(data.url); } } List<RequestData> requests = new List<RequestData>(); lock (m_RequestMap) { foreach (UrlData url in removeURLs) { foreach (UUID id in url.requests) { RequestData req; if (m_RequestMap.TryGetValue(id, out req)) { m_RequestMap.Remove(id); requests.Add(req); } } } } foreach (RequestData request in requests) { // Pulse this request. A 404 will be returned request.polledRequest.SendResponse(ProcessEvents(request.polledRequest, false)); } } public void ObjectRemoved(UUID objectID) { List<UrlData> removeURLs = new List<UrlData>(); lock (m_UrlMap) { foreach (UrlData url in m_UrlMap.Values) { if (url.hostID == objectID) { RemoveUrl(url); removeURLs.Add(url); } } foreach (UrlData data in removeURLs) { m_UrlMap.Remove(data.url); } } List<RequestData> requests = new List<RequestData>(); lock (m_RequestMap) { foreach (UrlData url in removeURLs) { foreach (UUID id in url.requests) { RequestData req; if (m_RequestMap.TryGetValue(id, out req)) { requests.Add(req); m_RequestMap.Remove(id); } } } } foreach (RequestData request in requests) { // Pulse this request. A 404 will be returned request.polledRequest.SendResponse(ProcessEvents(request.polledRequest, false)); } } private void RemoveUrl(UrlData data) { string url = data.url; bool is_ssl = url.Contains("lslhttps"); string protocol = (is_ssl ? "/lslhttps/" : "/lslhttp/"); m_HttpServer.RemoveStreamHandler("POST", protocol + data.urlcode.ToString() + "/"); m_HttpServer.RemoveStreamHandler("GET", protocol + data.urlcode.ToString() + "/"); } private string URLFromURI(string uri) { bool is_ssl = uri.Contains("lslhttps"); int pos1 = uri.IndexOf("/");// /lslhttp int pos2 = uri.IndexOf("/", pos1 + 1);// /lslhttp/ int pos3 = uri.IndexOf("/", pos2 + 1);// /lslhttp/<UUID>/ string uri_tmp = uri.Substring(0, pos3 + 1); if (!is_ssl) return (m_HttpServer.ServerURI + uri_tmp); else return (m_HttpsServer.ServerURI + uri_tmp); } #region PolledService Interface public void AsyncHttpRequest(IHttpServer server, string path, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { UUID urlcode; if (UUID.TryParse(path, out urlcode)) return; AsyncHttpRequest asyncRequest = new AsyncHttpRequest(server, httpRequest, httpResponse, urlcode, TimeoutHandler, m_DefaultTimeout); UUID requestID = asyncRequest.RequestID; Hashtable request = asyncRequest.RequestData; string uri = request["uri"].ToString(); bool is_ssl = uri.Contains("lslhttps"); try { Hashtable headers = (Hashtable)request["headers"]; //HTTP server code doesn't provide us with QueryStrings string queryString = ""; int pos1 = uri.IndexOf("/");// /lslhttp int pos2 = uri.IndexOf("/", pos1 + 1);// /lslhttp/ int pos3 = uri.IndexOf("/", pos2 + 1);// /lslhttp/<UUID>/ string pathInfo = uri.Substring(pos3); string url = URLFromURI(uri); UrlData urlData = null; lock (m_UrlMap) { m_UrlMap.TryGetValue(url, out urlData); // Returning NULL sends a 404 from the base server if (urlData == null) asyncRequest.SendResponse(server.SendHTML404(httpResponse)); } //for llGetHttpHeader support we need to store original URI here //to make x-path-info / x-query-string / x-script-url / x-remote-ip headers //as per http://wiki.secondlife.com/wiki/LlGetHTTPHeader RequestData requestData = new RequestData { requestId = asyncRequest.RequestID, polledRequest = asyncRequest, requestDone = false, startTime = Environment.TickCount, uri = uri }; if (requestData.headers == null) requestData.headers = new Dictionary<string, string>(); // Copy in the headers, convert keys to lower case: See. // http://wiki.secondlife.com/wiki/LlGetHTTPHeader foreach (DictionaryEntry header in headers) { string key = (string)header.Key; string value = (string)header.Value; requestData.headers.Add(key.ToLower(), value); } foreach (DictionaryEntry de in request) { if (de.Key.ToString() == "querystringkeys") { String[] keys = (String[])de.Value; foreach (String key in keys) { if (request.ContainsKey(key)) { string val = (String)request[key]; queryString = queryString + key + "=" + val + "&"; } } if (queryString.Length > 1) queryString = queryString.Substring(0, queryString.Length - 1); } } //if this machine is behind DNAT/port forwarding, currently this is being //set to address of port forwarding router requestData.headers["x-remote-ip"] = httpRequest.RemoteIPEndPoint.ToString(); requestData.headers["x-path-info"] = pathInfo; requestData.headers["x-query-string"] = queryString; requestData.headers["x-script-url"] = urlData.url; lock (m_RequestMap) { m_RequestMap.Add(requestID, requestData); } lock (m_UrlMap) { urlData.requests.Add(requestID); } urlData.engine.PostScriptEvent(urlData.itemID, "http_request", new Object[] { requestID.ToString(), request["http-method"].ToString(), request["body"].ToString() }); } catch (Exception we) { m_log.Warn("[HttpRequestHandler]: http-in request failed"); m_log.Warn(we.Message); m_log.Warn(we.StackTrace); asyncRequest.SendResponse(server.SendHTML500(httpResponse)); } } private void TimeoutHandler(AsyncHttpRequest pRequest) { pRequest.SendResponse(ProcessEvents(pRequest, true)); } private Hashtable ProcessEvents(AsyncHttpRequest pRequest, bool timedOut) { UUID requestID = pRequest.RequestID; UrlData urlData = null; RequestData requestData = null; Hashtable response = new Hashtable(); response["content_type"] = "text/plain"; lock (m_RequestMap) { if (m_RequestMap.TryGetValue(requestID, out requestData)) m_RequestMap.Remove(requestID); } if (requestData != null) { string url = URLFromURI(requestData.uri); lock (m_UrlMap) { if (m_UrlMap.TryGetValue(url, out urlData)) urlData.requests.Remove(requestID); } } if ((requestData == null) || (urlData == null)) { response["int_response_code"] = 404; response["str_response_string"] = "Request not found"; return response; } if ((timedOut == true) || ((requestData != null) && (requestData.requestDone == false))) { response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; } else { //put response response["int_response_code"] = requestData.responseCode; response["str_response_string"] = requestData.responseBody; response["content_type"] = requestData.contentType; } return response; } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; using QueryStatics = Apache.Geode.Client.Tests.QueryStatics; using QueryCategory = Apache.Geode.Client.Tests.QueryCategory; using QueryStrings = Apache.Geode.Client.Tests.QueryStrings; [TestFixture] [Category("group1")] [Category("unicast_only")] [Category("generics")] public class ThinClientRemoteQueryStructSetTests : ThinClientRegionSteps { #region Private members private UnitProcess m_client1; private UnitProcess m_client2; private static string[] QueryRegionNames = { "Portfolios", "Positions", "Portfolios2", "Portfolios3" }; #endregion protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); m_client2 = new UnitProcess(); return new ClientBase[] { m_client1, m_client2 }; } [TestFixtureSetUp] public override void InitTests() { base.InitTests(); } [TearDown] public override void EndTest() { m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServers(); base.EndTest(); } [SetUp] public override void InitTest() { m_client1.Call(InitClient); m_client2.Call(InitClient); } #region Functions invoked by the tests public void InitClient() { CacheHelper.Init(); CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(Portfolio.CreateDeserializable); CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(Position.CreateDeserializable); CacheHelper.DCache.TypeRegistry.RegisterPdxType(Apache.Geode.Client.Tests.PortfolioPdx.CreateDeserializable); CacheHelper.DCache.TypeRegistry.RegisterPdxType(Apache.Geode.Client.Tests.PositionPdx.CreateDeserializable); } public void StepOne(string locators, bool isPdx) { m_isPdx = isPdx; CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[0], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[1], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[2], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[3], true, true, null, locators, "__TESTPOOL1_", true); IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); Apache.Geode.Client.RegionAttributes<object, object> regattrs = region.Attributes; region.CreateSubRegion(QueryRegionNames[1], regattrs); } public void StepTwo(bool isPdx) { m_isPdx = isPdx; IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); IRegion<object, object> subRegion0 = (IRegion<object, object>)region0.GetSubRegion(QueryRegionNames[1]); IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(QueryRegionNames[1]); IRegion<object, object> region2 = CacheHelper.GetRegion<object, object>(QueryRegionNames[2]); IRegion<object, object> region3 = CacheHelper.GetRegion<object, object>(QueryRegionNames[3]); QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); Util.Log("SetSize {0}, NumSets {1}.", qh.PortfolioSetSize, qh.PortfolioNumSets); if (!m_isPdx) { qh.PopulatePortfolioData(region0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionData(subRegion0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionData(region1, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioData(region2, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioData(region3, qh.PortfolioSetSize, qh.PortfolioNumSets); } else { qh.PopulatePortfolioPdxData(region0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionPdxData(subRegion0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionPdxData(region1, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(region2, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(region3, qh.PortfolioSetSize, qh.PortfolioNumSets); } } public void StepThreeSS() { bool ErrorOccurred = false; QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService(); int qryIdx = 0; foreach (QueryStrings qrystr in QueryStatics.StructSetQueries) { if (qrystr.Category == QueryCategory.Unsupported) { Util.Log("Skipping query index {0} because it is unsupported.", qryIdx); qryIdx++; continue; } if (m_isPdx == true) { if (qryIdx == 12 || qryIdx == 4 || qryIdx == 7 || qryIdx == 22 || qryIdx == 30 || qryIdx == 34) { Util.Log("Skipping query index {0} for pdx because it has function.", qryIdx); qryIdx++; continue; } } Util.Log("Evaluating query index {0}. {1}", qryIdx, qrystr.Query); Query<object> query = qs.NewQuery<object>(qrystr.Query); ISelectResults<object> results = query.Execute(); int expectedRowCount = qh.IsExpectedRowsConstantSS(qryIdx) ? QueryStatics.StructSetRowCounts[qryIdx] : QueryStatics.StructSetRowCounts[qryIdx] * qh.PortfolioNumSets; if (!qh.VerifySS(results, expectedRowCount, QueryStatics.StructSetFieldCounts[qryIdx])) { ErrorOccurred = true; Util.Log("Query verify failed for query index {0}.", qryIdx); qryIdx++; continue; } StructSet<object> ss = results as StructSet<object>; if (ss == null) { Util.Log("Zero records found for query index {0}, continuing.", qryIdx); qryIdx++; continue; } uint rows = 0; Int32 fields = 0; foreach (Struct si in ss) { rows++; fields = (Int32)si.Length; } Util.Log("Query index {0} has {1} rows and {2} fields.", qryIdx, rows, fields); qryIdx++; } Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred."); } public void StepFourSS() { bool ErrorOccurred = false; QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService(); int qryIdx = 0; foreach (QueryStrings qrystr in QueryStatics.StructSetQueries) { if (qrystr.Category != QueryCategory.Unsupported) { qryIdx++; continue; } Util.Log("Evaluating unsupported query index {0}.", qryIdx); Query<object> query = qs.NewQuery<object>(qrystr.Query); try { ISelectResults<object> results = query.Execute(); Util.Log("Query exception did not occur for index {0}.", qryIdx); ErrorOccurred = true; qryIdx++; } catch (GeodeException) { // ok, exception expected, do nothing. qryIdx++; } catch (Exception) { Util.Log("Query unexpected exception occurred for index {0}.", qryIdx); ErrorOccurred = true; qryIdx++; } } Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur."); } public void KillServer() { CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); } public delegate void KillServerDelegate(); #endregion void runRemoteQuerySS() { CacheHelper.SetupJavaServers(true, "remotequeryN.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client2.Call(StepOne, CacheHelper.Locators, m_isPdx); Util.Log("StepOne complete."); m_client2.Call(StepTwo, m_isPdx); Util.Log("StepTwo complete."); m_client2.Call(StepThreeSS); Util.Log("StepThree complete."); m_client2.Call(StepFourSS); Util.Log("StepFour complete."); //m_client2.Call(GetAllRegionQuery); m_client2.Call(Close); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); } static bool m_isPdx = false; [Test] public void RemoteQuerySSWithPdx() { m_isPdx = true; runRemoteQuerySS(); } [Test] public void RemoteQuerySSWithoutPdx() { m_isPdx = false; runRemoteQuerySS(); } } }
/* * CID000e.cs - hu culture handler. * * Copyright (c) 2003 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "hu.txt". namespace I18N.West { using System; using System.Globalization; using I18N.Common; public class CID000e : RootCulture { public CID000e() : base(0x000E) {} public CID000e(int culture) : base(culture) {} public override String Name { get { return "hu"; } } public override String ThreeLetterISOLanguageName { get { return "hun"; } } public override String ThreeLetterWindowsLanguageName { get { return "HUN"; } } public override String TwoLetterISOLanguageName { get { return "hu"; } } public override DateTimeFormatInfo DateTimeFormat { get { DateTimeFormatInfo dfi = base.DateTimeFormat; dfi.AMDesignator = "DE"; dfi.PMDesignator = "DU"; dfi.AbbreviatedDayNames = new String[] {"V", "H", "K", "Sze", "Cs", "P", "Szo"}; dfi.DayNames = new String[] {"vas\u00E1rnap", "h\u00E9tf\u0151", "kedd", "szerda", "cs\u00FCt\u00F6rt\u00F6k", "p\u00E9ntek", "szombat"}; dfi.AbbreviatedMonthNames = new String[] {"jan.", "febr.", "m\u00E1rc.", "\u00E1pr.", "m\u00E1j.", "j\u00FAn.", "j\u00FAl.", "aug.", "szept.", "okt.", "nov.", "dec.", ""}; dfi.MonthNames = new String[] {"janu\u00E1r", "febru\u00E1r", "m\u00E1rcius", "\u00E1prilis", "m\u00E1jus", "j\u00FAnius", "j\u00FAlius", "augusztus", "szeptember", "okt\u00F3ber", "november", "december", ""}; dfi.DateSeparator = "."; dfi.TimeSeparator = ":"; dfi.LongDatePattern = "yyyy. MMMM d."; dfi.LongTimePattern = "H:mm:ss z"; dfi.ShortDatePattern = "yyyy.MM.dd."; dfi.ShortTimePattern = "H:mm"; dfi.FullDateTimePattern = "yyyy. MMMM d. H:mm:ss z"; dfi.I18NSetDateTimePatterns(new String[] { "d:yyyy.MM.dd.", "D:yyyy. MMMM d.", "f:yyyy. MMMM d. H:mm:ss z", "f:yyyy. MMMM d. H:mm:ss z", "f:yyyy. MMMM d. H:mm:ss", "f:yyyy. MMMM d. H:mm", "F:yyyy. MMMM d. HH:mm:ss", "g:yyyy.MM.dd. H:mm:ss z", "g:yyyy.MM.dd. H:mm:ss z", "g:yyyy.MM.dd. H:mm:ss", "g:yyyy.MM.dd. H:mm", "G:yyyy.MM.dd. HH:mm:ss", "m:MMMM dd", "M:MMMM dd", "r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "s:yyyy'-'MM'-'dd'T'HH':'mm':'ss", "t:H:mm:ss z", "t:H:mm:ss z", "t:H:mm:ss", "t:H:mm", "T:HH:mm:ss", "u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'", "U:dddd, dd MMMM yyyy HH:mm:ss", "y:yyyy MMMM", "Y:yyyy MMMM", }); return dfi; } set { base.DateTimeFormat = value; // not used } } public override NumberFormatInfo NumberFormat { get { NumberFormatInfo nfi = base.NumberFormat; nfi.CurrencyDecimalSeparator = ","; nfi.CurrencyGroupSeparator = "\u00A0"; nfi.NumberGroupSeparator = "\u00A0"; nfi.PercentGroupSeparator = "\u00A0"; nfi.NegativeSign = "-"; nfi.NumberDecimalSeparator = ","; nfi.PercentDecimalSeparator = ","; nfi.PercentSymbol = "%"; nfi.PerMilleSymbol = "\u2030"; return nfi; } set { base.NumberFormat = value; // not used } } public override String ResolveLanguage(String name) { switch(name) { case "hu": return "magyar"; } return base.ResolveLanguage(name); } public override String ResolveCountry(String name) { switch(name) { case "HU": return "Magyarorsz\u00E1g"; } return base.ResolveCountry(name); } private class PrivateTextInfo : _I18NTextInfo { public PrivateTextInfo(int culture) : base(culture) {} public override int ANSICodePage { get { return 1250; } } public override int EBCDICCodePage { get { return 500; } } public override int MacCodePage { get { return 10029; } } public override int OEMCodePage { get { return 852; } } public override String ListSeparator { get { return ";"; } } }; // class PrivateTextInfo public override TextInfo TextInfo { get { return new PrivateTextInfo(LCID); } } }; // class CID000e public class CNhu : CID000e { public CNhu() : base() {} }; // class CNhu }; // namespace I18N.West
// ------------------------------------------------------------------------------ // 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. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type DomainDnsTxtRecordRequest. /// </summary> public partial class DomainDnsTxtRecordRequest : BaseRequest, IDomainDnsTxtRecordRequest { /// <summary> /// Constructs a new DomainDnsTxtRecordRequest. /// </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 DomainDnsTxtRecordRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified DomainDnsTxtRecord using POST. /// </summary> /// <param name="domainDnsTxtRecordToCreate">The DomainDnsTxtRecord to create.</param> /// <returns>The created DomainDnsTxtRecord.</returns> public System.Threading.Tasks.Task<DomainDnsTxtRecord> CreateAsync(DomainDnsTxtRecord domainDnsTxtRecordToCreate) { return this.CreateAsync(domainDnsTxtRecordToCreate, CancellationToken.None); } /// <summary> /// Creates the specified DomainDnsTxtRecord using POST. /// </summary> /// <param name="domainDnsTxtRecordToCreate">The DomainDnsTxtRecord to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DomainDnsTxtRecord.</returns> public async System.Threading.Tasks.Task<DomainDnsTxtRecord> CreateAsync(DomainDnsTxtRecord domainDnsTxtRecordToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<DomainDnsTxtRecord>(domainDnsTxtRecordToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified DomainDnsTxtRecord. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified DomainDnsTxtRecord. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<DomainDnsTxtRecord>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified DomainDnsTxtRecord. /// </summary> /// <returns>The DomainDnsTxtRecord.</returns> public System.Threading.Tasks.Task<DomainDnsTxtRecord> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified DomainDnsTxtRecord. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The DomainDnsTxtRecord.</returns> public async System.Threading.Tasks.Task<DomainDnsTxtRecord> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<DomainDnsTxtRecord>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified DomainDnsTxtRecord using PATCH. /// </summary> /// <param name="domainDnsTxtRecordToUpdate">The DomainDnsTxtRecord to update.</param> /// <returns>The updated DomainDnsTxtRecord.</returns> public System.Threading.Tasks.Task<DomainDnsTxtRecord> UpdateAsync(DomainDnsTxtRecord domainDnsTxtRecordToUpdate) { return this.UpdateAsync(domainDnsTxtRecordToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified DomainDnsTxtRecord using PATCH. /// </summary> /// <param name="domainDnsTxtRecordToUpdate">The DomainDnsTxtRecord to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated DomainDnsTxtRecord.</returns> public async System.Threading.Tasks.Task<DomainDnsTxtRecord> UpdateAsync(DomainDnsTxtRecord domainDnsTxtRecordToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<DomainDnsTxtRecord>(domainDnsTxtRecordToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <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 IDomainDnsTxtRecordRequest 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 IDomainDnsTxtRecordRequest Expand(Expression<Func<DomainDnsTxtRecord, 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 IDomainDnsTxtRecordRequest 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 IDomainDnsTxtRecordRequest Select(Expression<Func<DomainDnsTxtRecord, 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> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="domainDnsTxtRecordToInitialize">The <see cref="DomainDnsTxtRecord"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(DomainDnsTxtRecord domainDnsTxtRecordToInitialize) { } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using Amazon; using Amazon.CloudWatch; using Amazon.CloudWatch.Model; using NUnit.Framework; using CommonTests.Framework; namespace CommonTests.IntegrationTests { [TestFixture] public class CloudWatch : TestBase<AmazonCloudWatchClient> { const string ALARM_BASENAME = "SDK-TEST-ALARM-"; [OneTimeTearDown] public void Cleanup() { var describeResult = Client.DescribeAlarmsAsync(new DescribeAlarmsRequest()).Result; List<string> toDelete = new List<string>(); foreach (MetricAlarm alarm in describeResult.MetricAlarms) { if (alarm.MetricName.StartsWith(ALARM_BASENAME) || alarm.AlarmName.StartsWith("An Alarm Name 2")) { toDelete.Add(alarm.AlarmName); } } if (toDelete.Count > 0) { DeleteAlarmsRequest delete = new DeleteAlarmsRequest() { AlarmNames = toDelete }; Client.DeleteAlarmsAsync(delete).Wait(); } BaseClean(); } [Test] [Category("CloudWatch")] public void UseDoubleForData() { var currentCulture = CultureInfo.DefaultThreadCurrentCulture; CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("sv-SE"); try { var data = new List<MetricDatum> { new MetricDatum() { MetricName="SDK-TEST-CloudWatchAppender", Unit="Seconds", Timestamp=DateTime.Now, Value=1.1 } }; Client.PutMetricDataAsync(new PutMetricDataRequest() { Namespace = "SDK-TEST-CloudWatchAppender", MetricData = data }).Wait(); UtilityMethods.Sleep(TimeSpan.FromSeconds(1)); GetMetricStatisticsResponse gmsRes = Client.GetMetricStatisticsAsync(new GetMetricStatisticsRequest() { Namespace = "SDK-TEST-CloudWatchAppender", MetricName = "SDK-TEST-CloudWatchAppender", StartTime = DateTime.Today.AddDays(-2), Period = 60 * 60, Statistics = new List<string> { "Maximum" }, EndTime = DateTime.Today.AddDays(2) }).Result; bool found = false; foreach (var dp in gmsRes.Datapoints) { if (dp.Maximum == 1.1) { found = true; break; } } Assert.IsTrue(found, "Did not found the 1.1 value"); } finally { CultureInfo.DefaultThreadCurrentCulture = currentCulture; } } [Test] [Category("CloudWatch")] public void CWExceptionTest() { GetMetricStatisticsRequest getMetricRequest = new GetMetricStatisticsRequest() { MetricName = "CPUUtilization", Namespace = "AWS/EC2", StartTime = DateTime.Parse("2008-02-26T19:00:00+00:00"), EndTime = DateTime.Parse("2011-02-26T19:00:00+00:00"), Statistics = new List<string> { "Average" }, Unit = "Percent", Period = 60 }; var exception = AssertExtensions.ExpectExceptionAsync<InvalidParameterCombinationException>(Client.GetMetricStatisticsAsync(getMetricRequest)).Result; AssertValidException(exception); Assert.AreEqual("InvalidParameterCombination", exception.ErrorCode); } [Test] [Category("CloudWatch")] public void BasicCRUD() { var listResult = Client.ListMetricsAsync(new ListMetricsRequest()).Result; Assert.IsNotNull(listResult); if (listResult.NextToken != null && listResult.NextToken.Length > 0) { listResult = Client.ListMetricsAsync(new ListMetricsRequest() { NextToken = listResult.NextToken }).Result; Assert.IsTrue(listResult.Metrics.Count > 0); } GetMetricStatisticsRequest getMetricRequest = new GetMetricStatisticsRequest() { MetricName = "NetworkIn", Namespace = "AWS/EC2", StartTime = DateTime.Parse("2008-01-01T19:00:00+00:00"), EndTime = DateTime.Parse("2009-12-01T19:00:00+00:00"), Statistics = new List<string> { "Average" }, Unit = "Percent", Period = 42000, }; var getMetricResult = Client.GetMetricStatisticsAsync(getMetricRequest).Result; Assert.IsNotNull(getMetricResult); Assert.IsTrue(getMetricResult.Datapoints.Count >= 0); Assert.IsNotNull(getMetricResult.Label); } [Test] [Category("CloudWatch")] public void AlarmTest() { var alarmName = ALARM_BASENAME + DateTime.Now.Ticks; var putResponse = Client.PutMetricAlarmAsync(new PutMetricAlarmRequest() { AlarmName = alarmName, Threshold = 100, Period = 120, EvaluationPeriods = 60, Namespace = "MyNamespace", Unit = "Percent", MetricName = "CPU", Statistic = "Average", ComparisonOperator = "GreaterThanThreshold", AlarmDescription = "This is very important" }).Result; try { var describeResponse = Client.DescribeAlarmsAsync(new DescribeAlarmsRequest() { AlarmNames = new List<string> { alarmName } }).Result; Assert.AreEqual(1, describeResponse.MetricAlarms.Count); MetricAlarm alarm = describeResponse.MetricAlarms[0]; Assert.AreEqual(100, alarm.Threshold); Assert.AreEqual(120, alarm.Period); Assert.AreEqual(60, alarm.EvaluationPeriods); Assert.AreEqual("MyNamespace", alarm.Namespace); Assert.AreEqual(StandardUnit.Percent, alarm.Unit); Assert.AreEqual(Statistic.Average, alarm.Statistic); Assert.AreEqual(ComparisonOperator.GreaterThanThreshold, alarm.ComparisonOperator); Assert.AreEqual("This is very important", alarm.AlarmDescription); var setResponse = Client.SetAlarmStateAsync(new SetAlarmStateRequest() { AlarmName = alarmName, StateValue = "ALARM", StateReason = "Just Testing" }).Result; describeResponse = Client.DescribeAlarmsAsync(new DescribeAlarmsRequest() { AlarmNames = new List<string> { alarmName } }).Result; alarm = describeResponse.MetricAlarms[0]; Assert.IsTrue("ALARM".Equals(alarm.StateValue) || "INSUFFICIENT_DATA".Equals(alarm.StateValue)); if ("ALARM".Equals(alarm.StateValue)) { Assert.AreEqual("Just Testing", alarm.StateReason); } Client.EnableAlarmActionsAsync(new EnableAlarmActionsRequest() { AlarmNames = new List<string> { alarmName } }).Wait(); describeResponse = Client.DescribeAlarmsAsync(new DescribeAlarmsRequest() { AlarmNames = new List<string> { alarmName } }).Result; alarm = describeResponse.MetricAlarms[0]; Assert.IsTrue(alarm.ActionsEnabled); Client.DisableAlarmActionsAsync(new DisableAlarmActionsRequest() { AlarmNames = new List<string> { alarmName } }).Wait(); describeResponse = Client.DescribeAlarmsAsync(new DescribeAlarmsRequest() { AlarmNames = new List<string> { alarmName } }).Result; alarm = describeResponse.MetricAlarms[0]; Assert.IsFalse(alarm.ActionsEnabled); var describeMetricResponse = Client.DescribeAlarmsForMetricAsync(new DescribeAlarmsForMetricRequest() { MetricName = "CPU", Namespace = "MyNamespace" }).Result; alarm = null; foreach (var a in describeMetricResponse.MetricAlarms) { if (a.AlarmName.Equals(alarmName)) { alarm = a; break; } } Assert.IsNotNull(alarm); var describeHistory = Client.DescribeAlarmHistoryAsync(new DescribeAlarmHistoryRequest() { AlarmName = alarmName }).Result; Assert.IsTrue(describeHistory.AlarmHistoryItems.Count > 0); } finally { Client.DeleteAlarmsAsync(new DeleteAlarmsRequest() { AlarmNames = new List<string> { alarmName } }).Wait(); } } const int ONE_WEEK_IN_MILLISECONDS = 1000 * 60 * 60 * 24 * 7; const int ONE_HOUR_IN_MILLISECONDS = 1000 * 60 * 60; /** * Tests that we can call the ListMetrics operation and correctly understand * the response. */ [Test] [Category("CloudWatch")] public void TestListMetrics() { var result = Client.ListMetricsAsync(new ListMetricsRequest()).Result; bool seenDimensions = false; Assert.IsTrue(result.Metrics.Count > 0); foreach (Metric metric in result.Metrics) { AssertNotEmpty(metric.MetricName); AssertNotEmpty(metric.Namespace); foreach (Dimension dimension in metric.Dimensions) { seenDimensions = true; AssertNotEmpty(dimension.Name); AssertNotEmpty(dimension.Value); } } Assert.IsTrue(seenDimensions); if (!string.IsNullOrEmpty(result.NextToken)) { result = Client.ListMetricsAsync(new ListMetricsRequest() { NextToken = result.NextToken }).Result; Assert.IsTrue(result.Metrics.Count > 0); } } /** * Tests that we can call the GetMetricStatistics operation and correctly * understand the response. */ [Test] [Category("CloudWatch")] public void TestGetMetricStatistics() { string measureName = "CPUUtilization"; GetMetricStatisticsRequest request = new GetMetricStatisticsRequest() { StartTime = DateTime.Now.AddMilliseconds(-ONE_WEEK_IN_MILLISECONDS), Namespace = "AWS/EC2", Period = 60 * 60, Dimensions = new List<Dimension> { new Dimension{ Name="InstanceType",Value="m1.small"} }, MetricName = measureName, Statistics = new List<string> { "Average", "Maximum", "Minimum", "Sum" }, EndTime = DateTime.Now }; var result = Client.GetMetricStatisticsAsync(request).Result; AssertNotEmpty(result.Label); Assert.AreEqual(measureName, result.Label); Assert.IsNotNull(result.Datapoints); } /** * Tests setting the state for an alarm and reading its history. */ [Test] [Category("CloudWatch")] public void TestSetAlarmStateAndHistory() { String metricName = this.GetType().Name + DateTime.Now.Ticks; PutMetricAlarmRequest[] rqs = CreateTwoNewAlarms(metricName); PutMetricAlarmRequest rq1 = rqs[0]; PutMetricAlarmRequest rq2 = rqs[1]; /* * Set the state */ SetAlarmStateRequest setAlarmStateRequest = new SetAlarmStateRequest() { AlarmName = rq1.AlarmName, StateValue = "ALARM", StateReason = "manual" }; Client.SetAlarmStateAsync(setAlarmStateRequest).Wait(); setAlarmStateRequest = new SetAlarmStateRequest() { AlarmName = rq2.AlarmName, StateValue = "ALARM", StateReason = "manual" }; Client.SetAlarmStateAsync(setAlarmStateRequest).Wait(); var describeResult = Client .DescribeAlarmsForMetricAsync( new DescribeAlarmsForMetricRequest() { Dimensions = rq1.Dimensions, MetricName = metricName, Namespace = rq1.Namespace }).Result; Assert.AreEqual(2, describeResult.MetricAlarms.Count); foreach (MetricAlarm alarm in describeResult.MetricAlarms) { Assert.IsTrue(rq1.AlarmName.Equals(alarm.AlarmName) || rq2.AlarmName.Equals(alarm.AlarmName)); Assert.IsTrue("ALARM".Equals(alarm.StateValue) || "INSUFFICIENT_DATA".Equals(alarm.StateValue)); if ("ALARM".Equals(alarm.StateValue)) { Assert.AreEqual(setAlarmStateRequest.StateReason, alarm.StateReason); } } /* * Get the history */ DescribeAlarmHistoryRequest alarmHistoryRequest = new DescribeAlarmHistoryRequest() { AlarmName = rq1.AlarmName, HistoryItemType = "StateUpdate" }; var historyResult = Client.DescribeAlarmHistoryAsync(alarmHistoryRequest).Result; Assert.IsTrue(historyResult.AlarmHistoryItems.Count > 0); } /** * Tests disabling and enabling alarms */ [Test] [Category("CloudWatch")] public void TestDisableEnableAlarms() { String metricName = this.GetType().Name + DateTime.Now.Ticks; PutMetricAlarmRequest[] rqs = CreateTwoNewAlarms(metricName); PutMetricAlarmRequest rq1 = rqs[0]; PutMetricAlarmRequest rq2 = rqs[1]; /* * Disable */ DisableAlarmActionsRequest disable = new DisableAlarmActionsRequest() { AlarmNames = new List<string> { rq1.AlarmName, rq2.AlarmName } }; Client.DisableAlarmActionsAsync(disable).Wait(); var describeResult = Client.DescribeAlarmsForMetricAsync(new DescribeAlarmsForMetricRequest() { Dimensions = rq1.Dimensions, MetricName = metricName, Namespace = rq1.Namespace }).Result; Assert.AreEqual(2, describeResult.MetricAlarms.Count); foreach (MetricAlarm alarm in describeResult.MetricAlarms) { Assert.IsTrue(rq1.AlarmName.Equals(alarm.AlarmName) || rq2.AlarmName.Equals(alarm.AlarmName)); Assert.IsFalse(alarm.ActionsEnabled); } /* * Enable */ EnableAlarmActionsRequest enable = new EnableAlarmActionsRequest() { AlarmNames = new List<string> { rq1.AlarmName, rq2.AlarmName } }; Client.EnableAlarmActionsAsync(enable).Wait(); describeResult = Client.DescribeAlarmsForMetricAsync(new DescribeAlarmsForMetricRequest() { Dimensions = rq1.Dimensions, MetricName = metricName, Namespace = rq1.Namespace }).Result; Assert.AreEqual(2, describeResult.MetricAlarms.Count); foreach (MetricAlarm alarm in describeResult.MetricAlarms) { Assert.IsTrue(rq1.AlarmName.Equals(alarm.AlarmName) || rq2.AlarmName.Equals(alarm.AlarmName)); Assert.IsTrue(alarm.ActionsEnabled); } } /** * Tests creating alarms and describing them */ [Test] [Category("CloudWatch")] public void TestDescribeAlarms() { string metricName = this.GetType().Name + DateTime.Now.Ticks; PutMetricAlarmRequest[] rqs = CreateTwoNewAlarms(metricName); PutMetricAlarmRequest rq1 = rqs[0]; PutMetricAlarmRequest rq2 = rqs[1]; /* * Describe them */ var describeResult = Client.DescribeAlarmsForMetricAsync(new DescribeAlarmsForMetricRequest() { Dimensions = rq1.Dimensions, MetricName = metricName, Namespace = rq1.Namespace }).Result; Assert.AreEqual(2, describeResult.MetricAlarms.Count); foreach (MetricAlarm alarm in describeResult.MetricAlarms) { Assert.IsTrue(rq1.AlarmName.Equals(alarm.AlarmName) || rq2.AlarmName.Equals(alarm.AlarmName)); Assert.IsTrue(alarm.ActionsEnabled); } } [Test] [Category("CloudWatch")] public void TestPutMetricData() { string metricName = "DotNetSDKTestMetric"; string nameSpace = "AWS-EC2"; List<MetricDatum> data = new List<MetricDatum>(); DateTime ts = DateTime.Now; data.Add(new MetricDatum() { MetricName = metricName, Timestamp = ts.AddHours(-1), Unit = "None", Value = 23.0 }); data.Add(new MetricDatum() { MetricName = metricName, Timestamp = ts, Unit = "None", Value = 21.0 }); data.Add(new MetricDatum() { MetricName = metricName, Timestamp = DateTime.Now.AddHours(1), Unit = "None", Value = 22.0 }); Client.PutMetricDataAsync(new PutMetricDataRequest() { Namespace = nameSpace, MetricData = data }).Wait(); UtilityMethods.Sleep(TimeSpan.FromSeconds(1)); GetMetricStatisticsResponse gmsRes = Client.GetMetricStatisticsAsync(new GetMetricStatisticsRequest() { Namespace = nameSpace, MetricName = metricName, StartTime = ts.AddDays(-1), Period = 60 * 60, Statistics = new List<string> { "Minimum", "Maximum" }, EndTime = ts.AddDays(1) }).Result; Assert.IsTrue(gmsRes.Datapoints.Count > 0); } /** * Creates two alarms on the metric name given and returns the two requests * as an array. */ private PutMetricAlarmRequest[] CreateTwoNewAlarms(String metricName) { PutMetricAlarmRequest[] rqs = new PutMetricAlarmRequest[2]; /* * Put two metric alarms */ rqs[0] = new PutMetricAlarmRequest() { ActionsEnabled = true, AlarmDescription = "Some alarm description", AlarmName = ALARM_BASENAME + metricName, ComparisonOperator = "GreaterThanThreshold", Dimensions = new List<Dimension> { new Dimension{Name="InstanceType",Value="m1.small"} }, EvaluationPeriods = 1, MetricName = metricName, Namespace = "AWS/EC2", Period = 60, Statistic = "Average", Threshold = 1.0, Unit = "Count" }; Client.PutMetricAlarmAsync(rqs[0]).Wait(); rqs[1] = new PutMetricAlarmRequest() { ActionsEnabled = true, AlarmDescription = "Some alarm description 2", AlarmName = "An Alarm Name 2" + metricName, ComparisonOperator = "GreaterThanThreshold", Dimensions = new List<Dimension> { new Dimension{Name="InstanceType",Value="m1.small"} }, EvaluationPeriods = 1, MetricName = metricName, Namespace = "AWS/EC2", Period = 60, Statistic = "Average", Threshold = 2.0, Unit = "Count" }; Client.PutMetricAlarmAsync(rqs[1]).Wait(); return rqs; } void AssertNotEmpty(String s) { Assert.IsNotNull(s); Assert.IsTrue(s.Length > 0); } private void AssertValidException(AmazonCloudWatchException e) { Assert.IsNotNull(e); Assert.IsNotNull(e.ErrorCode); Assert.IsNotNull(e.ErrorType); Assert.IsNotNull(e.Message); Assert.IsNotNull(e.RequestId); Assert.IsNotNull(e.StatusCode); Assert.IsTrue(e.ErrorCode.Length > 0); Assert.IsTrue(e.Message.Length > 0); Assert.IsTrue(e.RequestId.Length > 0); } } }
/****************************************************************************** * 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.LdapReferralException.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using Novell.Directory.Ldap.Utilclass; namespace Novell.Directory.Ldap { /// <summary> Thrown when a server returns a referral and when a referral has not /// been followed. It contains a list of URL strings corresponding /// to the referrals or search continuation references received on an Ldap /// operation. /// </summary> public class LdapReferralException : LdapException { /// <summary> Sets a referral that could not be processed /// /// </summary> /// <param name="url">The referral URL that could not be processed. /// </param> virtual public string FailedReferral { /* Gets the referral that could not be processed. If multiple referrals * could not be processed, the method returns one of them. * * @return the referral that could not be followed. */ get { return failedReferral; } set { failedReferral = value; } } private string failedReferral = null; private string[] referrals = null; /// <summary> Constructs a default exception with no specific error information.</summary> public LdapReferralException() : base() { } /// <summary> Constructs a default exception with a specified string as additional /// information. /// /// This form is used for lower-level errors. /// /// </summary> /// <param name="message">The additional error information. /// </param> public LdapReferralException(string message) : base(message, REFERRAL, (string)null) { } /// <summary> Constructs a default exception with a specified string as additional /// information. /// /// This form is used for lower-level errors. /// /// /// </summary> /// <param name="arguments"> The modifying arguments to be included in the /// message string. /// /// </param> /// <param name="message">The additional error information. /// </param> public LdapReferralException(string message, object[] arguments) : base(message, arguments, REFERRAL, (string)null) { } /// <summary> Constructs a default exception with a specified string as additional /// information and an exception that indicates a failure to follow a /// referral. This excepiton applies only to synchronous operations and /// is thrown only on receipt of a referral when the referral was not /// followed. /// /// </summary> /// <param name="message">The additional error information. /// /// /// </param> /// <param name="rootException">An exception which caused referral following to fail. /// </param> public LdapReferralException(string message, Exception rootException) : base(message, REFERRAL, null, rootException) { } /// <summary> Constructs a default exception with a specified string as additional /// information and an exception that indicates a failure to follow a /// referral. This excepiton applies only to synchronous operations and /// is thrown only on receipt of a referral when the referral was not /// followed. /// /// </summary> /// <param name="message">The additional error information. /// /// /// </param> /// <param name="arguments"> The modifying arguments to be included in the /// message string. /// /// </param> /// <param name="rootException">An exception which caused referral following to fail. /// </param> public LdapReferralException(string message, object[] arguments, Exception rootException) : base(message, arguments, REFERRAL, null, rootException) { } /// <summary> Constructs an exception with a specified error string, result code, and /// an error message from the server. /// /// </summary> /// <param name="message"> The additional error information. /// /// </param> /// <param name="resultCode"> The result code returned. /// /// </param> /// <param name="serverMessage"> Error message specifying additional information /// from the server. /// </param> public LdapReferralException(string message, int resultCode, string serverMessage) : base(message, resultCode, serverMessage) { } /// <summary> Constructs an exception with a specified error string, result code, and /// an error message from the server. /// /// </summary> /// <param name="message"> The additional error information. /// /// </param> /// <param name="arguments"> The modifying arguments to be included in the /// message string. /// /// </param> /// <param name="resultCode"> The result code returned. /// /// </param> /// <param name="serverMessage"> Error message specifying additional information /// from the server. /// </param> public LdapReferralException(string message, object[] arguments, int resultCode, string serverMessage) : base(message, arguments, resultCode, serverMessage) { } /// <summary> Constructs an exception with a specified error string, result code, /// an error message from the server, and an exception that indicates /// a failure to follow a referral. /// /// </summary> /// <param name="message"> The additional error information. /// /// </param> /// <param name="resultCode"> The result code returned. /// /// </param> /// <param name="serverMessage"> Error message specifying additional information /// from the server. /// </param> public LdapReferralException(string message, int resultCode, string serverMessage, Exception rootException) : base(message, resultCode, serverMessage, rootException) { } /// <summary> Constructs an exception with a specified error string, result code, /// an error message from the server, and an exception that indicates /// a failure to follow a referral. /// /// </summary> /// <param name="message"> The additional error information. /// /// </param> /// <param name="arguments"> The modifying arguments to be included in the /// message string. /// /// </param> /// <param name="resultCode"> The result code returned. /// /// </param> /// <param name="serverMessage"> Error message specifying additional information /// from the server. /// </param> public LdapReferralException(string message, object[] arguments, int resultCode, string serverMessage, Exception rootException) : base(message, arguments, resultCode, serverMessage, rootException) { } /// <summary> Gets the list of referral URLs (Ldap URLs to other servers) returned by /// the Ldap server. /// /// The referral list may include URLs of a type other than ones for an Ldap /// server (for example, a referral URL other than ldap://something). /// /// </summary> /// <returns> The list of URLs that comprise this referral /// </returns> public virtual string[] getReferrals() { return referrals; } /// <summary> Sets the list of referrals /// /// </summary> /// <param name="urls">the list of referrals returned by the Ldap server in a /// single response. /// </param> /* package */ internal virtual void setReferrals(string[] urls) { referrals = urls; } /// <summary> returns a string of information about the exception and the /// the nested exceptions, if any. /// </summary> public override string ToString() { string msg, tmsg; // Format the basic exception information msg = getExceptionString("LdapReferralException"); // Add failed referral information if ((object)failedReferral != null) { tmsg = ResourcesHandler.getMessage("FAILED_REFERRAL", new object[] { "LdapReferralException", failedReferral }); // If found no string from resource file, use a default string if (tmsg.ToUpper().Equals("SERVER_MSG".ToUpper())) { tmsg = "LdapReferralException: Failed Referral: " + failedReferral; } msg = msg + '\n' + tmsg; } // Add referral information, display all the referrals in the list if (referrals != null) { for (int i = 0; i < referrals.Length; i++) { tmsg = ResourcesHandler.getMessage("REFERRAL_ITEM", new object[] { "LdapReferralException", referrals[i] }); // If found no string from resource file, use a default string if (tmsg.ToUpper().Equals("SERVER_MSG".ToUpper())) { tmsg = "LdapReferralException: Referral: " + referrals[i]; } msg = msg + '\n' + tmsg; } } return msg; } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.IO; using System.Collections.Generic; using System.Text; using Autodesk.Revit; using Autodesk.Revit.DB.Events; using System.Windows.Forms; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.ApplicationServices; using Autodesk.RevitAddIns; namespace Revit.SDK.Samples.CancelSave.CS { /// <summary> /// This class is an external application which checks whether "Project Status" is updated /// once the project is about to be saved. If updated pass the save else cancel the save and inform user with one message. /// </summary> [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)] [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)] public class CancelSave : IExternalApplication { #region Memeber Variables const string thisAddinFileName = "CancelSave.addin"; // The dictionary contains document hashcode and its original "Project Status" pair. Dictionary<int, string> documentOriginalStatusDic = new Dictionary<int, string>(); #endregion #region IExternalApplication Members /// <summary> /// Implement OnStartup method of IExternalApplication interface. /// This method subscribes to DocumentOpened, DocumentCreated, DocumentSaving and DocumentSavingAs events. /// The first two events are used to reserve "Project Status" original value; /// The last two events are used to check whether "Project Status" has been updated, and re-reserve current value as new original value for next compare. /// </summary> /// <param name="application">Controlled application to be loaded to Revit process.</param> /// <returns>The status of the external application</returns> public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) { // subscribe to DocumentOpened, DocumentCreated, DocumentSaving and DocumentSavingAs events application.ControlledApplication.DocumentOpened += new EventHandler<DocumentOpenedEventArgs>(ReservePojectOriginalStatus); application.ControlledApplication.DocumentCreated += new EventHandler<DocumentCreatedEventArgs>(ReservePojectOriginalStatus); application.ControlledApplication.DocumentSaving += new EventHandler<DocumentSavingEventArgs>(CheckProjectStatusUpdate); application.ControlledApplication.DocumentSavingAs += new EventHandler<DocumentSavingAsEventArgs>(CheckProjectStatusUpdate); return Autodesk.Revit.UI.Result.Succeeded; } /// <summary> /// Implement OnShutdown method of IExternalApplication interface. /// </summary> /// <param name="application">Controlled application to be shutdown.</param> /// <returns>The status of the external application.</returns> public Autodesk.Revit.UI.Result OnShutdown(UIControlledApplication application) { // unsubscribe to DocumentOpened, DocumentCreated, DocumentSaving and DocumentSavingAs events application.ControlledApplication.DocumentOpened -= new EventHandler<DocumentOpenedEventArgs>(ReservePojectOriginalStatus); application.ControlledApplication.DocumentCreated -= new EventHandler<DocumentCreatedEventArgs>(ReservePojectOriginalStatus); application.ControlledApplication.DocumentSaving -= new EventHandler<DocumentSavingEventArgs>(CheckProjectStatusUpdate); application.ControlledApplication.DocumentSavingAs -= new EventHandler<DocumentSavingAsEventArgs>(CheckProjectStatusUpdate); // finalize the log file. LogManager.LogFinalize(); return Autodesk.Revit.UI.Result.Succeeded; } #endregion #region EventHandler /// <summary> /// Event handler method for DocumentOpened and DocumentCreated events. /// This method will reserve "Project Status" value after document has been opened or created. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">Event arguments that contains the event data.</param> private void ReservePojectOriginalStatus(Object sender, RevitAPIPostDocEventArgs args) { // The document associated with the event. Here means which document has been created or opened. Document doc = args.Document; // Project information is unavailable for Family document. if (doc.IsFamilyDocument) { return; } // write log file. LogManager.WriteLog(args, doc); // get the hashCode of this document. int docHashCode = doc.GetHashCode(); // retrieve the current value of "Project Status". string currentProjectStatus = RetrieveProjectCurrentStatus(doc); // reserve "Project Status" current value in one dictionary, and use this project's hashCode as key. documentOriginalStatusDic.Add(docHashCode, currentProjectStatus); // write log file. LogManager.WriteLog(" Current Project Status: " + currentProjectStatus); } /// <summary> /// Event handler method for DocumentSaving and DocumentSavingAs events. /// This method will check whether "Project Status" has been updated, and reserve current value as original value. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">Event arguments that contains the event data.</param> private void CheckProjectStatusUpdate(Object sender, RevitAPIPreDocEventArgs args) { // The document associated with the event. Here means which document is about to save / save as. Document doc = args.Document; // Project information is unavailable for Family document. if (doc.IsFamilyDocument) { return; } // write log file. LogManager.WriteLog(args, doc); // retrieve the current value of "Project Status". string currentProjectStatus = RetrieveProjectCurrentStatus(args.Document); // get the old value of "Project Status" for one dictionary. string originalProjectStatus = documentOriginalStatusDic[doc.GetHashCode()]; // write log file. LogManager.WriteLog(" Current Project Status: " + currentProjectStatus + "; Original Project Status: " + originalProjectStatus); // project status has not been updated. if ((string.IsNullOrEmpty(currentProjectStatus) && string.IsNullOrEmpty(originalProjectStatus)) || (0 == string.Compare(currentProjectStatus, originalProjectStatus,true))) { DealNotUpdate(args); return; } // update "Project Status" value reserved in the dictionary. documentOriginalStatusDic.Remove(doc.GetHashCode()); documentOriginalStatusDic.Add(doc.GetHashCode(), currentProjectStatus); } #endregion /// <summary> /// Deal with the case that the project status wasn't updated. /// If the event is Cancellable, cancel it and inform user else just inform user the status. /// </summary> /// <param name="args">Event arguments that contains the event data.</param> private static void DealNotUpdate(RevitAPIPreDocEventArgs args) { string mainMessage; string additionalText; TaskDialog taskDialog = new TaskDialog("CancelSave Sample"); if (args.Cancellable) { args.Cancel(); // cancel this event if it is cancellable. mainMessage = "CancelSave sample detected that the Project Status parameter on Project Info has not been updated. The file will not be saved."; // prompt to user. } else { // will not cancel this event since it isn't cancellable. mainMessage = "The file is about to save. But CancelSave sample detected that the Project Status parameter on Project Info has not been updated."; // prompt to user. } // taskDialog will not show when do regression test. if (!LogManager.RegressionTestNow) { additionalText = "You can disable this permanently by uninstaling the CancelSave sample from Revit. Remove or rename CancelSave.addin from the addins directory."; // use one taskDialog to inform user current situation. taskDialog.MainInstruction = mainMessage; taskDialog.MainContent = additionalText; taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Open the addins directory"); taskDialog.CommonButtons = TaskDialogCommonButtons.Close; taskDialog.DefaultButton = TaskDialogResult.Close; TaskDialogResult tResult = taskDialog.Show(); if (TaskDialogResult.CommandLink1 == tResult) { System.Diagnostics.Process.Start("explorer.exe", DetectAddinFileLocation(args.Document.Application)); } } // write log file. LogManager.WriteLog(" Project Status is not updated, taskDialog informs user: " + mainMessage); } /// <summary> /// Retrieve current value of Project Status. /// </summary> /// <param name="doc">Document of which the Project Status will be retrieved.</param> /// <returns>Current value of Project Status.</returns> private static string RetrieveProjectCurrentStatus(Document doc) { // Project information is unavailable for Family document. if (doc.IsFamilyDocument) { return null; } // get project status stored in project information object and return it. return doc.ProjectInformation.Status; } private static string DetectAddinFileLocation(Autodesk.Revit.ApplicationServices.Application applictaion) { string addinFileFolderLocation = null; IList<RevitProduct> installedRevitList = RevitProductUtility.GetAllInstalledRevitProducts(); foreach (RevitProduct revit in installedRevitList) { if (revit.Version.ToString().Contains(applictaion.VersionNumber)) { string allUsersAddInFolder = revit.AllUsersAddInFolder; string currentUserAddInFolder = revit.CurrentUserAddInFolder; if (File.Exists(Path.Combine(allUsersAddInFolder, thisAddinFileName))) { addinFileFolderLocation = allUsersAddInFolder; } else if (File.Exists(Path.Combine(currentUserAddInFolder, thisAddinFileName))) { addinFileFolderLocation = currentUserAddInFolder; } break; } } return addinFileFolderLocation; } } }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using Microsoft.NodejsTools.Debugger.Serialization; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Debugger.Interop; namespace Microsoft.NodejsTools.Debugger.DebugEngine { // Represents a logical stack frame on the thread stack. // Also implements the IDebugExpressionContext interface, which allows expression evaluation and watch windows. class AD7StackFrame : IDebugStackFrame2, IDebugExpressionContext2, IDebugProperty2 { private readonly IComparer<string> _comparer = new NaturalSortComparer(); private readonly AD7Engine _engine; private readonly NodeStackFrame _stackFrame; private readonly AD7Thread _thread; private AD7MemoryAddress _codeContext; private AD7DocumentContext _documentContext; public AD7StackFrame(AD7Engine engine, AD7Thread thread, NodeStackFrame stackFrame) { _engine = engine; _thread = thread; _stackFrame = stackFrame; } public NodeStackFrame StackFrame { get { return _stackFrame; } } public AD7Engine Engine { get { return _engine; } } public AD7Thread Thread { get { return _thread; } } private AD7MemoryAddress CodeContext { get { if (_codeContext == null) { _codeContext = new AD7MemoryAddress(_engine, _stackFrame); } return _codeContext; } } private AD7DocumentContext DocumentContext { get { if (_documentContext == null) { _documentContext = new AD7DocumentContext(CodeContext); } return _documentContext; } } #region Non-interface methods // Construct a FRAMEINFO for this stack frame with the requested information. public void SetFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, out FRAMEINFO frameInfo) { frameInfo = new FRAMEINFO(); // The debugger is asking for the formatted name of the function which is displayed in the callstack window. // There are several optional parts to this name including the module, argument types and values, and line numbers. // The optional information is requested by setting flags in the dwFieldSpec parameter. if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME) != 0) { string funcName = _stackFrame.FunctionName; if (funcName == "<module>") { if (_stackFrame.FileName.IndexOfAny(Path.GetInvalidPathChars()) == -1) { funcName = Path.GetFileName(_stackFrame.FileName) + " module"; } else if (_stackFrame.FileName.EndsWith("<string>", StringComparison.Ordinal)) { funcName = "<exec or eval>"; } else { funcName = _stackFrame.FileName + " unknown code"; } } else { if (_stackFrame.FileName != "<unknown>") { funcName = string.Format(CultureInfo.InvariantCulture, "{0} [{1}]", funcName, Path.GetFileName(_stackFrame.FileName)); } else { funcName = funcName + " in <unknown>"; } } frameInfo.m_bstrFuncName = string.Format(CultureInfo.InvariantCulture, "{0} Line {1}", funcName, _stackFrame.Line + 1); frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FUNCNAME; } if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_LANGUAGE) != 0) { Guid dummy; AD7Engine.MapLanguageInfo(_stackFrame.FileName, out frameInfo.m_bstrLanguage, out dummy); frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_LANGUAGE; } // The debugger is requesting the name of the module for this stack frame. if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_MODULE) != 0) { if (_stackFrame.FileName.IndexOfAny(Path.GetInvalidPathChars()) == -1) { frameInfo.m_bstrModule = Path.GetFileName(_stackFrame.FileName); } else if (_stackFrame.FileName.EndsWith("<string>", StringComparison.Ordinal)) { frameInfo.m_bstrModule = "<exec/eval>"; } else { frameInfo.m_bstrModule = "<unknown>"; } frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_MODULE; } // The debugger is requesting the IDebugStackFrame2 value for this frame info. if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FRAME) != 0) { frameInfo.m_pFrame = this; frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FRAME; } // Does this stack frame of symbols loaded? if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_DEBUGINFO) != 0) { frameInfo.m_fHasDebugInfo = 1; frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_DEBUGINFO; } // Is this frame stale? if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_STALECODE) != 0) { frameInfo.m_fStaleCode = 0; frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_STALECODE; } // The debugger would like a pointer to the IDebugModule2 that contains this stack frame. if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP) != 0) { // TODO: Module /* if (module != null) { AD7Module ad7Module = (AD7Module)module.Client; Debug.Assert(ad7Module != null); frameInfo.m_pModule = ad7Module; frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP; }*/ } } // Construct an instance of IEnumDebugPropertyInfo2 for the combined locals and parameters. private List<DEBUG_PROPERTY_INFO> CreateLocalsPlusArgsProperties(uint radix) { return CreateLocalProperties(radix).Union(CreateParameterProperties(radix)).ToList(); } // Construct an instance of IEnumDebugPropertyInfo2 for the locals collection only. private List<DEBUG_PROPERTY_INFO> CreateLocalProperties(uint radix) { var properties = new List<DEBUG_PROPERTY_INFO>(); IList<NodeEvaluationResult> locals = _stackFrame.Locals; for (int i = 0; i < locals.Count; i++) { var property = new AD7Property(this, locals[i]); properties.Add( property.ConstructDebugPropertyInfo( radix, enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD | enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME ) ); } return properties; } // Construct an instance of IEnumDebugPropertyInfo2 for the parameters collection only. private List<DEBUG_PROPERTY_INFO> CreateParameterProperties(uint radix) { var properties = new List<DEBUG_PROPERTY_INFO>(); IList<NodeEvaluationResult> parameters = _stackFrame.Parameters; for (int i = 0; i < parameters.Count; i++) { var property = new AD7Property(this, parameters[i]); properties.Add( property.ConstructDebugPropertyInfo( radix, enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD | enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME ) ); } return properties; } #endregion #region IDebugStackFrame2 Members // Creates an enumerator for properties associated with the stack frame, such as local variables. // The sample engine only supports returning locals and parameters. Other possible values include // class fields (this pointer), registers, exceptions... int IDebugStackFrame2.EnumProperties(enum_DEBUGPROP_INFO_FLAGS dwFields, uint nRadix, ref Guid guidFilter, uint dwTimeout, out uint elementsReturned, out IEnumDebugPropertyInfo2 enumObject) { List<DEBUG_PROPERTY_INFO> properties; elementsReturned = 0; enumObject = null; if (guidFilter == DebuggerConstants.guidFilterLocalsPlusArgs || guidFilter == DebuggerConstants.guidFilterAllLocalsPlusArgs || guidFilter == DebuggerConstants.guidFilterAllLocals) { properties = CreateLocalsPlusArgsProperties(nRadix); } else if (guidFilter == DebuggerConstants.guidFilterLocals) { properties = CreateLocalProperties(nRadix); } else if (guidFilter == DebuggerConstants.guidFilterArgs) { properties = CreateParameterProperties(nRadix); } else { return VSConstants.E_NOTIMPL; } // Select distinct values from arguments and local variables properties = properties.GroupBy(p => p.bstrName).Select(p => p.First()).ToList(); elementsReturned = (uint)properties.Count; enumObject = new AD7PropertyInfoEnum(properties.OrderBy(p => p.bstrName, _comparer).ToArray()); return VSConstants.S_OK; } // Gets the code context for this stack frame. The code context represents the current instruction pointer in this stack frame. int IDebugStackFrame2.GetCodeContext(out IDebugCodeContext2 memoryAddress) { memoryAddress = CodeContext; return VSConstants.S_OK; } // Gets a description of the properties of a stack frame. // Calling the IDebugProperty2::EnumChildren method with appropriate filters can retrieve the local variables, method parameters, registers, and "this" // pointer associated with the stack frame. The debugger calls EnumProperties to obtain these values in the sample. int IDebugStackFrame2.GetDebugProperty(out IDebugProperty2 property) { property = this; return VSConstants.S_OK; } // Gets the document context for this stack frame. The debugger will call this when the current stack frame is changed // and will use it to open the correct source document for this stack frame. int IDebugStackFrame2.GetDocumentContext(out IDebugDocumentContext2 docContext) { docContext = DocumentContext; return VSConstants.S_OK; } // Gets an evaluation context for expression evaluation within the current context of a stack frame and thread. // Generally, an expression evaluation context can be thought of as a scope for performing expression evaluation. // Call the IDebugExpressionContext2::ParseText method to parse an expression and then call the resulting IDebugExpression2::EvaluateSync // or IDebugExpression2::EvaluateAsync methods to evaluate the parsed expression. int IDebugStackFrame2.GetExpressionContext(out IDebugExpressionContext2 ppExprCxt) { ppExprCxt = this; return VSConstants.S_OK; } // Gets a description of the stack frame. int IDebugStackFrame2.GetInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, FRAMEINFO[] pFrameInfo) { SetFrameInfo(dwFieldSpec, out pFrameInfo[0]); return VSConstants.S_OK; } // Gets the language associated with this stack frame. // In this sample, all the supported stack frames are C++ int IDebugStackFrame2.GetLanguageInfo(ref string pbstrLanguage, ref Guid pguidLanguage) { AD7Engine.MapLanguageInfo(_stackFrame.FileName, out pbstrLanguage, out pguidLanguage); return VSConstants.S_OK; } // Gets the name of the stack frame. // The name of a stack frame is typically the name of the method being executed. int IDebugStackFrame2.GetName(out string name) { name = _stackFrame.FunctionName; return 0; } // Gets a machine-dependent representation of the range of physical addresses associated with a stack frame. int IDebugStackFrame2.GetPhysicalStackRange(out ulong addrMin, out ulong addrMax) { addrMin = 0; addrMax = 0; return VSConstants.S_OK; } // Gets the thread associated with a stack frame. int IDebugStackFrame2.GetThread(out IDebugThread2 thread) { thread = _thread; return VSConstants.S_OK; } #endregion #region IDebugExpressionContext2 Members // Retrieves the name of the evaluation context. // The name is the description of this evaluation context. It is typically something that can be parsed by an expression evaluator // that refers to this exact evaluation context. For example, in C++ the name is as follows: // "{ function-name, source-file-name, module-file-name }" int IDebugExpressionContext2.GetName(out string pbstrName) { pbstrName = string.Format(CultureInfo.InvariantCulture, "{{ {0} {1} }}", _stackFrame.FunctionName, _stackFrame.FileName); return VSConstants.S_OK; } // Parses a text-based expression for evaluation. // The engine sample only supports locals and parameters so the only task here is to check the names in those collections. int IDebugExpressionContext2.ParseText(string pszCode, enum_PARSEFLAGS dwFlags, uint nRadix, out IDebugExpression2 ppExpr, out string pbstrError, out uint pichError) { pbstrError = String.Empty; pichError = 0; IEnumerable<NodeEvaluationResult> evaluationResults = _stackFrame.Locals.Union(_stackFrame.Parameters); foreach (NodeEvaluationResult currVariable in evaluationResults) { if (String.CompareOrdinal(currVariable.Expression, pszCode) == 0) { ppExpr = new UncalculatedAD7Expression(this, currVariable.Expression); return VSConstants.S_OK; } } string errorMsg; if (!_stackFrame.TryParseText(pszCode, out errorMsg)) { pbstrError = "Error: " + errorMsg; pichError = (uint)pbstrError.Length; } ppExpr = new UncalculatedAD7Expression(this, pszCode); return VSConstants.S_OK; } #endregion #region IDebugProperty2 Members int IDebugProperty2.GetPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, uint dwTimeout, IDebugReference2[] rgpArgs, uint dwArgCount, DEBUG_PROPERTY_INFO[] pPropertyInfo) { return VSConstants.E_NOTIMPL; } int IDebugProperty2.SetValueAsString(string pszValue, uint dwRadix, uint dwTimeout) { return VSConstants.E_NOTIMPL; } int IDebugProperty2.SetValueAsReference(IDebugReference2[] rgpArgs, uint dwArgCount, IDebugReference2 pValue, uint dwTimeout) { return VSConstants.E_NOTIMPL; } int IDebugProperty2.EnumChildren(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, ref Guid guidFilter, enum_DBG_ATTRIB_FLAGS dwAttribFilter, string pszNameFilter, uint dwTimeout, out IEnumDebugPropertyInfo2 ppEnum) { uint pcelt; return ((IDebugStackFrame2)this).EnumProperties(dwFields, dwRadix, ref guidFilter, dwTimeout, out pcelt, out ppEnum); } int IDebugProperty2.GetParent(out IDebugProperty2 ppParent) { ppParent = null; return VSConstants.E_NOTIMPL; } int IDebugProperty2.GetDerivedMostProperty(out IDebugProperty2 ppDerivedMost) { ppDerivedMost = null; return VSConstants.E_NOTIMPL; } int IDebugProperty2.GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes) { ppMemoryBytes = null; return VSConstants.E_NOTIMPL; } int IDebugProperty2.GetMemoryContext(out IDebugMemoryContext2 ppMemory) { ppMemory = null; return VSConstants.E_NOTIMPL; } int IDebugProperty2.GetSize(out uint pdwSize) { pdwSize = 0; return VSConstants.E_NOTIMPL; } int IDebugProperty2.GetReference(out IDebugReference2 ppReference) { ppReference = null; return VSConstants.E_NOTIMPL; } int IDebugProperty2.GetExtendedInfo(ref Guid guidExtendedInfo, out object pExtendedInfo) { pExtendedInfo = null; return VSConstants.E_NOTIMPL; } #endregion } }
#define ASTAR_MORE_AREAS // Increases the number of areas to 65535 but reduces the maximum number of graphs to 4. Disabling gives a max number of areas of 1023 and 32 graphs. //#define ASTAR_NO_PENALTY // Enabling this disables the use of penalties. Reduces memory usage. using UnityEngine; using System.Collections.Generic; using Pathfinding.Serialization; namespace Pathfinding.Nodes { //class A{} } namespace Pathfinding { public delegate void GraphNodeDelegate (GraphNode node); public delegate bool GraphNodeDelegateCancelable (GraphNode node); [System.Obsolete("This class has been replaced with GraphNode, it may be removed in future versions",true)] public class Node { } public abstract class GraphNode { private int nodeIndex; protected uint flags; /** Penlty cost for walking on this node. This can be used to make it harder/slower to walk over certain areas. */ private uint penalty; // Some fallback properties [System.Obsolete ("This attribute is deprecated. Please use .position (not a capital P)")] public Int3 Position { get { return position; } } [System.Obsolete ("This attribute is deprecated. Please use .Walkable (with a capital W)")] public bool walkable { get { return Walkable; } set { Walkable = value; } } [System.Obsolete ("This attribute is deprecated. Please use .Tag (with a capital T)")] public uint tags { get { return Tag; } set { Tag = value; } } [System.Obsolete ("This attribute is deprecated. Please use .GraphIndex (with a capital G)")] public uint graphIndex { get { return GraphIndex; } set { GraphIndex = value; } } // End of fallback /** Constructor for a graph node. */ public GraphNode (AstarPath astar) { //this.nodeIndex = NextNodeIndex++; if (astar != null) { this.nodeIndex = astar.GetNewNodeIndex(); astar.InitializeNode (this); } else { throw new System.Exception ("No active AstarPath object to bind to"); } } /** Destroys the node. * Cleans up any temporary pathfinding data used for this node. * The graph is responsible for calling this method on nodes when they are destroyed, including when the whole graph is destoyed. * Otherwise memory leaks might present themselves. * * Once called, subsequent calls to this method will not do anything. * * \note Assumes the current active AstarPath instance is the same one that created this node. */ public void Destroy () { //Already destroyed if (nodeIndex == -1) return; ClearConnections(true); if (AstarPath.active != null) { AstarPath.active.DestroyNode(this); } nodeIndex = -1; //System.Console.WriteLine ("~"); } public bool Destroyed { get { return nodeIndex == -1; } } //~GraphNode () { //Debug.Log ("Destroyed GraphNode " + nodeIndex); //} public int NodeIndex { get {return nodeIndex;}} public Int3 position; #region Constants /** Position of the walkable bit. \see Walkable */ const int FlagsWalkableOffset = 0; /** Mask of the walkable bit. \see Walkable */ const uint FlagsWalkableMask = 1 << FlagsWalkableOffset; /** Start of region bits. \see Area */ const int FlagsAreaOffset = 1; /** Mask of region bits. \see Area */ const uint FlagsAreaMask = (1024-1) << FlagsAreaOffset; /** Start of graph index bits. \see GraphIndex */ const int FlagsGraphOffset = 11; /** Mask of graph index bits. \see GraphIndex */ const uint FlagsGraphMask = (32-1) << FlagsGraphOffset; public const uint MaxRegionCount = FlagsAreaMask >> FlagsAreaOffset; /** Max number of graphs */ public const uint MaxGraphCount = FlagsGraphMask >> FlagsGraphOffset; /** Start of tag bits. \see Tag */ const int FlagsTagOffset = 19; /** Mask of tag bits. \see Tag */ const uint FlagsTagMask = (32-1) << FlagsTagOffset; #endregion #region Properties /** Holds various bitpacked variables. */ public uint Flags { get { return flags; } set { flags = value; } } /** Penalty cost for walking on this node. This can be used to make it harder/slower to walk over certain areas. */ public uint Penalty { get { return penalty; } set { if (value > 0xFFFFF) Debug.LogWarning ("Very high penalty applied. Are you sure negative values haven't underflowed?\n" + "Penalty values this high could with long paths cause overflows and in some cases infinity loops because of that.\n" + "Penalty value applied: "+value); penalty = value; } } /** True if the node is traversable */ public bool Walkable { get { return (flags & FlagsWalkableMask) != 0; } set { flags = flags & ~FlagsWalkableMask | (value ? 1U : 0U) << FlagsWalkableOffset; } } public uint Area { get { return (flags & FlagsAreaMask) >> FlagsAreaOffset; } set { //Awesome! No parentheses flags = flags & ~FlagsAreaMask | value << FlagsAreaOffset; } } public uint GraphIndex { get { return (flags & FlagsGraphMask) >> FlagsGraphOffset; } set { flags = flags & ~FlagsGraphMask | value << FlagsGraphOffset; } } public uint Tag { get { return (flags & FlagsTagMask) >> FlagsTagOffset; } set { flags = flags & ~FlagsTagMask | value << FlagsTagOffset; } } #endregion public void UpdateG (Path path, PathNode pathNode) { pathNode.G = pathNode.parent.G + pathNode.cost + path.GetTraversalCost(this); } public virtual void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) { //Simple but slow default implementation UpdateG (path,pathNode); handler.PushNode (pathNode); GetConnections (delegate (GraphNode other) { PathNode otherPN = handler.GetPathNode (other); if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) other.UpdateRecursiveG (path, otherPN,handler); }); } public virtual void FloodFill (Stack<GraphNode> stack, uint region) { //Simple but slow default implementation GetConnections (delegate (GraphNode other) { if (other.Area != region) { other.Area = region; stack.Push (other); } }); } /** Calls the delegate with all connections from this node */ public abstract void GetConnections (GraphNodeDelegate del); public abstract void AddConnection (GraphNode node, uint cost); public abstract void RemoveConnection (GraphNode node); /** Remove all connections from this node. * \param alsoReverse if true, neighbours will be requested to remove connections to this node. */ public abstract void ClearConnections (bool alsoReverse); /** Checks if this node has a connection to the specified node */ public virtual bool ContainsConnection (GraphNode node) { //Simple but slow default implementation bool contains = false; GetConnections (delegate (GraphNode n) { if (n == node) contains = true; }); return contains; } /** Recalculates all connection costs from this node. * Depending on the node type, this may or may not be supported. * Nothing will be done if the operation is not supported * \todo Use interface? */ public virtual void RecalculateConnectionCosts () { } /** Add a portal from this node to the specified node. * This function should add a portal to the left and right lists which is connecting the two nodes (\a this and \a other). * * \param other The node which is on the other side of the portal (strictly speaking it does not actually have to be on the other side of the portal though). * \param left List of portal points on the left side of the funnel * \param right List of portal points on the right side of the funnel * \param backwards If this is true, the call was made on a node with the \a other node as the node before this one in the path. * In this case you may choose to do nothing since a similar call will be made to the \a other node with this node referenced as \a other (but then with backwards = true). * You do not have to care about switching the left and right lists, that is done for you already. * * \returns True if the call was deemed successful. False if some unknown case was encountered and no portal could be added. * If both calls to node1.GetPortal (node2,...) and node2.GetPortal (node1,...) return false, the funnel modifier will fall back to adding to the path * the positions of the node. * * The default implementation simply returns false. * * This function may add more than one portal if necessary. * * \see http://digestingduck.blogspot.se/2010/03/simple-stupid-funnel-algorithm.html */ public virtual bool GetPortal (GraphNode other, List<Vector3> left, List<Vector3> right, bool backwards) { return false; } /** Open the node */ public abstract void Open (Path path, PathNode pathNode, PathHandler handler); public virtual void SerializeNode (GraphSerializationContext ctx) { //Write basic node data. ctx.writer.Write (Penalty); ctx.writer.Write (Flags); } public virtual void DeserializeNode (GraphSerializationContext ctx) { Penalty = ctx.reader.ReadUInt32(); Flags = ctx.reader.ReadUInt32(); } /** Used to serialize references to other nodes e.g connections. * Use the GraphSerializationContext.GetNodeIdentifier and * GraphSerializationContext.GetNodeFromIdentifier methods * for serialization and deserialization respectively. * * Nodes must override this method and serialize their connections. * Graph generators do not need to call this method, it will be called automatically on all * nodes at the correct time by the serializer. */ public virtual void SerializeReferences (GraphSerializationContext ctx) { } /** Used to deserialize references to other nodes e.g connections. * Use the GraphSerializationContext.GetNodeIdentifier and * GraphSerializationContext.GetNodeFromIdentifier methods * for serialization and deserialization respectively. * * Nodes must override this method and serialize their connections. * Graph generators do not need to call this method, it will be called automatically on all * nodes at the correct time by the serializer. */ public virtual void DeserializeReferences (GraphSerializationContext ctx) { } } public abstract class MeshNode : GraphNode { public MeshNode (AstarPath astar) : base (astar) { } public GraphNode[] connections; public uint[] connectionCosts; public abstract Int3 GetVertex (int i); public abstract int GetVertexCount (); public abstract Vector3 ClosestPointOnNode (Vector3 p); public abstract Vector3 ClosestPointOnNodeXZ (Vector3 p); public override void ClearConnections (bool alsoReverse) { if (alsoReverse && connections != null) { for (int i=0;i<connections.Length;i++) { connections[i].RemoveConnection (this); } } connections = null; connectionCosts = null; } public override void GetConnections (GraphNodeDelegate del) { if (connections == null) return; for (int i=0;i<connections.Length;i++) del (connections[i]); } public override void FloodFill (Stack<GraphNode> stack, uint region) { //Faster, more specialized implementation to override the slow default implementation if (connections == null) return; for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; if (other.Area != region) { other.Area = region; stack.Push (other); } } } public override bool ContainsConnection (GraphNode node) { for (int i=0;i<connections.Length;i++) if (connections[i] == node) return true; return false; } public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) { UpdateG (path,pathNode); handler.PushNode (pathNode); for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; PathNode otherPN = handler.GetPathNode (other); if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) { other.UpdateRecursiveG (path, otherPN,handler); } } } /** Add a connection from this node to the specified node. * If the connection already exists, the cost will simply be updated and * no extra connection added. * * \note Only adds a one-way connection. Consider calling the same function on the other node * to get a two-way connection. */ public override void AddConnection (GraphNode node, uint cost) { if (connections != null) { for (int i=0;i<connections.Length;i++) { if (connections[i] == node) { connectionCosts[i] = cost; return; } } } int connLength = connections != null ? connections.Length : 0; GraphNode[] newconns = new GraphNode[connLength+1]; uint[] newconncosts = new uint[connLength+1]; for (int i=0;i<connLength;i++) { newconns[i] = connections[i]; newconncosts[i] = connectionCosts[i]; } newconns[connLength] = node; newconncosts[connLength] = cost; connections = newconns; connectionCosts = newconncosts; } /** Removes any connection from this node to the specified node. * If no such connection exists, nothing will be done. * * \note This only removes the connection from this node to the other node. * You may want to call the same function on the other node to remove its eventual connection * to this node. */ public override void RemoveConnection (GraphNode node) { if (connections == null) return; for (int i=0;i<connections.Length;i++) { if (connections[i] == node) { int connLength = connections.Length; GraphNode[] newconns = new GraphNode[connLength-1]; uint[] newconncosts = new uint[connLength-1]; for (int j=0;j<i;j++) { newconns[j] = connections[j]; newconncosts[j] = connectionCosts[j]; } for (int j=i+1;j<connLength;j++) { newconns[j-1] = connections[j]; newconncosts[j-1] = connectionCosts[j]; } connections = newconns; connectionCosts = newconncosts; return; } } } /** Checks if \a p is inside the node * * The default implementation uses XZ space and is in large part got from the website linked below * \author http://unifycommunity.com/wiki/index.php?title=PolyContainsPoint (Eric5h5) */ public virtual bool ContainsPoint (Int3 p) { bool inside = false; int count = GetVertexCount(); for (int i = 0, j=count-1; i < count; j = i++) { if ( ((GetVertex(i).z <= p.z && p.z < GetVertex(j).z) || (GetVertex(j).z <= p.z && p.z < GetVertex(i).z)) && (p.x < (GetVertex(j).x - GetVertex(i).x) * (p.z - GetVertex(i).z) / (GetVertex(j).z - GetVertex(i).z) + GetVertex(i).x)) inside = !inside; } return inside; } public override void SerializeReferences (GraphSerializationContext ctx) { if (connections == null) { ctx.writer.Write(-1); } else { ctx.writer.Write (connections.Length); for (int i=0;i<connections.Length;i++) { ctx.writer.Write (ctx.GetNodeIdentifier (connections[i])); ctx.writer.Write (connectionCosts[i]); } } } public override void DeserializeReferences (GraphSerializationContext ctx) { int count = ctx.reader.ReadInt32(); if (count == -1) { connections = null; connectionCosts = null; } else { connections = new GraphNode[count]; connectionCosts = new uint[count]; for (int i=0;i<count;i++) { connections[i] = ctx.GetNodeFromIdentifier (ctx.reader.ReadInt32()); connectionCosts[i] = ctx.reader.ReadUInt32(); } } } } }
/* * 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; using System.Linq; using QuantConnect.Brokerages; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Indicators; using QuantConnect.Orders; using QuantConnect.Securities; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// /// QCU: Opening Breakout Algorithm /// /// In this algorithm we attempt to provide a working algorithm that /// addresses many of the primary algorithm concerns. These concerns /// are: /// /// 1. Signal Generation /// This algorithm aims to generate signals for an opening /// breakout move before 10am. Signals are generated by /// producing the opening five minute bar, and then trading /// in the direction of the breakout from that bar. /// /// 2. Position Sizing /// Positions are sized using recently the average true range. /// The higher the recently movement, the smaller position. /// This helps to reduce the risk of losing a lot on a single /// transaction. /// /// 3. Active Stop Loss /// Stop losses are maintained at a fixed global percentage to /// limit maximum losses per day, while also a trailing stop /// loss is implemented using the parabolic stop and reverse /// in order to gauge exit points /// /// </summary> public class OpeningBreakoutAlgorithm : QCAlgorithm { // the equity symbol we're trading private const string symbol = "SPY"; // plotting and logging control private const bool EnablePlotting = true; private const bool EnableOrderUpdateLogging = false; private const int PricePlotFrequencyInSeconds = 15; // risk control private const decimal MaximumLeverage = 4; private const decimal GlobalStopLossPercent = 0.001m; private const decimal PercentProfitStartPsarTrailingStop = 0.0003m; private const decimal MaximumPorfolioRiskPercentPerPosition = .0025m; // entrance criteria private const int OpeningSpanInMinutes = 3; private const decimal BreakoutThresholdPercent = 0.00005m; private const decimal AtrVolatilityThresholdPercent = 0.00275m; private const decimal StdVolatilityThresholdPercent = 0.005m; // this is the security we're trading public Security Security; // define our indicators used for trading decisions public AverageTrueRange ATR14; public StandardDeviation STD14; public AverageDirectionalIndex ADX14; public ParabolicStopAndReverse PSARMin; // smoothed values public ExponentialMovingAverage SmoothedSTD14; public ExponentialMovingAverage SmoothedATR14; // working variable to control our algorithm // this flag is used to run some code only once after the algorithm is warmed up private bool FinishedWarmup; // this is used to record the last time we closed a position private DateTime LastExitTime; // this is our opening n minute bar private TradeBar OpeningBarRange; // this is the ticket from our market order (entrance) private OrderTicket MarketTicket; // this is the ticket from our stop loss order (exit) private OrderTicket StopLossTicket; // this flag is used to indicate we've switched from a global, non changing // stop loss to a dynamic trailing stop using the PSAR private bool EnablePsarTrailingStop; /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { // initialize algorithm level parameters SetStartDate(2013, 10, 07); SetEndDate(2013, 10, 11); //SetStartDate(2014, 01, 01); //SetEndDate(2014, 06, 01); SetCash(100000); // leverage tradier $1 traders SetBrokerageModel(BrokerageName.TradierBrokerage); // request high resolution equity data AddSecurity(SecurityType.Equity, symbol, Resolution.Second); // save off our security so we can reference it quickly later Security = Securities[symbol]; // Set our max leverage Security.SetLeverage(MaximumLeverage); // define our longer term indicators ADX14 = ADX(symbol, 28, Resolution.Hour); STD14 = STD(symbol, 14, Resolution.Daily); ATR14 = ATR(symbol, 14, resolution: Resolution.Daily); PSARMin = new ParabolicStopAndReverse(symbol, afStart: 0.0001m, afIncrement: 0.0001m); // smooth our ATR over a week, we'll use this to determine if recent volatilty warrants entrance var oneWeekInMarketHours = (int)(5*6.5); SmoothedATR14 = new ExponentialMovingAverage("Smoothed_" + ATR14.Name, oneWeekInMarketHours).Of(ATR14); // smooth our STD over a week as well SmoothedSTD14 = new ExponentialMovingAverage("Smoothed_"+STD14.Name, oneWeekInMarketHours).Of(STD14); // initialize our charts var chart = new Chart(symbol); chart.AddSeries(new Series(ADX14.Name, SeriesType.Line, 0)); chart.AddSeries(new Series("Enter", SeriesType.Scatter, 0)); chart.AddSeries(new Series("Exit", SeriesType.Scatter, 0)); chart.AddSeries(new Series(PSARMin.Name, SeriesType.Scatter, 0)); AddChart(chart); var history = History(symbol, 20, Resolution.Daily); foreach (var bar in history) { ADX14.Update(bar); ATR14.Update(bar); STD14.Update(bar.EndTime, bar.Close); } // schedule an event to run every day at five minutes after our symbol's market open Schedule.Event("MarketOpenSpan") .EveryDay(symbol) .AfterMarketOpen(symbol, minutesAfterOpen: OpeningSpanInMinutes) .Run(MarketOpeningSpanHandler); Schedule.Event("MarketOpen") .EveryDay(symbol) .AfterMarketOpen(symbol, minutesAfterOpen: -1) .Run(() => PSARMin.Reset()); } /// <summary> /// This function is scheduled to be run every day at the specified number of minutes after market open /// </summary> public void MarketOpeningSpanHandler() { // request the last n minutes of data in minute bars, we're going to // define the opening rang var history = History(symbol, OpeningSpanInMinutes, Resolution.Minute); // this is our bar size var openingSpan = TimeSpan.FromMinutes(OpeningSpanInMinutes); // we only care about the high and low here OpeningBarRange = new TradeBar { // time values Time = Time - openingSpan, EndTime = Time, Period = openingSpan, // high and low High = Security.Close, Low = Security.Close }; // aggregate the high/low for the opening range foreach (var tradeBar in history) { OpeningBarRange.Low = Math.Min(OpeningBarRange.Low, tradeBar.Low); OpeningBarRange.High = Math.Max(OpeningBarRange.High, tradeBar.High); } // widen the bar when looking for breakouts OpeningBarRange.Low *= 1 - BreakoutThresholdPercent; OpeningBarRange.High *= 1 + BreakoutThresholdPercent; Log("---------" + Time.Date + "---------"); Log("OpeningBarRange: Low: " + OpeningBarRange.Low.SmartRounding() + " High: " + OpeningBarRange.High.SmartRounding()); } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { // we don't need to run any of this during our warmup phase if (IsWarmingUp) return; // when we're done warming up, register our indicators to start plotting if (!IsWarmingUp && !FinishedWarmup) { // this is a run once flag for when we're finished warmup FinishedWarmup = true; // plot our hourly indicators automatically, wait for them to ready PlotIndicator("ADX", ADX14); PlotIndicator("ADX", ADX14.NegativeDirectionalIndex, ADX14.PositiveDirectionalIndex); PlotIndicator("ATR", true, ATR14); PlotIndicator("STD", true, STD14); PlotIndicator("ATR", true, SmoothedATR14); } // update our PSAR PSARMin.Update((TradeBar) Security.GetLastData()); // plot price until an hour after we close so we can see our execution skillz if (ShouldPlot) { // we can plot price more often if we want Plot(symbol, "Price", Security.Close); // only plot psar on the minute if (PSARMin.IsReady) { Plot(symbol, PSARMin); } } // first wait for our opening range bar to be set to today if (OpeningBarRange == null || OpeningBarRange.EndTime.Date != Time.Date || OpeningBarRange.EndTime == Time) return; // we only trade max once per day, so if we've already exited the stop loss, bail if (StopLossTicket != null && StopLossTicket.Status == OrderStatus.Filled) { // null these out to signal that we're done trading for the day OpeningBarRange = null; StopLossTicket = null; return; } // now that we have our opening bar, test to see if we're already in a positio if (!Security.Invested) { ScanForEntrance(); } else { // if we haven't exited yet then manage our stop loss, this controls our exit point if (Security.Invested) { ManageStopLoss(); } else if (StopLossTicket != null && StopLossTicket.Status.IsOpen()) { StopLossTicket.Cancel(); } } } /// <summary> /// Scans for a breakout from the opening range bar /// </summary> private void ScanForEntrance() { // scan for entrances, we only want to do this before 10am if (Time.TimeOfDay.Hours >= 10) return; // expect capture 10% of the daily range var expectedCaptureRange = 0.1m*ATR14; var allowedDollarLoss = MaximumPorfolioRiskPercentPerPosition * Portfolio.TotalPortfolioValue; var shares = (int) (allowedDollarLoss/expectedCaptureRange); // determine a position size based on an acceptable loss in proporton to our total portfolio value //var shares = (int) (MaximumLeverage*MaximumPorfolioRiskPercentPerPosition*Portfolio.TotalPortfolioValue/(0.4m*ATR14)); // max out at a little below our stated max, prevents margin calls and such var maxShare = CalculateOrderQuantity(symbol, MaximumLeverage); shares = Math.Min(shares, maxShare); // min out at 1x leverage //var minShare = CalculateOrderQuantity(symbol, MaximumLeverage/2m); //shares = Math.Max(shares, minShare); // we're looking for a breakout of the opening range bar in the direction of the medium term trend if (ShouldEnterLong) { // breakout to the upside, go long (fills synchronously) MarketTicket = MarketOrder(symbol, shares); Log("Enter long @ " + MarketTicket.AverageFillPrice.SmartRounding() + " Shares: " + shares); Plot(symbol, "Enter", MarketTicket.AverageFillPrice); // we'll start with a global, non-trailing stop loss EnablePsarTrailingStop = false; // submit stop loss order for max loss on the trade var stopPrice = Security.Low*(1 - GlobalStopLossPercent); StopLossTicket = StopMarketOrder(symbol, -shares, stopPrice); if (EnableOrderUpdateLogging) { Log("Submitted stop loss @ " + stopPrice.SmartRounding()); } } else if (ShouldEnterShort) { // breakout to the downside, go short MarketTicket = MarketOrder(symbol, - -shares); Log("Enter short @ " + MarketTicket.AverageFillPrice.SmartRounding()); Plot(symbol, "Enter", MarketTicket.AverageFillPrice); // we'll start with a global, non-trailing stop loss EnablePsarTrailingStop = false; // submit stop loss order for max loss on the trade var stopPrice = Security.High*(1 + GlobalStopLossPercent); StopLossTicket = StopMarketOrder(symbol, -shares, stopPrice); if (EnableOrderUpdateLogging) { Log("Submitted stop loss @ " + stopPrice.SmartRounding() + " Shares: " + shares); } } } /// <summary> /// Manages our stop loss ticket /// </summary> private void ManageStopLoss() { // if we've already exited then no need to do more if (StopLossTicket == null || StopLossTicket.Status == OrderStatus.Filled) return; // only do this once per minute //if (Time.RoundDown(TimeSpan.FromMinutes(1)) != Time) return; // get the current stop price var stopPrice = StopLossTicket.Get(OrderField.StopPrice); // check for enabling the psar trailing stop if (ShouldEnablePsarTrailingStop(stopPrice)) { EnablePsarTrailingStop = true; Log("Enabled PSAR trailing stop @ ProfitPercent: " + Security.Holdings.UnrealizedProfitPercent.SmartRounding()); } // we've trigger the psar trailing stop, so start updating our stop loss tick if (EnablePsarTrailingStop && PSARMin.IsReady) { StopLossTicket.Update(new UpdateOrderFields {StopPrice = PSARMin}); Log("Submitted stop loss @ " + PSARMin.Current.Value.SmartRounding()); } } /// <summary> /// This event handler is fired for each and every order event the algorithm /// receives. We'll perform some logging and house keeping here /// </summary> public override void OnOrderEvent(OrderEvent orderEvent) { // print debug messages for all order events if (LiveMode || orderEvent.Status.IsFill() || EnableOrderUpdateLogging) { LiveDebug("Filled: " + orderEvent.FillQuantity + " Price: " + orderEvent.FillPrice); } // if this is a fill and we now don't own any stock, that means we've closed for the day if (!Security.Invested && orderEvent.Status == OrderStatus.Filled) { // reset values for tomorrow LastExitTime = Time; var ticket = Transactions.GetOrderTickets(x => x.OrderId == orderEvent.OrderId).Single(); Plot(symbol, "Exit", ticket.AverageFillPrice); } } /// <summary> /// If we're still invested by the end of the day, liquidate /// </summary> public override void OnEndOfDay() { if (Security.Invested) { Liquidate(); } } /// <summary> /// Determines whether or not we should plot. This is used /// to provide enough plot points but not too many, we don't /// need to plot every second in backtests to get an idea of /// how good or bad our algorithm is performing /// </summary> public bool ShouldPlot { get { // always in live if (LiveMode) return true; // set in top to override plotting during long backtests if (!EnablePlotting) return false; // every 30 seconds in backtest if (Time.RoundDown(TimeSpan.FromSeconds(PricePlotFrequencyInSeconds)) != Time) return false; // always if we're invested if (Security.Invested) return true; // always if it's before noon if (Time.TimeOfDay.Hours < 10.25) return true; // for an hour after our exit if (Time - LastExitTime < TimeSpan.FromMinutes(30)) return true; return false; } } /// <summary> /// In live mode it's nice to push messages to the debug window /// as well as the log, this allows easy real time inspection of /// how the algorithm is performing /// </summary> public void LiveDebug(object msg) { if (msg == null) return; if (LiveMode) { Debug(msg.ToString()); Log(msg.ToString()); } else { Log(msg.ToString()); } } /// <summary> /// Determines whether or not we should end a long position /// </summary> private bool ShouldEnterLong { // check to go in the same direction of longer term trend and opening break out get { return IsUptrend && HasEnoughRecentVolatility && Security.Close > OpeningBarRange.High; } } /// <summary> /// Determines whether or not we're currently in a medium term up trend /// </summary> private bool IsUptrend { get { return ADX14 > 20 && ADX14.PositiveDirectionalIndex > ADX14.NegativeDirectionalIndex; } } /// <summary> /// Determines whether or not we should enter a short position /// </summary> private bool ShouldEnterShort { // check to go in the same direction of longer term trend and opening break out get { return IsDowntrend && HasEnoughRecentVolatility && Security.Close < OpeningBarRange.Low; } } /// <summary> /// Determines whether or not we're currently in a medium term down trend /// </summary> private bool IsDowntrend { get { return ADX14 > 20 && ADX14.NegativeDirectionalIndex > ADX14.PositiveDirectionalIndex; } } /// <summary> /// Determines whether or not there's been enough recent volatility for /// this strategy to work /// </summary> private bool HasEnoughRecentVolatility { get { return SmoothedATR14 > Security.Close*AtrVolatilityThresholdPercent || SmoothedSTD14 > Security.Close*StdVolatilityThresholdPercent; } } /// <summary> /// Determines whether or not we should enable the psar trailing stop /// </summary> /// <param name="stopPrice">current stop price of our stop loss tick</param> private bool ShouldEnablePsarTrailingStop(decimal stopPrice) { // no need to enable if it's already enabled return !EnablePsarTrailingStop // once we're up a certain percentage, we'll use PSAR to control our stop && Security.Holdings.UnrealizedProfitPercent > PercentProfitStartPsarTrailingStop // make sure the PSAR is on the right side && PsarIsOnRightSideOfPrice // make sure the PSAR is more profitable than our global loss && IsPsarMoreProfitableThanStop(stopPrice); } /// <summary> /// Determines whether or not the PSAR is on the right side of price depending on our long/short /// </summary> private bool PsarIsOnRightSideOfPrice { get { return (Security.Holdings.IsLong && PSARMin < Security.Close) || (Security.Holdings.IsShort && PSARMin > Security.Close); } } /// <summary> /// Determines whether or not the PSAR stop price is better than the specified stop price /// </summary> private bool IsPsarMoreProfitableThanStop(decimal stopPrice) { return (Security.Holdings.IsLong && PSARMin > stopPrice) || (Security.Holdings.IsShort && PSARMin < stopPrice); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace GradesIOProject.Areas.HelpPage { /// <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(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); } } } }
// 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 System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Diagnostics.Tests { public class ProcessWaitingTests : ProcessTestBase { [Fact] [ActiveIssue(31908, TargetFrameworkMonikers.Uap)] public void MultipleProcesses_StartAllKillAllWaitAll() { const int Iters = 10; Process[] processes = Enumerable.Range(0, Iters).Select(_ => CreateProcessLong()).ToArray(); foreach (Process p in processes) p.Start(); foreach (Process p in processes) p.Kill(); foreach (Process p in processes) Assert.True(p.WaitForExit(WaitInMS)); } [Fact] [ActiveIssue(31908, TargetFrameworkMonikers.Uap)] public void MultipleProcesses_SerialStartKillWait() { const int Iters = 10; for (int i = 0; i < Iters; i++) { Process p = CreateProcessLong(); p.Start(); p.Kill(); p.WaitForExit(WaitInMS); } } [Fact] [ActiveIssue(31908, TargetFrameworkMonikers.Uap)] public void MultipleProcesses_ParallelStartKillWait() { const int Tasks = 4, ItersPerTask = 10; Action work = () => { for (int i = 0; i < ItersPerTask; i++) { Process p = CreateProcessLong(); p.Start(); p.Kill(); p.WaitForExit(WaitInMS); } }; Task.WaitAll(Enumerable.Range(0, Tasks).Select(_ => Task.Run(work)).ToArray()); } [Theory] [InlineData(0)] // poll [InlineData(10)] // real timeout public void CurrentProcess_WaitNeverCompletes(int milliseconds) { Assert.False(Process.GetCurrentProcess().WaitForExit(milliseconds)); } [Fact] [ActiveIssue(31908, TargetFrameworkMonikers.Uap)] public void SingleProcess_TryWaitMultipleTimesBeforeCompleting() { Process p = CreateProcessLong(); p.Start(); // Verify we can try to wait for the process to exit multiple times Assert.False(p.WaitForExit(0)); Assert.False(p.WaitForExit(0)); // Then wait until it exits and concurrently kill it. // There's a race condition here, in that we really want to test // killing it while we're waiting, but we could end up killing it // before hand, in which case we're simply not testing exactly // what we wanted to test, but everything should still work. Task.Delay(10).ContinueWith(_ => p.Kill()); Assert.True(p.WaitForExit(WaitInMS)); Assert.True(p.WaitForExit(0)); } [Theory] [InlineData(false)] [InlineData(true)] [ActiveIssue(31908, TargetFrameworkMonikers.Uap)] public async Task SingleProcess_WaitAfterExited(bool addHandlerBeforeStart) { Process p = CreateProcessLong(); p.EnableRaisingEvents = true; var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); if (addHandlerBeforeStart) { p.Exited += delegate { tcs.SetResult(true); }; } p.Start(); if (!addHandlerBeforeStart) { p.Exited += delegate { tcs.SetResult(true); }; } p.Kill(); Assert.True(await tcs.Task); Assert.True(p.WaitForExit(0)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(127)] public async Task SingleProcess_EnableRaisingEvents_CorrectExitCode(int exitCode) { using (Process p = CreateProcessPortable(RemotelyInvokable.ExitWithCode, exitCode.ToString())) { var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); p.EnableRaisingEvents = true; p.Exited += delegate { tcs.SetResult(true); }; p.Start(); Assert.True(await tcs.Task); Assert.Equal(exitCode, p.ExitCode); } } [Fact] [ActiveIssue(31908, TargetFrameworkMonikers.Uap)] public void SingleProcess_CopiesShareExitInformation() { Process p = CreateProcessLong(); p.Start(); Process[] copies = Enumerable.Range(0, 3).Select(_ => Process.GetProcessById(p.Id)).ToArray(); Assert.False(p.WaitForExit(0)); p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); foreach (Process copy in copies) { Assert.True(copy.WaitForExit(0)); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Getting handle of child process running on UAP is not possible")] public void WaitForPeerProcess() { Process child1 = CreateProcessLong(); child1.Start(); Process child2 = CreateProcess(peerId => { Process peer = Process.GetProcessById(int.Parse(peerId)); Console.WriteLine("Signal"); Assert.True(peer.WaitForExit(WaitInMS)); return SuccessExitCode; }, child1.Id.ToString()); child2.StartInfo.RedirectStandardOutput = true; child2.Start(); char[] output = new char[6]; child2.StandardOutput.Read(output, 0, output.Length); Assert.Equal("Signal", new string(output)); // wait for the signal before killing the peer child1.Kill(); Assert.True(child1.WaitForExit(WaitInMS)); Assert.True(child2.WaitForExit(WaitInMS)); Assert.Equal(SuccessExitCode, child2.ExitCode); } [Fact] public void WaitForSignal() { const string expectedSignal = "Signal"; const string successResponse = "Success"; const int timeout = 30 * 1000; // 30 seconds, to allow for very slow machines Process p = CreateProcessPortable(RemotelyInvokable.WriteLineReadLine); p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; var mre = new ManualResetEventSlim(false); int linesReceived = 0; p.OutputDataReceived += (s, e) => { if (e.Data != null) { linesReceived++; if (e.Data == expectedSignal) { mre.Set(); } } }; p.Start(); p.BeginOutputReadLine(); Assert.True(mre.Wait(timeout)); Assert.Equal(1, linesReceived); // Wait a little bit to make sure process didn't exit on itself Thread.Sleep(100); Assert.False(p.HasExited, "Process has prematurely exited"); using (StreamWriter writer = p.StandardInput) { writer.WriteLine(successResponse); } Assert.True(p.WaitForExit(timeout), "Process has not exited"); Assert.Equal(RemotelyInvokable.SuccessExitCode, p.ExitCode); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Not applicable on uap - RemoteInvoke does not give back process handle")] [ActiveIssue(15844, TestPlatforms.AnyUnix)] public void WaitChain() { Process root = CreateProcess(() => { Process child1 = CreateProcess(() => { Process child2 = CreateProcess(() => { Process child3 = CreateProcess(() => SuccessExitCode); child3.Start(); Assert.True(child3.WaitForExit(WaitInMS)); return child3.ExitCode; }); child2.Start(); Assert.True(child2.WaitForExit(WaitInMS)); return child2.ExitCode; }); child1.Start(); Assert.True(child1.WaitForExit(WaitInMS)); return child1.ExitCode; }); root.Start(); Assert.True(root.WaitForExit(WaitInMS)); Assert.Equal(SuccessExitCode, root.ExitCode); } [Fact] public void WaitForSelfTerminatingChild() { Process child = CreateProcessPortable(RemotelyInvokable.SelfTerminate); child.Start(); Assert.True(child.WaitForExit(WaitInMS)); Assert.NotEqual(SuccessExitCode, child.ExitCode); } [Fact] public void WaitForInputIdle_NotDirected_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.WaitForInputIdle()); } [Fact] public void WaitForExit_NotDirected_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.WaitForExit()); } } }
/* * 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.Reflection; using System.Threading; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Osp; using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver; using OpenSim.Region.CoreModules.World.Serialiser; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; using OpenSim.Tests.Common.Setup; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests { [TestFixture] public class InventoryArchiverTests { protected ManualResetEvent mre = new ManualResetEvent(false); private void InventoryReceived(UUID userId) { lock (this) { Monitor.PulseAll(this); } } private void SaveCompleted( Guid id, bool succeeded, CachedUserInfo userInfo, string invPath, Stream saveStream, Exception reportedException) { mre.Set(); } /// <summary> /// Test saving a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet). /// </summary> // Commenting for now! The mock inventory service needs more beef, at least for // GetFolderForType [Test] public void TestSaveIarV0_1() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); InventoryArchiverModule archiverModule = new InventoryArchiverModule(true); Scene scene = SceneSetupHelpers.SetupScene("Inventory"); SceneSetupHelpers.SetupSceneModules(scene, archiverModule); CommunicationsManager cm = scene.CommsManager; // Create user string userFirstName = "Jock"; string userLastName = "Stirrup"; UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); lock (this) { UserProfileTestUtils.CreateUserWithInventory( cm, userFirstName, userLastName, userId, InventoryReceived); Monitor.Wait(this, 60000); } // Create asset SceneObjectGroup object1; SceneObjectPart part1; { string partName = "My Little Dog Object"; UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); Vector3 groupPosition = new Vector3(10, 20, 30); Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); Vector3 offsetPosition = new Vector3(5, 10, 15); part1 = new SceneObjectPart( ownerId, shape, groupPosition, rotationOffset, offsetPosition); part1.Name = partName; object1 = new SceneObjectGroup(part1); scene.AddNewSceneObject(object1, false); } UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060"); AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1); scene.AssetService.Store(asset1); // Create item UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080"); InventoryItemBase item1 = new InventoryItemBase(); item1.Name = "My Little Dog"; item1.AssetID = asset1.FullID; item1.ID = item1Id; InventoryFolderBase objsFolder = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects"); item1.Folder = objsFolder.ID; scene.AddInventoryItem(userId, item1); MemoryStream archiveWriteStream = new MemoryStream(); archiverModule.OnInventoryArchiveSaved += SaveCompleted; mre.Reset(); archiverModule.ArchiveInventory( Guid.NewGuid(), userFirstName, userLastName, "Objects", "troll", archiveWriteStream); mre.WaitOne(60000, false); byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); TarArchiveReader tar = new TarArchiveReader(archiveReadStream); //bool gotControlFile = false; bool gotObject1File = false; //bool gotObject2File = false; string expectedObject1FileName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1); string expectedObject1FilePath = string.Format( "{0}{1}{2}", ArchiveConstants.INVENTORY_PATH, InventoryArchiveWriteRequest.CreateArchiveFolderName(objsFolder), expectedObject1FileName); string filePath; TarArchiveReader.TarEntryType tarEntryType; Console.WriteLine("Reading archive"); while (tar.ReadEntry(out filePath, out tarEntryType) != null) { Console.WriteLine("Got {0}", filePath); // if (ArchiveConstants.CONTROL_FILE_PATH == filePath) // { // gotControlFile = true; // } if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH) && filePath.EndsWith(".xml")) { // string fileName = filePath.Remove(0, "Objects/".Length); // // if (fileName.StartsWith(part1.Name)) // { Assert.That(expectedObject1FilePath, Is.EqualTo(filePath)); gotObject1File = true; // } // else if (fileName.StartsWith(part2.Name)) // { // Assert.That(fileName, Is.EqualTo(expectedObject2FileName)); // gotObject2File = true; // } } } // Assert.That(gotControlFile, Is.True, "No control file in archive"); Assert.That(gotObject1File, Is.True, "No item1 file in archive"); // Assert.That(gotObject2File, Is.True, "No object2 file in archive"); // TODO: Test presence of more files and contents of files. } /// <summary> /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where /// an account exists with the creator name. /// </summary> /// /// This test also does some deeper probing of loading into nested inventory structures [Test] public void TestLoadIarV0_1ExistingUsers() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); string userFirstName = "Mr"; string userLastName = "Tiddles"; UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000555"); string userItemCreatorFirstName = "Lord"; string userItemCreatorLastName = "Lucan"; UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000000666"); string item1Name = "b.lsl"; string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1Name, UUID.Random()); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); InventoryItemBase item1 = new InventoryItemBase(); item1.Name = item1Name; item1.AssetID = UUID.Random(); item1.GroupID = UUID.Random(); item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName); //item1.CreatorId = userUuid.ToString(); //item1.CreatorId = "00000000-0000-0000-0000-000000000444"; item1.Owner = UUID.Zero; string item1FileName = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1)); tar.Close(); MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); SerialiserModule serialiserModule = new SerialiserModule(); InventoryArchiverModule archiverModule = new InventoryArchiverModule(true); // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene Scene scene = SceneSetupHelpers.SetupScene("inventory"); IUserAdminService userAdminService = scene.CommsManager.UserAdminService; SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); userAdminService.AddUser( userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid); userAdminService.AddUser( userItemCreatorFirstName, userItemCreatorLastName, "hampshire", String.Empty, 1000, 1000, userItemCreatorUuid); archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream); CachedUserInfo userInfo = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName); InventoryItemBase foundItem1 = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, item1Name); Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1"); // We have to disable this check since loaded items that did find users via OSPA resolution are now only storing the // UUID, not the OSPA itself. // Assert.That( // foundItem1.CreatorId, Is.EqualTo(item1.CreatorId), // "Loaded item non-uuid creator doesn't match original"); Assert.That( foundItem1.CreatorId, Is.EqualTo(userItemCreatorUuid.ToString()), "Loaded item non-uuid creator doesn't match original"); Assert.That( foundItem1.CreatorIdAsUuid, Is.EqualTo(userItemCreatorUuid), "Loaded item uuid creator doesn't match original"); Assert.That(foundItem1.Owner, Is.EqualTo(userUuid), "Loaded item owner doesn't match inventory reciever"); // Now try loading to a root child folder UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, userInfo.UserProfile.ID, "xA"); archiveReadStream = new MemoryStream(archiveReadStream.ToArray()); archiverModule.DearchiveInventory(userFirstName, userLastName, "xA", "meowfood", archiveReadStream); InventoryItemBase foundItem2 = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xA/" + item1Name); Assert.That(foundItem2, Is.Not.Null, "Didn't find loaded item 2"); // Now try loading to a more deeply nested folder UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, userInfo.UserProfile.ID, "xB/xC"); archiveReadStream = new MemoryStream(archiveReadStream.ToArray()); archiverModule.DearchiveInventory(userFirstName, userLastName, "xB/xC", "meowfood", archiveReadStream); InventoryItemBase foundItem3 = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xB/xC/" + item1Name); Assert.That(foundItem3, Is.Not.Null, "Didn't find loaded item 3"); } [Test] public void TestIarV0_1WithEscapedChars() { TestHelper.InMethod(); // log4net.Config.XmlConfigurator.Configure(); string itemName = "You & you are a mean/man/"; string humanEscapedItemName = @"You & you are a mean\/man\/"; string userPassword = "meowfood"; InventoryArchiverModule archiverModule = new InventoryArchiverModule(true); Scene scene = SceneSetupHelpers.SetupScene("Inventory"); SceneSetupHelpers.SetupSceneModules(scene, archiverModule); CommunicationsManager cm = scene.CommsManager; // Create user string userFirstName = "Jock"; string userLastName = "Stirrup"; UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); lock (this) { UserProfileTestUtils.CreateUserWithInventory( cm, userFirstName, userLastName, userPassword, userId, InventoryReceived); Monitor.Wait(this, 60000); } // Create asset SceneObjectGroup object1; SceneObjectPart part1; { string partName = "part name"; UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); Vector3 groupPosition = new Vector3(10, 20, 30); Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); Vector3 offsetPosition = new Vector3(5, 10, 15); part1 = new SceneObjectPart( ownerId, shape, groupPosition, rotationOffset, offsetPosition); part1.Name = partName; object1 = new SceneObjectGroup(part1); scene.AddNewSceneObject(object1, false); } UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060"); AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1); scene.AssetService.Store(asset1); // Create item UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080"); InventoryItemBase item1 = new InventoryItemBase(); item1.Name = itemName; item1.AssetID = asset1.FullID; item1.ID = item1Id; InventoryFolderBase objsFolder = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects"); item1.Folder = objsFolder.ID; scene.AddInventoryItem(userId, item1); MemoryStream archiveWriteStream = new MemoryStream(); archiverModule.OnInventoryArchiveSaved += SaveCompleted; mre.Reset(); archiverModule.ArchiveInventory( Guid.NewGuid(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream); mre.WaitOne(60000, false); // LOAD ITEM MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); archiverModule.DearchiveInventory(userFirstName, userLastName, "Scripts", userPassword, archiveReadStream); InventoryItemBase foundItem1 = InventoryArchiveUtils.FindItemByPath( scene.InventoryService, userId, "Scripts/Objects/" + humanEscapedItemName); Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1"); // Assert.That( // foundItem1.CreatorId, Is.EqualTo(userUuid), // "Loaded item non-uuid creator doesn't match that of the loading user"); Assert.That( foundItem1.Name, Is.EqualTo(itemName), "Loaded item name doesn't match saved name"); } /// <summary> /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where /// embedded creators do not exist in the system /// </summary> /// /// This may possibly one day get overtaken by the as yet incomplete temporary profiles feature /// (as tested in the a later commented out test) [Test] public void TestLoadIarV0_1AbsentUsers() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); string userFirstName = "Charlie"; string userLastName = "Chan"; UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000999"); string userItemCreatorFirstName = "Bat"; string userItemCreatorLastName = "Man"; //UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000008888"); string itemName = "b.lsl"; string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random()); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); InventoryItemBase item1 = new InventoryItemBase(); item1.Name = itemName; item1.AssetID = UUID.Random(); item1.GroupID = UUID.Random(); item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName); //item1.CreatorId = userUuid.ToString(); //item1.CreatorId = "00000000-0000-0000-0000-000000000444"; item1.Owner = UUID.Zero; string item1FileName = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1)); tar.Close(); MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); SerialiserModule serialiserModule = new SerialiserModule(); InventoryArchiverModule archiverModule = new InventoryArchiverModule(true); // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene Scene scene = SceneSetupHelpers.SetupScene("inventory"); IUserAdminService userAdminService = scene.CommsManager.UserAdminService; SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); userAdminService.AddUser( userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid); archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream); CachedUserInfo userInfo = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName); InventoryItemBase foundItem1 = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, itemName); Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1"); // Assert.That( // foundItem1.CreatorId, Is.EqualTo(userUuid), // "Loaded item non-uuid creator doesn't match that of the loading user"); Assert.That( foundItem1.CreatorIdAsUuid, Is.EqualTo(userUuid), "Loaded item uuid creator doesn't match that of the loading user"); } /// <summary> /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where /// no account exists with the creator name /// </summary> /// Disabled since temporary profiles have not yet been implemented. //[Test] public void TestLoadIarV0_1TempProfiles() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); string userFirstName = "Dennis"; string userLastName = "Menace"; UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000aaa"); string user2FirstName = "Walter"; string user2LastName = "Mitty"; string itemName = "b.lsl"; string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random()); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); InventoryItemBase item1 = new InventoryItemBase(); item1.Name = itemName; item1.AssetID = UUID.Random(); item1.GroupID = UUID.Random(); item1.CreatorId = OspResolver.MakeOspa(user2FirstName, user2LastName); item1.Owner = UUID.Zero; string item1FileName = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1)); tar.Close(); MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); SerialiserModule serialiserModule = new SerialiserModule(); InventoryArchiverModule archiverModule = new InventoryArchiverModule(true); // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene Scene scene = SceneSetupHelpers.SetupScene(); IUserAdminService userAdminService = scene.CommsManager.UserAdminService; SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); userAdminService.AddUser( userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid); archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "troll", archiveReadStream); // Check that a suitable temporary user profile has been created. UserProfileData user2Profile = scene.CommsManager.UserService.GetUserProfile( OspResolver.HashName(user2FirstName + " " + user2LastName)); Assert.That(user2Profile, Is.Not.Null); Assert.That(user2Profile.FirstName == user2FirstName); Assert.That(user2Profile.SurName == user2LastName); CachedUserInfo userInfo = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName); userInfo.OnInventoryReceived += InventoryReceived; lock (this) { userInfo.FetchInventory(); Monitor.Wait(this, 60000); } InventoryItemBase foundItem = userInfo.RootFolder.FindItemByPath(itemName); Assert.That(foundItem.CreatorId, Is.EqualTo(item1.CreatorId)); Assert.That( foundItem.CreatorIdAsUuid, Is.EqualTo(OspResolver.HashName(user2FirstName + " " + user2LastName))); Assert.That(foundItem.Owner, Is.EqualTo(userUuid)); Console.WriteLine("### Successfully completed {0} ###", MethodBase.GetCurrentMethod()); } /// <summary> /// Test replication of an archive path to the user's inventory. /// </summary> [Test] public void TestReplicateArchivePathToUserInventory() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); Scene scene = SceneSetupHelpers.SetupScene("inventory"); CommunicationsManager commsManager = scene.CommsManager; CachedUserInfo userInfo; lock (this) { userInfo = UserProfileTestUtils.CreateUserWithInventory(commsManager, InventoryReceived); Monitor.Wait(this, 60000); } //Console.WriteLine("userInfo.RootFolder 1: {0}", userInfo.RootFolder); Dictionary <string, InventoryFolderBase> foldersCreated = new Dictionary<string, InventoryFolderBase>(); List<InventoryNodeBase> nodesLoaded = new List<InventoryNodeBase>(); string folder1Name = "a"; string folder2Name = "b"; string itemName = "c.lsl"; string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1Name, UUID.Random()); string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random()); string itemArchiveName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random()); string itemArchivePath = string.Format( "{0}{1}{2}{3}", ArchiveConstants.INVENTORY_PATH, folder1ArchiveName, folder2ArchiveName, itemArchiveName); //Console.WriteLine("userInfo.RootFolder 2: {0}", userInfo.RootFolder); new InventoryArchiveReadRequest(scene, userInfo, null, (Stream)null) .ReplicateArchivePathToUserInventory( itemArchivePath, false, scene.InventoryService.GetRootFolder(userInfo.UserProfile.ID), foldersCreated, nodesLoaded); //Console.WriteLine("userInfo.RootFolder 3: {0}", userInfo.RootFolder); //InventoryFolderImpl folder1 = userInfo.RootFolder.FindFolderByPath("a"); InventoryFolderBase folder1 = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userInfo.UserProfile.ID, "a"); Assert.That(folder1, Is.Not.Null, "Could not find folder a"); InventoryFolderBase folder2 = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, "b"); Assert.That(folder2, Is.Not.Null, "Could not find folder b"); } } }
// 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; using System.Diagnostics; using System.Data; using System.IO; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Text; using System.Runtime.CompilerServices; using System.Data.SqlTypes; namespace Microsoft.SqlServer.Server { // The class that holds the offset, field, and normalizer for // a particular field. internal sealed class FieldInfoEx : IComparable { internal readonly int Offset; internal readonly FieldInfo FieldInfo; internal readonly Normalizer Normalizer; internal FieldInfoEx(FieldInfo fi, int offset, Normalizer normalizer) { FieldInfo = fi; Offset = offset; Debug.Assert(normalizer != null, "normalizer argument should not be null!"); Normalizer = normalizer; } // Sort fields by field offsets. public int CompareTo(object other) { FieldInfoEx otherF = other as FieldInfoEx; if (otherF == null) return -1; return Offset.CompareTo(otherF.Offset); } } // The most complex normalizer, a udt normalizer internal sealed class BinaryOrderedUdtNormalizer : Normalizer { internal readonly FieldInfoEx[] FieldsToNormalize; private int _size; private byte[] _padBuffer; internal readonly object NullInstance; //a boolean that tells us if a udt is a "top-level" udt, //i.e. one that does not require a null byte header. private bool _isTopLevelUdt; private FieldInfo[] GetFields(Type t) { return t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } internal BinaryOrderedUdtNormalizer(Type t, bool isTopLevelUdt) { _skipNormalize = false; if (_skipNormalize) { // if skipping normalization, dont write the null // byte header for IsNull _isTopLevelUdt = true; } _isTopLevelUdt = true; // get all the fields FieldInfo[] fields = GetFields(t); FieldsToNormalize = new FieldInfoEx[fields.Length]; int i = 0; foreach (FieldInfo fi in fields) { int offset = Marshal.OffsetOf(fi.DeclaringType, fi.Name).ToInt32(); FieldsToNormalize[i++] = new FieldInfoEx(fi, offset, GetNormalizer(fi.FieldType)); } //sort by offset Array.Sort(FieldsToNormalize); //if this is not a top-level udt, do setup for null values. //null values need to compare less than all other values, //so prefix a null byte indicator. if (!_isTopLevelUdt) { //get the null value for this type, special case for sql types, which //have a null field if (typeof(INullable).IsAssignableFrom(t)) { PropertyInfo pi = t.GetProperty("Null", BindingFlags.Public | BindingFlags.Static); if (pi == null || pi.PropertyType != t) { FieldInfo fi = t.GetField("Null", BindingFlags.Public | BindingFlags.Static); if (fi == null || fi.FieldType != t) throw new Exception("could not find Null field/property in nullable type " + t); else NullInstance = fi.GetValue(null); } else { NullInstance = pi.GetValue(null, null); } //create the padding buffer _padBuffer = new byte[Size - 1]; } } } internal bool IsNullable => (NullInstance != null); // Normalize the top-level udt internal void NormalizeTopObject(object udt, Stream s) { Normalize(null, udt, s); } // Denormalize a top-level udt and return it internal object DeNormalizeTopObject(Type t, Stream s) => DeNormalizeInternal(t, s); // Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set. [MethodImpl(MethodImplOptions.NoInlining)] private object DeNormalizeInternal(Type t, Stream s) { object result = null; //if nullable and not the top object, read the null marker if (!_isTopLevelUdt && typeof(INullable).IsAssignableFrom(t)) { byte nullByte = (byte)s.ReadByte(); if (nullByte == 0) { result = NullInstance; s.Read(_padBuffer, 0, _padBuffer.Length); return result; } } if (result == null) result = Activator.CreateInstance(t); foreach (FieldInfoEx myField in FieldsToNormalize) { myField.Normalizer.DeNormalize(myField.FieldInfo, result, s); } return result; } internal override void Normalize(FieldInfo fi, object obj, Stream s) { object inner; if (fi == null) { inner = obj; } else { inner = GetValue(fi, obj); } // If nullable and not the top object, write a null indicator if (inner is INullable oNullable && !_isTopLevelUdt) { if (oNullable.IsNull) { s.WriteByte(0); s.Write(_padBuffer, 0, _padBuffer.Length); return; } else { s.WriteByte(1); } } foreach (FieldInfoEx myField in FieldsToNormalize) { myField.Normalizer.Normalize(myField.FieldInfo, inner, s); } } internal override void DeNormalize(FieldInfo fi, object recvr, Stream s) { SetValue(fi, recvr, DeNormalizeInternal(fi.FieldType, s)); } internal override int Size { get { if (_size != 0) return _size; if (IsNullable && !_isTopLevelUdt) _size = 1; foreach (FieldInfoEx myField in FieldsToNormalize) { _size += myField.Normalizer.Size; } return _size; } } } internal abstract class Normalizer { protected bool _skipNormalize; internal static Normalizer GetNormalizer(Type t) { Normalizer n = null; if (t.IsPrimitive) { if (t == typeof(byte)) n = new ByteNormalizer(); else if (t == typeof(sbyte)) n = new SByteNormalizer(); else if (t == typeof(bool)) n = new BooleanNormalizer(); else if (t == typeof(short)) n = new ShortNormalizer(); else if (t == typeof(ushort)) n = new UShortNormalizer(); else if (t == typeof(int)) n = new IntNormalizer(); else if (t == typeof(uint)) n = new UIntNormalizer(); else if (t == typeof(float)) n = new FloatNormalizer(); else if (t == typeof(double)) n = new DoubleNormalizer(); else if (t == typeof(long)) n = new LongNormalizer(); else if (t == typeof(ulong)) n = new ULongNormalizer(); } else if (t.IsValueType) { n = new BinaryOrderedUdtNormalizer(t, false); } if (n == null) throw new Exception(SR.GetString(SR.SQL_CannotCreateNormalizer, t.FullName)); n._skipNormalize = false; return n; } internal abstract void Normalize(FieldInfo fi, object recvr, Stream s); internal abstract void DeNormalize(FieldInfo fi, object recvr, Stream s); protected void FlipAllBits(byte[] b) { for (int i = 0; i < b.Length; i++) b[i] = (byte)~b[i]; } protected object GetValue(FieldInfo fi, object obj) => fi.GetValue(obj); protected void SetValue(FieldInfo fi, object recvr, object value) { fi.SetValue(recvr, value); } internal abstract int Size { get; } } internal sealed class BooleanNormalizer : Normalizer { internal override void Normalize(FieldInfo fi, object obj, Stream s) { bool b = (bool)GetValue(fi, obj); s.WriteByte((byte)(b ? 1 : 0)); } internal override void DeNormalize(FieldInfo fi, object recvr, Stream s) { byte b = (byte)s.ReadByte(); SetValue(fi, recvr, b == 1); } internal override int Size => 1; } internal sealed class SByteNormalizer : Normalizer { internal override void Normalize(FieldInfo fi, object obj, Stream s) { sbyte sb = (sbyte)GetValue(fi, obj); byte b; unchecked { b = (byte)sb; } if (!_skipNormalize) b ^= 0x80; // flip the sign bit s.WriteByte(b); } internal override void DeNormalize(FieldInfo fi, object recvr, Stream s) { byte b = (byte)s.ReadByte(); if (!_skipNormalize) b ^= 0x80; // flip the sign bit sbyte sb; unchecked { sb = (sbyte)b; } SetValue(fi, recvr, sb); } internal override int Size => 1; } internal sealed class ByteNormalizer : Normalizer { internal override void Normalize(FieldInfo fi, object obj, Stream s) { byte b = (byte)GetValue(fi, obj); s.WriteByte(b); } internal override void DeNormalize(FieldInfo fi, object recvr, Stream s) { byte b = (byte)s.ReadByte(); SetValue(fi, recvr, b); } internal override int Size => 1; } internal sealed class ShortNormalizer : Normalizer { internal override void Normalize(FieldInfo fi, object obj, Stream s) { byte[] b = BitConverter.GetBytes((short)GetValue(fi, obj)); if (!_skipNormalize) { Array.Reverse(b); b[0] ^= 0x80; } s.Write(b, 0, b.Length); } internal override void DeNormalize(FieldInfo fi, object recvr, Stream s) { byte[] b = new byte[2]; s.Read(b, 0, b.Length); if (!_skipNormalize) { b[0] ^= 0x80; Array.Reverse(b); } SetValue(fi, recvr, BitConverter.ToInt16(b, 0)); } internal override int Size { get { return 2; } } } internal sealed class UShortNormalizer : Normalizer { internal override void Normalize(FieldInfo fi, object obj, Stream s) { byte[] b = BitConverter.GetBytes((ushort)GetValue(fi, obj)); if (!_skipNormalize) { Array.Reverse(b); } s.Write(b, 0, b.Length); } internal override void DeNormalize(FieldInfo fi, object recvr, Stream s) { byte[] b = new byte[2]; s.Read(b, 0, b.Length); if (!_skipNormalize) { Array.Reverse(b); } SetValue(fi, recvr, BitConverter.ToUInt16(b, 0)); } internal override int Size => 2; } internal sealed class IntNormalizer : Normalizer { internal override void Normalize(FieldInfo fi, object obj, Stream s) { byte[] b = BitConverter.GetBytes((int)GetValue(fi, obj)); if (!_skipNormalize) { Array.Reverse(b); b[0] ^= 0x80; } s.Write(b, 0, b.Length); } internal override void DeNormalize(FieldInfo fi, object recvr, Stream s) { byte[] b = new byte[4]; s.Read(b, 0, b.Length); if (!_skipNormalize) { b[0] ^= 0x80; Array.Reverse(b); } SetValue(fi, recvr, BitConverter.ToInt32(b, 0)); } internal override int Size => 4; } internal sealed class UIntNormalizer : Normalizer { internal override void Normalize(FieldInfo fi, object obj, Stream s) { byte[] b = BitConverter.GetBytes((uint)GetValue(fi, obj)); if (!_skipNormalize) { Array.Reverse(b); } s.Write(b, 0, b.Length); } internal override void DeNormalize(FieldInfo fi, object recvr, Stream s) { byte[] b = new byte[4]; s.Read(b, 0, b.Length); if (!_skipNormalize) { Array.Reverse(b); } SetValue(fi, recvr, BitConverter.ToUInt32(b, 0)); } internal override int Size => 4; } internal sealed class LongNormalizer : Normalizer { internal override void Normalize(FieldInfo fi, object obj, Stream s) { byte[] b = BitConverter.GetBytes((long)GetValue(fi, obj)); if (!_skipNormalize) { Array.Reverse(b); b[0] ^= 0x80; } s.Write(b, 0, b.Length); } internal override void DeNormalize(FieldInfo fi, object recvr, Stream s) { byte[] b = new byte[8]; s.Read(b, 0, b.Length); if (!_skipNormalize) { b[0] ^= 0x80; Array.Reverse(b); } SetValue(fi, recvr, BitConverter.ToInt64(b, 0)); } internal override int Size => 8; } internal sealed class ULongNormalizer : Normalizer { internal override void Normalize(FieldInfo fi, object obj, Stream s) { byte[] b = BitConverter.GetBytes((ulong)GetValue(fi, obj)); if (!_skipNormalize) { Array.Reverse(b); } s.Write(b, 0, b.Length); } internal override void DeNormalize(FieldInfo fi, object recvr, Stream s) { byte[] b = new byte[8]; s.Read(b, 0, b.Length); if (!_skipNormalize) { Array.Reverse(b); } SetValue(fi, recvr, BitConverter.ToUInt64(b, 0)); } internal override int Size => 8; } internal sealed class FloatNormalizer : Normalizer { internal override void Normalize(FieldInfo fi, object obj, Stream s) { float f = (float)GetValue(fi, obj); byte[] b = BitConverter.GetBytes(f); if (!_skipNormalize) { Array.Reverse(b); if ((b[0] & 0x80) == 0) { // This is a positive number. // Flip the highest bit b[0] ^= 0x80; } else { // This is a negative number. // If all zeroes, means it was a negative zero. // Treat it same as positive zero, so that // the normalized key will compare equal. if (f < 0) FlipAllBits(b); } } s.Write(b, 0, b.Length); } internal override void DeNormalize(FieldInfo fi, object recvr, Stream s) { byte[] b = new byte[4]; s.Read(b, 0, b.Length); if (!_skipNormalize) { if ((b[0] & 0x80) > 0) { // This is a positive number. // Flip the highest bit b[0] ^= 0x80; } else { // This is a negative number. FlipAllBits(b); } Array.Reverse(b); } SetValue(fi, recvr, BitConverter.ToSingle(b, 0)); } internal override int Size => 4; } internal sealed class DoubleNormalizer : Normalizer { internal override void Normalize(FieldInfo fi, object obj, Stream s) { double d = (double)GetValue(fi, obj); byte[] b = BitConverter.GetBytes(d); if (!_skipNormalize) { Array.Reverse(b); if ((b[0] & 0x80) == 0) { // This is a positive number. // Flip the highest bit b[0] ^= 0x80; } else { // This is a negative number. if (d < 0) { // If all zeroes, means it was a negative zero. // Treat it same as positive zero, so that // the normalized key will compare equal. FlipAllBits(b); } } } s.Write(b, 0, b.Length); } internal override void DeNormalize(FieldInfo fi, object recvr, Stream s) { byte[] b = new byte[8]; s.Read(b, 0, b.Length); if (!_skipNormalize) { if ((b[0] & 0x80) > 0) { // This is a positive number. // Flip the highest bit b[0] ^= 0x80; } else { // This is a negative number. FlipAllBits(b); } Array.Reverse(b); } SetValue(fi, recvr, BitConverter.ToDouble(b, 0)); } internal override int Size => 8; } }
using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Newtonsoft.Json.Linq; using NuGet.Test.Helpers; using Sleet; using Xunit; namespace SleetLib.Tests { public class PhysicalFileSystemTests { [Fact] public async Task GivenAFileChangeVerifyCommitSetsHasChangesFalse() { using (var target = new TestFolder()) using (var cache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var a = fileSystem.Get("a.txt"); await a.Write(new JObject(), log, CancellationToken.None); a.HasChanges.Should().BeTrue(); cache.Root.GetFiles().Length.Should().Be(1); await fileSystem.Commit(log, CancellationToken.None); a.HasChanges.Should().BeFalse(); cache.Root.GetFiles().Length.Should().Be(1); } } [Fact] public void GivenAFileVerifyGetPathGivesTheSameFile() { using (var target = new TestFolder()) using (var cache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var a = fileSystem.Get("a.txt"); var test1 = fileSystem.Get("a.txt"); var test2 = fileSystem.Get(new Uri(a.EntityUri.AbsoluteUri)); var test3 = fileSystem.Get("/a.txt"); ReferenceEquals(a, test1).Should().BeTrue(); ReferenceEquals(a, test2).Should().BeTrue(); ReferenceEquals(a, test3).Should().BeTrue(); } } [Fact] public async Task GivenAFileVerifyExistsDoesNotDownload() { using (var target = new TestFolder()) using (var cache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); File.WriteAllText(Path.Combine(target, "a.txt"), "."); var a = fileSystem.Get("a.txt"); var exists = await a.Exists(log, CancellationToken.None); exists.Should().BeTrue(); a.HasChanges.Should().BeFalse(); cache.Root.GetFiles().Should().BeEmpty(); } } [Fact] public async Task GivenAFileCheckExistsThenDownloadVerifyHasChangesFalse() { using (var target = new TestFolder()) using (var cache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); File.WriteAllText(Path.Combine(target, "a.txt"), "."); var a = fileSystem.Get("a.txt"); var exists = await a.Exists(log, CancellationToken.None); await a.FetchAsync(log, CancellationToken.None); exists.Should().BeTrue(); a.HasChanges.Should().BeFalse(); cache.Root.GetFiles().Length.Should().Be(1); } } [Fact] public async Task GivenAFileExistsVerifyWriteOverWrites() { using (var target = new TestFolder()) using (var cache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var path = Path.Combine(target, "a.txt"); File.WriteAllText(path, "."); var a = fileSystem.Get("a.txt"); await a.Write(new JObject(), log, CancellationToken.None); a.HasChanges.Should().BeTrue(); cache.Root.GetFiles().Length.Should().Be(1); await fileSystem.Commit(log, CancellationToken.None); File.ReadAllText(path).Should().StartWith("{"); } } [Fact] public async Task GivenAFileWriteVerifyExistsAfter() { using (var target = new TestFolder()) using (var cache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var a = fileSystem.Get("a.txt"); await a.Write(new JObject(), log, CancellationToken.None); var exists = await a.Exists(log, CancellationToken.None); a.HasChanges.Should().BeTrue(); cache.Root.GetFiles().Length.Should().Be(1); exists.Should().BeTrue(); } } [Fact] public async Task GivenAFileWriteVerifyGetAfter() { using (var target = new TestFolder()) using (var cache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var a = fileSystem.Get("a.txt"); await a.Write(new JObject(), log, CancellationToken.None); var json = await a.GetJson(log, CancellationToken.None); a.HasChanges.Should().BeTrue(); cache.Root.GetFiles().Length.Should().Be(1); json.ToString().Should().Be((new JObject()).ToString()); } } [Fact] public async Task GivenAFileWriteThenDeleteVerifyDoesNotExist() { using (var target = new TestFolder()) using (var cache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var a = fileSystem.Get("a.txt"); await a.Write(new JObject(), log, CancellationToken.None); a.Delete(log, CancellationToken.None); a.HasChanges.Should().BeTrue(); cache.Root.GetFiles().Should().BeEmpty(); await fileSystem.Commit(log, CancellationToken.None); var path = Path.Combine(target, "a.txt"); File.Exists(path).Should().BeFalse(); } } [Fact] public async Task GivenAFileWriteThenDeleteMultipleTimesVerifyDoesNotExist() { using (var target = new TestFolder()) using (var cache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var a = fileSystem.Get("a.txt"); await a.Write(new JObject(), log, CancellationToken.None); a.Delete(log, CancellationToken.None); await a.Write(new JObject(), log, CancellationToken.None); a.Delete(log, CancellationToken.None); await a.Write(new JObject(), log, CancellationToken.None); await a.Write(new JObject(), log, CancellationToken.None); await a.Write(new JObject(), log, CancellationToken.None); a.Delete(log, CancellationToken.None); a.HasChanges.Should().BeTrue(); cache.Root.GetFiles().Should().BeEmpty(); await fileSystem.Commit(log, CancellationToken.None); var path = Path.Combine(target, "a.txt"); File.Exists(path).Should().BeFalse(); } } [Fact] public async Task GivenThatICreateAndDeleteAFileInTheSameSessionVerifyItIsRemoved() { using (var target = new TestFolder()) using (var cache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var a = fileSystem.Get("a.txt"); await a.Write(new JObject(), log, CancellationToken.None); a.Delete(log, CancellationToken.None); await fileSystem.Commit(log, CancellationToken.None); File.Exists(a.RootPath.LocalPath).Should().BeFalse("the file was deleted"); } } [Fact] public async Task GivenThatIDeleteAFileVerifyItIsRemoved() { using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var cache2 = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var fileSystem2 = new PhysicalFileSystem(cache2, UriUtility.CreateUri(target.Root)); var a = fileSystem.Get("a.txt"); await a.Write(new JObject(), log, CancellationToken.None); await fileSystem.Commit(log, CancellationToken.None); File.Exists(a.RootPath.LocalPath).Should().BeTrue("the file was not deleted yet"); a = fileSystem2.Get("a.txt"); a.Delete(log, CancellationToken.None); await fileSystem2.Commit(log, CancellationToken.None); File.Exists(a.RootPath.LocalPath).Should().BeFalse("the file was deleted"); } } [Fact] public async Task GivenThatIDestroyAFeedItIsNowEmpty() { using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var cache2 = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var fileSystem2 = new PhysicalFileSystem(cache2, UriUtility.CreateUri(target.Root)); var a = fileSystem.Get("a.txt"); await a.Write(new JObject(), log, CancellationToken.None); await fileSystem.Commit(log, CancellationToken.None); File.Exists(a.RootPath.LocalPath).Should().BeTrue("the file was not deleted yet"); await fileSystem2.Destroy(log, CancellationToken.None); await fileSystem2.Commit(log, CancellationToken.None); Directory.Exists(target).Should().BeFalse("all files were deleted"); } } [Fact] public async Task GivenThatICallGetFilesReturnAKnownFile() { using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var cache2 = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var fileSystem2 = new PhysicalFileSystem(cache2, UriUtility.CreateUri(target.Root)); var a = fileSystem.Get("a.txt"); await a.Write(new JObject(), log, CancellationToken.None); await fileSystem.Commit(log, CancellationToken.None); File.Exists(a.RootPath.LocalPath).Should().BeTrue("the file was not deleted yet"); var results = await fileSystem2.GetFiles(log, CancellationToken.None); results.Select(e => Path.GetFileName(e.EntityUri.LocalPath)).ShouldBeEquivalentTo(new[] { "a.txt" }); } } [Fact] public void GivenAnHttpPathVerifyThrows() { using (var cache = new LocalCache()) { Exception ex = null; try { var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri("https://example.com/feed/")); } catch (Exception e) { ex = e; } ex.Should().NotBeNull(); ex.Message.Should().Be("Local feed path cannot be an http URI, use baseURI instead."); } } [Fact] public async Task GivenAFileLinkVerifyGetAfter() { using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var extCache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var jsonInput = new JObject(new JProperty("abc", "xyz")); var extFile = extCache.GetNewTempPath(); File.WriteAllText(extFile.FullName, jsonInput.ToString()); var a = fileSystem.Get("a.txt"); a.Link(extFile.FullName, log, CancellationToken.None); var json = await a.GetJson(log, CancellationToken.None); a.HasChanges.Should().BeTrue(); cache.Root.GetFiles().Length.Should().Be(0); json.ToString().Should().Be(jsonInput.ToString()); } } [Fact] public void GivenALinkedFileDeleteVerifyFileIsNotRemoved() { using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var extCache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var jsonInput = new JObject(new JProperty("abc", "xyz")); var extFile = extCache.GetNewTempPath(); File.WriteAllText(extFile.FullName, jsonInput.ToString()); var a = fileSystem.Get("a.txt"); a.Link(extFile.FullName, log, CancellationToken.None); a.Delete(log, CancellationToken.None); a.HasChanges.Should().BeTrue(); cache.Root.GetFiles().Length.Should().Be(0); File.Exists(extFile.FullName).Should().BeTrue("The original file should not be removed"); } } [Fact] public async Task GivenALinkedFileDeleteAndRecreateVerifyFile() { using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var extCache = new LocalCache()) { var log = new TestLogger(); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root)); var jsonInput = new JObject(new JProperty("abc", "xyz")); var jsonInput2 = new JObject(new JProperty("abc", "abc")); var extFile = extCache.GetNewTempPath(); File.WriteAllText(extFile.FullName, jsonInput.ToString()); var a = fileSystem.Get("a.txt"); // Link to an ext file a.Link(extFile.FullName, log, CancellationToken.None); // Overwrite with a different file await a.Write(jsonInput2, log, CancellationToken.None); var json = await a.GetJson(log, CancellationToken.None); json.ToString().Should().Be(jsonInput2.ToString()); a.HasChanges.Should().BeTrue(); File.Exists(extFile.FullName).Should().BeTrue("The original file should not be removed"); } } [Fact] public async Task VerifyHasBucketReturnsFalse() { using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var extCache = new LocalCache()) { var log = new TestLogger(); var root = Path.Combine(target.RootDirectory.FullName, "testFeed"); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(root)); var exists = await fileSystem.HasBucket(log, CancellationToken.None); exists.Should().Be(false); } } [Fact] public async Task VerifyHasBucketWithMultipleLevelsReturnsFalse() { using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var extCache = new LocalCache()) { var log = new TestLogger(); var root = Path.Combine(target.RootDirectory.FullName, "testParent2/testParent1/testFeed"); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(root)); var exists = await fileSystem.HasBucket(log, CancellationToken.None); exists.Should().Be(false); } } [Fact] public async Task VerifyCreateBucketCreates() { using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var extCache = new LocalCache()) { var log = new TestLogger(); var root = Path.Combine(target.RootDirectory.FullName, "testParent2/testParent1/testFeed"); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(root)); await fileSystem.CreateBucket(log, CancellationToken.None); var exists = await fileSystem.HasBucket(log, CancellationToken.None); exists.Should().Be(true); } } [Fact] public async Task VerifyDeleteBucketRemovesFolder() { using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var extCache = new LocalCache()) { var log = new TestLogger(); var root = Path.Combine(target.RootDirectory.FullName, "testParent2/testParent1/testFeed"); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(root)); await fileSystem.CreateBucket(log, CancellationToken.None); await fileSystem.DeleteBucket(log, CancellationToken.None); var exists = await fileSystem.HasBucket(log, CancellationToken.None); exists.Should().Be(false); } } [Fact] public async Task VerifyValidate() { using (var target = new TestFolder()) using (var cache = new LocalCache()) using (var extCache = new LocalCache()) { var log = new TestLogger(); var root = Path.Combine(target.RootDirectory.FullName, "testParent2/testParent1/testFeed"); var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(root)); (await fileSystem.HasBucket(log, CancellationToken.None)).Should().BeFalse(); await fileSystem.CreateBucket(log, CancellationToken.None); (await fileSystem.HasBucket(log, CancellationToken.None)).Should().BeTrue(); } } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 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. */ using System; using System.IO; using Aurora.Framework; using OpenSim.Region.Framework.Scenes; namespace Aurora.Modules.Terrain.FileLoaders { public class LLRAW : ITerrainLoader { /// <summary> /// Lookup table to speed up terrain exports /// </summary> private HeightmapLookupValue[] LookupHeightTable; #region ITerrainLoader Members public ITerrainChannel LoadFile(string filename, IScene scene) { FileInfo file = new FileInfo(filename); FileStream s = file.Open(FileMode.Open, FileAccess.Read); ITerrainChannel retval = LoadStream(s, scene); s.Close(); return retval; } public ITerrainChannel LoadFile(string filename, int offsetX, int offsetY, int fileWidth, int fileHeight, int sectionWidth, int sectionHeight) { TerrainChannel retval = new TerrainChannel(sectionWidth, sectionHeight, null); FileInfo file = new FileInfo(filename); FileStream s = file.Open(FileMode.Open, FileAccess.Read); BinaryReader bs = new BinaryReader(s); int currFileYOffset = fileHeight - 1; // if our region isn't on the first Y section of the areas to be landscaped, then // advance to our section of the file while (currFileYOffset > offsetY) { // read a whole strip of regions int heightsToRead = sectionHeight*(fileWidth*sectionWidth); bs.ReadBytes(heightsToRead*13); // because there are 13 fun channels currFileYOffset--; } // got to the Y start offset within the file of our region // so read the file bits associated with our region int y; // for each Y within our Y offset for (y = sectionHeight - 1; y >= 0; y--) { int currFileXOffset = 0; // if our region isn't the first X section of the areas to be landscaped, then // advance the stream to the X start pos of our section in the file // i.e. eat X upto where we start while (currFileXOffset < offsetX) { bs.ReadBytes(sectionWidth*13); currFileXOffset++; } // got to our X offset, so write our regions X line int x; for (x = 0; x < sectionWidth; x++) { // Read a strip and continue retval[x, y] = bs.ReadByte()*(bs.ReadByte()/128); bs.ReadBytes(11); } // record that we wrote it currFileXOffset++; // if our region isn't the last X section of the areas to be landscaped, then // advance the stream to the end of this Y column while (currFileXOffset < fileWidth) { // eat the next regions x line bs.ReadBytes(sectionWidth*13); //The 13 channels again currFileXOffset++; } } bs.Close(); s.Close(); return retval; } public ITerrainChannel LoadStream(Stream s, IScene scene) { int size = (int) Math.Sqrt(s.Length/13); TerrainChannel retval = new TerrainChannel(size, size, scene); BinaryReader bs = new BinaryReader(s); int y; for (y = 0; y < retval.Height; y++) { int x; for (x = 0; x < retval.Width; x++) { retval[x, (retval.Width - 1) - y] = bs.ReadByte()*(bs.ReadByte()/128f); bs.ReadBytes(11); // Advance the stream to next bytes. } } bs.Close(); return retval; } public void SaveFile(string filename, ITerrainChannel map) { FileInfo file = new FileInfo(filename); FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write); SaveStream(s, map); s.Close(); } public void SaveStream(Stream s, ITerrainChannel map) { if (LookupHeightTable == null) { LookupHeightTable = new HeightmapLookupValue[map.Height*map.Width]; for (int i = 0; i < map.Height; i++) { for (int j = 0; j < map.Width; j++) { LookupHeightTable[i + (j*map.Width)] = new HeightmapLookupValue((ushort) (i + (j*map.Width)), (float) (i*((double) j/(map.Width/2)))); } } Array.Sort(LookupHeightTable); } BinaryWriter binStream = new BinaryWriter(s); // Output the calculated raw for (int y = 0; y < map.Height; y++) { for (int x = 0; x < map.Width; x++) { double t = map[x, (map.Height - 1) - y]; //if height is less than 0, set it to 0 as //can't save -ve values in a LLRAW file if (t < 0d) { t = 0d; } int index = 0; // The lookup table is pre-sorted, so we either find an exact match or // the next closest (smaller) match with a binary search index = Array.BinarySearch(LookupHeightTable, new HeightmapLookupValue(0, (float) t)); if (index < 0) index = ~index - 1; index = LookupHeightTable[index].Index; byte red = (byte) (index & 0xFF); byte green = (byte) ((index >> 8) & 0xFF); const byte blue = 20; const byte alpha1 = 0; const byte alpha2 = 0; const byte alpha3 = 0; const byte alpha4 = 0; const byte alpha5 = 255; const byte alpha6 = 255; const byte alpha7 = 255; const byte alpha8 = 255; byte alpha9 = red; byte alpha10 = green; binStream.Write(red); binStream.Write(green); binStream.Write(blue); binStream.Write(alpha1); binStream.Write(alpha2); binStream.Write(alpha3); binStream.Write(alpha4); binStream.Write(alpha5); binStream.Write(alpha6); binStream.Write(alpha7); binStream.Write(alpha8); binStream.Write(alpha9); binStream.Write(alpha10); } } binStream.Close(); } public string FileExtension { get { return ".raw"; } } #endregion public override string ToString() { return "LL/SL RAW"; } #region Nested type: HeightmapLookupValue public struct HeightmapLookupValue : IComparable<HeightmapLookupValue> { public ushort Index; public float Value; public HeightmapLookupValue(ushort index, float value) { Index = index; Value = value; } #region IComparable<HeightmapLookupValue> Members public int CompareTo(HeightmapLookupValue val) { return Value.CompareTo(val.Value); } #endregion } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using GitReleaseManager.Core.Configuration; using GitReleaseManager.Core.Model; using GitReleaseManager.Core.Provider; using GitReleaseManager.Core.ReleaseNotes; using GitReleaseManager.Core.Templates; using NSubstitute; using NUnit.Framework; using Serilog; using Shouldly; using ItemState = GitReleaseManager.Core.Model.ItemState; using ItemStateFilter = GitReleaseManager.Core.Model.ItemStateFilter; using Label = GitReleaseManager.Core.Model.Label; using Milestone = GitReleaseManager.Core.Model.Milestone; using NotFoundException = GitReleaseManager.Core.Exceptions.NotFoundException; using Release = GitReleaseManager.Core.Model.Release; namespace GitReleaseManager.Core.Tests { public class VcsServiceTests { private const string OWNER = "owner"; private const string REPOSITORY = "repository"; private const int MILESTONE_NUMBER = 1; private const string MILESTONE_TITLE = "0.1.0"; private const string TAG_NAME = "0.1.0"; private const string RELEASE_NOTES = "Release Notes"; private const string ASSET_CONTENT = "Asset Content"; private const bool SKIP_PRERELEASES = false; private const string UNABLE_TO_FOUND_MILESTONE_MESSAGE = "Unable to find a {State} milestone with title '{Title}' on '{Owner}/{Repository}'"; private const string UNABLE_TO_FOUND_RELEASE_MESSAGE = "Unable to find a release with tag '{TagName}' on '{Owner}/{Repository}'"; private static readonly string _tempPath = Path.GetTempPath(); private static readonly string _releaseNotesTemplate = Path.Combine(_tempPath, "ReleaseNotesTemplate.txt"); private readonly List<string> _assets = new List<string>(); private readonly List<string> _files = new List<string>(); private readonly NotFoundException _notFoundException = new NotFoundException("NotFound"); private IReleaseNotesExporter _releaseNotesExporter; private IReleaseNotesBuilder _releaseNotesBuilder; private ILogger _logger; private IVcsProvider _vcsProvider; private Config _configuration; private VcsService _vcsService; private string _releaseNotesFilePath; private string _releaseNotesTemplateFilePath; private string _releaseNotesEmptyTemplateFilePath; [OneTimeSetUp] public void OneTimeSetUp() { _releaseNotesFilePath = Path.Combine(_tempPath, "ReleaseNotes.txt"); _releaseNotesTemplateFilePath = Path.Combine(_tempPath, "ReleaseNotesTemplate.txt"); _releaseNotesEmptyTemplateFilePath = Path.Combine(_tempPath, "ReleaseNotesEmptyTemplate.txt"); var fileContent = new Dictionary<string, string> { { _releaseNotesFilePath, RELEASE_NOTES }, { _releaseNotesTemplateFilePath, _releaseNotesTemplate }, { _releaseNotesEmptyTemplateFilePath, string.Empty }, }; for (int i = 0; i < 3; i++) { var fileName = $"Asset{i + 1}.txt"; var filePath = Path.Combine(_tempPath, fileName); _assets.Add(filePath); fileContent.Add(filePath, ASSET_CONTENT); } _files.Add(_releaseNotesFilePath); _files.Add(_releaseNotesTemplateFilePath); _files.Add(_releaseNotesEmptyTemplateFilePath); _files.AddRange(_assets); foreach (var file in _files) { if (!File.Exists(file)) { File.WriteAllText(file, fileContent[file]); } } } [OneTimeTearDown] public void OneTimeTearDown() { foreach (var file in _files) { if (!File.Exists(file)) { File.Delete(file); } } } [SetUp] public void Setup() { _releaseNotesExporter = Substitute.For<IReleaseNotesExporter>(); _releaseNotesBuilder = Substitute.For<IReleaseNotesBuilder>(); _logger = Substitute.For<ILogger>(); _vcsProvider = Substitute.For<IVcsProvider>(); _configuration = new Config(); _vcsService = new VcsService(_vcsProvider, _logger, _releaseNotesBuilder, _releaseNotesExporter, _configuration); } [Test] public async Task Should_Add_Assets() { var release = new Release { Assets = new List<ReleaseAsset>() }; var assetsCount = _assets.Count; _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME) .Returns(release); await _vcsService.AddAssetsAsync(OWNER, REPOSITORY, TAG_NAME, _assets).ConfigureAwait(false); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.DidNotReceive().DeleteAssetAsync(OWNER, REPOSITORY, Arg.Any<int>()).ConfigureAwait(false); await _vcsProvider.Received(assetsCount).UploadAssetAsync(release, Arg.Any<ReleaseAssetUpload>()).ConfigureAwait(false); _logger.DidNotReceive().Warning(Arg.Any<string>(), Arg.Any<string>()); _logger.Received(assetsCount).Verbose(Arg.Any<string>(), Arg.Any<string>(), TAG_NAME, OWNER, REPOSITORY); _logger.Received(assetsCount).Debug(Arg.Any<string>(), Arg.Any<ReleaseAssetUpload>()); } [Test] public async Task Should_Add_Assets_With_Deleting_Existing_Assets() { var releaseAsset = new ReleaseAsset { Id = 1, Name = "Asset1.txt" }; var release = new Release { Assets = new List<ReleaseAsset> { releaseAsset } }; var releaseAssetsCount = release.Assets.Count; var assetsCount = _assets.Count; _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME) .Returns(release); await _vcsService.AddAssetsAsync(OWNER, REPOSITORY, TAG_NAME, _assets).ConfigureAwait(false); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.Received(releaseAssetsCount).DeleteAssetAsync(OWNER, REPOSITORY, releaseAsset.Id).ConfigureAwait(false); await _vcsProvider.Received(assetsCount).UploadAssetAsync(release, Arg.Any<ReleaseAssetUpload>()).ConfigureAwait(false); _logger.Received(releaseAssetsCount).Warning(Arg.Any<string>(), Arg.Any<string>()); _logger.Received(assetsCount).Verbose(Arg.Any<string>(), Arg.Any<string>(), TAG_NAME, OWNER, REPOSITORY); _logger.Received(assetsCount).Debug(Arg.Any<string>(), Arg.Any<ReleaseAssetUpload>()); } [Test] public async Task Should_Throw_Exception_On_Adding_Assets_When_Asset_File_Not_Exists() { var release = new Release(); var assetFilePath = Path.Combine(_tempPath, "AssetNotExists.txt"); _assets[0] = assetFilePath; _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME) .Returns(release); var ex = await Should.ThrowAsync<FileNotFoundException>(() => _vcsService.AddAssetsAsync(OWNER, REPOSITORY, TAG_NAME, _assets)).ConfigureAwait(false); ex.Message.ShouldContain(assetFilePath); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.DidNotReceive().DeleteAssetAsync(OWNER, REPOSITORY, Arg.Any<int>()).ConfigureAwait(false); await _vcsProvider.DidNotReceive().UploadAssetAsync(release, Arg.Any<ReleaseAssetUpload>()).ConfigureAwait(false); } [TestCaseSource(nameof(Assets_TestCases))] public async Task Should_Do_Nothing_On_Missing_Assets(IList<string> assets) { await _vcsService.AddAssetsAsync(OWNER, REPOSITORY, TAG_NAME, assets).ConfigureAwait(false); await _vcsProvider.DidNotReceive().GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.DidNotReceive().DeleteAssetAsync(OWNER, REPOSITORY, Arg.Any<int>()).ConfigureAwait(false); await _vcsProvider.DidNotReceive().UploadAssetAsync(Arg.Any<Release>(), Arg.Any<ReleaseAssetUpload>()).ConfigureAwait(false); } public static IEnumerable Assets_TestCases() { yield return new TestCaseData(null); yield return new TestCaseData(new List<string>()); } [Test] public async Task Should_Create_Labels() { var labels = new List<Label> { new Label { Name = "Bug" }, new Label { Name = "Feature" }, new Label { Name = "Improvement" }, }; _vcsProvider.GetLabelsAsync(OWNER, REPOSITORY) .Returns(Task.FromResult((IEnumerable<Label>)labels)); _vcsProvider.DeleteLabelAsync(OWNER, REPOSITORY, Arg.Any<string>()) .Returns(Task.CompletedTask); _vcsProvider.CreateLabelAsync(OWNER, REPOSITORY, Arg.Any<Label>()) .Returns(Task.CompletedTask); await _vcsService.CreateLabelsAsync(OWNER, REPOSITORY).ConfigureAwait(false); await _vcsProvider.Received(1).GetLabelsAsync(OWNER, REPOSITORY).ConfigureAwait(false); await _vcsProvider.Received(labels.Count).DeleteLabelAsync(OWNER, REPOSITORY, Arg.Any<string>()).ConfigureAwait(false); await _vcsProvider.Received(_configuration.Labels.Count).CreateLabelAsync(OWNER, REPOSITORY, Arg.Any<Label>()).ConfigureAwait(false); _logger.Received(1).Verbose(Arg.Any<string>(), OWNER, REPOSITORY); _logger.Received(2).Verbose(Arg.Any<string>()); _logger.Received(2).Debug(Arg.Any<string>(), Arg.Any<IEnumerable<Label>>()); } [Test] public async Task Should_Log_An_Warning_When_Labels_Not_Configured() { _configuration.Labels.Clear(); await _vcsService.CreateLabelsAsync(OWNER, REPOSITORY).ConfigureAwait(false); _logger.Received(1).Warning(Arg.Any<string>()); } [Test] public async Task Should_Close_Milestone() { var milestone = new Milestone { Number = MILESTONE_NUMBER }; _vcsProvider.GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Open) .Returns(Task.FromResult(milestone)); _vcsProvider.SetMilestoneStateAsync(OWNER, REPOSITORY, milestone.Number, ItemState.Closed) .Returns(Task.CompletedTask); await _vcsService.CloseMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false); await _vcsProvider.Received(1).GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Open).ConfigureAwait(false); await _vcsProvider.Received(1).SetMilestoneStateAsync(OWNER, REPOSITORY, milestone.Number, ItemState.Closed).ConfigureAwait(false); } [Test] public async Task Should_Log_An_Warning_On_Closing_When_Milestone_Cannot_Be_Found() { _vcsProvider.GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Open) .Returns(Task.FromException<Milestone>(_notFoundException)); await _vcsService.CloseMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false); await _vcsProvider.Received(1).GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Open).ConfigureAwait(false); await _vcsProvider.DidNotReceive().SetMilestoneStateAsync(OWNER, REPOSITORY, MILESTONE_NUMBER, ItemState.Closed).ConfigureAwait(false); _logger.Received(1).Warning(UNABLE_TO_FOUND_MILESTONE_MESSAGE, "open", MILESTONE_TITLE, OWNER, REPOSITORY); } [Test] public async Task Should_Open_Milestone() { var milestone = new Milestone { Number = MILESTONE_NUMBER }; _vcsProvider.GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Closed) .Returns(Task.FromResult(milestone)); _vcsProvider.SetMilestoneStateAsync(OWNER, REPOSITORY, milestone.Number, ItemState.Open) .Returns(Task.CompletedTask); await _vcsService.OpenMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false); await _vcsProvider.Received(1).GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Closed).ConfigureAwait(false); await _vcsProvider.Received(1).SetMilestoneStateAsync(OWNER, REPOSITORY, milestone.Number, ItemState.Open).ConfigureAwait(false); _logger.Received(2).Verbose(Arg.Any<string>(), MILESTONE_TITLE, OWNER, REPOSITORY); } [Test] public async Task Should_Log_An_Warning_On_Opening_When_Milestone_Cannot_Be_Found() { _vcsProvider.GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Closed) .Returns(Task.FromException<Milestone>(_notFoundException)); await _vcsService.OpenMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false); await _vcsProvider.Received(1).GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Closed).ConfigureAwait(false); await _vcsProvider.DidNotReceive().SetMilestoneStateAsync(OWNER, REPOSITORY, MILESTONE_NUMBER, ItemState.Open).ConfigureAwait(false); _logger.Received(1).Warning(UNABLE_TO_FOUND_MILESTONE_MESSAGE, "closed", MILESTONE_TITLE, OWNER, REPOSITORY); } [Test] public async Task Should_Create_Release_From_Milestone() { var release = new Release(); _releaseNotesBuilder.BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, ReleaseTemplates.DEFAULT_NAME) .Returns(Task.FromResult(RELEASE_NOTES)); _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE) .Returns(Task.FromResult<Release>(null)); _vcsProvider.CreateReleaseAsync(OWNER, REPOSITORY, Arg.Any<Release>()) .Returns(Task.FromResult(release)); var result = await _vcsService.CreateReleaseFromMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, MILESTONE_TITLE, null, null, false, null).ConfigureAwait(false); result.ShouldBeSameAs(release); await _releaseNotesBuilder.Received(1).BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, ReleaseTemplates.DEFAULT_NAME).ConfigureAwait(false); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false); await _vcsProvider.Received(1).CreateReleaseAsync(OWNER, REPOSITORY, Arg.Is<Release>(o => o.Body == RELEASE_NOTES && o.Name == MILESTONE_TITLE && o.TagName == MILESTONE_TITLE)).ConfigureAwait(false); _logger.Received(1).Verbose(Arg.Any<string>(), MILESTONE_TITLE, OWNER, REPOSITORY); _logger.Received(1).Debug(Arg.Any<string>(), Arg.Any<Release>()); } [Test] public async Task Should_Create_Release_From_Milestone_Using_Template_File() { var release = new Release(); _releaseNotesBuilder.BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, _releaseNotesTemplate) .Returns(Task.FromResult(RELEASE_NOTES)); _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE) .Returns(Task.FromResult<Release>(null)); _vcsProvider.CreateReleaseAsync(OWNER, REPOSITORY, Arg.Any<Release>()) .Returns(Task.FromResult(release)); var result = await _vcsService.CreateReleaseFromMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, MILESTONE_TITLE, null, null, false, _releaseNotesTemplateFilePath).ConfigureAwait(false); result.ShouldBeSameAs(release); await _releaseNotesBuilder.Received(1).BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, _releaseNotesTemplate).ConfigureAwait(false); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false); await _vcsProvider.Received(1).CreateReleaseAsync(OWNER, REPOSITORY, Arg.Is<Release>(o => o.Body == RELEASE_NOTES && o.Name == MILESTONE_TITLE && o.TagName == MILESTONE_TITLE)).ConfigureAwait(false); _logger.Received(1).Verbose(Arg.Any<string>(), MILESTONE_TITLE, OWNER, REPOSITORY); _logger.Received(1).Debug(Arg.Any<string>(), Arg.Any<Release>()); } [Test] [Ignore("This may be handled by the TemplateLoader instead")] public async Task Should_Throw_Exception_On_Creating_Release_With_Empty_Template() { _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME) .Returns(Task.FromException<Release>(_notFoundException)); await Should.ThrowAsync<ArgumentException>(() => _vcsService.CreateReleaseFromMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, MILESTONE_TITLE, null, null, false, _releaseNotesEmptyTemplateFilePath)).ConfigureAwait(false); await _releaseNotesBuilder.DidNotReceive().BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, Arg.Any<string>()).ConfigureAwait(false); } [Test] [Ignore("This may be handled by the TemplateLoader instead")] public async Task Should_Throw_Exception_On_Creating_Release_With_Invalid_Template_File_Path() { _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME) .Returns(Task.FromException<Release>(_notFoundException)); var fileName = "InvalidReleaseNotesTemplate.txt"; var invalidReleaseNotesTemplateFilePath = Path.Combine(_tempPath, fileName); var ex = await Should.ThrowAsync<FileNotFoundException>(() => _vcsService.CreateReleaseFromMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, MILESTONE_TITLE, null, null, false, invalidReleaseNotesTemplateFilePath)).ConfigureAwait(false); ex.Message.ShouldContain(invalidReleaseNotesTemplateFilePath); ex.FileName.ShouldBe(fileName); await _releaseNotesBuilder.DidNotReceive().BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, Arg.Any<string>()).ConfigureAwait(false); } [TestCase(true, false)] [TestCase(true, true)] [TestCase(false, true)] public async Task Should_Update_Published_Release_On_Creating_Release_From_Milestone(bool isDraft, bool updatePublishedRelease) { var release = new Release { Draft = isDraft }; _configuration.Create.AllowUpdateToPublishedRelease = updatePublishedRelease; _releaseNotesBuilder.BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, ReleaseTemplates.DEFAULT_NAME) .Returns(Task.FromResult(RELEASE_NOTES)); _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE) .Returns(Task.FromResult(release)); _vcsProvider.UpdateReleaseAsync(OWNER, REPOSITORY, release) .Returns(Task.FromResult(new Release())); var result = await _vcsService.CreateReleaseFromMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, MILESTONE_TITLE, null, null, false, null).ConfigureAwait(false); result.ShouldBeSameAs(release); await _releaseNotesBuilder.Received(1).BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, ReleaseTemplates.DEFAULT_NAME).ConfigureAwait(false); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false); await _vcsProvider.Received(1).UpdateReleaseAsync(OWNER, REPOSITORY, release).ConfigureAwait(false); _logger.Received(1).Warning(Arg.Any<string>(), MILESTONE_TITLE); _logger.Received(1).Verbose(Arg.Any<string>(), MILESTONE_TITLE, OWNER, REPOSITORY); _logger.Received(1).Debug(Arg.Any<string>(), release); } [Test] public async Task Should_Throw_Exception_While_Updating_Published_Release_On_Creating_Release_From_Milestone() { var release = new Release { Draft = false }; _configuration.Create.AllowUpdateToPublishedRelease = false; _releaseNotesBuilder.BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, ReleaseTemplates.DEFAULT_NAME) .Returns(Task.FromResult(RELEASE_NOTES)); _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE) .Returns(Task.FromResult(release)); var ex = await Should.ThrowAsync<InvalidOperationException>(() => _vcsService.CreateReleaseFromMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, MILESTONE_TITLE, null, null, false, null)).ConfigureAwait(false); ex.Message.ShouldBe($"Release with tag '{MILESTONE_TITLE}' not in draft state, so not updating"); await _releaseNotesBuilder.Received(1).BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, ReleaseTemplates.DEFAULT_NAME).ConfigureAwait(false); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false); } [Test] public async Task Should_Create_Release_From_InputFile() { var release = new Release(); _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE) .Returns(Task.FromResult<Release>(null)); _vcsProvider.CreateReleaseAsync(OWNER, REPOSITORY, Arg.Any<Release>()) .Returns(Task.FromResult(release)); var result = await _vcsService.CreateReleaseFromInputFileAsync(OWNER, REPOSITORY, MILESTONE_TITLE, _releaseNotesFilePath, null, null, false).ConfigureAwait(false); result.ShouldBeSameAs(release); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false); await _vcsProvider.Received(1).CreateReleaseAsync(OWNER, REPOSITORY, Arg.Is<Release>(o => o.Body == RELEASE_NOTES && o.Name == MILESTONE_TITLE && o.TagName == MILESTONE_TITLE)).ConfigureAwait(false); _logger.Received(1).Verbose(Arg.Any<string>(), MILESTONE_TITLE, OWNER, REPOSITORY); _logger.Received(1).Debug(Arg.Any<string>(), Arg.Any<Release>()); } [TestCase(true, false)] [TestCase(true, true)] [TestCase(false, true)] public async Task Should_Update_Published_Release_On_Creating_Release_From_InputFile(bool isDraft, bool updatePublishedRelease) { var release = new Release { Draft = isDraft }; _configuration.Create.AllowUpdateToPublishedRelease = updatePublishedRelease; _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE) .Returns(Task.FromResult(release)); _vcsProvider.UpdateReleaseAsync(OWNER, REPOSITORY, release) .Returns(Task.FromResult(new Release())); var result = await _vcsService.CreateReleaseFromInputFileAsync(OWNER, REPOSITORY, MILESTONE_TITLE, _releaseNotesFilePath, null, null, false).ConfigureAwait(false); result.ShouldBeSameAs(release); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false); await _vcsProvider.Received(1).UpdateReleaseAsync(OWNER, REPOSITORY, release).ConfigureAwait(false); _logger.Received(1).Warning(Arg.Any<string>(), MILESTONE_TITLE); _logger.Received(1).Verbose(Arg.Any<string>(), MILESTONE_TITLE, OWNER, REPOSITORY); _logger.Received(1).Debug(Arg.Any<string>(), release); } [Test] public async Task Should_Throw_Exception_While_Updating_Published_Release_On_Creating_Release_From_InputFile() { var release = new Release { Draft = false }; _configuration.Create.AllowUpdateToPublishedRelease = false; _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE) .Returns(Task.FromResult(release)); var ex = await Should.ThrowAsync<InvalidOperationException>(() => _vcsService.CreateReleaseFromInputFileAsync(OWNER, REPOSITORY, MILESTONE_TITLE, _releaseNotesFilePath, null, null, false)).ConfigureAwait(false); ex.Message.ShouldBe($"Release with tag '{MILESTONE_TITLE}' not in draft state, so not updating"); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false); } [Test] public async Task Should_Throw_Exception_Creating_Release_From_InputFile() { var fileName = "NonExistingReleaseNotes.txt"; var filePath = Path.Combine(Path.GetTempPath(), fileName); var ex = await Should.ThrowAsync<FileNotFoundException>(() => _vcsService.CreateReleaseFromInputFileAsync(OWNER, REPOSITORY, MILESTONE_TITLE, filePath, null, null, false)).ConfigureAwait(false); ex.Message.ShouldBe("Unable to locate input file."); ex.FileName.ShouldBe(fileName); } [Test] public async Task Should_Delete_Draft_Release() { var release = new Release { Id = 1, Draft = true, }; _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME) .Returns(Task.FromResult(release)); _vcsProvider.DeleteReleaseAsync(OWNER, REPOSITORY, release.Id) .Returns(Task.CompletedTask); await _vcsService.DiscardReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.Received(1).DeleteReleaseAsync(OWNER, REPOSITORY, release.Id).ConfigureAwait(false); } [Test] public async Task Should_Not_Delete_Published_Release() { var release = new Release { Id = 1 }; _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME) .Returns(Task.FromResult(release)); await _vcsService.DiscardReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.DidNotReceive().DeleteReleaseAsync(OWNER, REPOSITORY, release.Id).ConfigureAwait(false); _logger.Received(1).Warning(Arg.Any<string>(), TAG_NAME); } [Test] public async Task Should_Log_An_Warning_On_Deleting_Release_For_Non_Existing_Tag() { _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME) .Returns(Task.FromException<Release>(_notFoundException)); await _vcsService.DiscardReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.Received().GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.DidNotReceiveWithAnyArgs().DeleteReleaseAsync(OWNER, REPOSITORY, default).ConfigureAwait(false); _logger.Received(1).Warning(UNABLE_TO_FOUND_RELEASE_MESSAGE, TAG_NAME, OWNER, REPOSITORY); } [Test] public async Task Should_Publish_Release() { var release = new Release { Id = 1 }; _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME) .Returns(Task.FromResult(release)); _vcsProvider.PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME, release.Id) .Returns(Task.CompletedTask); await _vcsService.PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.Received(1).PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME, release.Id).ConfigureAwait(false); _logger.Received(1).Verbose(Arg.Any<string>(), TAG_NAME, OWNER, REPOSITORY); _logger.Received(1).Debug(Arg.Any<string>(), Arg.Any<Release>()); } [Test] public async Task Should_Log_An_Warning_On_Publishing_Release_For_Non_Existing_Tag() { _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME) .Returns(Task.FromException<Release>(_notFoundException)); await _vcsService.PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.Received().GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.DidNotReceiveWithAnyArgs().PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME, default).ConfigureAwait(false); _logger.Received(1).Warning(Arg.Any<string>(), TAG_NAME, OWNER, REPOSITORY); } [Test] public async Task Should_Get_Release_Notes() { var releases = Enumerable.Empty<Release>(); var releaseNotes = "Release Notes"; _vcsProvider.GetReleasesAsync(OWNER, REPOSITORY, SKIP_PRERELEASES) .Returns(Task.FromResult(releases)); _releaseNotesExporter.ExportReleaseNotes(Arg.Any<IEnumerable<Release>>()) .Returns(releaseNotes); var result = await _vcsService.ExportReleasesAsync(OWNER, REPOSITORY, null, SKIP_PRERELEASES).ConfigureAwait(false); result.ShouldBeSameAs(releaseNotes); await _vcsProvider.DidNotReceive().GetReleaseAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()).ConfigureAwait(false); await _vcsProvider.Received(1).GetReleasesAsync(OWNER, REPOSITORY, SKIP_PRERELEASES).ConfigureAwait(false); _logger.Received(1).Verbose(Arg.Any<string>(), OWNER, REPOSITORY); _releaseNotesExporter.Received(1).ExportReleaseNotes(Arg.Any<IEnumerable<Release>>()); } [Test] public async Task Should_Get_Release_Notes_For_Tag() { var release = new Release(); _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME) .Returns(Task.FromResult(release)); _releaseNotesExporter.ExportReleaseNotes(Arg.Any<IEnumerable<Release>>()) .Returns(RELEASE_NOTES); var result = await _vcsService.ExportReleasesAsync(OWNER, REPOSITORY, TAG_NAME, SKIP_PRERELEASES).ConfigureAwait(false); result.ShouldBeSameAs(RELEASE_NOTES); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); await _vcsProvider.DidNotReceive().GetReleasesAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>()).ConfigureAwait(false); _logger.Received(1).Verbose(Arg.Any<string>(), OWNER, REPOSITORY, TAG_NAME); _releaseNotesExporter.Received(1).ExportReleaseNotes(Arg.Any<IEnumerable<Release>>()); } [Test] public async Task Should_Get_Default_Release_Notes_For_Non_Existent_Tag() { _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME) .Returns(Task.FromException<Release>(_notFoundException)); _releaseNotesExporter.ExportReleaseNotes(Arg.Any<IEnumerable<Release>>()) .Returns(RELEASE_NOTES); var result = await _vcsService.ExportReleasesAsync(OWNER, REPOSITORY, TAG_NAME, SKIP_PRERELEASES).ConfigureAwait(false); result.ShouldBeSameAs(RELEASE_NOTES); await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false); _logger.Received(1).Warning(UNABLE_TO_FOUND_RELEASE_MESSAGE, TAG_NAME, OWNER, REPOSITORY); _releaseNotesExporter.Received(1).ExportReleaseNotes(Arg.Any<IEnumerable<Release>>()); } } }
// 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; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Collections.Specialized { /// <summary> /// This enum describes the action that caused a CollectionChanged event. /// </summary> public enum NotifyCollectionChangedAction { /// <summary> One or more items were added to the collection. </summary> Add, /// <summary> One or more items were removed from the collection. </summary> Remove, /// <summary> One or more items were replaced in the collection. </summary> Replace, /// <summary> One or more items were moved within the collection. </summary> Move, /// <summary> The contents of the collection changed dramatically. </summary> Reset, } /// <summary> /// Arguments for the CollectionChanged event. /// A collection that supports INotifyCollectionChangedThis raises this event /// whenever an item is added or removed, or when the contents of the collection /// changes dramatically. /// </summary> public class NotifyCollectionChangedEventArgs : EventArgs { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a reset change. /// </summary> /// <param name="action">The action that caused the event (must be Reset).</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action) { if (action != NotifyCollectionChangedAction.Reset) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Reset), nameof(action)); InitializeAdd(action, null, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item change. /// </summary> /// <param name="action">The action that caused the event; can only be Reset, Add or Remove action.</param> /// <param name="changedItem">The item affected by the change.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, nameof(action)); if (action == NotifyCollectionChangedAction.Reset) { if (changedItem != null) throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); InitializeAdd(action, null, -1); } else { InitializeAddOrRemove(action, new object[] { changedItem }, -1); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item change. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItem">The item affected by the change.</param> /// <param name="index">The index where the change occurred.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem, int index) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, nameof(action)); if (action == NotifyCollectionChangedAction.Reset) { if (changedItem != null) throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); if (index != -1) throw new ArgumentException(SR.ResetActionRequiresIndexMinus1, nameof(action)); InitializeAdd(action, null, -1); } else { InitializeAddOrRemove(action, new object[] { changedItem }, index); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item change. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, nameof(action)); if (action == NotifyCollectionChangedAction.Reset) { if (changedItems != null) throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); InitializeAdd(action, null, -1); } else { if (changedItems == null) throw new ArgumentNullException(nameof(changedItems)); InitializeAddOrRemove(action, changedItems, -1); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item change (or a reset). /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> /// <param name="startingIndex">The index where the change occurred.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems, int startingIndex) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, nameof(action)); if (action == NotifyCollectionChangedAction.Reset) { if (changedItems != null) throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); if (startingIndex != -1) throw new ArgumentException(SR.ResetActionRequiresIndexMinus1, nameof(action)); InitializeAdd(action, null, -1); } else { if (changedItems == null) throw new ArgumentNullException(nameof(changedItems)); if (startingIndex < -1) throw new ArgumentException(SR.IndexCannotBeNegative, nameof(startingIndex)); InitializeAddOrRemove(action, changedItems, startingIndex); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItem">The new item replacing the original item.</param> /// <param name="oldItem">The original item that is replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object newItem, object oldItem) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); InitializeMoveOrReplace(action, new object[] { newItem }, new object[] { oldItem }, -1, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItem">The new item replacing the original item.</param> /// <param name="oldItem">The original item that is replaced.</param> /// <param name="index">The index of the item being replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object newItem, object oldItem, int index) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); InitializeMoveOrReplace(action, new object[] { newItem }, new object[] { oldItem }, index, index); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItems">The new items replacing the original items.</param> /// <param name="oldItems">The original items that are replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); if (newItems == null) throw new ArgumentNullException(nameof(newItems)); if (oldItems == null) throw new ArgumentNullException(nameof(oldItems)); InitializeMoveOrReplace(action, newItems, oldItems, -1, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItems">The new items replacing the original items.</param> /// <param name="oldItems">The original items that are replaced.</param> /// <param name="startingIndex">The starting index of the items being replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); if (newItems == null) throw new ArgumentNullException(nameof(newItems)); if (oldItems == null) throw new ArgumentNullException(nameof(oldItems)); InitializeMoveOrReplace(action, newItems, oldItems, startingIndex, startingIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Move event. /// </summary> /// <param name="action">Can only be a Move action.</param> /// <param name="changedItem">The item affected by the change.</param> /// <param name="index">The new index for the changed item.</param> /// <param name="oldIndex">The old index for the changed item.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem, int index, int oldIndex) { if (action != NotifyCollectionChangedAction.Move) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Move), nameof(action)); if (index < 0) throw new ArgumentException(SR.IndexCannotBeNegative, nameof(index)); object[] changedItems = new object[] { changedItem }; InitializeMoveOrReplace(action, changedItems, changedItems, index, oldIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Move event. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> /// <param name="index">The new index for the changed items.</param> /// <param name="oldIndex">The old index for the changed items.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems, int index, int oldIndex) { if (action != NotifyCollectionChangedAction.Move) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Move), nameof(action)); if (index < 0) throw new ArgumentException(SR.IndexCannotBeNegative, nameof(index)); InitializeMoveOrReplace(action, changedItems, changedItems, index, oldIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs with given fields (no validation). Used by WinRT marshaling. /// </summary> internal NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int newIndex, int oldIndex) { _action = action; _newItems = (newItems == null) ? null : new ReadOnlyList(newItems); _oldItems = (oldItems == null) ? null : new ReadOnlyList(oldItems); _newStartingIndex = newIndex; _oldStartingIndex = oldIndex; } private void InitializeAddOrRemove(NotifyCollectionChangedAction action, IList changedItems, int startingIndex) { if (action == NotifyCollectionChangedAction.Add) InitializeAdd(action, changedItems, startingIndex); else if (action == NotifyCollectionChangedAction.Remove) InitializeRemove(action, changedItems, startingIndex); else Debug.Assert(false, string.Format("Unsupported action: {0}", action.ToString())); } private void InitializeAdd(NotifyCollectionChangedAction action, IList newItems, int newStartingIndex) { _action = action; _newItems = (newItems == null) ? null : new ReadOnlyList(newItems); _newStartingIndex = newStartingIndex; } private void InitializeRemove(NotifyCollectionChangedAction action, IList oldItems, int oldStartingIndex) { _action = action; _oldItems = (oldItems == null) ? null : new ReadOnlyList(oldItems); _oldStartingIndex = oldStartingIndex; } private void InitializeMoveOrReplace(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex, int oldStartingIndex) { InitializeAdd(action, newItems, startingIndex); InitializeRemove(action, oldItems, oldStartingIndex); } //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ /// <summary> /// The action that caused the event. /// </summary> public NotifyCollectionChangedAction Action { get { return _action; } } /// <summary> /// The items affected by the change. /// </summary> public IList NewItems { get { return _newItems; } } /// <summary> /// The old items affected by the change (for Replace events). /// </summary> public IList OldItems { get { return _oldItems; } } /// <summary> /// The index where the change occurred. /// </summary> public int NewStartingIndex { get { return _newStartingIndex; } } /// <summary> /// The old index where the change occurred (for Move events). /// </summary> public int OldStartingIndex { get { return _oldStartingIndex; } } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ private NotifyCollectionChangedAction _action; private IList _newItems, _oldItems; private int _newStartingIndex = -1; private int _oldStartingIndex = -1; } /// <summary> /// The delegate to use for handlers that receive the CollectionChanged event. /// </summary> public delegate void NotifyCollectionChangedEventHandler(object sender, NotifyCollectionChangedEventArgs e); internal sealed class ReadOnlyList : IList { private readonly IList _list; internal ReadOnlyList(IList list) { Debug.Assert(list != null); _list = list; } public int Count { get { return _list.Count; } } public bool IsReadOnly { get { return true; } } public bool IsFixedSize { get { return true; } } public bool IsSynchronized { get { return _list.IsSynchronized; } } public object this[int index] { get { return _list[index]; } set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } public object SyncRoot { get { return _list.SyncRoot; } } public int Add(object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public void Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public bool Contains(object value) { return _list.Contains(value); } public void CopyTo(Array array, int index) { _list.CopyTo(array, index); } public IEnumerator GetEnumerator() { return _list.GetEnumerator(); } public int IndexOf(object value) { return _list.IndexOf(value); } public void Insert(int index, object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public void Remove(object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } }
// 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.IO; using System.Text; using System.Diagnostics; using System.Globalization; namespace System.Xml { // XmlTextEncoder // // This class does special handling of text content for XML. For example // it will replace special characters with entities whenever necessary. internal class XmlTextEncoder { // // Fields // // output text writer private TextWriter _textWriter; // true when writing out the content of attribute value private bool _inAttribute; // quote char of the attribute (when inAttribute) private char _quoteChar; // caching of attribute value private StringBuilder _attrValue; private bool _cacheAttrValue; // XmlCharType private XmlCharType _xmlCharType; // // Constructor // internal XmlTextEncoder(TextWriter textWriter) { _textWriter = textWriter; _quoteChar = '"'; _xmlCharType = XmlCharType.Instance; } // // Internal methods and properties // internal char QuoteChar { set { _quoteChar = value; } } internal void StartAttribute(bool cacheAttrValue) { _inAttribute = true; _cacheAttrValue = cacheAttrValue; if (cacheAttrValue) { if (_attrValue == null) { _attrValue = new StringBuilder(); } else { _attrValue.Length = 0; } } } internal void EndAttribute() { if (_cacheAttrValue) { _attrValue.Length = 0; } _inAttribute = false; _cacheAttrValue = false; } internal string AttributeValue { get { if (_cacheAttrValue) { return _attrValue.ToString(); } else { return String.Empty; } } } internal void WriteSurrogateChar(char lowChar, char highChar) { if (!XmlCharType.IsLowSurrogate(lowChar) || !XmlCharType.IsHighSurrogate(highChar)) { throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, highChar); } _textWriter.Write(highChar); _textWriter.Write(lowChar); } [System.Security.SecurityCritical] internal void Write(char[] array, int offset, int count) { if (null == array) { throw new ArgumentNullException(nameof(array)); } if (0 > offset) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (0 > count) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > array.Length - offset) { throw new ArgumentOutOfRangeException(nameof(count)); } if (_cacheAttrValue) { _attrValue.Append(array, offset, count); } int endPos = offset + count; int i = offset; char ch = (char)0; for (; ;) { int startPos = i; unsafe { while (i < endPos && _xmlCharType.IsAttributeValueChar(ch = array[i])) { i++; } } if (startPos < i) { _textWriter.Write(array, startPos, i - startPos); } if (i == endPos) { break; } switch (ch) { case (char)0x9: _textWriter.Write(ch); break; case (char)0xA: case (char)0xD: if (_inAttribute) { WriteCharEntityImpl(ch); } else { _textWriter.Write(ch); } break; case '<': WriteEntityRefImpl("lt"); break; case '>': WriteEntityRefImpl("gt"); break; case '&': WriteEntityRefImpl("amp"); break; case '\'': if (_inAttribute && _quoteChar == ch) { WriteEntityRefImpl("apos"); } else { _textWriter.Write('\''); } break; case '"': if (_inAttribute && _quoteChar == ch) { WriteEntityRefImpl("quot"); } else { _textWriter.Write('"'); } break; default: if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 < endPos) { WriteSurrogateChar(array[++i], ch); } else { throw new ArgumentException(SR.Xml_SurrogatePairSplit); } } else if (XmlCharType.IsLowSurrogate(ch)) { throw XmlConvert.CreateInvalidHighSurrogateCharException(ch); } else { Debug.Assert((ch < 0x20 && !_xmlCharType.IsWhiteSpace(ch)) || (ch > 0xFFFD)); WriteCharEntityImpl(ch); } break; } i++; } } internal void WriteSurrogateCharEntity(char lowChar, char highChar) { if (!XmlCharType.IsLowSurrogate(lowChar) || !XmlCharType.IsHighSurrogate(highChar)) { throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, highChar); } int surrogateChar = XmlCharType.CombineSurrogateChar(lowChar, highChar); if (_cacheAttrValue) { _attrValue.Append(highChar); _attrValue.Append(lowChar); } _textWriter.Write("&#x"); _textWriter.Write(surrogateChar.ToString("X", NumberFormatInfo.InvariantInfo)); _textWriter.Write(';'); } [System.Security.SecurityCritical] internal void Write(string text) { if (text == null) { return; } if (_cacheAttrValue) { _attrValue.Append(text); } // scan through the string to see if there are any characters to be escaped int len = text.Length; int i = 0; int startPos = 0; char ch = (char)0; for (; ;) { unsafe { while (i < len && _xmlCharType.IsAttributeValueChar(ch = text[i])) { i++; } } if (i == len) { // reached the end of the string -> write it whole out _textWriter.Write(text); return; } if (_inAttribute) { if (ch == 0x9) { i++; continue; } } else { if (ch == 0x9 || ch == 0xA || ch == 0xD || ch == '"' || ch == '\'') { i++; continue; } } // some character that needs to be escaped is found: break; } char[] helperBuffer = new char[256]; for (; ;) { if (startPos < i) { WriteStringFragment(text, startPos, i - startPos, helperBuffer); } if (i == len) { break; } switch (ch) { case (char)0x9: _textWriter.Write(ch); break; case (char)0xA: case (char)0xD: if (_inAttribute) { WriteCharEntityImpl(ch); } else { _textWriter.Write(ch); } break; case '<': WriteEntityRefImpl("lt"); break; case '>': WriteEntityRefImpl("gt"); break; case '&': WriteEntityRefImpl("amp"); break; case '\'': if (_inAttribute && _quoteChar == ch) { WriteEntityRefImpl("apos"); } else { _textWriter.Write('\''); } break; case '"': if (_inAttribute && _quoteChar == ch) { WriteEntityRefImpl("quot"); } else { _textWriter.Write('"'); } break; default: if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 < len) { WriteSurrogateChar(text[++i], ch); } else { throw XmlConvert.CreateInvalidSurrogatePairException(text[i], ch); } } else if (XmlCharType.IsLowSurrogate(ch)) { throw XmlConvert.CreateInvalidHighSurrogateCharException(ch); } else { Debug.Assert((ch < 0x20 && !_xmlCharType.IsWhiteSpace(ch)) || (ch > 0xFFFD)); WriteCharEntityImpl(ch); } break; } i++; startPos = i; unsafe { while (i < len && _xmlCharType.IsAttributeValueChar(ch = text[i])) { i++; } } } } [System.Security.SecurityCritical] internal void WriteRawWithSurrogateChecking(string text) { if (text == null) { return; } if (_cacheAttrValue) { _attrValue.Append(text); } int len = text.Length; int i = 0; char ch = (char)0; for (; ;) { unsafe { while (i < len && (_xmlCharType.IsCharData(ch = text[i]) || ch < 0x20)) { i++; } } if (i == len) { break; } if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 < len) { char lowChar = text[i + 1]; if (XmlCharType.IsLowSurrogate(lowChar)) { i += 2; continue; } else { throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, ch); } } throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar); } else if (XmlCharType.IsLowSurrogate(ch)) { throw XmlConvert.CreateInvalidHighSurrogateCharException(ch); } else { i++; } } _textWriter.Write(text); return; } internal void WriteRaw(string value) { if (_cacheAttrValue) { _attrValue.Append(value); } _textWriter.Write(value); } internal void WriteRaw(char[] array, int offset, int count) { if (null == array) { throw new ArgumentNullException(nameof(array)); } if (0 > count) { throw new ArgumentOutOfRangeException(nameof(count)); } if (0 > offset) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count > array.Length - offset) { throw new ArgumentOutOfRangeException(nameof(count)); } if (_cacheAttrValue) { _attrValue.Append(array, offset, count); } _textWriter.Write(array, offset, count); } internal void WriteCharEntity(char ch) { if (XmlCharType.IsSurrogate(ch)) { throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar); } string strVal = ((int)ch).ToString("X", NumberFormatInfo.InvariantInfo); if (_cacheAttrValue) { _attrValue.Append("&#x"); _attrValue.Append(strVal); _attrValue.Append(';'); } WriteCharEntityImpl(strVal); } internal void WriteEntityRef(string name) { if (_cacheAttrValue) { _attrValue.Append('&'); _attrValue.Append(name); _attrValue.Append(';'); } WriteEntityRefImpl(name); } internal void Flush() { } // // Private implementation methods // // This is a helper method to workaround the fact that TextWriter does not have a Write method // for fragment of a string such as Write( string, offset, count). // The string fragment will be written out by copying into a small helper buffer and then // calling textWriter to write out the buffer. private void WriteStringFragment(string str, int offset, int count, char[] helperBuffer) { int bufferSize = helperBuffer.Length; while (count > 0) { int copyCount = count; if (copyCount > bufferSize) { copyCount = bufferSize; } str.CopyTo(offset, helperBuffer, 0, copyCount); _textWriter.Write(helperBuffer, 0, copyCount); offset += copyCount; count -= copyCount; } } private void WriteCharEntityImpl(char ch) { WriteCharEntityImpl(((int)ch).ToString("X", NumberFormatInfo.InvariantInfo)); } private void WriteCharEntityImpl(string strVal) { _textWriter.Write("&#x"); _textWriter.Write(strVal); _textWriter.Write(';'); } private void WriteEntityRefImpl(string name) { _textWriter.Write('&'); _textWriter.Write(name); _textWriter.Write(';'); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; #pragma warning disable 0414 namespace System.Reflection.Tests { public class FieldInfoTests { [Theory] [InlineData(nameof(FieldInfoTests.ConstIntField), 222)] [InlineData(nameof(FieldInfoTests.ConstStringField), "new value")] [InlineData(nameof(FieldInfoTests.ConstCharField), 'A')] [InlineData(nameof(FieldInfoTests.ConstBoolField), false)] [InlineData(nameof(FieldInfoTests.ConstFloatField), 4.56f)] [InlineData(nameof(FieldInfoTests.ConstDoubleField), double.MaxValue)] [InlineData(nameof(FieldInfoTests.ConstInt64Field), long.MaxValue)] [InlineData(nameof(FieldInfoTests.ConstByteField), byte.MaxValue)] public void SetValue_ConstantField_ThrowsFieldAccessException(string field, object value) { FieldInfo fieldInfo = GetField(typeof(FieldInfoTests), field); Assert.Throws<FieldAccessException>(() => fieldInfo.SetValue(new FieldInfoTests(), value)); } [Fact] public void SetValue_ReadonlyField() { FieldInfo fieldInfo = typeof(FieldInfoTests).GetTypeInfo().GetDeclaredField("readonlyIntField"); FieldInfoTests myInstance = new FieldInfoTests(); object current = fieldInfo.GetValue(myInstance); Assert.Equal(1, current); fieldInfo.SetValue(myInstance, int.MinValue); Assert.Equal(int.MinValue, fieldInfo.GetValue(myInstance)); } [Theory] [InlineData(typeof(Int32Attr), "[System.Reflection.Tests.Int32Attr((Int32)77, name = \"Int32AttrSimple\")]")] [InlineData(typeof(Int64Attr), "[System.Reflection.Tests.Int64Attr((Int64)77, name = \"Int64AttrSimple\")]")] [InlineData(typeof(StringAttr), "[System.Reflection.Tests.StringAttr(\"hello\", name = \"StringAttrSimple\")]")] [InlineData(typeof(EnumAttr), "[System.Reflection.Tests.EnumAttr((System.Reflection.Tests.PublicEnum)1, name = \"EnumAttrSimple\")]")] [InlineData(typeof(TypeAttr), "[System.Reflection.Tests.TypeAttr(typeof(System.Object), name = \"TypeAttrSimple\")]")] [InlineData(typeof(Attr), "[System.Reflection.Tests.Attr((Int32)77, name = \"AttrSimple\")]")] private static void CustomAttributes(Type type, string expectedToString) { FieldInfo fieldInfo = GetField(typeof(FieldInfoTests), "fieldWithAttributes"); CustomAttributeData attributeData = fieldInfo.CustomAttributes.First(attribute => attribute.AttributeType.Equals(type)); Assert.Equal(expectedToString, attributeData.ToString()); } public static IEnumerable<object[]> GetValue_TestData() { yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.s_intField), new FieldInfoTests(), 100 }; yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.s_intField), null, 100 }; yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.intField), new FieldInfoTests(), 101 }; yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.s_stringField), new FieldInfoTests(), "static" }; yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), new FieldInfoTests(), "non static" }; } [Theory] [MemberData(nameof(GetValue_TestData))] public void GetValue(Type type, string name, object obj, object expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.GetValue(obj)); } public static IEnumerable<object[]> GetValue_Invalid_TestData() { yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), null, typeof(TargetException) }; yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), new object(), typeof(ArgumentException) }; } [Theory] [MemberData(nameof(GetValue_Invalid_TestData))] public void GetValue_Invalid(Type type, string name, object obj, Type exceptionType) { FieldInfo fieldInfo = GetField(type, name); Assert.Throws(exceptionType, () => fieldInfo.GetValue(obj)); } public static IEnumerable<object[]> SetValue_TestData() { yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.s_intField), new FieldInfoTests(), 1000 }; yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.s_intField), null, 1000 }; yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.intField), new FieldInfoTests(), 1000 }; yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.s_stringField), new FieldInfoTests(), "new" }; yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), new FieldInfoTests(), "new" }; } [Theory] [MemberData(nameof(SetValue_TestData))] public void SetValue(Type type, string name, object obj, object value) { FieldInfo fieldInfo = GetField(type, name); object original = fieldInfo.GetValue(obj); try { fieldInfo.SetValue(obj, value); Assert.Equal(value, fieldInfo.GetValue(obj)); } finally { fieldInfo.SetValue(obj, original); } } public static IEnumerable<object[]> SetValue_Invalid_TestData() { yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), null, "new", typeof(TargetException) }; yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), new object(), "new", typeof(ArgumentException) }; yield return new object[] { typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), new FieldInfoTests(), 100, typeof(ArgumentException) }; } [Theory] [MemberData(nameof(SetValue_Invalid_TestData))] public void SetValue_Invalid(Type type, string name, object obj, object value, Type exceptionType) { FieldInfo fieldInfo = GetField(type, name); Assert.Throws(exceptionType, () => fieldInfo.SetValue(obj, value)); } [Theory] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), true)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), typeof(FieldInfoTests), nameof(FieldInfoTests.s_intField), false)] public void Equals(Type type1, string name1, Type type2, string name2, bool expected) { FieldInfo fieldInfo1 = GetField(type1, name1); FieldInfo fieldInfo2 = GetField(type2, name2); Assert.Equal(expected, fieldInfo1.Equals(fieldInfo2)); } [Fact] public void GetHashCodeTest() { FieldInfo fieldInfo = GetField(typeof(FieldInfoTests), nameof(FieldInfoTests.stringField)); Assert.NotEqual(0, fieldInfo.GetHashCode()); } [Theory] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.intField), typeof(int))] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), typeof(string))] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField1), typeof(object))] public void FieldType(Type type, string name, Type expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.FieldType); } [Theory] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_intField), true)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.intField), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_stringField), true)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), false)] [InlineData(typeof(FieldInfoTests), "privateIntField", false)] public void IsStatic(Type type, string name, bool expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.IsStatic); } [Theory] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField1), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField2), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField3), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField4), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField5), true)] public void IsAssembly(Type type, string name, bool expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.IsAssembly); } [Theory] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField1), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField2), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField3), true)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField4), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField5), false)] public void IsFamily(Type type, string name, bool expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.IsFamily); } [Theory] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField1), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField2), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField3), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField4), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField5), false)] public void IsFamilyAndAssembly(Type type, string name, bool expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.IsFamilyAndAssembly); } [Theory] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField1), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField2), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField3), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField4), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_assemblyField5), false)] public void IsFamilyOrAssembly(Type type, string name, bool expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.IsFamilyOrAssembly); } [Theory] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), true)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_intField), true)] [InlineData(typeof(FieldInfoTests), "privateIntField", false)] [InlineData(typeof(FieldInfoTests), "privateStringField", false)] public void IsPublic(Type type, string name, bool expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.IsPublic); } [Theory] [InlineData(typeof(FieldInfoTests), "privateIntField", true)] [InlineData(typeof(FieldInfoTests), "privateStringField", true)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.stringField), false)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_intField), false)] public void IsPrivate(Type type, string name, bool expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.IsPrivate); } [Theory] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.readonlyIntField), true)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.intField), false)] public void IsInitOnly(Type type, string name, bool expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.IsInitOnly); } [Theory] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.ConstIntField), true)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.intField), false)] public void IsLiteral(Type type, string name, bool expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.IsLiteral); } [Theory] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.intField), FieldAttributes.Public)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.s_intField), FieldAttributes.Public | FieldAttributes.Static)] [InlineData(typeof(FieldInfoTests), "privateIntField", FieldAttributes.Private)] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.readonlyIntField), FieldAttributes.Public | FieldAttributes.InitOnly)] public void Attributes(Type type, string name, FieldAttributes expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.Attributes); } [Theory] [InlineData(typeof(FieldInfoTests), nameof(FieldInfoTests.intField), false)] public void IsSpecialName(Type type, string name, bool expected) { FieldInfo fieldInfo = GetField(type, name); Assert.Equal(expected, fieldInfo.IsSpecialName); } [Fact] public void SetValue_MixedArrayTypes_CommonBaseClass() { FI_BaseClass[] ATypeWithMixedAB = new FI_BaseClass[] { new FI_BaseClass(), new FI_SubClass() }; FI_BaseClass[] ATypeWithAllA = new FI_BaseClass[] { new FI_BaseClass(), new FI_BaseClass() }; FI_BaseClass[] ATypeWithAllB = new FI_BaseClass[] { new FI_SubClass(), new FI_SubClass() }; FI_SubClass[] BTypeWithAllB = new FI_SubClass[] { new FI_SubClass(), new FI_SubClass() }; FI_BaseClass[] BTypeWithAllB_Contra = new FI_SubClass[] { new FI_SubClass(), new FI_SubClass() }; Type type = typeof(FI_FieldArray); object obj = Activator.CreateInstance(type); FieldInfo fieldInfo = GetField(type, "aArray"); fieldInfo.SetValue(obj, ATypeWithMixedAB); Assert.Equal(ATypeWithMixedAB, fieldInfo.GetValue(obj)); fieldInfo.SetValue(obj, ATypeWithAllA); Assert.Equal(ATypeWithAllA, fieldInfo.GetValue(obj)); fieldInfo.SetValue(obj, ATypeWithAllB); Assert.Equal(ATypeWithAllB, fieldInfo.GetValue(obj)); fieldInfo.SetValue(obj, BTypeWithAllB); Assert.Equal(BTypeWithAllB, fieldInfo.GetValue(obj)); fieldInfo.SetValue(obj, BTypeWithAllB_Contra); Assert.Equal(BTypeWithAllB_Contra, fieldInfo.GetValue(obj)); } [Fact] public void SetValue_MixedArrayTypes_SubClass() { FI_BaseClass[] ATypeWithMixedAB = new FI_BaseClass[] { new FI_BaseClass(), new FI_SubClass() }; FI_BaseClass[] ATypeWithAllA = new FI_BaseClass[] { new FI_BaseClass(), new FI_BaseClass() }; FI_BaseClass[] ATypeWithAllB = new FI_BaseClass[] { new FI_SubClass(), new FI_SubClass() }; FI_SubClass[] BTypeWithAllB = new FI_SubClass[] { new FI_SubClass(), new FI_SubClass() }; FI_BaseClass[] BTypeWithAllB_Contra = new FI_SubClass[] { new FI_SubClass(), new FI_SubClass() }; Type type = typeof(FI_FieldArray); object obj = Activator.CreateInstance(type); FieldInfo fieldInfo = GetField(type, "bArray"); Assert.Throws<ArgumentException>(() => fieldInfo.SetValue(obj, ATypeWithMixedAB)); Assert.Throws<ArgumentException>(() => fieldInfo.SetValue(obj, ATypeWithAllA)); Assert.Throws<ArgumentException>(() => fieldInfo.SetValue(obj, ATypeWithAllB)); fieldInfo.SetValue(obj, BTypeWithAllB); Assert.Equal(BTypeWithAllB, fieldInfo.GetValue(obj)); fieldInfo.SetValue(obj, BTypeWithAllB_Contra); Assert.Equal(BTypeWithAllB_Contra, fieldInfo.GetValue(obj)); } [Fact] public void SetValue_MixedArrayTypes_Interface() { Type type = typeof(FI_FieldArray); object obj = Activator.CreateInstance(type); FieldInfo fieldInfo = GetField(type, "iArray"); FI_Interface[] mixedMN = new FI_Interface[] { new FI_ClassWithInterface1(), new FI_ClassWithInterface2() }; fieldInfo.SetValue(obj, mixedMN); Assert.Equal(mixedMN, fieldInfo.GetValue(obj)); } [Fact] public void SetValue_MixedArrayTypes_IntByte() { Type type = typeof(FI_FieldArray); object obj = Activator.CreateInstance(type); FieldInfo fieldInfo = GetField(type, "intArray"); int[] intArray = new int[] { 200, -200, 30, 2 }; fieldInfo.SetValue(obj, intArray); Assert.Equal(intArray, fieldInfo.GetValue(obj)); Assert.Throws<ArgumentException>(() => fieldInfo.SetValue(obj, new byte[] { 2, 3, 4 })); } [Fact] public void SetValue_MixedArrayTypes_ObjectArray() { Type type = typeof(FI_FieldArray); object obj = Activator.CreateInstance(type); FieldInfo fieldInfo = GetField(type, "objectArray"); FI_Interface[] mixedMN = new FI_Interface[] { new FI_ClassWithInterface1(), new FI_ClassWithInterface2() }; fieldInfo.SetValue(obj, mixedMN); Assert.Equal(mixedMN, fieldInfo.GetValue(obj)); FI_BaseClass[] BTypeWithAllB_Contra = new FI_SubClass[] { new FI_SubClass(), new FI_SubClass() }; fieldInfo.SetValue(obj, BTypeWithAllB_Contra); Assert.Equal(BTypeWithAllB_Contra, fieldInfo.GetValue(obj)); Assert.Throws<ArgumentException>(null, () => fieldInfo.SetValue(obj, new int[] { 1, -1, 2, -2 })); Assert.Throws<ArgumentException>(null, () => fieldInfo.SetValue(obj, new byte[] { 2, 3, 4 })); } public static IEnumerable<object[]> FieldInfoRTGenericTests_TestData() { foreach (Type genericType in new Type[] { typeof(FI_GenericClassField<>), typeof(FI_StaticGenericField<>) }) { yield return new object[] { genericType, typeof(int), "genparamField", 0, -300 }; yield return new object[] { genericType, typeof(int), "dependField", null, g_int }; yield return new object[] { genericType, typeof(int), "gparrayField", null, gpa_int }; yield return new object[] { genericType, typeof(int), "arrayField", null, ga_int }; yield return new object[] { genericType, typeof(string), "genparamField", null, "hello !" }; yield return new object[] { genericType, typeof(string), "dependField", null, g_string }; yield return new object[] { genericType, typeof(string), "gparrayField", null, gpa_string }; yield return new object[] { genericType, typeof(string), "arrayField", null, ga_string }; yield return new object[] { genericType, typeof(object), "genparamField", null, 300 }; yield return new object[] { genericType, typeof(object), "dependField", null, g_object }; yield return new object[] { genericType, typeof(object), "gparrayField", null, gpa_object }; yield return new object[] { genericType, typeof(object), "arrayField", null, ga_object }; yield return new object[] { genericType, typeof(FI_GenericClass<object>), "genparamField", null, g_object }; yield return new object[] { genericType, typeof(FI_GenericClass<object>), "dependField", null, g_g_object }; yield return new object[] { genericType, typeof(FI_GenericClass<object>), "gparrayField", null, gpa_g_object }; yield return new object[] { genericType, typeof(FI_GenericClass<object>), "arrayField", null, ga_g_object }; } yield return new object[] { typeof(FI_GenericClassField<>), typeof(int), nameof(FI_GenericClassField<int>.selfField), null, pfg_int }; yield return new object[] { typeof(FI_GenericClassField<>), typeof(string), nameof(FI_GenericClassField<int>.selfField), null, pfg_string }; yield return new object[] { typeof(FI_GenericClassField<>), typeof(object), nameof(FI_GenericClassField<int>.selfField), null, pfg_object }; yield return new object[] { typeof(FI_GenericClassField<>), typeof(FI_GenericClass<object>), nameof(FI_GenericClassField<int>.selfField), null, pfg_g_object }; yield return new object[] { typeof(FI_StaticGenericField<>), typeof(int), nameof(FI_GenericClassField<int>.selfField), null, sfg_int }; yield return new object[] { typeof(FI_StaticGenericField<>), typeof(string), nameof(FI_GenericClassField<int>.selfField), null, sfg_string }; yield return new object[] { typeof(FI_StaticGenericField<>), typeof(object), nameof(FI_GenericClassField<int>.selfField), null, sfg_object }; yield return new object[] { typeof(FI_StaticGenericField<>), typeof(FI_GenericClass<object>), nameof(FI_GenericClassField<int>.selfField), null, sfg_g_object }; } [Theory] [MemberData(nameof(FieldInfoRTGenericTests_TestData))] public static void SetValue_Generic(Type openType, Type gaType, string fieldName, object initialValue, object changedValue) { Type type = openType.MakeGenericType(gaType); object obj = Activator.CreateInstance(type); FieldInfo fi = GetField(type, fieldName); Assert.Equal(initialValue, fi.GetValue(obj)); fi.SetValue(obj, changedValue); Assert.Equal(changedValue, fi.GetValue(obj)); fi.SetValue(obj, null); Assert.Equal(initialValue, fi.GetValue(obj)); } private static FieldInfo GetField(Type type, string name) { return type.GetTypeInfo().DeclaredFields.FirstOrDefault(fieldInfo => fieldInfo.Name.Equals(name)); } public readonly int readonlyIntField = 1; public const int ConstIntField = 1222; public const string ConstStringField = "Hello"; public const char ConstCharField = 'c'; public const bool ConstBoolField = true; public const float ConstFloatField = (float)22 / 7; public const double ConstDoubleField = 22.33; public const long ConstInt64Field = 1000; public const byte ConstByteField = 0; public static int s_intField = 100; public static string s_stringField = "static"; public int intField = 101; public string stringField = "non static"; private int privateIntField = 1; private string privateStringField = "privateStringField"; [Attr(77, name = "AttrSimple"), Int32Attr(77, name = "Int32AttrSimple"), Int64Attr(77, name = "Int64AttrSimple"), StringAttr("hello", name = "StringAttrSimple"), EnumAttr(PublicEnum.Case1, name = "EnumAttrSimple"), TypeAttr(typeof(object), name = "TypeAttrSimple")] public string fieldWithAttributes = ""; private static object s_assemblyField1 = null; // Without keyword private static object s_assemblyField2 = null; // With private keyword protected static object s_assemblyField3 = null; // With protected keyword public static object s_assemblyField4 = null; // With public keyword internal static object s_assemblyField5 = null; // With internal keyword public static FI_GenericClass<int> g_int = new FI_GenericClass<int>(); public static FI_GenericClassField<int> pfg_int = new FI_GenericClassField<int>(); public static FI_StaticGenericField<int> sfg_int = new FI_StaticGenericField<int>(); public static int[] gpa_int = new int[] { 300, 400 }; public static FI_GenericClass<int>[] ga_int = new FI_GenericClass<int>[] { g_int }; public static FI_GenericClass<string> g_string = new FI_GenericClass<string>(); public static FI_GenericClassField<string> pfg_string = new FI_GenericClassField<string>(); public static FI_StaticGenericField<string> sfg_string = new FI_StaticGenericField<string>(); public static string[] gpa_string = new string[] { "forget", "about this" }; public static FI_GenericClass<string>[] ga_string = new FI_GenericClass<string>[] { g_string, g_string }; public static FI_GenericClass<object> g_object = new FI_GenericClass<object>(); public static FI_GenericClassField<object> pfg_object = new FI_GenericClassField<object>(); public static FI_StaticGenericField<object> sfg_object = new FI_StaticGenericField<object>(); public static object[] gpa_object = new object[] { "world", 300, g_object }; public static FI_GenericClass<object>[] ga_object = new FI_GenericClass<object>[] { g_object, g_object, g_object }; public static FI_GenericClass<FI_GenericClass<object>> g_g_object = new FI_GenericClass<FI_GenericClass<object>>(); public static FI_GenericClassField<FI_GenericClass<object>> pfg_g_object = new FI_GenericClassField<FI_GenericClass<object>>(); public static FI_StaticGenericField<FI_GenericClass<object>> sfg_g_object = new FI_StaticGenericField<FI_GenericClass<object>>(); public static FI_GenericClass<object>[] gpa_g_object = new FI_GenericClass<object>[] { g_object, g_object }; public static FI_GenericClass<FI_GenericClass<object>>[] ga_g_object = new FI_GenericClass<FI_GenericClass<object>>[] { g_g_object, g_g_object, g_g_object, g_g_object }; public class FI_BaseClass { } public class FI_SubClass : FI_BaseClass { } public interface FI_Interface { } public class FI_ClassWithInterface1 : FI_Interface { } public class FI_ClassWithInterface2 : FI_Interface { } public class FI_FieldArray { public FI_BaseClass[] aArray; public FI_SubClass[] bArray; public FI_Interface[] iArray; public int[] intArray; public object[] objectArray; } public class FI_GenericClass<T> { public FI_GenericClass() { } } public class FI_GenericClassField<T> { public T genparamField; public T[] gparrayField; public FI_GenericClass<T> dependField; public FI_GenericClass<T>[] arrayField; public FI_GenericClassField<T> selfField; } public class FI_StaticGenericField<T> { public static T genparamField; public static T[] gparrayField; public static FI_GenericClass<T> dependField; public static FI_GenericClass<T>[] arrayField; public static FI_StaticGenericField<T> selfField; } } }
namespace XenAdmin.Dialogs { partial class AssignLicenseDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { licenseServerNameTextBox.TextChanged -= licenseServerPortTextBox_TextChanged; licenseServerPortTextBox.TextChanged -= licenseServerNameTextBox_TextChanged; components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AssignLicenseDialog)); this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.mainLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.licenseServerLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.licenseServerNameLabel = new System.Windows.Forms.Label(); this.licenseServerNameTextBox = new System.Windows.Forms.TextBox(); this.colonLabel = new System.Windows.Forms.Label(); this.licenseServerPortTextBox = new System.Windows.Forms.TextBox(); this.mainLabel = new System.Windows.Forms.Label(); this.editionsGroupBox = new System.Windows.Forms.GroupBox(); this.editionLayoutPanel = new System.Windows.Forms.FlowLayoutPanel(); this.perSocketRadioButton = new System.Windows.Forms.RadioButton(); this.xenDesktopEnterpriseRadioButton = new System.Windows.Forms.RadioButton(); this.enterprisePerSocketRadioButton = new System.Windows.Forms.RadioButton(); this.enterprisePerUserRadioButton = new System.Windows.Forms.RadioButton(); this.desktopPlusRadioButton = new System.Windows.Forms.RadioButton(); this.desktopRadioButton = new System.Windows.Forms.RadioButton(); this.desktopCloudRadioButton = new System.Windows.Forms.RadioButton(); this.standardPerSocketRadioButton = new System.Windows.Forms.RadioButton(); this.buttonsLayoutPanel = new System.Windows.Forms.FlowLayoutPanel(); this.mainLayoutPanel.SuspendLayout(); this.licenseServerLayoutPanel.SuspendLayout(); this.editionsGroupBox.SuspendLayout(); this.editionLayoutPanel.SuspendLayout(); this.buttonsLayoutPanel.SuspendLayout(); this.SuspendLayout(); // // okButton // resources.ApplyResources(this.okButton, "okButton"); this.okButton.Name = "okButton"; this.okButton.UseVisualStyleBackColor = true; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.cancelButton, "cancelButton"); this.cancelButton.Name = "cancelButton"; this.cancelButton.UseVisualStyleBackColor = true; // // mainLayoutPanel // resources.ApplyResources(this.mainLayoutPanel, "mainLayoutPanel"); this.mainLayoutPanel.Controls.Add(this.licenseServerLayoutPanel, 0, 1); this.mainLayoutPanel.Controls.Add(this.mainLabel, 0, 0); this.mainLayoutPanel.Controls.Add(this.editionsGroupBox, 0, 2); this.mainLayoutPanel.Controls.Add(this.buttonsLayoutPanel, 0, 3); this.mainLayoutPanel.Name = "mainLayoutPanel"; // // licenseServerLayoutPanel // resources.ApplyResources(this.licenseServerLayoutPanel, "licenseServerLayoutPanel"); this.licenseServerLayoutPanel.Controls.Add(this.licenseServerNameLabel, 0, 0); this.licenseServerLayoutPanel.Controls.Add(this.licenseServerNameTextBox, 1, 0); this.licenseServerLayoutPanel.Controls.Add(this.colonLabel, 2, 0); this.licenseServerLayoutPanel.Controls.Add(this.licenseServerPortTextBox, 3, 0); this.licenseServerLayoutPanel.Name = "licenseServerLayoutPanel"; // // licenseServerNameLabel // resources.ApplyResources(this.licenseServerNameLabel, "licenseServerNameLabel"); this.licenseServerNameLabel.Name = "licenseServerNameLabel"; // // licenseServerNameTextBox // resources.ApplyResources(this.licenseServerNameTextBox, "licenseServerNameTextBox"); this.licenseServerNameTextBox.Name = "licenseServerNameTextBox"; // // colonLabel // resources.ApplyResources(this.colonLabel, "colonLabel"); this.colonLabel.Name = "colonLabel"; // // licenseServerPortTextBox // resources.ApplyResources(this.licenseServerPortTextBox, "licenseServerPortTextBox"); this.licenseServerPortTextBox.Name = "licenseServerPortTextBox"; // // mainLabel // resources.ApplyResources(this.mainLabel, "mainLabel"); this.mainLabel.Name = "mainLabel"; // // editionsGroupBox // resources.ApplyResources(this.editionsGroupBox, "editionsGroupBox"); this.editionsGroupBox.Controls.Add(this.editionLayoutPanel); this.editionsGroupBox.Name = "editionsGroupBox"; this.editionsGroupBox.TabStop = false; // // editionLayoutPanel // resources.ApplyResources(this.editionLayoutPanel, "editionLayoutPanel"); this.editionLayoutPanel.Controls.Add(this.perSocketRadioButton); this.editionLayoutPanel.Controls.Add(this.xenDesktopEnterpriseRadioButton); this.editionLayoutPanel.Controls.Add(this.enterprisePerSocketRadioButton); this.editionLayoutPanel.Controls.Add(this.enterprisePerUserRadioButton); this.editionLayoutPanel.Controls.Add(this.desktopPlusRadioButton); this.editionLayoutPanel.Controls.Add(this.desktopRadioButton); this.editionLayoutPanel.Controls.Add(this.desktopCloudRadioButton); this.editionLayoutPanel.Controls.Add(this.standardPerSocketRadioButton); this.editionLayoutPanel.Name = "editionLayoutPanel"; // // perSocketRadioButton // resources.ApplyResources(this.perSocketRadioButton, "perSocketRadioButton"); this.perSocketRadioButton.Checked = true; this.perSocketRadioButton.Name = "perSocketRadioButton"; this.perSocketRadioButton.TabStop = true; this.perSocketRadioButton.UseVisualStyleBackColor = true; // // xenDesktopEnterpriseRadioButton // resources.ApplyResources(this.xenDesktopEnterpriseRadioButton, "xenDesktopEnterpriseRadioButton"); this.xenDesktopEnterpriseRadioButton.Name = "xenDesktopEnterpriseRadioButton"; this.xenDesktopEnterpriseRadioButton.UseVisualStyleBackColor = true; // // enterprisePerSocketRadioButton // resources.ApplyResources(this.enterprisePerSocketRadioButton, "enterprisePerSocketRadioButton"); this.enterprisePerSocketRadioButton.Name = "enterprisePerSocketRadioButton"; this.enterprisePerSocketRadioButton.UseVisualStyleBackColor = true; // // enterprisePerUserRadioButton // resources.ApplyResources(this.enterprisePerUserRadioButton, "enterprisePerUserRadioButton"); this.enterprisePerUserRadioButton.Name = "enterprisePerUserRadioButton"; this.enterprisePerUserRadioButton.UseVisualStyleBackColor = true; // // desktopPlusRadioButton // resources.ApplyResources(this.desktopPlusRadioButton, "desktopPlusRadioButton"); this.desktopPlusRadioButton.Name = "desktopPlusRadioButton"; this.desktopPlusRadioButton.UseVisualStyleBackColor = true; // // desktopRadioButton // resources.ApplyResources(this.desktopRadioButton, "desktopRadioButton"); this.desktopRadioButton.Name = "desktopRadioButton"; this.desktopRadioButton.UseVisualStyleBackColor = true; // // desktopCloudRadioButton // resources.ApplyResources(this.desktopCloudRadioButton, "desktopCloudRadioButton"); this.desktopCloudRadioButton.Name = "desktopCloudRadioButton"; this.desktopCloudRadioButton.UseVisualStyleBackColor = true; // // standardPerSocketRadioButton // resources.ApplyResources(this.standardPerSocketRadioButton, "standardPerSocketRadioButton"); this.standardPerSocketRadioButton.Name = "standardPerSocketRadioButton"; this.standardPerSocketRadioButton.UseVisualStyleBackColor = true; // // buttonsLayoutPanel // resources.ApplyResources(this.buttonsLayoutPanel, "buttonsLayoutPanel"); this.buttonsLayoutPanel.Controls.Add(this.okButton); this.buttonsLayoutPanel.Controls.Add(this.cancelButton); this.buttonsLayoutPanel.Name = "buttonsLayoutPanel"; // // AssignLicenseDialog // this.AcceptButton = this.okButton; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.CancelButton = this.cancelButton; this.Controls.Add(this.mainLayoutPanel); this.Name = "AssignLicenseDialog"; this.Shown += new System.EventHandler(this.AssignLicenseDialog_Shown); this.mainLayoutPanel.ResumeLayout(false); this.mainLayoutPanel.PerformLayout(); this.licenseServerLayoutPanel.ResumeLayout(false); this.licenseServerLayoutPanel.PerformLayout(); this.editionsGroupBox.ResumeLayout(false); this.editionsGroupBox.PerformLayout(); this.editionLayoutPanel.ResumeLayout(false); this.editionLayoutPanel.PerformLayout(); this.buttonsLayoutPanel.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.TableLayoutPanel mainLayoutPanel; private System.Windows.Forms.Label mainLabel; private System.Windows.Forms.FlowLayoutPanel buttonsLayoutPanel; private System.Windows.Forms.TableLayoutPanel licenseServerLayoutPanel; private System.Windows.Forms.Label licenseServerNameLabel; private System.Windows.Forms.TextBox licenseServerNameTextBox; private System.Windows.Forms.TextBox licenseServerPortTextBox; private System.Windows.Forms.Label colonLabel; private System.Windows.Forms.GroupBox editionsGroupBox; private System.Windows.Forms.FlowLayoutPanel editionLayoutPanel; private System.Windows.Forms.RadioButton perSocketRadioButton; private System.Windows.Forms.RadioButton xenDesktopEnterpriseRadioButton; private System.Windows.Forms.RadioButton enterprisePerSocketRadioButton; private System.Windows.Forms.RadioButton enterprisePerUserRadioButton; private System.Windows.Forms.RadioButton desktopRadioButton; private System.Windows.Forms.RadioButton standardPerSocketRadioButton; private System.Windows.Forms.RadioButton desktopPlusRadioButton; private System.Windows.Forms.RadioButton desktopCloudRadioButton; } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { //Only contains static methods. Does not require serialization using System; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Security; using System.Runtime; [System.Runtime.InteropServices.ComVisible(true)] public static class Buffer { // Copies from one primitive array to another primitive array without // respecting types. This calls memmove internally. The count and // offset parameters here are in bytes. If you want to use traditional // array element indices and counts, use Array.Copy. [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count); // A very simple and efficient memmove that assumes all of the // parameter validation has already been done. The count and offset // parameters here are in bytes. If you want to use traditional // array element indices and counts, use Array.Copy. [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalBlockCopy(Array src, int srcOffsetBytes, Array dst, int dstOffsetBytes, int byteCount); // This is ported from the optimized CRT assembly in memchr.asm. The JIT generates // pretty good code here and this ends up being within a couple % of the CRT asm. // It is however cross platform as the CRT hasn't ported their fast version to 64-bit // platforms. // [System.Security.SecurityCritical] // auto-generated internal unsafe static int IndexOfByte(byte* src, byte value, int index, int count) { Contract.Assert(src != null, "src should not be null"); byte* pByte = src + index; // Align up the pointer to sizeof(int). while (((int)pByte & 3) != 0) { if (count == 0) return -1; else if (*pByte == value) return (int) (pByte - src); count--; pByte++; } // Fill comparer with value byte for comparisons // // comparer = 0/0/value/value uint comparer = (((uint)value << 8) + (uint)value); // comparer = value/value/value/value comparer = (comparer << 16) + comparer; // Run through buffer until we hit a 4-byte section which contains // the byte we're looking for or until we exhaust the buffer. while (count > 3) { // Test the buffer for presence of value. comparer contains the byte // replicated 4 times. uint t1 = *(uint*)pByte; t1 = t1 ^ comparer; uint t2 = 0x7efefeff + t1; t1 = t1 ^ 0xffffffff; t1 = t1 ^ t2; t1 = t1 & 0x81010100; // if t1 is zero then these 4-bytes don't contain a match if (t1 != 0) { // We've found a match for value, figure out which position it's in. int foundIndex = (int) (pByte - src); if (pByte[0] == value) return foundIndex; else if (pByte[1] == value) return foundIndex + 1; else if (pByte[2] == value) return foundIndex + 2; else if (pByte[3] == value) return foundIndex + 3; } count -= 4; pByte += 4; } // Catch any bytes that might be left at the tail of the buffer while (count > 0) { if (*pByte == value) return (int) (pByte - src); count--; pByte++; } // If we don't have a match return -1; return -1; } // Returns a bool to indicate if the array is of primitive data types // or not. [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool IsPrimitiveTypeArray(Array array); // Gets a particular byte out of the array. The array must be an // array of primitives. // // This essentially does the following: // return ((byte*)array) + index. // [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern byte _GetByte(Array array, int index); [System.Security.SecuritySafeCritical] // auto-generated public static byte GetByte(Array array, int index) { // Is the array present? if (array == null) throw new ArgumentNullException("array"); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), "array"); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) throw new ArgumentOutOfRangeException("index"); return _GetByte(array, index); } // Sets a particular byte in an the array. The array must be an // array of primitives. // // This essentially does the following: // *(((byte*)array) + index) = value. // [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _SetByte(Array array, int index, byte value); [System.Security.SecuritySafeCritical] // auto-generated public static void SetByte(Array array, int index, byte value) { // Is the array present? if (array == null) throw new ArgumentNullException("array"); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), "array"); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) throw new ArgumentOutOfRangeException("index"); // Make the FCall to do the work _SetByte(array, index, value); } // Gets a particular byte out of the array. The array must be an // array of primitives. // // This essentially does the following: // return array.length * sizeof(array.UnderlyingElementType). // [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int _ByteLength(Array array); [System.Security.SecuritySafeCritical] // auto-generated public static int ByteLength(Array array) { // Is the array present? if (array == null) throw new ArgumentNullException("array"); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), "array"); return _ByteLength(array); } [System.Security.SecurityCritical] // auto-generated internal unsafe static void ZeroMemory(byte* src, long len) { while(len-- > 0) *(src + len) = 0; } [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) { Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); Contract.Assert(dest.Length - destIndex >= len, "not enough bytes in dest"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. if (len==0) return; fixed(byte* pDest = dest) { Memcpy(pDest + destIndex, src + srcIndex, len); } } [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len) { Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); Contract.Assert(src.Length - srcIndex >= len, "not enough bytes in src"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. if (len==0) return; fixed(byte* pSrc = src) { Memcpy(pDest + destIndex, pSrc + srcIndex, len); } } // This is tricky to get right AND fast, so lets make it useful for the whole Fx. // E.g. System.Runtime.WindowsRuntime!WindowsRuntimeBufferExtensions.MemCopy uses it. // This method has a slightly different behavior on arm and other platforms. // On arm this method behaves like memcpy and does not handle overlapping buffers. // While on other platforms it behaves like memmove and handles overlapping buffers. // This behavioral difference is unfortunate but intentional because // 1. This method is given access to other internal dlls and this close to release we do not want to change it. // 2. It is difficult to get this right for arm and again due to release dates we would like to visit it later. [FriendAccessAllowed] [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if ARM [MethodImplAttribute(MethodImplOptions.InternalCall)] internal unsafe static extern void Memcpy(byte* dest, byte* src, int len); #else // ARM [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] internal unsafe static void Memcpy(byte* dest, byte* src, int len) { Contract.Assert(len >= 0, "Negative length in memcopy!"); Memmove(dest, src, (uint)len); } #endif // ARM // This method has different signature for x64 and other platforms and is done for performance reasons. [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if WIN64 internal unsafe static void Memmove(byte* dest, byte* src, ulong len) #else internal unsafe static void Memmove(byte* dest, byte* src, uint len) #endif { // P/Invoke into the native version when the buffers are overlapping and the copy needs to be performed backwards // This check can produce false positives for lengths greater than Int32.MaxInt. It is fine because we want to use PInvoke path for the large lengths anyway. #if WIN64 if ((ulong)dest - (ulong)src < len) goto PInvoke; #else if (((uint)dest - (uint)src) < len) goto PInvoke; #endif // // This is portable version of memcpy. It mirrors what the hand optimized assembly versions of memcpy typically do. // // Ideally, we would just use the cpblk IL instruction here. Unfortunately, cpblk IL instruction is not as efficient as // possible yet and so we have this implementation here for now. // switch (len) { case 0: return; case 1: *dest = *src; return; case 2: *(short *)dest = *(short *)src; return; case 3: *(short *)dest = *(short *)src; *(dest + 2) = *(src + 2); return; case 4: *(int *)dest = *(int *)src; return; case 5: *(int*)dest = *(int*)src; *(dest + 4) = *(src + 4); return; case 6: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); return; case 7: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); *(dest + 6) = *(src + 6); return; case 8: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif return; case 9: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(dest + 8) = *(src + 8); return; case 10: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(short*)(dest + 8) = *(short*)(src + 8); return; case 11: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(short*)(dest + 8) = *(short*)(src + 8); *(dest + 10) = *(src + 10); return; case 12: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); return; case 13: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(dest + 12) = *(src + 12); return; case 14: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); return; case 15: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); *(dest + 14) = *(src + 14); return; case 16: #if WIN64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif return; default: break; } // P/Invoke into the native version for large lengths if (len >= 512) goto PInvoke; if (((int)dest & 3) != 0) { if (((int)dest & 1) != 0) { *dest = *src; src++; dest++; len--; if (((int)dest & 2) == 0) goto Aligned; } *(short *)dest = *(short *)src; src += 2; dest += 2; len -= 2; Aligned: ; } #if WIN64 if (((int)dest & 4) != 0) { *(int *)dest = *(int *)src; src += 4; dest += 4; len -= 4; } #endif #if WIN64 ulong count = len / 16; #else uint count = len / 16; #endif while (count > 0) { #if WIN64 ((long*)dest)[0] = ((long*)src)[0]; ((long*)dest)[1] = ((long*)src)[1]; #else ((int*)dest)[0] = ((int*)src)[0]; ((int*)dest)[1] = ((int*)src)[1]; ((int*)dest)[2] = ((int*)src)[2]; ((int*)dest)[3] = ((int*)src)[3]; #endif dest += 16; src += 16; count--; } if ((len & 8) != 0) { #if WIN64 ((long*)dest)[0] = ((long*)src)[0]; #else ((int*)dest)[0] = ((int*)src)[0]; ((int*)dest)[1] = ((int*)src)[1]; #endif dest += 8; src += 8; } if ((len & 4) != 0) { ((int*)dest)[0] = ((int*)src)[0]; dest += 4; src += 4; } if ((len & 2) != 0) { ((short*)dest)[0] = ((short*)src)[0]; dest += 2; src += 2; } if ((len & 1) != 0) *dest = *src; return; PInvoke: _Memmove(dest, src, len); } // Non-inlinable wrapper around the QCall that avoids poluting the fast path // with P/Invoke prolog/epilog. [SecurityCritical] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [MethodImplAttribute(MethodImplOptions.NoInlining)] #if WIN64 private unsafe static void _Memmove(byte* dest, byte* src, ulong len) #else private unsafe static void _Memmove(byte* dest, byte* src, uint len) #endif { __Memmove(dest, src, len); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [SecurityCritical] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if WIN64 extern private unsafe static void __Memmove(byte* dest, byte* src, ulong len); #else extern private unsafe static void __Memmove(byte* dest, byte* src, uint len); #endif // The attributes on this method are chosen for best JIT performance. // Please do not edit unless intentional. [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static unsafe void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceBytesToCopy); } #if WIN64 Memmove((byte*)destination, (byte*)source, checked((ulong) sourceBytesToCopy)); #else Memmove((byte*)destination, (byte*)source, checked((uint)sourceBytesToCopy)); #endif // WIN64 } // The attributes on this method are chosen for best JIT performance. // Please do not edit unless intentional. [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static unsafe void MemoryCopy(void* source, void* destination, ulong destinationSizeInBytes, ulong sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceBytesToCopy); } #if WIN64 Memmove((byte*)destination, (byte*)source, sourceBytesToCopy); #else Memmove((byte*)destination, (byte*)source, checked((uint)sourceBytesToCopy)); #endif // WIN64 } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; namespace Multiverse.ToolBox { public class Property { public string Name; public string Type; public string Default; public List<string> Enum; } public class NameValueTemplate { public string Name; public bool Waypoint = false; public bool Boundary = false; public bool Road = false; public bool Object = false; public bool SpawnGenerator = false; public bool Asset = false; public Dictionary<string, Property> properties; } public class NameValueTemplateCollection { Dictionary<string,NameValueTemplate> NameValueTemplates; public NameValueTemplateCollection(string directoryName) { NameValueTemplates = new Dictionary<string, NameValueTemplate>(); if (Directory.Exists(directoryName)) { foreach(string filename in Directory.GetFiles(directoryName)) { if (filename.EndsWith(".xml") || filename.EndsWith(".Xml") || filename.EndsWith(".XML")) { TextReader r = new StreamReader(filename); FromXML(r); r.Close(); } } } } public List<string> List(string type) { List<string> list = new List<string>(); foreach (string Name in NameValueTemplates.Keys) { NameValueTemplate template; NameValueTemplates.TryGetValue(Name, out template); if (template != null) { if ((String.Equals(type, "Region") && template.Boundary) || (String.Equals(type, "Object") && template.Object) || (String.Equals(type, "Marker") && template.Waypoint) || (String.Equals(type, "Road") && template.Road) || (String.Equals(type, "SpawnGenerator") && template.SpawnGenerator) || (String.Equals(type, "Asset") && template.Asset)) { list.Add(Name); } } } return list; } public List<string> NameValuePropertiesList(string templateName) { List<string> list = new List<string>(); NameValueTemplate template; if (NameValueTemplates.TryGetValue(templateName, out template)) { if (template != null) { foreach (string propertyName in template.properties.Keys) { list.Add(propertyName); } } } return list; } public string DefaultValue(string templateName, string propertyName) { NameValueTemplate template; Property prop; if (NameValueTemplates.TryGetValue(templateName, out template)) { if ((template != null) && (template.properties.TryGetValue(propertyName, out prop))) { if (prop.Default != null) { return prop.Default; } } } return ""; } public string PropertyType(string templateName, string propertyName) { NameValueTemplate template; Property prop; if (NameValueTemplates.TryGetValue(templateName, out template)) { if ((template != null) && (template.properties.TryGetValue(propertyName, out prop))) { return prop.Type; } } return ""; } public List<string> Enum(string typeName, string propertyName) { NameValueTemplate template; Property prop; if (NameValueTemplates.TryGetValue(typeName, out template)) { if (template.properties.TryGetValue(propertyName, out prop)) { return prop.Enum; } } return null; } protected string parseTextNode(XmlTextReader r) { // read the value r.Read(); if (r.NodeType == XmlNodeType.Whitespace) { while (r.NodeType == XmlNodeType.Whitespace) { r.Read(); } } if (r.NodeType != XmlNodeType.Text) { return (null); } string ret = r.Value; // error out if we dont see an end element here r.Read(); if (r.NodeType == XmlNodeType.Whitespace) { while (r.NodeType == XmlNodeType.Whitespace) { r.Read(); } } if (r.NodeType != XmlNodeType.EndElement) { // XXX - should generate an exception here? return (null); } return (ret); } protected List<string> parseEnum(XmlTextReader r) { List<string> list = new List<string>(); while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } if (r.NodeType == XmlNodeType.EndElement) { break; } if (r.NodeType == XmlNodeType.Element) { if (r.Name == "Value") { list.Add(parseTextNode(r)); } } if (r.NodeType != XmlNodeType.EndElement) { return null; } } return list; } protected Dictionary<string, Property> parseTypeProperties(XmlTextReader r) { Dictionary<string, Property> props = new Dictionary<string, Property>(); while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } if (r.NodeType == XmlNodeType.EndElement) { break; } if (r.NodeType == XmlNodeType.Element) { if (r.Name == "Property") { r.Read(); Property prop = parseTypeProperty(r); props.Add(prop.Name, prop); } } } return props; } protected Property parseTypeProperty(XmlTextReader r) { Property prop = new Property(); while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } if (r.NodeType == XmlNodeType.EndElement) { break; } if (r.NodeType == XmlNodeType.Element) { switch (r.Name) { case "Name": prop.Name = parseTextNode(r); break; case "Type": prop.Type = parseTextNode(r); break; case "Enums": prop.Enum = parseEnum(r); break; case "Default": prop.Default = parseTextNode(r); break; } } } return prop; } private void parseObjectTypes(XmlTextReader r, NameValueTemplate template) { while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } if (r.NodeType == XmlNodeType.Element) { switch (r.Name) { case "Marker": template.Waypoint = true; break; case "Region": template.Boundary = true; break; case "Road": template.Road = true; break; case "StaticObject": template.Object = true; break; case "SpawnGenerator": template.SpawnGenerator = true; break; } } if (r.NodeType == XmlNodeType.EndElement) { break; } } } protected Dictionary<string, NameValueTemplate> parseTemplate(XmlTextReader r) { NameValueTemplate template = new NameValueTemplate(); while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } if (r.NodeType == XmlNodeType.Element) { switch (r.Name) { case "Name": template.Name = parseTextNode(r); break; case "Properties": r.Read(); template.properties = parseTypeProperties(r); break; case "ObjectTypes": r.Read(); parseObjectTypes(r, template); break; } } } NameValueTemplates.Add(template.Name, template); return NameValueTemplates; } private void FromXML(TextReader t) { XmlTextReader r = new XmlTextReader(t); while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } // look for the start of the assets list if (r.NodeType == XmlNodeType.Element) { if (r.Name == "NameValueTemplate") { // we found the list of assets, now parse it parseTemplate(r); } } } } } }
/* * 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: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT 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; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// /// First published in XenServer 4.1. /// </summary> public partial class Bond : XenObject<Bond> { #region Constructors public Bond() { } public Bond(string uuid, XenRef<PIF> master, List<XenRef<PIF>> slaves, Dictionary<string, string> other_config, XenRef<PIF> primary_slave, bond_mode mode, Dictionary<string, string> properties, long links_up, bool auto_update_mac) { this.uuid = uuid; this.master = master; this.slaves = slaves; this.other_config = other_config; this.primary_slave = primary_slave; this.mode = mode; this.properties = properties; this.links_up = links_up; this.auto_update_mac = auto_update_mac; } /// <summary> /// Creates a new Bond from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Bond(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Bond from a Proxy_Bond. /// </summary> /// <param name="proxy"></param> public Bond(Proxy_Bond proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Bond. /// </summary> public override void UpdateFrom(Bond record) { uuid = record.uuid; master = record.master; slaves = record.slaves; other_config = record.other_config; primary_slave = record.primary_slave; mode = record.mode; properties = record.properties; links_up = record.links_up; auto_update_mac = record.auto_update_mac; } internal void UpdateFrom(Proxy_Bond proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; master = proxy.master == null ? null : XenRef<PIF>.Create(proxy.master); slaves = proxy.slaves == null ? null : XenRef<PIF>.Create(proxy.slaves); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); primary_slave = proxy.primary_slave == null ? null : XenRef<PIF>.Create(proxy.primary_slave); mode = proxy.mode == null ? (bond_mode) 0 : (bond_mode)Helper.EnumParseDefault(typeof(bond_mode), (string)proxy.mode); properties = proxy.properties == null ? null : Maps.convert_from_proxy_string_string(proxy.properties); links_up = proxy.links_up == null ? 0 : long.Parse(proxy.links_up); auto_update_mac = (bool)proxy.auto_update_mac; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Bond /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("master")) master = Marshalling.ParseRef<PIF>(table, "master"); if (table.ContainsKey("slaves")) slaves = Marshalling.ParseSetRef<PIF>(table, "slaves"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("primary_slave")) primary_slave = Marshalling.ParseRef<PIF>(table, "primary_slave"); if (table.ContainsKey("mode")) mode = (bond_mode)Helper.EnumParseDefault(typeof(bond_mode), Marshalling.ParseString(table, "mode")); if (table.ContainsKey("properties")) properties = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "properties")); if (table.ContainsKey("links_up")) links_up = Marshalling.ParseLong(table, "links_up"); if (table.ContainsKey("auto_update_mac")) auto_update_mac = Marshalling.ParseBool(table, "auto_update_mac"); } public Proxy_Bond ToProxy() { Proxy_Bond result_ = new Proxy_Bond(); result_.uuid = uuid ?? ""; result_.master = master ?? ""; result_.slaves = slaves == null ? new string[] {} : Helper.RefListToStringArray(slaves); result_.other_config = Maps.convert_to_proxy_string_string(other_config); result_.primary_slave = primary_slave ?? ""; result_.mode = bond_mode_helper.ToString(mode); result_.properties = Maps.convert_to_proxy_string_string(properties); result_.links_up = links_up.ToString(); result_.auto_update_mac = auto_update_mac; return result_; } public bool DeepEquals(Bond other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._master, other._master) && Helper.AreEqual2(this._slaves, other._slaves) && Helper.AreEqual2(this._other_config, other._other_config) && Helper.AreEqual2(this._primary_slave, other._primary_slave) && Helper.AreEqual2(this._mode, other._mode) && Helper.AreEqual2(this._properties, other._properties) && Helper.AreEqual2(this._links_up, other._links_up) && Helper.AreEqual2(this._auto_update_mac, other._auto_update_mac); } public override string SaveChanges(Session session, string opaqueRef, Bond server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { Bond.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given Bond. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> public static Bond get_record(Session session, string _bond) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_record(session.opaque_ref, _bond); else return new Bond(session.XmlRpcProxy.bond_get_record(session.opaque_ref, _bond ?? "").parse()); } /// <summary> /// Get a reference to the Bond instance with the specified UUID. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Bond> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Bond>.Create(session.XmlRpcProxy.bond_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given Bond. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> public static string get_uuid(Session session, string _bond) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_uuid(session.opaque_ref, _bond); else return session.XmlRpcProxy.bond_get_uuid(session.opaque_ref, _bond ?? "").parse(); } /// <summary> /// Get the master field of the given Bond. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> public static XenRef<PIF> get_master(Session session, string _bond) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_master(session.opaque_ref, _bond); else return XenRef<PIF>.Create(session.XmlRpcProxy.bond_get_master(session.opaque_ref, _bond ?? "").parse()); } /// <summary> /// Get the slaves field of the given Bond. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> public static List<XenRef<PIF>> get_slaves(Session session, string _bond) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_slaves(session.opaque_ref, _bond); else return XenRef<PIF>.Create(session.XmlRpcProxy.bond_get_slaves(session.opaque_ref, _bond ?? "").parse()); } /// <summary> /// Get the other_config field of the given Bond. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> public static Dictionary<string, string> get_other_config(Session session, string _bond) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_other_config(session.opaque_ref, _bond); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.bond_get_other_config(session.opaque_ref, _bond ?? "").parse()); } /// <summary> /// Get the primary_slave field of the given Bond. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> public static XenRef<PIF> get_primary_slave(Session session, string _bond) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_primary_slave(session.opaque_ref, _bond); else return XenRef<PIF>.Create(session.XmlRpcProxy.bond_get_primary_slave(session.opaque_ref, _bond ?? "").parse()); } /// <summary> /// Get the mode field of the given Bond. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> public static bond_mode get_mode(Session session, string _bond) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_mode(session.opaque_ref, _bond); else return (bond_mode)Helper.EnumParseDefault(typeof(bond_mode), (string)session.XmlRpcProxy.bond_get_mode(session.opaque_ref, _bond ?? "").parse()); } /// <summary> /// Get the properties field of the given Bond. /// First published in XenServer 6.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> public static Dictionary<string, string> get_properties(Session session, string _bond) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_properties(session.opaque_ref, _bond); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.bond_get_properties(session.opaque_ref, _bond ?? "").parse()); } /// <summary> /// Get the links_up field of the given Bond. /// First published in XenServer 6.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> public static long get_links_up(Session session, string _bond) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_links_up(session.opaque_ref, _bond); else return long.Parse(session.XmlRpcProxy.bond_get_links_up(session.opaque_ref, _bond ?? "").parse()); } /// <summary> /// Get the auto_update_mac field of the given Bond. /// First published in Citrix Hypervisor 8.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> public static bool get_auto_update_mac(Session session, string _bond) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_auto_update_mac(session.opaque_ref, _bond); else return (bool)session.XmlRpcProxy.bond_get_auto_update_mac(session.opaque_ref, _bond ?? "").parse(); } /// <summary> /// Set the other_config field of the given Bond. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _bond, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.bond_set_other_config(session.opaque_ref, _bond, _other_config); else session.XmlRpcProxy.bond_set_other_config(session.opaque_ref, _bond ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given Bond. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _bond, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.bond_add_to_other_config(session.opaque_ref, _bond, _key, _value); else session.XmlRpcProxy.bond_add_to_other_config(session.opaque_ref, _bond ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given Bond. If the key is not in that Map, then do nothing. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _bond, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.bond_remove_from_other_config(session.opaque_ref, _bond, _key); else session.XmlRpcProxy.bond_remove_from_other_config(session.opaque_ref, _bond ?? "", _key ?? "").parse(); } /// <summary> /// Create an interface bond /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_network">Network to add the bonded PIF to</param> /// <param name="_members">PIFs to add to this bond</param> /// <param name="_mac">The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave.</param> public static XenRef<Bond> create(Session session, string _network, List<XenRef<PIF>> _members, string _mac) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_create(session.opaque_ref, _network, _members, _mac); else return XenRef<Bond>.Create(session.XmlRpcProxy.bond_create(session.opaque_ref, _network ?? "", _members == null ? new string[] {} : Helper.RefListToStringArray(_members), _mac ?? "").parse()); } /// <summary> /// Create an interface bond /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_network">Network to add the bonded PIF to</param> /// <param name="_members">PIFs to add to this bond</param> /// <param name="_mac">The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave.</param> public static XenRef<Task> async_create(Session session, string _network, List<XenRef<PIF>> _members, string _mac) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_bond_create(session.opaque_ref, _network, _members, _mac); else return XenRef<Task>.Create(session.XmlRpcProxy.async_bond_create(session.opaque_ref, _network ?? "", _members == null ? new string[] {} : Helper.RefListToStringArray(_members), _mac ?? "").parse()); } /// <summary> /// Create an interface bond /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_network">Network to add the bonded PIF to</param> /// <param name="_members">PIFs to add to this bond</param> /// <param name="_mac">The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave.</param> /// <param name="_mode">Bonding mode to use for the new bond First published in XenServer 6.0.</param> public static XenRef<Bond> create(Session session, string _network, List<XenRef<PIF>> _members, string _mac, bond_mode _mode) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_create(session.opaque_ref, _network, _members, _mac, _mode); else return XenRef<Bond>.Create(session.XmlRpcProxy.bond_create(session.opaque_ref, _network ?? "", _members == null ? new string[] {} : Helper.RefListToStringArray(_members), _mac ?? "", bond_mode_helper.ToString(_mode)).parse()); } /// <summary> /// Create an interface bond /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_network">Network to add the bonded PIF to</param> /// <param name="_members">PIFs to add to this bond</param> /// <param name="_mac">The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave.</param> /// <param name="_mode">Bonding mode to use for the new bond First published in XenServer 6.0.</param> public static XenRef<Task> async_create(Session session, string _network, List<XenRef<PIF>> _members, string _mac, bond_mode _mode) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_bond_create(session.opaque_ref, _network, _members, _mac, _mode); else return XenRef<Task>.Create(session.XmlRpcProxy.async_bond_create(session.opaque_ref, _network ?? "", _members == null ? new string[] {} : Helper.RefListToStringArray(_members), _mac ?? "", bond_mode_helper.ToString(_mode)).parse()); } /// <summary> /// Create an interface bond /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_network">Network to add the bonded PIF to</param> /// <param name="_members">PIFs to add to this bond</param> /// <param name="_mac">The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave.</param> /// <param name="_mode">Bonding mode to use for the new bond First published in XenServer 6.0.</param> /// <param name="_properties">Additional configuration parameters specific to the bond mode First published in XenServer 6.1.</param> public static XenRef<Bond> create(Session session, string _network, List<XenRef<PIF>> _members, string _mac, bond_mode _mode, Dictionary<string, string> _properties) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_create(session.opaque_ref, _network, _members, _mac, _mode, _properties); else return XenRef<Bond>.Create(session.XmlRpcProxy.bond_create(session.opaque_ref, _network ?? "", _members == null ? new string[] {} : Helper.RefListToStringArray(_members), _mac ?? "", bond_mode_helper.ToString(_mode), Maps.convert_to_proxy_string_string(_properties)).parse()); } /// <summary> /// Create an interface bond /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_network">Network to add the bonded PIF to</param> /// <param name="_members">PIFs to add to this bond</param> /// <param name="_mac">The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave.</param> /// <param name="_mode">Bonding mode to use for the new bond First published in XenServer 6.0.</param> /// <param name="_properties">Additional configuration parameters specific to the bond mode First published in XenServer 6.1.</param> public static XenRef<Task> async_create(Session session, string _network, List<XenRef<PIF>> _members, string _mac, bond_mode _mode, Dictionary<string, string> _properties) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_bond_create(session.opaque_ref, _network, _members, _mac, _mode, _properties); else return XenRef<Task>.Create(session.XmlRpcProxy.async_bond_create(session.opaque_ref, _network ?? "", _members == null ? new string[] {} : Helper.RefListToStringArray(_members), _mac ?? "", bond_mode_helper.ToString(_mode), Maps.convert_to_proxy_string_string(_properties)).parse()); } /// <summary> /// Destroy an interface bond /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> public static void destroy(Session session, string _bond) { if (session.JsonRpcClient != null) session.JsonRpcClient.bond_destroy(session.opaque_ref, _bond); else session.XmlRpcProxy.bond_destroy(session.opaque_ref, _bond ?? "").parse(); } /// <summary> /// Destroy an interface bond /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> public static XenRef<Task> async_destroy(Session session, string _bond) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_bond_destroy(session.opaque_ref, _bond); else return XenRef<Task>.Create(session.XmlRpcProxy.async_bond_destroy(session.opaque_ref, _bond ?? "").parse()); } /// <summary> /// Change the bond mode /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> /// <param name="_value">The new bond mode</param> public static void set_mode(Session session, string _bond, bond_mode _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.bond_set_mode(session.opaque_ref, _bond, _value); else session.XmlRpcProxy.bond_set_mode(session.opaque_ref, _bond ?? "", bond_mode_helper.ToString(_value)).parse(); } /// <summary> /// Change the bond mode /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> /// <param name="_value">The new bond mode</param> public static XenRef<Task> async_set_mode(Session session, string _bond, bond_mode _value) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_bond_set_mode(session.opaque_ref, _bond, _value); else return XenRef<Task>.Create(session.XmlRpcProxy.async_bond_set_mode(session.opaque_ref, _bond ?? "", bond_mode_helper.ToString(_value)).parse()); } /// <summary> /// Set the value of a property of the bond /// First published in XenServer 6.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> /// <param name="_name">The property name</param> /// <param name="_value">The property value</param> public static void set_property(Session session, string _bond, string _name, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.bond_set_property(session.opaque_ref, _bond, _name, _value); else session.XmlRpcProxy.bond_set_property(session.opaque_ref, _bond ?? "", _name ?? "", _value ?? "").parse(); } /// <summary> /// Set the value of a property of the bond /// First published in XenServer 6.1. /// </summary> /// <param name="session">The session</param> /// <param name="_bond">The opaque_ref of the given bond</param> /// <param name="_name">The property name</param> /// <param name="_value">The property value</param> public static XenRef<Task> async_set_property(Session session, string _bond, string _name, string _value) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_bond_set_property(session.opaque_ref, _bond, _name, _value); else return XenRef<Task>.Create(session.XmlRpcProxy.async_bond_set_property(session.opaque_ref, _bond ?? "", _name ?? "", _value ?? "").parse()); } /// <summary> /// Return a list of all the Bonds known to the system. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Bond>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_all(session.opaque_ref); else return XenRef<Bond>.Create(session.XmlRpcProxy.bond_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the Bond Records at once, in a single XML RPC call /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Bond>, Bond> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.bond_get_all_records(session.opaque_ref); else return XenRef<Bond>.Create<Proxy_Bond>(session.XmlRpcProxy.bond_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// The bonded interface /// </summary> [JsonConverter(typeof(XenRefConverter<PIF>))] public virtual XenRef<PIF> master { get { return _master; } set { if (!Helper.AreEqual(value, _master)) { _master = value; NotifyPropertyChanged("master"); } } } private XenRef<PIF> _master = new XenRef<PIF>(Helper.NullOpaqueRef); /// <summary> /// The interfaces which are part of this bond /// </summary> [JsonConverter(typeof(XenRefListConverter<PIF>))] public virtual List<XenRef<PIF>> slaves { get { return _slaves; } set { if (!Helper.AreEqual(value, _slaves)) { _slaves = value; NotifyPropertyChanged("slaves"); } } } private List<XenRef<PIF>> _slaves = new List<XenRef<PIF>>() {}; /// <summary> /// additional configuration /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; /// <summary> /// The PIF of which the IP configuration and MAC were copied to the bond, and which will receive all configuration/VLANs/VIFs on the bond if the bond is destroyed /// First published in XenServer 6.0. /// </summary> [JsonConverter(typeof(XenRefConverter<PIF>))] public virtual XenRef<PIF> primary_slave { get { return _primary_slave; } set { if (!Helper.AreEqual(value, _primary_slave)) { _primary_slave = value; NotifyPropertyChanged("primary_slave"); } } } private XenRef<PIF> _primary_slave = new XenRef<PIF>("OpaqueRef:NULL"); /// <summary> /// The algorithm used to distribute traffic among the bonded NICs /// First published in XenServer 6.0. /// </summary> [JsonConverter(typeof(bond_modeConverter))] public virtual bond_mode mode { get { return _mode; } set { if (!Helper.AreEqual(value, _mode)) { _mode = value; NotifyPropertyChanged("mode"); } } } private bond_mode _mode = bond_mode.balance_slb; /// <summary> /// Additional configuration properties specific to the bond mode. /// First published in XenServer 6.1. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> properties { get { return _properties; } set { if (!Helper.AreEqual(value, _properties)) { _properties = value; NotifyPropertyChanged("properties"); } } } private Dictionary<string, string> _properties = new Dictionary<string, string>() {}; /// <summary> /// Number of links up in this bond /// First published in XenServer 6.1. /// </summary> public virtual long links_up { get { return _links_up; } set { if (!Helper.AreEqual(value, _links_up)) { _links_up = value; NotifyPropertyChanged("links_up"); } } } private long _links_up = 0; /// <summary> /// true if the MAC was taken from the primary slave when the bond was created, and false if the client specified the MAC /// First published in Citrix Hypervisor 8.1. /// </summary> public virtual bool auto_update_mac { get { return _auto_update_mac; } set { if (!Helper.AreEqual(value, _auto_update_mac)) { _auto_update_mac = value; NotifyPropertyChanged("auto_update_mac"); } } } private bool _auto_update_mac = true; } }
//******************************* // Created By Rocher Kong // Github https://github.com/RocherKong // Date 2018.02.09 //******************************* using IP2Region.Models; using System; using System.IO; using System.Text; using System.Threading.Tasks; namespace IP2Region { public class DbSearcher : IDisposable { const int BTREE_ALGORITHM = 1; const int BINARY_ALGORITHM = 2; const int MEMORY_ALGORITYM = 3; private DbConfig _dbConfig = null; /// <summary> /// db file access handler /// </summary> private Stream _raf = null; /// <summary> /// header blocks buffer /// </summary> private long[] _headerSip = null; private int[] _headerPtr = null; private int _headerLength; /// <summary> /// super blocks info /// </summary> private long _firstIndexPtr = 0; private long _lastIndexPtr = 0; private int _totalIndexBlocks = 0; /// <summary> /// for memory mode /// the original db binary string /// </summary> private byte[] _dbBinStr = null; /// <summary> /// Get by index ptr. /// </summary> private DataBlock GetByIndexPtr(long ptr) { _raf.Seek(ptr, SeekOrigin.Begin); byte[] buffer = new byte[12]; _raf.Read(buffer, 0, buffer.Length); long extra = Utils.GetIntLong(buffer, 8); int dataLen = (int)((extra >> 24) & 0xFF); int dataPtr = (int)((extra & 0x00FFFFFF)); _raf.Seek(dataPtr, SeekOrigin.Begin); byte[] data = new byte[dataLen]; _raf.Read(data, 0, data.Length); int city_id = (int)Utils.GetIntLong(data, 0); string region = Encoding.UTF8.GetString(data, 4, data.Length - 4); return new DataBlock(city_id, region, dataPtr); } public DbSearcher(DbConfig dbConfig, string dbFile) { if (_dbConfig == null) { _dbConfig = dbConfig; } _raf = new FileStream(dbFile, FileMode.Open, FileAccess.Read, FileShare.Read); } public DbSearcher(string dbFile) : this(null, dbFile) { } public DbSearcher(DbConfig dbConfig, Stream dbFileStream) { if (_dbConfig == null) { _dbConfig = dbConfig; } _raf = dbFileStream; } public DbSearcher(Stream dbFileStream) : this(null, dbFileStream) { } #region Sync Methods /// <summary> /// Get the region with a int ip address with memory binary search algorithm. /// </summary> private DataBlock MemorySearch(long ip) { int blen = IndexBlock.LENGTH; if (_dbBinStr == null) { _dbBinStr = new byte[(int)_raf.Length]; _raf.Seek(0L, SeekOrigin.Begin); _raf.Read(_dbBinStr, 0, _dbBinStr.Length); //initialize the global vars _firstIndexPtr = Utils.GetIntLong(_dbBinStr, 0); _lastIndexPtr = Utils.GetIntLong(_dbBinStr, 4); _totalIndexBlocks = (int)((_lastIndexPtr - _firstIndexPtr) / blen) + 1; } //search the index blocks to define the data int l = 0, h = _totalIndexBlocks; long sip = 0; while (l <= h) { int m = (l + h) >> 1; int p = (int)(_firstIndexPtr + m * blen); sip = Utils.GetIntLong(_dbBinStr, p); if (ip < sip) { h = m - 1; } else { sip = Utils.GetIntLong(_dbBinStr, p + 4); if (ip > sip) { l = m + 1; } else { sip = Utils.GetIntLong(_dbBinStr, p + 8); break; } } } //not matched if (sip == 0) return null; //get the data int dataLen = (int)((sip >> 24) & 0xFF); int dataPtr = (int)((sip & 0x00FFFFFF)); int city_id = (int)Utils.GetIntLong(_dbBinStr, dataPtr); string region = Encoding.UTF8.GetString(_dbBinStr, dataPtr + 4, dataLen - 4);//new String(dbBinStr, dataPtr + 4, dataLen - 4, Encoding.UTF8); return new DataBlock(city_id, region, dataPtr); } /// <summary> /// Get the region throught the ip address with memory binary search algorithm. /// </summary> public DataBlock MemorySearch(string ip) { return MemorySearch(Utils.Ip2long(ip)); } /// <summary> /// Get the region with a int ip address with b-tree algorithm. /// </summary> private DataBlock BtreeSearch(long ip) { //check and load the header if (_headerSip == null) { _raf.Seek(8L, SeekOrigin.Begin); //pass the super block byte[] b = new byte[4096]; _raf.Read(b, 0, b.Length); //fill the header int len = b.Length >> 3, idx = 0; //b.lenght / 8 _headerSip = new long[len]; _headerPtr = new int[len]; long startIp, dataPtrTemp; for (int i = 0; i < b.Length; i += 8) { startIp = Utils.GetIntLong(b, i); dataPtrTemp = Utils.GetIntLong(b, i + 4); if (dataPtrTemp == 0) break; _headerSip[idx] = startIp; _headerPtr[idx] = (int)dataPtrTemp; idx++; } _headerLength = idx; } //1. define the index block with the binary search if (ip == _headerSip[0]) { return GetByIndexPtr(_headerPtr[0]); } else if (ip == _headerPtr[_headerLength - 1]) { return GetByIndexPtr(_headerPtr[_headerLength - 1]); } int l = 0, h = _headerLength, sptr = 0, eptr = 0; int m = 0; while (l <= h) { m = (l + h) >> 1; //perfectly matched, just return it if (ip == _headerSip[m]) { if (m > 0) { sptr = _headerPtr[m - 1]; eptr = _headerPtr[m]; } else { sptr = _headerPtr[m]; eptr = _headerPtr[m + 1]; } } //less then the middle value else if (ip < _headerSip[m]) { if (m == 0) { sptr = _headerPtr[m]; eptr = _headerPtr[m + 1]; break; } else if (ip > _headerSip[m - 1]) { sptr = _headerPtr[m - 1]; eptr = _headerPtr[m]; break; } h = m - 1; } else { if (m == _headerLength - 1) { sptr = _headerPtr[m - 1]; eptr = _headerPtr[m]; break; } else if (ip <= _headerSip[m + 1]) { sptr = _headerPtr[m]; eptr = _headerPtr[m + 1]; break; } l = m + 1; } } //match nothing just stop it if (sptr == 0) return null; //2. search the index blocks to define the data int blockLen = eptr - sptr, blen = IndexBlock.LENGTH; byte[] iBuffer = new byte[blockLen + blen]; //include the right border block _raf.Seek(sptr, SeekOrigin.Begin); _raf.Read(iBuffer, 0, iBuffer.Length); l = 0; h = blockLen / blen; long sip = 0; int p = 0; while (l <= h) { m = (l + h) >> 1; p = m * blen; sip = Utils.GetIntLong(iBuffer, p); if (ip < sip) { h = m - 1; } else { sip = Utils.GetIntLong(iBuffer, p + 4); if (ip > sip) { l = m + 1; } else { sip = Utils.GetIntLong(iBuffer, p + 8); break; } } } //not matched if (sip == 0) return null; //3. get the data int dataLen = (int)((sip >> 24) & 0xFF); int dataPtr = (int)((sip & 0x00FFFFFF)); _raf.Seek(dataPtr, SeekOrigin.Begin); byte[] data = new byte[dataLen]; _raf.Read(data, 0, data.Length); int city_id = (int)Utils.GetIntLong(data, 0); String region = Encoding.UTF8.GetString(data, 4, data.Length - 4);// new String(data, 4, data.Length - 4, "UTF-8"); return new DataBlock(city_id, region, dataPtr); } /// <summary> /// Get the region throught the ip address with b-tree search algorithm. /// </summary> public DataBlock BtreeSearch(string ip) { return BtreeSearch(Utils.Ip2long(ip)); } /// <summary> /// Get the region with a int ip address with binary search algorithm. /// </summary> private DataBlock BinarySearch(long ip) { int blen = IndexBlock.LENGTH; if (_totalIndexBlocks == 0) { _raf.Seek(0L, SeekOrigin.Begin); byte[] superBytes = new byte[8]; _raf.Read(superBytes, 0, superBytes.Length); //initialize the global vars _firstIndexPtr = Utils.GetIntLong(superBytes, 0); _lastIndexPtr = Utils.GetIntLong(superBytes, 4); _totalIndexBlocks = (int)((_lastIndexPtr - _firstIndexPtr) / blen) + 1; } //search the index blocks to define the data int l = 0, h = _totalIndexBlocks; byte[] buffer = new byte[blen]; long sip = 0; while (l <= h) { int m = (l + h) >> 1; _raf.Seek(_firstIndexPtr + m * blen, SeekOrigin.Begin); //set the file pointer _raf.Read(buffer, 0, buffer.Length); sip = Utils.GetIntLong(buffer, 0); if (ip < sip) { h = m - 1; } else { sip = Utils.GetIntLong(buffer, 4); if (ip > sip) { l = m + 1; } else { sip = Utils.GetIntLong(buffer, 8); break; } } } //not matched if (sip == 0) return null; //get the data int dataLen = (int)((sip >> 24) & 0xFF); int dataPtr = (int)((sip & 0x00FFFFFF)); _raf.Seek(dataPtr, SeekOrigin.Begin); byte[] data = new byte[dataLen]; _raf.Read(data, 0, data.Length); int city_id = (int)Utils.GetIntLong(data, 0); String region = Encoding.UTF8.GetString(data, 4, data.Length - 4);//new String(data, 4, data.Length - 4, "UTF-8"); return new DataBlock(city_id, region, dataPtr); } /// <summary> /// Get the region throught the ip address with binary search algorithm. /// </summary> public DataBlock BinarySearch(String ip) { return BinarySearch(Utils.Ip2long(ip)); } #endregion #region Async Methods /// <summary> /// Get the region throught the ip address with memory binary search algorithm. /// </summary> public Task<DataBlock> MemorySearchAsync(string ip) { return Task.FromResult(MemorySearch(ip)); } /// <summary> /// Get the region throught the ip address with b-tree search algorithm. /// </summary> public Task<DataBlock> BtreeSearchAsync(string ip) { return Task.FromResult(BtreeSearch(ip)); } /// <summary> /// Get the region throught the ip address with binary search algorithm. /// </summary> public Task<DataBlock> BinarySearchAsync(string ip) { return Task.FromResult(BinarySearch(ip)); } #endregion /// <summary> /// Close the db. /// </summary> public void Close() { _headerSip = null; _headerPtr = null; _dbBinStr = null; _raf.Close(); } public void Dispose() { Close(); } } }
/* * Copyright 2010-2013 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. */ using System.Collections.Generic; using Amazon.Redshift.Model; using Amazon.Runtime.Internal.Transform; namespace Amazon.Redshift.Model.Internal.MarshallTransformations { /// <summary> /// Cluster Unmarshaller /// </summary> internal class ClusterUnmarshaller : IUnmarshaller<Cluster, XmlUnmarshallerContext>, IUnmarshaller<Cluster, JsonUnmarshallerContext> { public Cluster Unmarshall(XmlUnmarshallerContext context) { Cluster cluster = new Cluster(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; if (context.IsStartOfDocument) targetDepth++; while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("ClusterIdentifier", targetDepth)) { cluster.ClusterIdentifier = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("NodeType", targetDepth)) { cluster.NodeType = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("ClusterStatus", targetDepth)) { cluster.ClusterStatus = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("ModifyStatus", targetDepth)) { cluster.ModifyStatus = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("MasterUsername", targetDepth)) { cluster.MasterUsername = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("DBName", targetDepth)) { cluster.DBName = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("Endpoint", targetDepth)) { cluster.Endpoint = EndpointUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("ClusterCreateTime", targetDepth)) { cluster.ClusterCreateTime = DateTimeUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("AutomatedSnapshotRetentionPeriod", targetDepth)) { cluster.AutomatedSnapshotRetentionPeriod = IntUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("ClusterSecurityGroups/ClusterSecurityGroup", targetDepth)) { cluster.ClusterSecurityGroups.Add(ClusterSecurityGroupMembershipUnmarshaller.GetInstance().Unmarshall(context)); continue; } if (context.TestExpression("VpcSecurityGroups/VpcSecurityGroup", targetDepth)) { cluster.VpcSecurityGroups.Add(VpcSecurityGroupMembershipUnmarshaller.GetInstance().Unmarshall(context)); continue; } if (context.TestExpression("ClusterParameterGroups/ClusterParameterGroup", targetDepth)) { cluster.ClusterParameterGroups.Add(ClusterParameterGroupStatusUnmarshaller.GetInstance().Unmarshall(context)); continue; } if (context.TestExpression("ClusterSubnetGroupName", targetDepth)) { cluster.ClusterSubnetGroupName = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("VpcId", targetDepth)) { cluster.VpcId = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("AvailabilityZone", targetDepth)) { cluster.AvailabilityZone = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("PreferredMaintenanceWindow", targetDepth)) { cluster.PreferredMaintenanceWindow = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("PendingModifiedValues", targetDepth)) { cluster.PendingModifiedValues = PendingModifiedValuesUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("ClusterVersion", targetDepth)) { cluster.ClusterVersion = StringUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("AllowVersionUpgrade", targetDepth)) { cluster.AllowVersionUpgrade = BoolUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("NumberOfNodes", targetDepth)) { cluster.NumberOfNodes = IntUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("PubliclyAccessible", targetDepth)) { cluster.PubliclyAccessible = BoolUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("Encrypted", targetDepth)) { cluster.Encrypted = BoolUnmarshaller.GetInstance().Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return cluster; } } return cluster; } public Cluster Unmarshall(JsonUnmarshallerContext context) { return null; } private static ClusterUnmarshaller instance; public static ClusterUnmarshaller GetInstance() { if (instance == null) instance = new ClusterUnmarshaller(); return instance; } } }
// 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.Diagnostics; using System.Runtime.InteropServices; namespace System.Drawing.Internal { /// <summary> /// Represents a Win32 device context. Provides operations for setting some of the properties of a device context. /// It's the managed wrapper for an HDC. /// /// This class is divided into two files separating the code that needs to be compiled into retail builds and /// debugging code. /// </summary> internal sealed partial class DeviceContext : MarshalByRefObject, IDeviceContext, IDisposable { /// <summary> /// This class is a wrapper to a Win32 device context, and the Hdc property is the way to get a /// handle to it. /// /// The hDc is released/deleted only when owned by the object, meaning it was created internally; /// in this case, the object is responsible for releasing/deleting it. /// In the case the object is created from an existing hdc, it is not released; this is consistent /// with the Win32 guideline that says if you call GetDC/CreateDC/CreatIC/CreateEnhMetafile, you are /// responsible for calling ReleaseDC/DeleteDC/DeleteEnhMetafile respectively. /// /// This class implements some of the operations commonly performed on the properties of a dc in WinForms, /// specially for interacting with GDI+, like clipping and coordinate transformation. /// Several properties are not persisted in the dc but instead they are set/reset during a more comprehensive /// operation like text rendering or painting; for instance text alignment is set and reset during DrawText (GDI), /// DrawString (GDI+). /// /// Other properties are persisted from operation to operation until they are reset, like clipping, /// one can make several calls to Graphics or WindowsGraphics object after setting the dc clip area and /// before resetting it; these kinds of properties are the ones implemented in this class. /// This kind of properties place an extra challenge in the scenario where a DeviceContext is obtained /// from a Graphics object that has been used with GDI+, because GDI+ saves the hdc internally, rendering the /// DeviceContext underlying hdc out of sync. DeviceContext needs to support these kind of properties to /// be able to keep the GDI+ and GDI HDCs in sync. /// /// A few other persisting properties have been implemented in DeviceContext2, among them: /// 1. Window origin. /// 2. Bounding rectangle. /// 3. DC origin. /// 4. View port extent. /// 5. View port origin. /// 6. Window extent /// /// Other non-persisted properties just for information: Background/Foreground color, Palette, Color adjustment, /// Color space, ICM mode and profile, Current pen position, Binary raster op (not supported by GDI+), /// Background mode, Logical Pen, DC pen color, ARc direction, Miter limit, Logical brush, DC brush color, /// Brush origin, Polygon filling mode, Bitmap stretching mode, Logical font, Intercharacter spacing, /// Font mapper flags, Text alignment, Test justification, Layout, Path, Meta region. /// See book "Windows Graphics Programming - Feng Yuang", P315 - Device Context Attributes. /// </summary> private IntPtr _hDC; private DeviceContextType _dcType; public event EventHandler Disposing; private bool _disposed; // We cache the hWnd when creating the dc from one, to provide support forIDeviceContext.GetHdc/ReleaseHdc. // This hWnd could be null, in such case it is referring to the screen. private IntPtr _hWnd = (IntPtr)(-1); // Unlikely to be a valid hWnd. private IntPtr _hInitialPen; private IntPtr _hInitialBrush; private IntPtr _hInitialBmp; private IntPtr _hInitialFont; private IntPtr _hCurrentPen; private IntPtr _hCurrentBrush; private IntPtr _hCurrentBmp; private IntPtr _hCurrentFont; private Stack _contextStack; #if GDI_FINALIZATION_WATCH private string AllocationSite = DbgUtil.StackTrace; private string DeAllocationSite = ""; #endif /// <summary> /// This object's hdc. If this property is called, then the object will be used as an HDC wrapper, so the hdc /// is cached and calls to GetHdc/ReleaseHdc won't PInvoke into GDI. Call Dispose to properly release the hdc. /// </summary> public IntPtr Hdc { get { if (_hDC == IntPtr.Zero) { if (_dcType == DeviceContextType.Display) { Debug.Assert(!_disposed, "Accessing a disposed DC, forcing recreation of HDC - this will generate a Handle leak!"); // Note: ReleaseDC must be called from the same thread. This applies only to HDC obtained // from calling GetDC. This means Display DeviceContext objects should never be finalized. _hDC = ((IDeviceContext)this).GetHdc(); // _hDC will be released on call to Dispose. CacheInitialState(); } #if GDI_FINALIZATION_WATCH else { try { Debug.WriteLine($"Allocation stack:\r\n{AllocationSite}\r\nDeallocation stack:\r\n{DeAllocationSite}"); } catch {} } #endif } Debug.Assert(_hDC != IntPtr.Zero, "Attempt to use deleted HDC - DC type: " + _dcType); return _hDC; } } // Due to a problem with calling DeleteObject() on currently selected GDI objects, we now track the initial set // of objects when a DeviceContext is created. Then, we also track which objects are currently selected in the // DeviceContext. When a currently selected object is disposed, it is first replaced in the DC and then deleted. private void CacheInitialState() { Debug.Assert(_hDC != IntPtr.Zero, "Cannot get initial state without a valid HDC"); _hCurrentPen = _hInitialPen = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, _hDC), IntNativeMethods.OBJ_PEN); _hCurrentBrush = _hInitialBrush = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, _hDC), IntNativeMethods.OBJ_BRUSH); _hCurrentBmp = _hInitialBmp = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, _hDC), IntNativeMethods.OBJ_BITMAP); _hCurrentFont = _hInitialFont = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, _hDC), IntNativeMethods.OBJ_FONT); } /// <summary> /// Constructor to construct a DeviceContext object from an window handle. /// </summary> private DeviceContext(IntPtr hWnd) { _hWnd = hWnd; _dcType = DeviceContextType.Display; DeviceContexts.AddDeviceContext(this); // the hDc will be created on demand. #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr(string.Format( "DeviceContext( hWnd=0x{0:x8} )", unchecked((int) hWnd)))); #endif } /// <summary> /// Constructor to construct a DeviceContext object from an existing Win32 device context handle. /// </summary> private DeviceContext(IntPtr hDC, DeviceContextType dcType) { _hDC = hDC; _dcType = dcType; CacheInitialState(); DeviceContexts.AddDeviceContext(this); if (dcType == DeviceContextType.Display) { _hWnd = IntUnsafeNativeMethods.WindowFromDC(new HandleRef(this, _hDC)); } #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( string.Format("DeviceContext( hDC=0x{0:X8}, Type={1} )", unchecked((int) hDC), dcType) )); #endif } /// <summary> /// CreateDC creates a DeviceContext object wrapping an hdc created with the Win32 CreateDC function. /// </summary> public static DeviceContext CreateDC(string driverName, string deviceName, string fileName, HandleRef devMode) { // Note: All input params can be null but not at the same time. See MSDN for information. IntPtr hdc = IntUnsafeNativeMethods.CreateDC(driverName, deviceName, fileName, devMode); return new DeviceContext(hdc, DeviceContextType.NamedDevice); } /// <summary> /// CreateIC creates a DeviceContext object wrapping an hdc created with the Win32 CreateIC function. /// </summary> public static DeviceContext CreateIC(string driverName, string deviceName, string fileName, HandleRef devMode) { // Note: All input params can be null but not at the same time. See MSDN for information. IntPtr hdc = IntUnsafeNativeMethods.CreateIC(driverName, deviceName, fileName, devMode); return new DeviceContext(hdc, DeviceContextType.Information); } /// <summary> /// Creates a DeviceContext object wrapping a memory DC compatible with the specified device. /// </summary> public static DeviceContext FromCompatibleDC(IntPtr hdc) { // If hdc is null, the function creates a memory DC compatible with the application's current screen. // Win2K+: (See CreateCompatibleDC in the MSDN). // In this case the thread that calls CreateCompatibleDC owns the HDC that is created. When this thread is destroyed, // the HDC is no longer valid. IntPtr compatibleDc = IntUnsafeNativeMethods.CreateCompatibleDC(new HandleRef(null, hdc)); return new DeviceContext(compatibleDc, DeviceContextType.Memory); } /// <summary> /// Used for wrapping an existing hdc. In this case, this object doesn't own the hdc so calls to /// GetHdc/ReleaseHdc don't PInvoke into GDI. /// </summary> public static DeviceContext FromHdc(IntPtr hdc) { Debug.Assert(hdc != IntPtr.Zero, "hdc == 0"); return new DeviceContext(hdc, DeviceContextType.Unknown); } /// <summary> /// When hwnd is null, we are getting the screen DC. /// </summary> public static DeviceContext FromHwnd(IntPtr hwnd) => new DeviceContext(hwnd); ~DeviceContext() => Dispose(false); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } internal void Dispose(bool disposing) { if (_disposed) { return; } Disposing?.Invoke(this, EventArgs.Empty); _disposed = true; switch (_dcType) { case DeviceContextType.Display: Debug.Assert(disposing, "WARNING: Finalizing a Display DeviceContext.\r\nReleaseDC may fail when not called from the same thread GetDC was called from."); ((IDeviceContext)this).ReleaseHdc(); break; case DeviceContextType.Information: case DeviceContextType.NamedDevice: IntUnsafeNativeMethods.DeleteDC(new HandleRef(this, _hDC)); _hDC = IntPtr.Zero; break; case DeviceContextType.Memory: IntUnsafeNativeMethods.DeleteDC(new HandleRef(this, _hDC)); _hDC = IntPtr.Zero; break; // case DeviceContextType.Metafile: - not yet supported. case DeviceContextType.Unknown: default: return; // do nothing, the hdc is not owned by this object. // in this case it is ok if disposed throught finalization. } DbgUtil.AssertFinalization(this, disposing); } /// <summary> /// Explicit interface method implementation to hide them a bit for usability reasons so the object is seen as /// a wrapper around an hdc that is always available, and for performance reasons since it caches the hdc if /// used in this way. /// </summary> IntPtr IDeviceContext.GetHdc() { if (_hDC == IntPtr.Zero) { Debug.Assert(_dcType == DeviceContextType.Display, "Calling GetDC from a non display/window device."); // Note: for common DCs, GetDC assigns default attributes to the DC each time it is retrieved. // For example, the default font is System. _hDC = UnsafeNativeMethods.GetDC(new HandleRef(this, _hWnd)); #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( string.Format("hdc[0x{0:x8}]=DC.GetHdc(hWnd=0x{1:x8})", unchecked((int) _hDC), unchecked((int) _hWnd)))); #endif } return _hDC; } ///<summary> /// If the object was created from a DC, this object doesn't 'own' the dc so we just ignore this call. ///</summary> void IDeviceContext.ReleaseHdc() { if (_hDC != IntPtr.Zero && _dcType == DeviceContextType.Display) { #if TRACK_HDC int retVal = #endif UnsafeNativeMethods.ReleaseDC(new HandleRef(this, _hWnd), new HandleRef(this, _hDC)); // Note: retVal == 0 means it was not released but doesn't necessarily means an error; class or private DCs are never released. #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( string.Format("[ret={0}]=DC.ReleaseDC(hDc=0x{1:x8}, hWnd=0x{2:x8})", retVal, unchecked((int) _hDC), unchecked((int) _hWnd)))); #endif _hDC = IntPtr.Zero; } } /// <summary> /// Restores the device context to the specified state. The DC is restored by popping state information off a /// stack created by earlier calls to the SaveHdc function. /// The stack can contain the state information for several instances of the DC. If the state specified by the /// specified parameter is not at the top of the stack, RestoreDC deletes all state information between the top /// of the stack and the specified instance. /// Specifies the saved state to be restored. If this parameter is positive, nSavedDC represents a specific /// instance of the state to be restored. If this parameter is negative, nSavedDC represents an instance relative /// to the current state. For example, -1 restores the most recently saved state. /// See MSDN for more info. /// </summary> public void RestoreHdc() { #if TRACK_HDC bool result = #endif // Note: Don't use the Hdc property here, it would force handle creation. IntUnsafeNativeMethods.RestoreDC(new HandleRef(this, _hDC), -1); #if TRACK_HDC // Note: Winforms may call this method during app exit at which point the DC may have been finalized already causing this assert to popup. Debug.WriteLine( DbgUtil.StackTraceToStr( string.Format("ret[0]=DC.RestoreHdc(hDc=0x{1:x8}, state={2})", result, unchecked((int) _hDC), restoreState) )); #endif Debug.Assert(_contextStack != null, "Someone is calling RestoreHdc() before SaveHdc()"); if (_contextStack != null) { GraphicsState g = (GraphicsState)_contextStack.Pop(); _hCurrentBmp = g.hBitmap; _hCurrentBrush = g.hBrush; _hCurrentPen = g.hPen; _hCurrentFont = g.hFont; } #if OPTIMIZED_MEASUREMENTDC // in this case, GDI will copy back the previously saved font into the DC. // we dont actually know what the font is in our measurement DC so // we need to clear it off. MeasurementDCInfo.ResetIfIsMeasurementDC(_hDC); #endif } /// <summary> /// Saves the current state of the device context by copying data describing selected objects and graphic /// modes (such as the bitmap, brush, palette, font, pen, region, drawing mode, and mapping mode) to a /// context stack. /// The SaveDC function can be used any number of times to save any number of instances of the DC state. /// A saved state can be restored by using the RestoreHdc method. /// See MSDN for more details. /// </summary> public int SaveHdc() { HandleRef hdc = new HandleRef(this, _hDC); int state = IntUnsafeNativeMethods.SaveDC(hdc); if (_contextStack == null) { _contextStack = new Stack(); } GraphicsState g = new GraphicsState(); g.hBitmap = _hCurrentBmp; g.hBrush = _hCurrentBrush; g.hPen = _hCurrentPen; g.hFont = _hCurrentFont; _contextStack.Push(g); #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( string.Format("state[0]=DC.SaveHdc(hDc=0x{1:x8})", state, unchecked((int) _hDC)) )); #endif return state; } /// <summary> /// Selects a region as the current clipping region for the device context. /// Remarks (From MSDN): /// - Only a copy of the selected region is used. The region itself can be selected for any number of other device contexts or it can be deleted. /// - The SelectClipRgn function assumes that the coordinates for a region are specified in device units. /// - To remove a device-context's clipping region, specify a NULL region handle. /// </summary> public void SetClip(WindowsRegion region) { HandleRef hdc = new HandleRef(this, _hDC); HandleRef hRegion = new HandleRef(region, region.HRegion); IntUnsafeNativeMethods.SelectClipRgn(hdc, hRegion); } ///<summary> /// Creates a new clipping region from the intersection of the current clipping region and the specified rectangle. ///</summary> public void IntersectClip(WindowsRegion wr) { //if the incoming windowsregion is infinite, there is no need to do any intersecting. if (wr.HRegion == IntPtr.Zero) { return; } WindowsRegion clip = new WindowsRegion(0, 0, 0, 0); try { int result = IntUnsafeNativeMethods.GetClipRgn(new HandleRef(this, _hDC), new HandleRef(clip, clip.HRegion)); // If the function succeeds and there is a clipping region for the given device context, the return value is 1. if (result == 1) { Debug.Assert(clip.HRegion != IntPtr.Zero); wr.CombineRegion(clip, wr, RegionCombineMode.AND); //1 = AND (or Intersect) } SetClip(wr); } finally { clip.Dispose(); } } /// <summary> /// Modifies the viewport origin for a device context using the specified horizontal and vertical offsets in /// logical units. /// </summary> public void TranslateTransform(int dx, int dy) { IntNativeMethods.POINT orgn = new IntNativeMethods.POINT(); IntUnsafeNativeMethods.OffsetViewportOrgEx(new HandleRef(this, _hDC), dx, dy, orgn); } /// <summary> /// </summary> public override bool Equals(object obj) { DeviceContext other = obj as DeviceContext; if (other == this) { return true; } if (other == null) { return false; } // Note: Use property instead of field so the HDC is initialized. Also, this avoid serialization issues (the obj could be a proxy that does not have access to private fields). return other.Hdc == _hDC; } /// <summary> /// This allows collections to treat DeviceContext objects wrapping the same HDC as the same objects. /// </summary> public override int GetHashCode() => _hDC.GetHashCode(); internal class GraphicsState { internal IntPtr hBrush; internal IntPtr hFont; internal IntPtr hPen; internal IntPtr hBitmap; } } }