context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.27.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Stackdriver Trace API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://cloud.google.com/trace'>Stackdriver Trace API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20170711 (922)
* <tr><th>API Docs
* <td><a href='https://cloud.google.com/trace'>
* https://cloud.google.com/trace</a>
* <tr><th>Discovery Name<td>cloudtrace
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Stackdriver Trace API can be found at
* <a href='https://cloud.google.com/trace'>https://cloud.google.com/trace</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.CloudTrace.v1
{
/// <summary>The CloudTrace Service.</summary>
public class CloudTraceService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public CloudTraceService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public CloudTraceService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "cloudtrace"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://cloudtrace.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://cloudtrace.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Stackdriver Trace API.</summary>
public class Scope
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>Write Trace data for a project or application</summary>
public static string TraceAppend = "https://www.googleapis.com/auth/trace.append";
/// <summary>Read Trace data for a project or application</summary>
public static string TraceReadonly = "https://www.googleapis.com/auth/trace.readonly";
}
private readonly ProjectsResource projects;
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects
{
get { return projects; }
}
}
///<summary>A base abstract class for CloudTrace requests.</summary>
public abstract class CloudTraceBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new CloudTraceBaseServiceRequest instance.</summary>
protected CloudTraceBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>OAuth bearer token.</summary>
[Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string BearerToken { get; set; }
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Pretty-print response.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Pp { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes CloudTrace parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"bearer_token", new Google.Apis.Discovery.Parameter
{
Name = "bearer_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pp", new Google.Apis.Discovery.Parameter
{
Name = "pp",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
traces = new TracesResource(service);
}
private readonly TracesResource traces;
/// <summary>Gets the Traces resource.</summary>
public virtual TracesResource Traces
{
get { return traces; }
}
/// <summary>The "traces" collection of methods.</summary>
public class TracesResource
{
private const string Resource = "traces";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public TracesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Gets a single trace by its ID.</summary>
/// <param name="projectId">ID of the Cloud project where the trace data is stored.</param>
/// <param
/// name="traceId">ID of the trace to return.</param>
public virtual GetRequest Get(string projectId, string traceId)
{
return new GetRequest(service, projectId, traceId);
}
/// <summary>Gets a single trace by its ID.</summary>
public class GetRequest : CloudTraceBaseServiceRequest<Google.Apis.CloudTrace.v1.Data.Trace>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string projectId, string traceId)
: base(service)
{
ProjectId = projectId;
TraceId = traceId;
InitParameters();
}
/// <summary>ID of the Cloud project where the trace data is stored.</summary>
[Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ProjectId { get; private set; }
/// <summary>ID of the trace to return.</summary>
[Google.Apis.Util.RequestParameterAttribute("traceId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string TraceId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/projects/{projectId}/traces/{traceId}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"projectId", new Google.Apis.Discovery.Parameter
{
Name = "projectId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"traceId", new Google.Apis.Discovery.Parameter
{
Name = "traceId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Returns of a list of traces that match the specified filter conditions.</summary>
/// <param name="projectId">ID of the Cloud project where the trace data is stored.</param>
public virtual ListRequest List(string projectId)
{
return new ListRequest(service, projectId);
}
/// <summary>Returns of a list of traces that match the specified filter conditions.</summary>
public class ListRequest : CloudTraceBaseServiceRequest<Google.Apis.CloudTrace.v1.Data.ListTracesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string projectId)
: base(service)
{
ProjectId = projectId;
InitParameters();
}
/// <summary>ID of the Cloud project where the trace data is stored.</summary>
[Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ProjectId { get; private set; }
/// <summary>Field used to sort the returned traces. Optional. Can be one of the following:
///
/// * `trace_id` * `name` (`name` field of root span in the trace) * `duration` (difference
/// between `end_time` and `start_time` fields of the root span) * `start` (`start_time` field of the
/// root span)
///
/// Descending order can be specified by appending `desc` to the sort field (for example, `name desc`).
///
/// Only one sort field is permitted.</summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>An optional filter against labels for the request.
///
/// By default, searches use prefix matching. To specify exact match, prepend a plus symbol (`+`) to the
/// search term. Multiple terms are ANDed. Syntax:
///
/// * `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces where any root span starts with
/// `NAME_PREFIX`. * `+root:NAME` or `+NAME`: Return traces where any root span's name is exactly
/// `NAME`. * `span:NAME_PREFIX`: Return traces where any span starts with `NAME_PREFIX`. *
/// `+span:NAME`: Return traces where any span's name is exactly `NAME`. * `latency:DURATION`: Return
/// traces whose overall latency is greater or equal to than `DURATION`. Accepted units are nanoseconds
/// (`ns`), milliseconds (`ms`), and seconds (`s`). Default is `ms`. For example, `latency:24ms` returns
/// traces whose overall latency is greater than or equal to 24 milliseconds. * `label:LABEL_KEY`:
/// Return all traces containing the specified label key (exact match, case-sensitive) regardless of the
/// key:value pair's value (including empty values). * `LABEL_KEY:VALUE_PREFIX`: Return all traces
/// containing the specified label key (exact match, case-sensitive) whose value starts with
/// `VALUE_PREFIX`. Both a key and a value must be specified. * `+LABEL_KEY:VALUE`: Return all traces
/// containing a key:value pair exactly matching the specified text. Both a key and a value must be
/// specified. * `method:VALUE`: Equivalent to `/http/method:VALUE`. * `url:VALUE`: Equivalent to
/// `/http/url:VALUE`.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>End of the time interval (inclusive) during which the trace data was collected from the
/// application.</summary>
[Google.Apis.Util.RequestParameterAttribute("endTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual object EndTime { get; set; }
/// <summary>Start of the time interval (inclusive) during which the trace data was collected from the
/// application.</summary>
[Google.Apis.Util.RequestParameterAttribute("startTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual object StartTime { get; set; }
/// <summary>Token identifying the page of results to return. If provided, use the value of the
/// `next_page_token` field from a previous request. Optional.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Maximum number of traces to return. If not specified or <= 0, the implementation selects a
/// reasonable value. The implementation may return fewer traces than the requested page size.
/// Optional.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>Type of data returned for traces in the list. Optional. Default is `MINIMAL`.</summary>
[Google.Apis.Util.RequestParameterAttribute("view", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<ViewEnum> View { get; set; }
/// <summary>Type of data returned for traces in the list. Optional. Default is `MINIMAL`.</summary>
public enum ViewEnum
{
[Google.Apis.Util.StringValueAttribute("VIEW_TYPE_UNSPECIFIED")]
VIEWTYPEUNSPECIFIED,
[Google.Apis.Util.StringValueAttribute("MINIMAL")]
MINIMAL,
[Google.Apis.Util.StringValueAttribute("ROOTSPAN")]
ROOTSPAN,
[Google.Apis.Util.StringValueAttribute("COMPLETE")]
COMPLETE,
}
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/projects/{projectId}/traces"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"projectId", new Google.Apis.Discovery.Parameter
{
Name = "projectId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"endTime", new Google.Apis.Discovery.Parameter
{
Name = "endTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"startTime", new Google.Apis.Discovery.Parameter
{
Name = "startTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"view", new Google.Apis.Discovery.Parameter
{
Name = "view",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you
/// send matches that of an existing trace, any fields in the existing trace and its spans are overwritten by
/// the provided values, and any new fields provided are merged with the existing trace data. If the ID does not
/// match, a new trace is created.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="projectId">ID of the Cloud project where the trace data is stored.</param>
public virtual PatchTracesRequest PatchTraces(Google.Apis.CloudTrace.v1.Data.Traces body, string projectId)
{
return new PatchTracesRequest(service, body, projectId);
}
/// <summary>Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you
/// send matches that of an existing trace, any fields in the existing trace and its spans are overwritten by
/// the provided values, and any new fields provided are merged with the existing trace data. If the ID does not
/// match, a new trace is created.</summary>
public class PatchTracesRequest : CloudTraceBaseServiceRequest<Google.Apis.CloudTrace.v1.Data.Empty>
{
/// <summary>Constructs a new PatchTraces request.</summary>
public PatchTracesRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudTrace.v1.Data.Traces body, string projectId)
: base(service)
{
ProjectId = projectId;
Body = body;
InitParameters();
}
/// <summary>ID of the Cloud project where the trace data is stored.</summary>
[Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ProjectId { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudTrace.v1.Data.Traces Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patchTraces"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/projects/{projectId}/traces"; }
}
/// <summary>Initializes PatchTraces parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"projectId", new Google.Apis.Discovery.Parameter
{
Name = "projectId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.CloudTrace.v1.Data
{
/// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A
/// typical example is to use it as the request or the response type of an API method. For instance:
///
/// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
///
/// The JSON representation for `Empty` is empty JSON object `{}`.</summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for the `ListTraces` method.</summary>
public class ListTracesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>If defined, indicates that there are more traces that match the request and that this value should
/// be passed to the next request to continue retrieving additional traces.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>List of trace records returned.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("traces")]
public virtual System.Collections.Generic.IList<Trace> Traces { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A trace describes how long it takes for an application to perform an operation. It consists of a set of
/// spans, each of which represent a single timed event within the operation.</summary>
public class Trace : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Project ID of the Cloud project where the trace data is stored.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("projectId")]
public virtual string ProjectId { get; set; }
/// <summary>Collection of spans in the trace.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("spans")]
public virtual System.Collections.Generic.IList<TraceSpan> Spans { get; set; }
/// <summary>Globally unique identifier for the trace. This identifier is a 128-bit numeric value formatted as a
/// 32-byte hex string.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("traceId")]
public virtual string TraceId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A span represents a single timed event within a trace. Spans can be nested and form a trace tree.
/// Often, a trace contains a root span that describes the end-to-end latency of an operation and, optionally, one
/// or more subspans for its suboperations. Spans do not need to be contiguous. There may be gaps between spans in a
/// trace.</summary>
public class TraceSpan : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>End time of the span in nanoseconds from the UNIX epoch.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>Distinguishes between spans generated in a particular context. For example, two spans with the same
/// name may be distinguished using `RPC_CLIENT` and `RPC_SERVER` to identify queueing latency associated with
/// the span.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Collection of labels associated with the span. Label keys must be less than 128 bytes. Label values
/// must be less than 16 kilobytes (10MB for `/stacktrace` values).
///
/// Some predefined label keys exist, or you may create your own. When creating your own, we recommend the
/// following formats:
///
/// * `/category/product/key` for agents of well-known products (e.g. `/db/mongodb/read_size`). *
/// `short_host/path/key` for domain-specific keys (e.g. `foo.com/myproduct/bar`)
///
/// Predefined labels include:
///
/// * `/agent` * `/component` * `/error/message` * `/error/name` * `/http/client_city` *
/// `/http/client_country` * `/http/client_protocol` * `/http/client_region` * `/http/host` *
/// `/http/method` * `/http/redirected_url` * `/http/request/size` * `/http/response/size` *
/// `/http/status_code` * `/http/url` * `/http/user_agent` * `/pid` * `/stacktrace` * `/tid`</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string,string> Labels { get; set; }
/// <summary>Name of the span. Must be less than 128 bytes. The span name is sanitized and displayed in the
/// Stackdriver Trace tool in the {% dynamic print site_values.console_name %}. The name may be a method name or
/// some other per-call site name. For the same executable and the same call point, a best practice is to use a
/// consistent name, which makes it easier to correlate cross-trace spans.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>ID of the parent span, if any. Optional.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parentSpanId")]
public virtual System.Nullable<ulong> ParentSpanId { get; set; }
/// <summary>Identifier for the span. Must be a 64-bit integer other than 0 and unique within a trace.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("spanId")]
public virtual System.Nullable<ulong> SpanId { get; set; }
/// <summary>Start time of the span in nanoseconds from the UNIX epoch.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startTime")]
public virtual object StartTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>List of new or updated traces.</summary>
public class Traces : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>List of traces.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("traces")]
public virtual System.Collections.Generic.IList<Trace> TracesValue { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
namespace it.unifi.dsi.stlab.networkreasoner.model.gas
{
public class ReachabilityValidator : ValidatorAbstract
{
protected interface NodeState
{
void visitFor (NodeForReachabilityValidator aNode);
void assertVisitedSignalingIfFalseFor (
NodeForReachabilityValidator aNode,
Action<NodeForReachabilityValidator> aBlockIfAssertFails);
}
class NodeStateVisited : NodeState
{
#region NodeState implementation
public void visitFor (NodeForReachabilityValidator aNode)
{
// since the vertex is already visited we haven't to
// continue the visiting of its neighborhood.
}
public void assertVisitedSignalingIfFalseFor (
NodeForReachabilityValidator aNode,
Action<NodeForReachabilityValidator> aBlockIfAssertFails)
{
// nothing to raise since the node is visited.
}
#endregion
}
class NodeStateNotVisited : NodeState
{
#region NodeState implementation
public void visitFor (NodeForReachabilityValidator aNode)
{
aNode.State = new NodeStateVisited ();
aNode.Neighborhood.ForEach (neighbor => neighbor.visit ());
}
public void assertVisitedSignalingIfFalseFor (
NodeForReachabilityValidator aNode,
Action<NodeForReachabilityValidator> aBlockIfAssertFails)
{
// since the node isn't visited we have to signal the anomaly
// using the given block.
aBlockIfAssertFails.Invoke (aNode);
}
#endregion
}
protected interface NodeRole
{
void startVisitFor (NodeForReachabilityValidator aNode);
}
class NodeRoleSupplier : NodeRole
{
#region NodeRole implementation
public void startVisitFor (NodeForReachabilityValidator aNode)
{
aNode.visit ();
}
#endregion
}
class NodeRoleLoader : NodeRole
{
#region NodeRole implementation
public void startVisitFor (NodeForReachabilityValidator aNode)
{
// since aNode is a node with a load gadget, we can say
// that it is a loader, hence it cannot start a reachability
// visit since it cannot supply pressure.
}
#endregion
}
protected class NodeForReachabilityValidator :
GasNodeVisitor,
GasNodeGadgetVisitor
{
public String Identifier{ get; set; }
public List<NodeForReachabilityValidator> Neighborhood{ get; set; }
public NodeState State{ get; set; }
public NodeRole Role{ get; set; }
#region GasNodeVisitor implementation
public void forNodeWithTopologicalInfo (
GasNodeTopological gasNodeTopological)
{
this.Identifier = gasNodeTopological.Identifier;
}
public void forNodeWithGadget (
GasNodeWithGadget gasNodeWithGadget)
{
gasNodeWithGadget.Gadget.accept (this);
gasNodeWithGadget.Equipped.accept (this);
}
public void forNodeAntecedentInPressureReduction (
GasNodeAntecedentInPressureRegulator gasNodeAntecedentInPressureRegulator)
{
gasNodeAntecedentInPressureRegulator.ToppedNode.accept (this);
}
#endregion
#region GasNodeGadgetVisitor implementation
public void forLoadGadget (GasNodeGadgetLoad aLoadGadget)
{
this.Role = new NodeRoleLoader ();
}
public void forSupplyGadget (GasNodeGadgetSupply aSupplyGadget)
{
this.Role = new NodeRoleSupplier ();
}
#endregion
public void visit ()
{
this.State.visitFor (this);
}
public void startVisit ()
{
this.Role.startVisitFor (this);
}
public void assertVisitedSignalingIfFalse (
Action<NodeForReachabilityValidator> aBlockIfAssertFails)
{
this.State.assertVisitedSignalingIfFalseFor (this, aBlockIfAssertFails);
}
}
protected class EdgeForReachabilityValidator : GasEdgeVisitor
{
Dictionary<GasNodeAbstract, NodeForReachabilityValidator> newNodesByKey{ get; set; }
public EdgeForReachabilityValidator (
Dictionary<GasNodeAbstract, NodeForReachabilityValidator> newNodesByKey)
{
this.newNodesByKey = newNodesByKey;
}
#region GasEdgeVisitor implementation
public void forPhysicalEdge (GasEdgePhysical gasEdgePhysical)
{
// we don't care about the physical properties.
gasEdgePhysical.Described.accept (this);
}
public void forTopologicalEdge (GasEdgeTopological gasEdgeTopological)
{
var startVertex = newNodesByKey [gasEdgeTopological.StartNode];
var endVertex = newNodesByKey [gasEdgeTopological.EndNode];
startVertex.Neighborhood.Add (endVertex);
endVertex.Neighborhood.Add (startVertex);
}
public void forEdgeWithGadget (GasEdgeWithGadget gasEdgeWithGadget)
{
gasEdgeWithGadget.Gadget.accept (
new GasEdgeGadgetVisitorStopRecursionOnSwitchOff (
this, gasEdgeWithGadget.Equipped)
);
}
#endregion
class GasEdgeGadgetVisitorStopRecursionOnSwitchOff : GasEdgeGadgetVisitor
{
EdgeForReachabilityValidator edgeForReachabilityValidator{ get; set; }
GasEdgeAbstract equipped{ get; set; }
public GasEdgeGadgetVisitorStopRecursionOnSwitchOff (
EdgeForReachabilityValidator edgeForReachabilityValidator,
GasEdgeAbstract equipped)
{
this.edgeForReachabilityValidator = edgeForReachabilityValidator;
this.equipped = equipped;
}
#region GasEdgeGadgetVisitor implementation
public void forSwitchOffGadget (
GasEdgeGadgetSwitchOff gasEdgeGadgetSwitchOff)
{
// since this gadget turns off the edge we do not proceed
// the recursive application of the visitor, so we
// do not reach the very bottom case of TopologicalEdge
// where the neighborhoods are updated.
}
public void forPressureRegulatorGadget (GasEdgeGadgetPressureRegulator gasEdgeGadgetPressureRegulator)
{
this.equipped.accept (this.edgeForReachabilityValidator);
}
#endregion
// the following is the code for an edge with a switch on gadget
// (which it doesn't exists up to now).
// #region GasEdgeGadgetVisitor implementation
// public void forSwitchOnGadget (
// GasEdgeGadgetSwitchOn gasEdgeGadgetSwitchOn)
// {
// this.equipped.accept (this.edgeForReachabilityValidator);
// }
// #endregion
}
}
void setupValidatorFor (
GasNetwork gasNetwork,
out List<NodeForReachabilityValidator> nodes)
{
var newNodesByKey = new Dictionary<GasNodeAbstract, NodeForReachabilityValidator> ();
gasNetwork.doOnNodes (new NodeHandlerWithDelegateOnKeyedNode<GasNodeAbstract> (
(aKey, aNode) => {
var newNode = new NodeForReachabilityValidator {
State = new NodeStateNotVisited (),
Role = new NodeRoleLoader(),
Neighborhood = new List<NodeForReachabilityValidator>()
};
aNode.accept (newNode);
newNodesByKey.Add (aNode, newNode);
}
)
);
EdgeForReachabilityValidator edgeVisitor =
new EdgeForReachabilityValidator (newNodesByKey);
gasNetwork.doOnEdges (new NodeHandlerWithDelegateOnRawNode<GasEdgeAbstract> (
anEdge => anEdge.accept (edgeVisitor))
);
nodes = new List<NodeForReachabilityValidator> (newNodesByKey.Values);
}
public void validate (GasNetwork gasNetwork)
{
List<NodeForReachabilityValidator> nodes;
this.setupValidatorFor (gasNetwork, out nodes);
foreach (var node in nodes) {
node.startVisit ();
}
foreach (var aNode in nodes) {
aNode.assertVisitedSignalingIfFalse (HandleNotVisitedNode);
}
}
protected virtual void HandleNotVisitedNode (
NodeForReachabilityValidator aNotVisitedNode)
{
throw new NetworkNotConnectedException (string.Format (
"The node ``{0}'' isn't connected to a vertex with a supply gadget.",
aNotVisitedNode.Identifier)
);
}
public class NetworkNotConnectedException : Exception
{
public NetworkNotConnectedException (String message):base(message)
{
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Microsoft.Zelig.Tools.IRViewer
{
public partial class MethodViewer : Form
{
//
// State
//
Dictionary< string, Method > m_lookupMethod;
Method m_method;
string m_phaseName;
bool m_fExpandBasicBlocks;
object m_selectedObjectAttr;
object m_selectedObject;
BasicBlock m_selectedBasicBlock;
//
// Constructor Methods
//
public MethodViewer( Dictionary< string, Method > lookupMethod ,
Method method ,
string phaseName )
{
m_lookupMethod = lookupMethod;
m_method = method;
m_phaseName = phaseName;
m_fExpandBasicBlocks = false;
InitializeComponent();
}
private void UpdateDisplay()
{
textBox1.Text = m_method.Name;
Text = "MethodViewer - " + m_method.Name + " - Phase: " + m_phaseName;
//--//
CreateGraph();
ListVariables();
SelectBasicBlock( null );
}
//--//
private void CreateGraph()
{
Microsoft.Glee.Drawing.Graph g = new Microsoft.Glee.Drawing.Graph( string.Format( "Method for {0}", m_method.Name ) );
g.GraphAttr.NodeAttr.Padding = 3;
foreach(BasicBlockEdge edge in m_method.BasicBlockEdges)
{
Microsoft.Glee.Drawing.Edge edgeG = g.AddEdge( edge.From.Id, edge.To.Id ) as Microsoft.Glee.Drawing.Edge;
Microsoft.Glee.Drawing.EdgeAttr attr = edgeG.Attr;
attr.Label = edge.Kind;
attr.Fontsize -= 4;
//attr.Styles = new Style[] { Microsoft.Glee.Drawing.Style.Dashed };
}
foreach(BasicBlock bb in m_method.BasicBlocks)
{
Microsoft.Glee.Drawing.Node node = CreateNode( g, bb, m_fExpandBasicBlocks );
}
gViewer1.Graph = g;
}
private static Microsoft.Glee.Drawing.Edge CreateEdge( Microsoft.Glee.Drawing.Graph graph ,
string from ,
string to ,
string label )
{
Microsoft.Glee.Drawing.Edge edge = graph.AddEdge( from, to ) as Microsoft.Glee.Drawing.Edge;
Microsoft.Glee.Drawing.EdgeAttr attr = edge.Attr;
if(label != null)
{
attr.Label = label;
attr.Fontsize -= 4;
}
return edge;
}
private static Microsoft.Glee.Drawing.Node CreateNode( Microsoft.Glee.Drawing.Graph graph ,
BasicBlock bb ,
bool fExpandBasicBlocks )
{
Microsoft.Glee.Drawing.Node node = graph.AddNode( bb.Id ) as Microsoft.Glee.Drawing.Node;
Microsoft.Glee.Drawing.NodeAttr attr = node.Attr;
if(bb.Type == "EntryBasicBlock")
{
//attr.Shape = Microsoft.Glee.Drawing.Shape.DoubleCircle;
attr.Shape = Microsoft.Glee.Drawing.Shape.Box;
attr.Fillcolor = Microsoft.Glee.Drawing.Color.Green;
}
else if(bb.Type == "ExitBasicBlock")
{
//attr.Shape = Microsoft.Glee.Drawing.Shape.DoubleCircle;
attr.Shape = Microsoft.Glee.Drawing.Shape.Box;
attr.Fillcolor = Microsoft.Glee.Drawing.Color.Red;
}
else if(bb.Type == "ExceptionHandlerBasicBlock")
{
//attr.Shape = Microsoft.Glee.Drawing.Shape.DoubleCircle;
attr.Shape = Microsoft.Glee.Drawing.Shape.Box;
attr.Fillcolor = Microsoft.Glee.Drawing.Color.Purple;
}
else
{
attr.Shape = Microsoft.Glee.Drawing.Shape.Box;
//attr.Padding = 30.0;
}
if(fExpandBasicBlocks)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat( "{0}:", bb.Id );
sb.AppendLine();
foreach(Operator op in bb.Operators)
{
sb.AppendLine( op.Value );
}
node.Attr.Label = sb.ToString();
}
else
{
attr.Label = bb.Id + " - " + bb.Index;
}
return node;
}
//// private static void CreateSourceNode( Microsoft.Glee.Drawing.NodeAttr attr )
//// {
//// attr.Shape = Microsoft.Glee.Drawing.Shape.Box;
//// attr.XRad = 3;
//// attr.YRad = 3;
//// attr.Fillcolor = Microsoft.Glee.Drawing.Color.Green;
//// attr.LineWidth = 10;
//// }
////
//// private void CreateTargetNode( Microsoft.Glee.Drawing.NodeAttr attr )
//// {
//// attr.Shape = Microsoft.Glee.Drawing.Shape.DoubleCircle;
//// attr.Fillcolor = Microsoft.Glee.Drawing.Color.LightGray;
////
//// attr.Fontsize += 4;
//// }
//--//
private void ListVariables()
{
ListView.ListViewItemCollection col = listViewVariables.Items;
listViewVariables.SuspendLayout();
col.Clear();
foreach(Variable var in m_method.Variables)
{
ListViewItem lvi = new ListViewItem( var.Name );
lvi.SubItems.Add( var.Type );
col.Add( lvi );
}
listViewVariables.ResumeLayout();
tabControl1.SelectedTab = tabPageVariables;
}
//--//--//
private void SelectBasicBlock( BasicBlock bb )
{
ListBox.ObjectCollection col = listBoxBasicBlock.Items;
listBoxBasicBlock.SuspendLayout();
col.Clear();
m_selectedBasicBlock = bb;
if(bb != null)
{
foreach(Operator op in bb.Operators)
{
col.Add( op.Value );
}
}
listBoxBasicBlock.ResumeLayout();
tabControl1.SelectedTab = tabPageBasicBlock;
}
//--//--//
private void MethodViewer_Load( object sender ,
EventArgs e )
{
UpdateDisplay();
}
private void gViewer1_SelectionChanged( object sender ,
EventArgs e )
{
if(m_selectedObject != null)
{
if(m_selectedObject is Microsoft.Glee.Drawing.Edge)
{
Microsoft.Glee.Drawing.Edge edge = (Microsoft.Glee.Drawing.Edge)m_selectedObject;
edge.Attr = m_selectedObjectAttr as Microsoft.Glee.Drawing.EdgeAttr;
}
else if(m_selectedObject is Microsoft.Glee.Drawing.Node)
{
Microsoft.Glee.Drawing.Node node = (Microsoft.Glee.Drawing.Node)m_selectedObject;
node.Attr = m_selectedObjectAttr as Microsoft.Glee.Drawing.NodeAttr;
}
m_selectedObject = null;
m_selectedObjectAttr = null;
}
if(gViewer1.SelectedObject == null)
{
//// label1.Text = "No object under the mouse";
//// this.gViewer.SetToolTip( toolTip1, "" );
}
else
{
m_selectedObject = gViewer1.SelectedObject;
if(m_selectedObject is Microsoft.Glee.Drawing.Edge)
{
Microsoft.Glee.Drawing.Edge edge = (Microsoft.Glee.Drawing.Edge)m_selectedObject;
m_selectedObjectAttr = edge.Attr.Clone();
edge.Attr.Color = Microsoft.Glee.Drawing.Color.Magenta;
edge.Attr.Fontcolor = Microsoft.Glee.Drawing.Color.Magenta;
//// //here you can use e.Attr.Id or e.UserData to get back to you data
//// this.gViewer.SetToolTip( this.toolTip1, String.Format( "edge from {0} {1}", edge.Source, edge.Target ) );
}
else if(m_selectedObject is Microsoft.Glee.Drawing.Node)
{
Microsoft.Glee.Drawing.Node node = (Microsoft.Glee.Drawing.Node)m_selectedObject;
m_selectedObjectAttr = node.Attr.Clone();
node.Attr.Color = Microsoft.Glee.Drawing.Color.Magenta;
node.Attr.Fontcolor = Microsoft.Glee.Drawing.Color.Magenta;
//// //here you can use e.Attr.Id to get back to your data
//// this.gViewer.SetToolTip( toolTip1, String.Format( "node {0}", (selectedObject as Node).Attr.Label ) );
}
}
gViewer1.Invalidate();
}
private void gViewer1_MouseClick( object sender ,
MouseEventArgs e )
{
if(gViewer1.SelectedObject is Microsoft.Glee.Drawing.Node)
{
Microsoft.Glee.Drawing.Node node = (Microsoft.Glee.Drawing.Node)gViewer1.SelectedObject;
foreach(BasicBlock bb in m_method.BasicBlocks)
{
if(bb.Id == node.Id)
{
SelectBasicBlock( bb );
break;
}
}
}
}
private void listBoxBasicBlock_DoubleClick( object sender ,
EventArgs e )
{
if(m_selectedBasicBlock != null)
{
int i = listBoxBasicBlock.SelectedIndex;
if(i >= 0 && i < m_selectedBasicBlock.Operators.Count)
{
Operator op = m_selectedBasicBlock.Operators[i];
if(op.Call != null)
{
Method method;
if(m_lookupMethod.TryGetValue( op.Call, out method ))
{
m_method = method;
UpdateDisplay();
}
}
}
}
}
private void checkBoxExpandBasicBlocks_CheckedChanged( object sender ,
EventArgs e )
{
m_fExpandBasicBlocks = checkBoxExpandBasicBlocks.Checked;
CreateGraph();
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="GetUserSettingsResponse.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the GetUserSettingsResponse class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Autodiscover
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml;
using Microsoft.Exchange.WebServices.Data;
/// <summary>
/// Represents the response to a GetUsersSettings call for an individual user.
/// </summary>
public sealed class GetUserSettingsResponse : AutodiscoverResponse
{
/// <summary>
/// Initializes a new instance of the <see cref="GetUserSettingsResponse"/> class.
/// </summary>
public GetUserSettingsResponse()
: base()
{
this.SmtpAddress = string.Empty;
this.Settings = new Dictionary<UserSettingName, object>();
this.UserSettingErrors = new Collection<UserSettingError>();
}
/// <summary>
/// Tries the get the user setting value.
/// </summary>
/// <typeparam name="T">Type of user setting.</typeparam>
/// <param name="setting">The setting.</param>
/// <param name="value">The setting value.</param>
/// <returns>True if setting was available.</returns>
public bool TryGetSettingValue<T>(UserSettingName setting, out T value)
{
object objValue;
if (this.Settings.TryGetValue(setting, out objValue))
{
value = (T)objValue;
return true;
}
else
{
value = default(T);
return false;
}
}
/// <summary>
/// Gets the SMTP address this response applies to.
/// </summary>
public string SmtpAddress
{
get; internal set;
}
/// <summary>
/// Gets the redirectionTarget (URL or email address)
/// </summary>
public string RedirectTarget
{
get; internal set;
}
/// <summary>
/// Gets the requested settings for the user.
/// </summary>
public IDictionary<UserSettingName, object> Settings
{
get; internal set;
}
/// <summary>
/// Gets error information for settings that could not be returned.
/// </summary>
public Collection<UserSettingError> UserSettingErrors
{
get; internal set;
}
/// <summary>
/// Loads response from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="endElementName">End element name.</param>
internal override void LoadFromXml(EwsXmlReader reader, string endElementName)
{
do
{
reader.Read();
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case XmlElementNames.RedirectTarget:
this.RedirectTarget = reader.ReadElementValue();
break;
case XmlElementNames.UserSettingErrors:
this.LoadUserSettingErrorsFromXml(reader);
break;
case XmlElementNames.UserSettings:
this.LoadUserSettingsFromXml(reader);
break;
default:
base.LoadFromXml(reader, endElementName);
break;
}
}
}
while (!reader.IsEndElement(XmlNamespace.Autodiscover, endElementName));
}
/// <summary>
/// Loads from XML.
/// </summary>
/// <param name="reader">The reader.</param>
internal void LoadUserSettingsFromXml(EwsXmlReader reader)
{
if (!reader.IsEmptyElement)
{
do
{
reader.Read();
if ((reader.NodeType == XmlNodeType.Element) && (reader.LocalName == XmlElementNames.UserSetting))
{
string settingClass = reader.ReadAttributeValue(XmlNamespace.XmlSchemaInstance, XmlAttributeNames.Type);
switch (settingClass)
{
case XmlElementNames.StringSetting:
case XmlElementNames.WebClientUrlCollectionSetting:
case XmlElementNames.AlternateMailboxCollectionSetting:
case XmlElementNames.ProtocolConnectionCollectionSetting:
case XmlElementNames.DocumentSharingLocationCollectionSetting:
this.ReadSettingFromXml(reader);
break;
default:
EwsUtilities.Assert(
false,
"GetUserSettingsResponse.LoadUserSettingsFromXml",
string.Format("Invalid setting class '{0}' returned", settingClass));
break;
}
}
}
while (!reader.IsEndElement(XmlNamespace.Autodiscover, XmlElementNames.UserSettings));
}
}
/// <summary>
/// Reads user setting from XML.
/// </summary>
/// <param name="reader">The reader.</param>
private void ReadSettingFromXml(EwsXmlReader reader)
{
string name = null;
object value = null;
do
{
reader.Read();
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case XmlElementNames.Name:
name = reader.ReadElementValue<string>();
break;
case XmlElementNames.Value:
value = reader.ReadElementValue();
break;
case XmlElementNames.WebClientUrls:
value = WebClientUrlCollection.LoadFromXml(reader);
break;
case XmlElementNames.ProtocolConnections:
value = ProtocolConnectionCollection.LoadFromXml(reader);
break;
case XmlElementNames.AlternateMailboxes:
value = AlternateMailboxCollection.LoadFromXml(reader);
break;
case XmlElementNames.DocumentSharingLocations:
value = DocumentSharingLocationCollection.LoadFromXml(reader);
break;
}
}
}
while (!reader.IsEndElement(XmlNamespace.Autodiscover, XmlElementNames.UserSetting));
// EWS Managed API is broken with AutoDSvc endpoint in RedirectUrl scenario
try
{
UserSettingName userSettingName = EwsUtilities.Parse<UserSettingName>(name);
this.Settings.Add(userSettingName, value);
}
catch (ArgumentException)
{
// ignore unexpected UserSettingName in the response (due to the server-side bugs).
// it'd be better if this is hooked into ITraceListener, but that is unavailable here.
//
// in case "name" is null, EwsUtilities.Parse throws ArgumentNullException
// (which derives from ArgumentException).
//
EwsUtilities.Assert(
false,
"GetUserSettingsResponse.ReadSettingFromXml",
"Unexpected or empty name element in user setting");
}
}
/// <summary>
/// Loads the user setting errors.
/// </summary>
/// <param name="reader">The reader.</param>
private void LoadUserSettingErrorsFromXml(EwsXmlReader reader)
{
if (!reader.IsEmptyElement)
{
do
{
reader.Read();
if ((reader.NodeType == XmlNodeType.Element) && (reader.LocalName == XmlElementNames.UserSettingError))
{
UserSettingError error = new UserSettingError();
error.LoadFromXml(reader);
this.UserSettingErrors.Add(error);
}
}
while (!reader.IsEndElement(XmlNamespace.Autodiscover, XmlElementNames.UserSettingErrors));
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
namespace System.Management.Automation
{
/// <summary>
/// This class contains strings required for serialization
/// </summary>
internal static class SerializationStrings
{
#region element tags
/// <summary>
/// Element tag for root node
/// </summary>
internal const string RootElementTag = "Objs";
#region PSObject
/// <summary>
/// Element tag for PSObject
/// </summary>
internal const string PSObjectTag = "Obj";
/// <summary>
/// Element tag for properties
/// </summary>
internal const string AdapterProperties = "Props";
/// <summary>
/// TypeNames tag
/// </summary>
internal const string TypeNamesTag = "TN";
/// <summary>
/// Tag for type item in typeanmes
/// </summary>
internal const string TypeNamesItemTag = "T";
/// <summary>
/// TypeName reference
/// </summary>
internal const string TypeNamesReferenceTag = "TNRef";
/// <summary>
/// Memberset
/// </summary>
internal const string MemberSet = "MS";
/// <summary>
/// Individual notes
/// </summary>
internal const string NoteProperty = "N";
/// <summary>
/// Tag for ToString value
/// </summary>
internal const string ToStringElementTag = "ToString";
#endregion PSObject
#region known container tags
/// <summary>
/// Element tag used for IEnumerables.
/// </summary>
internal const string CollectionTag = "IE";
/// <summary>
/// Element tag used for Dictionary
/// </summary>
internal const string DictionaryTag = "DCT";
/// <summary>
/// Element tag used for Dictionary entry
/// </summary>
internal const string DictionaryEntryTag = "En";
/// <summary>
/// Value of name attribute for dictionary key part in dictnary entry
/// </summary>
internal const string DictionaryKey = "Key";
/// <summary>
/// Value of name attribute for dictionary value part in dictnary entry
/// </summary>
internal const string DictionaryValue = "Value";
/// <summary>
/// Element tag used for Stack
/// </summary>
internal const string StackTag = "STK";
/// <summary>
/// Element tag used for Queue
/// </summary>
internal const string QueueTag = "QUE";
/// <summary>
/// Element tag used for List
/// </summary>
internal const string ListTag = "LST";
#endregion known container tags
#region primitive known type tags
/// <summary>
/// Element tag for char property.
/// </summary>
/// <remarks>This property is used for System.Char type</remarks>
internal const string CharTag = "C";
/// <summary>
/// Element tag for guid property.
/// </summary>
/// <remarks>This property is used for System.Guid type</remarks>
internal const string GuidTag = "G";
/// <summary>
/// Element tag for boolean property.
/// </summary>
/// <remarks>This property is used for System.Boolean type</remarks>
internal const string BooleanTag = "B";
/// <summary>
/// Element tag for unsignedByte property.
/// </summary>
/// <remarks>This property is used for System.Byte type</remarks>
internal const string UnsignedByteTag = "By";
/// <summary>
/// Element tag for dateTime property.
/// </summary>
/// <remarks>This property is used for System.DateTime type</remarks>
internal const string DateTimeTag = "DT";
/// <summary>
/// Element tag for decimal property.
/// </summary>
/// <remarks>This property is used for System.Decimal type</remarks>
internal const string DecimalTag = "D";
/// <summary>
/// Element tag for double property.
/// </summary>
/// <remarks>This property is used for System.Double type</remarks>
internal const string DoubleTag = "Db";
/// <summary>
/// Element tag for duration property.
/// </summary>
/// <remarks>This property is used for System.TimeSpan type</remarks>
internal const string DurationTag = "TS";
/// <summary>
/// Element tag for float property.
/// </summary>
/// <remarks>This property is used for System.Single type</remarks>
internal const string FloatTag = "Sg";
/// <summary>
/// Element tag for int property.
/// </summary>
/// <remarks>This property is used for System.Int32 type</remarks>
internal const string IntTag = "I32";
/// <summary>
/// Element tag for long property.
/// </summary>
/// <remarks>This property is used for System.Int64 type</remarks>
internal const string LongTag = "I64";
/// <summary>
/// Element tag for byte property.
/// </summary>
/// <remarks>This property is used for System.SByte type</remarks>
internal const string ByteTag = "SB";
/// <summary>
/// Element tag for short property.
/// </summary>
/// <remarks>This property is used for System.Int16 type</remarks>
internal const string ShortTag = "I16";
/// <summary>
/// Element tag for base64Binary property.
/// </summary>
/// <remarks>This property is used for System.IO.Stream type</remarks>
internal const string Base64BinaryTag = "BA";
/// <summary>
/// Element tag for scriptblock property.
/// </summary>
/// <remarks>This property is used for System.Management.Automation.ScriptBlock type</remarks>
internal const string ScriptBlockTag = "SBK";
/// <summary>
/// Element tag for string property.
/// </summary>
/// <remarks>This property is used for System.String type</remarks>
internal const string StringTag = "S";
/// <summary>
/// Element tag for secure string property
/// </summary>
/// <remarks>This property is used for System.Security.SecureString type</remarks>
internal const string SecureStringTag = "SS";
/// <summary>
/// Element tag for unsignedShort property.
/// </summary>
/// <remarks>This property is used for System.UInt16 Stream type</remarks>
internal const string UnsignedShortTag = "U16";
/// <summary>
/// Element tag for unsignedInt property.
/// </summary>
/// <remarks>This property is used for System.UInt32 type</remarks>
internal const string UnsignedIntTag = "U32";
/// <summary>
/// Element tag for unsignedLong property.
/// </summary>
/// <remarks>This property is used for System.Long type</remarks>
internal const string UnsignedLongTag = "U64";
/// <summary>
/// Element tag for anyUri property.
/// </summary>
/// <remarks>This property is used for System.Uri type</remarks>
internal const string AnyUriTag = "URI";
/// <summary>
/// Element tag for Version property
/// </summary>
internal const string VersionTag = "Version";
/// <summary>
/// Element tag for SemanticVersion property
/// </summary>
internal const string SemanticVersionTag = "SemanticVersion";
/// <summary>
/// Element tag for XmlDocument
/// </summary>
internal const string XmlDocumentTag = "XD";
/// <summary>
/// Element tag for property whose value is null
/// </summary>
internal const string NilTag = "Nil";
/// <summary>
/// Element tag for PSObjectReference property.
/// </summary>
/// <remarks>This property is used for a reference to a property bag</remarks>
internal const string ReferenceTag = "Ref";
#region progress record
internal const string ProgressRecord = "PR";
internal const string ProgressRecordActivityId = "AI";
internal const string ProgressRecordParentActivityId = "PI";
internal const string ProgressRecordActivity = "AV";
internal const string ProgressRecordStatusDescription = "SD";
internal const string ProgressRecordCurrentOperation = "CO";
internal const string ProgressRecordPercentComplete = "PC";
internal const string ProgressRecordSecondsRemaining = "SR";
internal const string ProgressRecordType = "T";
#endregion progress record
#endregion primitive known type tags
#endregion element tags
#region attribute tags
/// <summary>
/// String for reference id attribute
/// </summary>
internal const string ReferenceIdAttribute = "RefId";
/// <summary>
/// String for name attribute
/// </summary>
internal const string NameAttribute = "N";
/// <summary>
/// String for version attribute
/// </summary>
internal const string VersionAttribute = "Version";
/// <summary>
/// String for stream attribute
/// </summary>
internal const string StreamNameAttribute = "S";
#endregion attribute tags
#region namespace values
/// <summary>
/// Monad namespace
/// </summary>
internal const string MonadNamespace = "http://schemas.microsoft.com/powershell/2004/04";
/// <summary>
/// Prefix string for monad namespace
/// </summary>
internal const string MonadNamespacePrefix = "ps";
#endregion namespace values
};
}
| |
// 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.CompilerServices;
using System.Security;
namespace System.Net.Http
{
internal static class WinHttpTraceHelper
{
private const string WinHtpTraceEnvironmentVariable = "WINHTTPHANDLER_TRACE";
private static readonly bool s_traceEnabled = IsTraceEnabledViaEnvironmentVariable();
private static bool IsTraceEnabledViaEnvironmentVariable()
{
string env;
try
{
env = Environment.GetEnvironmentVariable(WinHtpTraceEnvironmentVariable);
}
catch (SecurityException)
{
env = null;
}
return !string.IsNullOrEmpty(env);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsTraceEnabled()
{
return s_traceEnabled;
}
public static void Trace(string message)
{
if (!IsTraceEnabled())
{
return;
}
Debug.WriteLine(message);
}
public static void Trace(string format, bool arg0)
{
if (!IsTraceEnabled())
{
return;
}
Debug.WriteLine(format, arg0);
}
public static void Trace(string format, int arg0)
{
if (!IsTraceEnabled())
{
return;
}
Debug.WriteLine(format, arg0);
}
public static void Trace(string format, string arg0)
{
if (!IsTraceEnabled())
{
return;
}
Debug.WriteLine(format, arg0);
}
public static void Trace(string format, string arg0, string arg1)
{
if (!IsTraceEnabled())
{
return;
}
Debug.WriteLine(format, arg0, arg1);
}
public static void Trace(string format, IntPtr arg0, bool arg1, bool arg2)
{
if (!IsTraceEnabled())
{
return;
}
Debug.WriteLine(format, arg0, arg1, arg2);
}
public static void Trace(string format, string arg0, bool arg1, string arg2, string arg3)
{
if (!IsTraceEnabled())
{
return;
}
Debug.WriteLine(format, arg0, arg1, arg2, arg3);
}
public static void TraceCallbackStatus(string message, IntPtr handle, IntPtr context, uint status)
{
if (!IsTraceEnabled())
{
return;
}
Debug.WriteLine(
"{0}: handle=0x{1:X}, context=0x{2:X}, {3}",
message,
handle,
context,
GetStringFromInternetStatus(status));
}
public static void TraceAsyncError(string message, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult)
{
if (!IsTraceEnabled())
{
return;
}
uint apiIndex = (uint)asyncResult.dwResult.ToInt32();
uint error = asyncResult.dwError;
Debug.WriteLine(
"{0}: api={1}, error={2}({3}) \"{4}\"",
message,
GetNameFromApiIndex(apiIndex),
GetNameFromError(error),
error,
WinHttpException.GetErrorMessage((int)error));
}
private static string GetNameFromApiIndex(uint index)
{
switch (index)
{
case Interop.WinHttp.API_RECEIVE_RESPONSE:
return "API_RECEIVE_RESPONSE";
case Interop.WinHttp.API_QUERY_DATA_AVAILABLE:
return "API_QUERY_DATA_AVAILABLE";
case Interop.WinHttp.API_READ_DATA:
return "API_READ_DATA";
case Interop.WinHttp.API_WRITE_DATA:
return "API_WRITE_DATA";
case Interop.WinHttp.API_SEND_REQUEST:
return "API_SEND_REQUEST";
default:
return index.ToString();
}
}
private static string GetNameFromError(uint error)
{
switch (error)
{
case Interop.WinHttp.ERROR_FILE_NOT_FOUND:
return "ERROR_FILE_NOT_FOUND";
case Interop.WinHttp.ERROR_INVALID_HANDLE:
return "ERROR_INVALID_HANDLE";
case Interop.WinHttp.ERROR_INVALID_PARAMETER:
return "ERROR_INVALID_PARAMETER";
case Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER:
return "ERROR_INSUFFICIENT_BUFFER";
case Interop.WinHttp.ERROR_NOT_FOUND:
return "ERROR_NOT_FOUND";
case Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION:
return "WINHTTP_INVALID_OPTION";
case Interop.WinHttp.ERROR_WINHTTP_LOGIN_FAILURE:
return "WINHTTP_LOGIN_FAILURE";
case Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED:
return "WINHTTP_OPERATION_CANCELLED";
case Interop.WinHttp.ERROR_WINHTTP_INCORRECT_HANDLE_STATE:
return "WINHTTP_INCORRECT_HANDLE_STATE";
case Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR:
return "WINHTTP_CONNECTION_ERROR";
case Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST:
return "WINHTTP_RESEND_REQUEST";
case Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED:
return "WINHTTP_CLIENT_AUTH_CERT_NEEDED";
case Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND:
return "WINHTTP_HEADER_NOT_FOUND";
case Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE:
return "WINHTTP_SECURE_FAILURE";
case Interop.WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED:
return "WINHTTP_AUTODETECTION_FAILED";
default:
return error.ToString();
}
}
private static string GetStringFromInternetStatus(uint status)
{
switch (status)
{
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_RESOLVING_NAME:
return "STATUS_RESOLVING_NAME";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_NAME_RESOLVED:
return "STATUS_NAME_RESOLVED";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER:
return "STATUS_CONNECTING_TO_SERVER";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER:
return "STATUS_CONNECTED_TO_SERVER";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDING_REQUEST:
return "STATUS_SENDING_REQUEST";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_SENT:
return "STATUS_REQUEST_SENT";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE:
return "STATUS_RECEIVING_RESPONSE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED:
return "STATUS_RESPONSE_RECEIVED";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION:
return "STATUS_CLOSING_CONNECTION";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED:
return "STATUS_CONNECTION_CLOSED";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CREATED:
return "STATUS_HANDLE_CREATED";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING:
return "STATUS_HANDLE_CLOSING";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DETECTING_PROXY:
return "STATUS_DETECTING_PROXY";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REDIRECT:
return "STATUS_REDIRECT";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE:
return "STATUS_INTERMEDIATE_RESPONSE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SECURE_FAILURE:
return "STATUS_SECURE_FAILURE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE:
return "STATUS_HEADERS_AVAILABLE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
return "STATUS_DATA_AVAILABLE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
return "STATUS_READ_COMPLETE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE:
return "STATUS_WRITE_COMPLETE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
return "STATUS_REQUEST_ERROR";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE:
return "STATUS_SENDREQUEST_COMPLETE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE:
return "STATUS_GETPROXYFORURL_COMPLETE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE:
return "STATUS_CLOSE_COMPLETE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE:
return "STATUS_SHUTDOWN_COMPLETE";
default:
return string.Format("0x{0:X}", status);
}
}
}
}
| |
using Lucene.Net.Analysis.TokenAttributes;
using NUnit.Framework;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Analysis
{
/*
* 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 Attribute = Lucene.Net.Util.Attribute;
using BytesRef = Lucene.Net.Util.BytesRef;
using IAttribute = Lucene.Net.Util.IAttribute;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestToken : LuceneTestCase
{
[Test]
public virtual void TestCtor()
{
Token t = new Token();
char[] content = "hello".ToCharArray();
t.CopyBuffer(content, 0, content.Length);
Assert.AreNotSame(t.Buffer, content);
Assert.AreEqual(0, t.StartOffset);
Assert.AreEqual(0, t.EndOffset);
Assert.AreEqual("hello", t.ToString());
Assert.AreEqual("word", t.Type);
Assert.AreEqual(0, t.Flags);
t = new Token(6, 22);
t.CopyBuffer(content, 0, content.Length);
Assert.AreEqual("hello", t.ToString());
Assert.AreEqual("hello", t.ToString());
Assert.AreEqual(6, t.StartOffset);
Assert.AreEqual(22, t.EndOffset);
Assert.AreEqual("word", t.Type);
Assert.AreEqual(0, t.Flags);
t = new Token(6, 22, 7);
t.CopyBuffer(content, 0, content.Length);
Assert.AreEqual("hello", t.ToString());
Assert.AreEqual("hello", t.ToString());
Assert.AreEqual(6, t.StartOffset);
Assert.AreEqual(22, t.EndOffset);
Assert.AreEqual("word", t.Type);
Assert.AreEqual(7, t.Flags);
t = new Token(6, 22, "junk");
t.CopyBuffer(content, 0, content.Length);
Assert.AreEqual("hello", t.ToString());
Assert.AreEqual("hello", t.ToString());
Assert.AreEqual(6, t.StartOffset);
Assert.AreEqual(22, t.EndOffset);
Assert.AreEqual("junk", t.Type);
Assert.AreEqual(0, t.Flags);
}
[Test]
public virtual void TestResize()
{
Token t = new Token();
char[] content = "hello".ToCharArray();
t.CopyBuffer(content, 0, content.Length);
for (int i = 0; i < 2000; i++)
{
t.ResizeBuffer(i);
Assert.IsTrue(i <= t.Buffer.Length);
Assert.AreEqual("hello", t.ToString());
}
}
[Test]
public virtual void TestGrow()
{
Token t = new Token();
StringBuilder buf = new StringBuilder("ab");
for (int i = 0; i < 20; i++)
{
char[] content = buf.ToString().ToCharArray();
t.CopyBuffer(content, 0, content.Length);
Assert.AreEqual(buf.Length, t.Length);
Assert.AreEqual(buf.ToString(), t.ToString());
buf.Append(buf.ToString());
}
Assert.AreEqual(1048576, t.Length);
// now as a string, second variant
t = new Token();
buf = new StringBuilder("ab");
for (int i = 0; i < 20; i++)
{
t.SetEmpty().Append(buf);
string content = buf.ToString();
Assert.AreEqual(content.Length, t.Length);
Assert.AreEqual(content, t.ToString());
buf.Append(content);
}
Assert.AreEqual(1048576, t.Length);
// Test for slow growth to a long term
t = new Token();
buf = new StringBuilder("a");
for (int i = 0; i < 20000; i++)
{
t.SetEmpty().Append(buf);
string content = buf.ToString();
Assert.AreEqual(content.Length, t.Length);
Assert.AreEqual(content, t.ToString());
buf.Append("a");
}
Assert.AreEqual(20000, t.Length);
// Test for slow growth to a long term
t = new Token();
buf = new StringBuilder("a");
for (int i = 0; i < 20000; i++)
{
t.SetEmpty().Append(buf);
string content = buf.ToString();
Assert.AreEqual(content.Length, t.Length);
Assert.AreEqual(content, t.ToString());
buf.Append("a");
}
Assert.AreEqual(20000, t.Length);
}
[Test]
public virtual void TestToString()
{
char[] b = new char[] { 'a', 'l', 'o', 'h', 'a' };
Token t = new Token("", 0, 5);
t.CopyBuffer(b, 0, 5);
Assert.AreEqual("aloha", t.ToString());
t.SetEmpty().Append("hi there");
Assert.AreEqual("hi there", t.ToString());
}
[Test]
public virtual void TestTermBufferEquals()
{
Token t1a = new Token();
char[] content1a = "hello".ToCharArray();
t1a.CopyBuffer(content1a, 0, 5);
Token t1b = new Token();
char[] content1b = "hello".ToCharArray();
t1b.CopyBuffer(content1b, 0, 5);
Token t2 = new Token();
char[] content2 = "hello2".ToCharArray();
t2.CopyBuffer(content2, 0, 6);
Assert.IsTrue(t1a.Equals(t1b));
Assert.IsFalse(t1a.Equals(t2));
Assert.IsFalse(t2.Equals(t1b));
}
[Test]
public virtual void TestMixedStringArray()
{
Token t = new Token("hello", 0, 5);
Assert.AreEqual(t.Length, 5);
Assert.AreEqual(t.ToString(), "hello");
t.SetEmpty().Append("hello2");
Assert.AreEqual(t.Length, 6);
Assert.AreEqual(t.ToString(), "hello2");
t.CopyBuffer("hello3".ToCharArray(), 0, 6);
Assert.AreEqual(t.ToString(), "hello3");
char[] buffer = t.Buffer;
buffer[1] = 'o';
Assert.AreEqual(t.ToString(), "hollo3");
}
[Test]
public virtual void TestClone()
{
Token t = new Token(0, 5);
char[] content = "hello".ToCharArray();
t.CopyBuffer(content, 0, 5);
char[] buf = t.Buffer;
Token copy = AssertCloneIsEqual(t);
Assert.AreEqual(t.ToString(), copy.ToString());
Assert.AreNotSame(buf, copy.Buffer);
BytesRef pl = new BytesRef(new byte[] { 1, 2, 3, 4 });
t.Payload = pl;
copy = AssertCloneIsEqual(t);
Assert.AreEqual(pl, copy.Payload);
Assert.AreNotSame(pl, copy.Payload);
}
[Test]
public virtual void TestCopyTo()
{
Token t = new Token();
Token copy = AssertCopyIsEqual(t);
Assert.AreEqual("", t.ToString());
Assert.AreEqual("", copy.ToString());
t = new Token(0, 5);
char[] content = "hello".ToCharArray();
t.CopyBuffer(content, 0, 5);
char[] buf = t.Buffer;
copy = AssertCopyIsEqual(t);
Assert.AreEqual(t.ToString(), copy.ToString());
Assert.AreNotSame(buf, copy.Buffer);
BytesRef pl = new BytesRef(new byte[] { 1, 2, 3, 4 });
t.Payload = pl;
copy = AssertCopyIsEqual(t);
Assert.AreEqual(pl, copy.Payload);
Assert.AreNotSame(pl, copy.Payload);
}
public interface ISenselessAttribute : Lucene.Net.Util.IAttribute
{
}
public sealed class SenselessAttribute : Attribute, ISenselessAttribute
{
public override void CopyTo(IAttribute target)
{
}
public override void Clear()
{
}
public override bool Equals(object o)
{
return (o is SenselessAttribute);
}
public override int GetHashCode()
{
return 0;
}
}
[Test]
public virtual void TestTokenAttributeFactory()
{
TokenStream ts = new MockTokenizer(Token.TOKEN_ATTRIBUTE_FACTORY, new StringReader("foo bar"), MockTokenizer.WHITESPACE, false, MockTokenizer.DEFAULT_MAX_TOKEN_LENGTH);
Assert.IsTrue(ts.AddAttribute<ISenselessAttribute>() is SenselessAttribute, "SenselessAttribute is not implemented by SenselessAttributeImpl");
Assert.IsTrue(ts.AddAttribute<ICharTermAttribute>() is Token, "CharTermAttribute is not implemented by Token");
Assert.IsTrue(ts.AddAttribute<IOffsetAttribute>() is Token, "OffsetAttribute is not implemented by Token");
Assert.IsTrue(ts.AddAttribute<IFlagsAttribute>() is Token, "FlagsAttribute is not implemented by Token");
Assert.IsTrue(ts.AddAttribute<IPayloadAttribute>() is Token, "PayloadAttribute is not implemented by Token");
Assert.IsTrue(ts.AddAttribute<IPositionIncrementAttribute>() is Token, "PositionIncrementAttribute is not implemented by Token");
Assert.IsTrue(ts.AddAttribute<ITypeAttribute>() is Token, "TypeAttribute is not implemented by Token");
}
[Test]
public virtual void TestAttributeReflection()
{
Token t = new Token("foobar", 6, 22, 8);
TestUtil.AssertAttributeReflection(t, new Dictionary<string, object>()
{
{ typeof(ICharTermAttribute).Name + "#term", "foobar" },
{ typeof(ITermToBytesRefAttribute).Name + "#bytes", new BytesRef("foobar") },
{ typeof(IOffsetAttribute).Name + "#startOffset", 6 },
{ typeof(IOffsetAttribute).Name + "#endOffset", 22 },
{ typeof(IPositionIncrementAttribute).Name + "#positionIncrement", 1 },
{ typeof(IPayloadAttribute).Name + "#payload", null },
{ typeof(ITypeAttribute).Name + "#type", TypeAttribute.DEFAULT_TYPE },
{ typeof(IFlagsAttribute).Name + "#flags", 8 }
});
}
public static T AssertCloneIsEqual<T>(T att) where T : Attribute
{
T clone = (T)att.Clone();
Assert.AreEqual(att, clone, "Clone must be equal");
Assert.AreEqual(att.GetHashCode(), clone.GetHashCode(), "Clone's hashcode must be equal");
return clone;
}
public static T AssertCopyIsEqual<T>(T att) where T : Attribute
{
T copy = (T)System.Activator.CreateInstance(att.GetType());
att.CopyTo(copy);
Assert.AreEqual(att, copy, "Copied instance must be equal");
Assert.AreEqual(att.GetHashCode(), copy.GetHashCode(), "Copied instance's hashcode must be equal");
return copy;
}
}
}
| |
/*
* 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.
*/
//#define SPAM
using System;
using System.Collections.Generic;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO.Compression;
using PrimMesher;
using log4net;
using Nini.Config;
using System.Reflection;
using System.IO;
using ComponentAce.Compression.Libs.zlib;
namespace OpenSim.Region.Physics.Meshing
{
public class MeshmerizerPlugin : IMeshingPlugin
{
public MeshmerizerPlugin()
{
}
public string GetName()
{
return "Meshmerizer";
}
public IMesher GetMesher(IConfigSource config)
{
return new Meshmerizer(config);
}
}
public class Meshmerizer : IMesher
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Setting baseDir to a path will enable the dumping of raw files
// raw files can be imported by blender so a visual inspection of the results can be done
#if SPAM
const string baseDir = "rawFiles";
#else
private const string baseDir = null; //"rawFiles";
#endif
private bool cacheSculptMaps = true;
private string decodedSculptMapPath = null;
private bool useMeshiesPhysicsMesh = false;
private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh
private Dictionary<ulong, Mesh> m_uniqueMeshes = new Dictionary<ulong, Mesh>();
public Meshmerizer(IConfigSource config)
{
IConfig start_config = config.Configs["Startup"];
IConfig mesh_config = config.Configs["Mesh"];
decodedSculptMapPath = start_config.GetString("DecodedSculptMapPath","j2kDecodeCache");
cacheSculptMaps = start_config.GetBoolean("CacheSculptMaps", cacheSculptMaps);
if(mesh_config != null)
useMeshiesPhysicsMesh = mesh_config.GetBoolean("UseMeshiesPhysicsMesh", useMeshiesPhysicsMesh);
try
{
if (!Directory.Exists(decodedSculptMapPath))
Directory.CreateDirectory(decodedSculptMapPath);
}
catch (Exception e)
{
m_log.WarnFormat("[SCULPT]: Unable to create {0} directory: ", decodedSculptMapPath, e.Message);
}
}
/// <summary>
/// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may
/// be useful as a backup proxy when level of detail is not needed or when more complex meshes fail
/// for some reason
/// </summary>
/// <param name="minX"></param>
/// <param name="maxX"></param>
/// <param name="minY"></param>
/// <param name="maxY"></param>
/// <param name="minZ"></param>
/// <param name="maxZ"></param>
/// <returns></returns>
private static Mesh CreateSimpleBoxMesh(float minX, float maxX, float minY, float maxY, float minZ, float maxZ)
{
Mesh box = new Mesh();
List<Vertex> vertices = new List<Vertex>();
// bottom
vertices.Add(new Vertex(minX, maxY, minZ));
vertices.Add(new Vertex(maxX, maxY, minZ));
vertices.Add(new Vertex(maxX, minY, minZ));
vertices.Add(new Vertex(minX, minY, minZ));
box.Add(new Triangle(vertices[0], vertices[1], vertices[2]));
box.Add(new Triangle(vertices[0], vertices[2], vertices[3]));
// top
vertices.Add(new Vertex(maxX, maxY, maxZ));
vertices.Add(new Vertex(minX, maxY, maxZ));
vertices.Add(new Vertex(minX, minY, maxZ));
vertices.Add(new Vertex(maxX, minY, maxZ));
box.Add(new Triangle(vertices[4], vertices[5], vertices[6]));
box.Add(new Triangle(vertices[4], vertices[6], vertices[7]));
// sides
box.Add(new Triangle(vertices[5], vertices[0], vertices[3]));
box.Add(new Triangle(vertices[5], vertices[3], vertices[6]));
box.Add(new Triangle(vertices[1], vertices[0], vertices[5]));
box.Add(new Triangle(vertices[1], vertices[5], vertices[4]));
box.Add(new Triangle(vertices[7], vertices[1], vertices[4]));
box.Add(new Triangle(vertices[7], vertices[2], vertices[1]));
box.Add(new Triangle(vertices[3], vertices[2], vertices[7]));
box.Add(new Triangle(vertices[3], vertices[7], vertices[6]));
return box;
}
/// <summary>
/// Creates a simple bounding box mesh for a complex input mesh
/// </summary>
/// <param name="meshIn"></param>
/// <returns></returns>
private static Mesh CreateBoundingBoxMesh(Mesh meshIn)
{
float minX = float.MaxValue;
float maxX = float.MinValue;
float minY = float.MaxValue;
float maxY = float.MinValue;
float minZ = float.MaxValue;
float maxZ = float.MinValue;
foreach (Vector3 v in meshIn.getVertexList())
{
if (v.X < minX) minX = v.X;
if (v.Y < minY) minY = v.Y;
if (v.Z < minZ) minZ = v.Z;
if (v.X > maxX) maxX = v.X;
if (v.Y > maxY) maxY = v.Y;
if (v.Z > maxZ) maxZ = v.Z;
}
return CreateSimpleBoxMesh(minX, maxX, minY, maxY, minZ, maxZ);
}
private void ReportPrimError(string message, string primName, PrimMesh primMesh)
{
m_log.Error(message);
m_log.Error("\nPrim Name: " + primName);
m_log.Error("****** PrimMesh Parameters ******\n" + primMesh.ParamsToDisplayString());
}
/// <summary>
/// Add a submesh to an existing list of coords and faces.
/// </summary>
/// <param name="subMeshData"></param>
/// <param name="size">Size of entire object</param>
/// <param name="coords"></param>
/// <param name="faces"></param>
private void AddSubMesh(OSDMap subMeshData, Vector3 size, List<Coord> coords, List<Face> faces)
{
// Console.WriteLine("subMeshMap for {0} - {1}", primName, Util.GetFormattedXml((OSD)subMeshMap));
// As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level
// of Detail Blocks (maps) contain just a NoGeometry key to signal there is no
// geometry for this submesh.
if (subMeshData.ContainsKey("NoGeometry") && ((OSDBoolean)subMeshData["NoGeometry"]))
return;
OpenMetaverse.Vector3 posMax = ((OSDMap)subMeshData["PositionDomain"])["Max"].AsVector3();
OpenMetaverse.Vector3 posMin = ((OSDMap)subMeshData["PositionDomain"])["Min"].AsVector3();
ushort faceIndexOffset = (ushort)coords.Count;
byte[] posBytes = subMeshData["Position"].AsBinary();
for (int i = 0; i < posBytes.Length; i += 6)
{
ushort uX = Utils.BytesToUInt16(posBytes, i);
ushort uY = Utils.BytesToUInt16(posBytes, i + 2);
ushort uZ = Utils.BytesToUInt16(posBytes, i + 4);
Coord c = new Coord(
Utils.UInt16ToFloat(uX, posMin.X, posMax.X) * size.X,
Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y) * size.Y,
Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z) * size.Z);
coords.Add(c);
}
byte[] triangleBytes = subMeshData["TriangleList"].AsBinary();
for (int i = 0; i < triangleBytes.Length; i += 6)
{
ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset);
ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset);
ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset);
Face f = new Face(v1, v2, v3);
faces.Add(f);
}
}
/// <summary>
/// Create a physics mesh from data that comes with the prim. The actual data used depends on the prim type.
/// </summary>
/// <param name="primName"></param>
/// <param name="primShape"></param>
/// <param name="size"></param>
/// <param name="lod"></param>
/// <returns></returns>
private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
{
// m_log.DebugFormat(
// "[MESH]: Creating physics proxy for {0}, shape {1}",
// primName, (OpenMetaverse.SculptType)primShape.SculptType);
List<Coord> coords;
List<Face> faces;
if (primShape.SculptEntry)
{
if (((OpenMetaverse.SculptType)primShape.SculptType) == SculptType.Mesh)
{
if (!useMeshiesPhysicsMesh)
return null;
if (!GenerateCoordsAndFacesFromPrimMeshData(primName, primShape, size, out coords, out faces))
return null;
}
else
{
if (!GenerateCoordsAndFacesFromPrimSculptData(primName, primShape, size, lod, out coords, out faces))
return null;
}
}
else
{
if (!GenerateCoordsAndFacesFromPrimShapeData(primName, primShape, size, lod, out coords, out faces))
return null;
}
// Remove the reference to any JPEG2000 sculpt data so it can be GCed
primShape.SculptData = Utils.EmptyBytes;
int numCoords = coords.Count;
int numFaces = faces.Count;
// Create the list of vertices
List<Vertex> vertices = new List<Vertex>();
for (int i = 0; i < numCoords; i++)
{
Coord c = coords[i];
vertices.Add(new Vertex(c.X, c.Y, c.Z));
}
Mesh mesh = new Mesh();
// Add the corresponding triangles to the mesh
for (int i = 0; i < numFaces; i++)
{
Face f = faces[i];
mesh.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3]));
}
return mesh;
}
/// <summary>
/// Generate the co-ords and faces necessary to construct a mesh from the mesh data the accompanies a prim.
/// </summary>
/// <param name="primName"></param>
/// <param name="primShape"></param>
/// <param name="size"></param>
/// <param name="coords">Coords are added to this list by the method.</param>
/// <param name="faces">Faces are added to this list by the method.</param>
/// <returns>true if coords and faces were successfully generated, false if not</returns>
private bool GenerateCoordsAndFacesFromPrimMeshData(
string primName, PrimitiveBaseShape primShape, Vector3 size, out List<Coord> coords, out List<Face> faces)
{
// m_log.DebugFormat("[MESH]: experimental mesh proxy generation for {0}", primName);
coords = new List<Coord>();
faces = new List<Face>();
OSD meshOsd = null;
if (primShape.SculptData.Length <= 0)
{
// XXX: At the moment we can not log here since ODEPrim, for instance, ends up triggering this
// method twice - once before it has loaded sculpt data from the asset service and once afterwards.
// The first time will always call with unloaded SculptData if this needs to be uploaded.
// m_log.ErrorFormat("[MESH]: asset data for {0} is zero length", primName);
return false;
}
long start = 0;
using (MemoryStream data = new MemoryStream(primShape.SculptData))
{
try
{
OSD osd = OSDParser.DeserializeLLSDBinary(data);
if (osd is OSDMap)
meshOsd = (OSDMap)osd;
else
{
m_log.Warn("[Mesh}: unable to cast mesh asset to OSDMap");
return false;
}
}
catch (Exception e)
{
m_log.Error("[MESH]: Exception deserializing mesh asset header:" + e.ToString());
}
start = data.Position;
}
if (meshOsd is OSDMap)
{
OSDMap physicsParms = null;
OSDMap map = (OSDMap)meshOsd;
if (map.ContainsKey("physics_shape"))
physicsParms = (OSDMap)map["physics_shape"]; // old asset format
else if (map.ContainsKey("physics_mesh"))
physicsParms = (OSDMap)map["physics_mesh"]; // new asset format
if (physicsParms == null)
{
m_log.WarnFormat("[MESH]: No recognized physics mesh found in mesh asset for {0}", primName);
return false;
}
int physOffset = physicsParms["offset"].AsInteger() + (int)start;
int physSize = physicsParms["size"].AsInteger();
if (physOffset < 0 || physSize == 0)
return false; // no mesh data in asset
OSD decodedMeshOsd = new OSD();
byte[] meshBytes = new byte[physSize];
System.Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize);
// byte[] decompressed = new byte[physSize * 5];
try
{
using (MemoryStream inMs = new MemoryStream(meshBytes))
{
using (MemoryStream outMs = new MemoryStream())
{
using (ZOutputStream zOut = new ZOutputStream(outMs))
{
byte[] readBuffer = new byte[2048];
int readLen = 0;
while ((readLen = inMs.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
zOut.Write(readBuffer, 0, readLen);
}
zOut.Flush();
outMs.Seek(0, SeekOrigin.Begin);
byte[] decompressedBuf = outMs.GetBuffer();
decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
}
}
}
}
catch (Exception e)
{
m_log.Error("[MESH]: exception decoding physical mesh: " + e.ToString());
return false;
}
OSDArray decodedMeshOsdArray = null;
// physics_shape is an array of OSDMaps, one for each submesh
if (decodedMeshOsd is OSDArray)
{
// Console.WriteLine("decodedMeshOsd for {0} - {1}", primName, Util.GetFormattedXml(decodedMeshOsd));
decodedMeshOsdArray = (OSDArray)decodedMeshOsd;
foreach (OSD subMeshOsd in decodedMeshOsdArray)
{
if (subMeshOsd is OSDMap)
AddSubMesh(subMeshOsd as OSDMap, size, coords, faces);
}
}
}
return true;
}
/// <summary>
/// Generate the co-ords and faces necessary to construct a mesh from the sculpt data the accompanies a prim.
/// </summary>
/// <param name="primName"></param>
/// <param name="primShape"></param>
/// <param name="size"></param>
/// <param name="lod"></param>
/// <param name="coords">Coords are added to this list by the method.</param>
/// <param name="faces">Faces are added to this list by the method.</param>
/// <returns>true if coords and faces were successfully generated, false if not</returns>
private bool GenerateCoordsAndFacesFromPrimSculptData(
string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces)
{
coords = new List<Coord>();
faces = new List<Face>();
PrimMesher.SculptMesh sculptMesh;
Image idata = null;
string decodedSculptFileName = "";
if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero)
{
decodedSculptFileName = System.IO.Path.Combine(decodedSculptMapPath, "smap_" + primShape.SculptTexture.ToString());
try
{
if (File.Exists(decodedSculptFileName))
{
idata = Image.FromFile(decodedSculptFileName);
}
}
catch (Exception e)
{
m_log.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e.Message);
}
//if (idata != null)
// m_log.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString());
}
if (idata == null)
{
if (primShape.SculptData == null || primShape.SculptData.Length == 0)
return false;
try
{
OpenMetaverse.Imaging.ManagedImage unusedData;
OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out unusedData, out idata);
if (idata == null)
{
// In some cases it seems that the decode can return a null bitmap without throwing
// an exception
m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName);
return false;
}
unusedData = null;
//idata = CSJ2K.J2kImage.FromBytes(primShape.SculptData);
if (cacheSculptMaps)
{
try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); }
catch (Exception e) { m_log.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e.Message); }
}
}
catch (DllNotFoundException)
{
m_log.Error("[PHYSICS]: OpenJpeg is not installed correctly on this system. Physics Proxy generation failed. Often times this is because of an old version of GLIBC. You must have version 2.4 or above!");
return false;
}
catch (IndexOutOfRangeException)
{
m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
return false;
}
catch (Exception ex)
{
m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
return false;
}
}
PrimMesher.SculptMesh.SculptType sculptType;
switch ((OpenMetaverse.SculptType)primShape.SculptType)
{
case OpenMetaverse.SculptType.Cylinder:
sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
break;
case OpenMetaverse.SculptType.Plane:
sculptType = PrimMesher.SculptMesh.SculptType.plane;
break;
case OpenMetaverse.SculptType.Torus:
sculptType = PrimMesher.SculptMesh.SculptType.torus;
break;
case OpenMetaverse.SculptType.Sphere:
sculptType = PrimMesher.SculptMesh.SculptType.sphere;
break;
default:
sculptType = PrimMesher.SculptMesh.SculptType.plane;
break;
}
bool mirror = ((primShape.SculptType & 128) != 0);
bool invert = ((primShape.SculptType & 64) != 0);
sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert);
idata.Dispose();
sculptMesh.DumpRaw(baseDir, primName, "primMesh");
sculptMesh.Scale(size.X, size.Y, size.Z);
coords = sculptMesh.coords;
faces = sculptMesh.faces;
return true;
}
/// <summary>
/// Generate the co-ords and faces necessary to construct a mesh from the shape data the accompanies a prim.
/// </summary>
/// <param name="primName"></param>
/// <param name="primShape"></param>
/// <param name="size"></param>
/// <param name="coords">Coords are added to this list by the method.</param>
/// <param name="faces">Faces are added to this list by the method.</param>
/// <returns>true if coords and faces were successfully generated, false if not</returns>
private bool GenerateCoordsAndFacesFromPrimShapeData(
string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces)
{
PrimMesh primMesh;
coords = new List<Coord>();
faces = new List<Face>();
float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
if (profileHollow > 0.95f)
profileHollow = 0.95f;
int sides = 4;
LevelOfDetail iLOD = (LevelOfDetail)lod;
if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
sides = 3;
else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
{
switch (iLOD)
{
case LevelOfDetail.High: sides = 24; break;
case LevelOfDetail.Medium: sides = 12; break;
case LevelOfDetail.Low: sides = 6; break;
case LevelOfDetail.VeryLow: sides = 3; break;
default: sides = 24; break;
}
}
else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
{ // half circle, prim is a sphere
switch (iLOD)
{
case LevelOfDetail.High: sides = 24; break;
case LevelOfDetail.Medium: sides = 12; break;
case LevelOfDetail.Low: sides = 6; break;
case LevelOfDetail.VeryLow: sides = 3; break;
default: sides = 24; break;
}
profileBegin = 0.5f * profileBegin + 0.5f;
profileEnd = 0.5f * profileEnd + 0.5f;
}
int hollowSides = sides;
if (primShape.HollowShape == HollowShape.Circle)
{
switch (iLOD)
{
case LevelOfDetail.High: hollowSides = 24; break;
case LevelOfDetail.Medium: hollowSides = 12; break;
case LevelOfDetail.Low: hollowSides = 6; break;
case LevelOfDetail.VeryLow: hollowSides = 3; break;
default: hollowSides = 24; break;
}
}
else if (primShape.HollowShape == HollowShape.Square)
hollowSides = 4;
else if (primShape.HollowShape == HollowShape.Triangle)
hollowSides = 3;
primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
if (primMesh.errorMessage != null)
if (primMesh.errorMessage.Length > 0)
m_log.Error("[ERROR] " + primMesh.errorMessage);
primMesh.topShearX = pathShearX;
primMesh.topShearY = pathShearY;
primMesh.pathCutBegin = pathBegin;
primMesh.pathCutEnd = pathEnd;
if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
{
primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
primMesh.twistEnd = primShape.PathTwist * 18 / 10;
primMesh.taperX = pathScaleX;
primMesh.taperY = pathScaleY;
if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
{
ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
if (profileBegin < 0.0f) profileBegin = 0.0f;
if (profileEnd > 1.0f) profileEnd = 1.0f;
}
#if SPAM
m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
#endif
try
{
primMesh.ExtrudeLinear();
}
catch (Exception ex)
{
ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
return false;
}
}
else
{
primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
primMesh.radius = 0.01f * primShape.PathRadiusOffset;
primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
primMesh.skew = 0.01f * primShape.PathSkew;
primMesh.twistBegin = primShape.PathTwistBegin * 36 / 10;
primMesh.twistEnd = primShape.PathTwist * 36 / 10;
primMesh.taperX = primShape.PathTaperX * 0.01f;
primMesh.taperY = primShape.PathTaperY * 0.01f;
if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
{
ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
if (profileBegin < 0.0f) profileBegin = 0.0f;
if (profileEnd > 1.0f) profileEnd = 1.0f;
}
#if SPAM
m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
#endif
try
{
primMesh.ExtrudeCircular();
}
catch (Exception ex)
{
ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
return false;
}
}
primMesh.DumpRaw(baseDir, primName, "primMesh");
primMesh.Scale(size.X, size.Y, size.Z);
coords = primMesh.coords;
faces = primMesh.faces;
return true;
}
public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
{
return CreateMesh(primName, primShape, size, lod, false, true);
}
public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
{
return CreateMesh(primName, primShape, size, lod, isPhysical, true);
}
public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache)
{
#if SPAM
m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName);
#endif
Mesh mesh = null;
ulong key = 0;
// If this mesh has been created already, return it instead of creating another copy
// For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
if (shouldCache)
{
key = primShape.GetMeshKey(size, lod);
if (m_uniqueMeshes.TryGetValue(key, out mesh))
return mesh;
}
if (size.X < 0.01f) size.X = 0.01f;
if (size.Y < 0.01f) size.Y = 0.01f;
if (size.Z < 0.01f) size.Z = 0.01f;
mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod);
if (mesh != null)
{
if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh)
{
#if SPAM
m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " +
minSizeForComplexMesh.ToString() + " - creating simple bounding box");
#endif
mesh = CreateBoundingBoxMesh(mesh);
mesh.DumpRaw(baseDir, primName, "Z extruded");
}
// trim the vertex and triangle lists to free up memory
mesh.TrimExcess();
if (shouldCache)
{
m_uniqueMeshes.Add(key, mesh);
}
}
return mesh;
}
}
}
| |
//
// AssemblyNameReference.cs
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Mono.Cecil
{
public class AssemblyNameReference : IMetadataScope
{
string name;
string culture;
Version version;
uint attributes;
byte[] public_key;
byte[] public_key_token;
AssemblyHashAlgorithm hash_algorithm;
byte[] hash;
internal MetadataToken token;
string full_name;
public string Name
{
get { return name; }
set
{
name = value;
full_name = null;
}
}
public string Culture
{
get { return culture; }
set
{
culture = value;
full_name = null;
}
}
public Version Version
{
get { return version; }
set
{
version = value;
full_name = null;
}
}
public AssemblyAttributes Attributes
{
get { return (AssemblyAttributes)attributes; }
set { attributes = (uint)value; }
}
public bool HasPublicKey
{
get { return Mixin.GetAttributes(attributes,(uint)AssemblyAttributes.PublicKey); }
set { attributes =Mixin.SetAttributes(attributes,(uint)AssemblyAttributes.PublicKey, value); }
}
public bool IsSideBySideCompatible
{
get { return Mixin.GetAttributes(attributes,(uint)AssemblyAttributes.SideBySideCompatible); }
set { attributes =Mixin.SetAttributes(attributes,(uint)AssemblyAttributes.SideBySideCompatible, value); }
}
public bool IsRetargetable
{
get { return Mixin.GetAttributes(attributes,(uint)AssemblyAttributes.Retargetable); }
set { attributes =Mixin.SetAttributes(attributes,(uint)AssemblyAttributes.Retargetable, value); }
}
public bool IsWindowsRuntime
{
get { return Mixin.GetAttributes(attributes,(uint)AssemblyAttributes.WindowsRuntime); }
set { attributes =Mixin.SetAttributes(attributes,(uint)AssemblyAttributes.WindowsRuntime, value); }
}
public byte[] PublicKey
{
get { return public_key ?? Empty<byte>.Array; }
set
{
public_key = value;
HasPublicKey = !Mixin.IsNullOrEmpty(public_key);
public_key_token = Empty<byte>.Array;
full_name = null;
}
}
public byte[] PublicKeyToken
{
get
{
if (Mixin.IsNullOrEmpty(public_key_token) && !Mixin.IsNullOrEmpty(public_key))
{
var hash = HashPublicKey();
// we need the last 8 bytes in reverse order
byte[] local_public_key_token = new byte[8];
Array.Copy(hash, (hash.Length - 8), local_public_key_token, 0, 8);
Array.Reverse(local_public_key_token, 0, 8);
public_key_token = local_public_key_token; // publish only once finished (required for thread-safety)
}
return public_key_token ?? Empty<byte>.Array;
}
set
{
public_key_token = value;
full_name = null;
}
}
byte[] HashPublicKey()
{
HashAlgorithm algorithm;
switch (hash_algorithm)
{
case AssemblyHashAlgorithm.Reserved:
throw new NotSupportedException();
default:
// None default to SHA1
algorithm = new SHA1Managed();
break;
}
using (algorithm)
return algorithm.ComputeHash(public_key);
}
public virtual MetadataScopeType MetadataScopeType
{
get { return MetadataScopeType.AssemblyNameReference; }
}
public string FullName
{
get
{
if (full_name != null)
return full_name;
const string sep = ", ";
var builder = new StringBuilder();
builder.Append(name);
if (version != null)
{
builder.Append(sep);
builder.Append("Version=");
builder.Append(version.ToString());
}
builder.Append(sep);
builder.Append("Culture=");
builder.Append(string.IsNullOrEmpty(culture) ? "neutral" : culture);
builder.Append(sep);
builder.Append("PublicKeyToken=");
var pk_token = PublicKeyToken;
if (!Mixin.IsNullOrEmpty(pk_token) && pk_token.Length > 0)
{
for (int i = 0; i < pk_token.Length; i++)
{
builder.Append(pk_token[i].ToString("x2"));
}
}
else
builder.Append("null");
return full_name = builder.ToString();
}
}
public static AssemblyNameReference Parse(string fullName)
{
if (fullName == null)
throw new ArgumentNullException("fullName");
if (fullName.Length == 0)
throw new ArgumentException("Name can not be empty");
var name = new AssemblyNameReference();
var tokens = fullName.Split(',');
for (int i = 0; i < tokens.Length; i++)
{
var token = tokens[i].Trim();
if (i == 0)
{
name.Name = token;
continue;
}
var parts = token.Split('=');
if (parts.Length != 2)
throw new ArgumentException("Malformed name");
switch (parts[0].ToLowerInvariant())
{
case "version":
name.Version = new Version(parts[1]);
break;
case "culture":
name.Culture = parts[1];
break;
case "publickeytoken":
var pk_token = parts[1];
if (pk_token == "null")
break;
name.PublicKeyToken = new byte[pk_token.Length / 2];
for (int j = 0; j < name.PublicKeyToken.Length; j++)
name.PublicKeyToken[j] = Byte.Parse(pk_token.Substring(j * 2, 2), NumberStyles.HexNumber);
break;
}
}
return name;
}
public AssemblyHashAlgorithm HashAlgorithm
{
get { return hash_algorithm; }
set { hash_algorithm = value; }
}
public virtual byte[] Hash
{
get { return hash; }
set { hash = value; }
}
public MetadataToken MetadataToken
{
get { return token; }
set { token = value; }
}
internal AssemblyNameReference()
{
}
public AssemblyNameReference(string name, Version version)
{
if (name == null)
throw new ArgumentNullException("name");
this.name = name;
this.version = version;
this.hash_algorithm = AssemblyHashAlgorithm.None;
this.token = new MetadataToken(TokenType.AssemblyRef);
}
public override string ToString()
{
return this.FullName;
}
}
}
| |
// 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.Concurrent;
using System.Globalization;
using System.Reflection;
namespace System.Runtime.Serialization.Formatters.Binary
{
internal sealed class ParseRecord
{
// Enums
internal InternalParseTypeE _parseTypeEnum = InternalParseTypeE.Empty;
internal InternalObjectTypeE _objectTypeEnum = InternalObjectTypeE.Empty;
internal InternalArrayTypeE _arrayTypeEnum = InternalArrayTypeE.Empty;
internal InternalMemberTypeE _memberTypeEnum = InternalMemberTypeE.Empty;
internal InternalMemberValueE _memberValueEnum = InternalMemberValueE.Empty;
internal InternalObjectPositionE _objectPositionEnum = InternalObjectPositionE.Empty;
// Object
internal string _name;
// Value
internal string _value;
internal object _varValue;
// dt attribute
internal string _keyDt;
internal Type _dtType;
internal InternalPrimitiveTypeE _dtTypeCode;
// Object ID
internal long _objectId;
// Reference ID
internal long _idRef;
// Array
// Array Element Type
internal string _arrayElementTypeString;
internal Type _arrayElementType;
internal bool _isArrayVariant = false;
internal InternalPrimitiveTypeE _arrayElementTypeCode;
// Parsed array information
internal int _rank;
internal int[] _lengthA;
internal int[] _lowerBoundA;
// Array map for placing array elements in array
internal int[] _indexMap;
internal int _memberIndex;
internal int _linearlength;
internal int[] _rectangularMap;
internal bool _isLowerBound;
// MemberInfo accumulated during parsing of members
internal ReadObjectInfo _objectInfo;
// ValueType Fixup needed
internal bool _isValueTypeFixup = false;
// Created object
internal object _newObj;
internal object[] _objectA; //optimization, will contain object[]
internal PrimitiveArray _primitiveArray; // for Primitive Soap arrays, optimization
internal bool _isRegistered; // Used when registering nested classes
internal object[] _memberData; // member data is collected here before populating
internal SerializationInfo _si;
internal int _consecutiveNullArrayEntryCount;
internal ParseRecord() { }
// Initialize ParseRecord. Called when reusing.
internal void Init()
{
// Enums
_parseTypeEnum = InternalParseTypeE.Empty;
_objectTypeEnum = InternalObjectTypeE.Empty;
_arrayTypeEnum = InternalArrayTypeE.Empty;
_memberTypeEnum = InternalMemberTypeE.Empty;
_memberValueEnum = InternalMemberValueE.Empty;
_objectPositionEnum = InternalObjectPositionE.Empty;
// Object
_name = null;
// Value
_value = null;
// dt attribute
_keyDt = null;
_dtType = null;
_dtTypeCode = InternalPrimitiveTypeE.Invalid;
// Object ID
_objectId = 0;
// Reference ID
_idRef = 0;
// Array
// Array Element Type
_arrayElementTypeString = null;
_arrayElementType = null;
_isArrayVariant = false;
_arrayElementTypeCode = InternalPrimitiveTypeE.Invalid;
// Parsed array information
_rank = 0;
_lengthA = null;
_lowerBoundA = null;
// Array map for placing array elements in array
_indexMap = null;
_memberIndex = 0;
_linearlength = 0;
_rectangularMap = null;
_isLowerBound = false;
// ValueType Fixup needed
_isValueTypeFixup = false;
_newObj = null;
_objectA = null;
_primitiveArray = null;
_objectInfo = null;
_isRegistered = false;
_memberData = null;
_si = null;
_consecutiveNullArrayEntryCount = 0;
}
}
// Implements a stack used for parsing
internal sealed class SerStack
{
internal object[] _objects = new object[5];
internal string _stackId;
internal int _top = -1;
internal SerStack(string stackId)
{
_stackId = stackId;
}
// Push the object onto the stack
internal void Push(object obj)
{
if (_top == (_objects.Length - 1))
{
IncreaseCapacity();
}
_objects[++_top] = obj;
}
// Pop the object from the stack
internal object Pop()
{
if (_top < 0)
{
return null;
}
object obj = _objects[_top];
_objects[_top--] = null;
return obj;
}
internal void IncreaseCapacity()
{
int size = _objects.Length * 2;
object[] newItems = new object[size];
Array.Copy(_objects, 0, newItems, 0, _objects.Length);
_objects = newItems;
}
// Gets the object on the top of the stack
internal object Peek() => _top < 0 ? null : _objects[_top];
// Gets the second entry in the stack.
internal object PeekPeek() => _top < 1 ? null : _objects[_top - 1];
// The number of entries in the stack
internal bool IsEmpty() => _top <= 0;
}
// Implements a Growable array
[Serializable]
internal sealed class SizedArray : ICloneable
{
internal object[] _objects = null;
internal object[] _negObjects = null;
internal SizedArray()
{
_objects = new object[16];
_negObjects = new object[4];
}
internal SizedArray(int length)
{
_objects = new object[length];
_negObjects = new object[length];
}
private SizedArray(SizedArray sizedArray)
{
_objects = new object[sizedArray._objects.Length];
sizedArray._objects.CopyTo(_objects, 0);
_negObjects = new object[sizedArray._negObjects.Length];
sizedArray._negObjects.CopyTo(_negObjects, 0);
}
public object Clone() => new SizedArray(this);
internal object this[int index]
{
get
{
if (index < 0)
{
return -index > _negObjects.Length - 1 ? null : _negObjects[-index];
}
else
{
return index > _objects.Length - 1 ? null : _objects[index];
}
}
set
{
if (index < 0)
{
if (-index > _negObjects.Length - 1)
{
IncreaseCapacity(index);
}
_negObjects[-index] = value;
}
else
{
if (index > _objects.Length - 1)
{
IncreaseCapacity(index);
}
_objects[index] = value;
}
}
}
internal void IncreaseCapacity(int index)
{
try
{
if (index < 0)
{
int size = Math.Max(_negObjects.Length * 2, (-index) + 1);
object[] newItems = new object[size];
Array.Copy(_negObjects, 0, newItems, 0, _negObjects.Length);
_negObjects = newItems;
}
else
{
int size = Math.Max(_objects.Length * 2, index + 1);
object[] newItems = new object[size];
Array.Copy(_objects, 0, newItems, 0, _objects.Length);
_objects = newItems;
}
}
catch (Exception)
{
throw new SerializationException(SR.Serialization_CorruptedStream);
}
}
}
[Serializable]
internal sealed class IntSizedArray : ICloneable
{
internal int[] _objects = new int[16];
internal int[] _negObjects = new int[4];
public IntSizedArray() { }
private IntSizedArray(IntSizedArray sizedArray)
{
_objects = new int[sizedArray._objects.Length];
sizedArray._objects.CopyTo(_objects, 0);
_negObjects = new int[sizedArray._negObjects.Length];
sizedArray._negObjects.CopyTo(_negObjects, 0);
}
public object Clone() => new IntSizedArray(this);
internal int this[int index]
{
get
{
if (index < 0)
{
return -index > _negObjects.Length - 1 ? 0 : _negObjects[-index];
}
else
{
return index > _objects.Length - 1 ? 0 : _objects[index];
}
}
set
{
if (index < 0)
{
if (-index > _negObjects.Length - 1)
{
IncreaseCapacity(index);
}
_negObjects[-index] = value;
}
else
{
if (index > _objects.Length - 1)
{
IncreaseCapacity(index);
}
_objects[index] = value;
}
}
}
internal void IncreaseCapacity(int index)
{
try
{
if (index < 0)
{
int size = Math.Max(_negObjects.Length * 2, (-index) + 1);
int[] newItems = new int[size];
Array.Copy(_negObjects, 0, newItems, 0, _negObjects.Length);
_negObjects = newItems;
}
else
{
int size = Math.Max(_objects.Length * 2, index + 1);
int[] newItems = new int[size];
Array.Copy(_objects, 0, newItems, 0, _objects.Length);
_objects = newItems;
}
}
catch (Exception)
{
throw new SerializationException(SR.Serialization_CorruptedStream);
}
}
}
internal sealed class NameCache
{
private static readonly ConcurrentDictionary<string, object> s_ht = new ConcurrentDictionary<string, object>();
private string _name = null;
internal object GetCachedValue(string name)
{
_name = name;
object value;
return s_ht.TryGetValue(name, out value) ? value : null;
}
internal void SetCachedValue(object value) => s_ht[_name] = value;
}
// Used to fixup value types. Only currently used for valuetypes which are array items.
internal sealed class ValueFixup
{
internal ValueFixupEnum _valueFixupEnum = ValueFixupEnum.Empty;
internal Array _arrayObj;
internal int[] _indexMap;
internal object _header = null;
internal object _memberObject;
internal ReadObjectInfo _objectInfo;
internal string _memberName;
internal ValueFixup(Array arrayObj, int[] indexMap)
{
_valueFixupEnum = ValueFixupEnum.Array;
_arrayObj = arrayObj;
_indexMap = indexMap;
}
internal ValueFixup(object memberObject, string memberName, ReadObjectInfo objectInfo)
{
_valueFixupEnum = ValueFixupEnum.Member;
_memberObject = memberObject;
_memberName = memberName;
_objectInfo = objectInfo;
}
internal void Fixup(ParseRecord record, ParseRecord parent)
{
object obj = record._newObj;
switch (_valueFixupEnum)
{
case ValueFixupEnum.Array:
_arrayObj.SetValue(obj, _indexMap);
break;
case ValueFixupEnum.Header:
throw new PlatformNotSupportedException();
case ValueFixupEnum.Member:
if (_objectInfo._isSi)
{
_objectInfo._objectManager.RecordDelayedFixup(parent._objectId, _memberName, record._objectId);
}
else
{
MemberInfo memberInfo = _objectInfo.GetMemberInfo(_memberName);
if (memberInfo != null)
{
_objectInfo._objectManager.RecordFixup(parent._objectId, memberInfo, record._objectId);
}
}
break;
}
}
}
// Class used to transmit Enums from the XML and Binary Formatter class to the ObjectWriter and ObjectReader class
internal sealed class InternalFE
{
internal FormatterTypeStyle _typeFormat;
internal FormatterAssemblyStyle _assemblyFormat;
internal TypeFilterLevel _securityLevel;
internal InternalSerializerTypeE _serializerTypeEnum;
}
internal sealed class NameInfo
{
internal string _fullName; // Name from SerObjectInfo.GetType
internal long _objectId;
internal long _assemId;
internal InternalPrimitiveTypeE _primitiveTypeEnum = InternalPrimitiveTypeE.Invalid;
internal Type _type;
internal bool _isSealed;
internal bool _isArray;
internal bool _isArrayItem;
internal bool _transmitTypeOnObject;
internal bool _transmitTypeOnMember;
internal bool _isParentTypeOnObject;
internal InternalArrayTypeE _arrayEnum;
private bool _sealedStatusChecked = false;
internal NameInfo() { }
internal void Init()
{
_fullName = null;
_objectId = 0;
_assemId = 0;
_primitiveTypeEnum = InternalPrimitiveTypeE.Invalid;
_type = null;
_isSealed = false;
_transmitTypeOnObject = false;
_transmitTypeOnMember = false;
_isParentTypeOnObject = false;
_isArray = false;
_isArrayItem = false;
_arrayEnum = InternalArrayTypeE.Empty;
_sealedStatusChecked = false;
}
public bool IsSealed
{
get
{
if (!_sealedStatusChecked)
{
_isSealed = _type.IsSealed;
_sealedStatusChecked = true;
}
return _isSealed;
}
}
public string NIname
{
get { return _fullName ?? (_fullName = _type.FullName); }
set { _fullName = value; }
}
}
internal sealed class PrimitiveArray
{
private InternalPrimitiveTypeE _code;
private bool[] _booleanA = null;
private char[] _charA = null;
private double[] _doubleA = null;
private short[] _int16A = null;
private int[] _int32A = null;
private long[] _int64A = null;
private sbyte[] _sbyteA = null;
private float[] _singleA = null;
private ushort[] _uint16A = null;
private uint[] _uint32A = null;
private ulong[] _uint64A = null;
internal PrimitiveArray(InternalPrimitiveTypeE code, Array array)
{
_code = code;
switch (code)
{
case InternalPrimitiveTypeE.Boolean: _booleanA = (bool[])array; break;
case InternalPrimitiveTypeE.Char: _charA = (char[])array; break;
case InternalPrimitiveTypeE.Double: _doubleA = (double[])array; break;
case InternalPrimitiveTypeE.Int16: _int16A = (short[])array; break;
case InternalPrimitiveTypeE.Int32: _int32A = (int[])array; break;
case InternalPrimitiveTypeE.Int64: _int64A = (long[])array; break;
case InternalPrimitiveTypeE.SByte: _sbyteA = (sbyte[])array; break;
case InternalPrimitiveTypeE.Single: _singleA = (float[])array; break;
case InternalPrimitiveTypeE.UInt16: _uint16A = (ushort[])array; break;
case InternalPrimitiveTypeE.UInt32: _uint32A = (uint[])array; break;
case InternalPrimitiveTypeE.UInt64: _uint64A = (ulong[])array; break;
}
}
internal void SetValue(string value, int index)
{
switch (_code)
{
case InternalPrimitiveTypeE.Boolean:
_booleanA[index] = bool.Parse(value);
break;
case InternalPrimitiveTypeE.Char:
if ((value[0] == '_') && (value.Equals("_0x00_")))
{
_charA[index] = char.MinValue;
}
else
{
_charA[index] = char.Parse(value);
}
break;
case InternalPrimitiveTypeE.Double:
_doubleA[index] = double.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Int16:
_int16A[index] = short.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Int32:
_int32A[index] = int.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Int64:
_int64A[index] = long.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.SByte:
_sbyteA[index] = sbyte.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Single:
_singleA[index] = float.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.UInt16:
_uint16A[index] = ushort.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.UInt32:
_uint32A[index] = uint.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.UInt64:
_uint64A[index] = ulong.Parse(value, CultureInfo.InvariantCulture);
break;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using Microsoft.AspNetCore.Routing;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ApplicationModels
{
public class AttributeRouteModelTests
{
[Fact]
public void CopyConstructor_CopiesAllProperties()
{
// Arrange
var route = new AttributeRouteModel(new HttpGetAttribute("/api/Products"))
{
Name = "products",
Order = 5,
SuppressLinkGeneration = true,
SuppressPathMatching = true,
};
// Act
var route2 = new AttributeRouteModel(route);
// Assert
foreach (var property in typeof(AttributeRouteModel).GetProperties())
{
var value1 = property.GetValue(route);
var value2 = property.GetValue(route2);
if (typeof(IEnumerable<object>).IsAssignableFrom(property.PropertyType))
{
Assert.Equal<object>((IEnumerable<object>)value1, (IEnumerable<object>)value2);
// Ensure non-default value
Assert.NotEmpty((IEnumerable<object>)value1);
}
else if (property.PropertyType.IsValueType ||
Nullable.GetUnderlyingType(property.PropertyType) != null)
{
Assert.Equal(value1, value2);
// Ensure non-default value
Assert.NotEqual(value1, Activator.CreateInstance(property.PropertyType));
}
else
{
Assert.Same(value1, value2);
// Ensure non-default value
Assert.NotNull(value1);
}
}
}
[Theory]
[InlineData(null, null, null)]
[InlineData("", null, "")]
[InlineData(null, "", "")]
[InlineData("/", null, "")]
[InlineData(null, "/", "")]
[InlineData("/", "", "")]
[InlineData("", "/", "")]
[InlineData("/", "/", "")]
[InlineData("~/", null, "")]
[InlineData("~/", "", "")]
[InlineData("~/", "/", "")]
[InlineData("~/", "~/", "")]
[InlineData(null, "~/", "")]
[InlineData("", "~/", "")]
[InlineData("/", "~/", "")]
public void Combine_EmptyTemplates(string left, string right, string expected)
{
// Arrange & Act
var combined = AttributeRouteModel.CombineTemplates(left, right);
// Assert
Assert.Equal(expected, combined);
}
[Theory]
[InlineData("home", null, "home")]
[InlineData("home", "", "home")]
[InlineData("/home/", "/", "")]
[InlineData("/home/", "~/", "")]
[InlineData(null, "GetEmployees", "GetEmployees")]
[InlineData("/", "GetEmployees", "GetEmployees")]
[InlineData("~/", "Blog/Index/", "Blog/Index")]
[InlineData("", "/GetEmployees/{id}/", "GetEmployees/{id}")]
[InlineData("~/home", null, "home")]
[InlineData("~/home", "", "home")]
[InlineData("~/home", "/", "")]
[InlineData(null, "~/home", "home")]
[InlineData("", "~/home", "home")]
[InlineData("", "~/home/", "home")]
[InlineData("/", "~/home", "home")]
public void Combine_OneTemplateHasValue(string left, string right, string expected)
{
// Arrange & Act
var combined = AttributeRouteModel.CombineTemplates(left, right);
// Assert
Assert.Equal(expected, combined);
}
[Theory]
[InlineData("home", "About", "home/About")]
[InlineData("home/", "/About", "About")]
[InlineData("home/", "/About/", "About")]
[InlineData("/home/{action}", "{id}", "home/{action}/{id}")]
[InlineData("home", "~/index", "index")]
[InlineData("home", "~/index/", "index")]
public void Combine_BothTemplatesHasValue(string left, string right, string expected)
{
// Arrange & Act
var combined = AttributeRouteModel.CombineTemplates(left, right);
// Assert
Assert.Equal(expected, combined);
}
[Theory]
[InlineData("~~/", null, "~~")]
[InlineData("~~/", "", "~~")]
[InlineData("~~/", "//", "//")]
[InlineData("~~/", "~~/", "~~/~~")]
[InlineData("~~/", "home", "~~/home")]
[InlineData("~~/", "home/", "~~/home")]
[InlineData("//", null, "//")]
[InlineData("//", "", "//")]
[InlineData("//", "//", "//")]
[InlineData("//", "~~/", "/~~")]
[InlineData("//", "home", "/home")]
[InlineData("//", "home/", "/home")]
[InlineData("////", null, "//")]
[InlineData("~~//", null, "~~/")]
public void Combine_InvalidTemplates(string left, string right, string expected)
{
// Arrange & Act
var combined = AttributeRouteModel.CombineTemplates(left, right);
// Assert
Assert.Equal(expected, combined);
}
[Theory]
[MemberData(nameof(ReplaceTokens_ValueValuesData))]
public void ReplaceTokens_ValidValues(string template, Dictionary<string, string> values, string expected)
{
// Arrange
// Act
var result = AttributeRouteModel.ReplaceTokens(template, values);
// Assert
Assert.Equal(expected, result);
}
[Theory]
[MemberData(nameof(ReplaceTokens_InvalidFormatValuesData))]
public void ReplaceTokens_InvalidFormat(string template, Dictionary<string, string> values, string reason)
{
// Arrange
var expected = string.Format(
CultureInfo.InvariantCulture,
"The route template '{0}' has invalid syntax. {1}",
template,
reason);
// Act
var ex = Assert.Throws<InvalidOperationException>(
() => { AttributeRouteModel.ReplaceTokens(template, values); });
// Assert
Assert.Equal(expected, ex.Message);
}
[Theory]
[InlineData("[area]/[controller]/[action]/{deptName:regex(^[a-zA-Z]{1}[a-zA-Z0-9_]*$)}", "a-zA-Z")]
[InlineData("[area]/[controller]/[action2]", "action2")]
public void ReplaceTokens_UnknownValue(string template, string token)
{
// Arrange
var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "area", "Help" },
{ "controller", "Admin" },
{ "action", "SeeUsers" },
};
var expected =
$"While processing template '{template}', " +
$"a replacement value for the token '{token}' could not be found. " +
"Available tokens: 'action, area, controller'. To use a '[' or ']' as a literal string in a " +
"route or within a constraint, use '[[' or ']]' instead.";
// Act
var ex = Assert.Throws<InvalidOperationException>(
() => { AttributeRouteModel.ReplaceTokens(template, values); });
// Assert
Assert.Equal(expected, ex.Message);
}
[Theory]
[MemberData(nameof(CombineOrdersTestData))]
public void Combine_Orders(
AttributeRouteModel left,
AttributeRouteModel right,
int? expected)
{
// Arrange & Act
var combined = AttributeRouteModel.CombineAttributeRouteModel(left, right);
// Assert
Assert.NotNull(combined);
Assert.Equal(expected, combined.Order);
}
[Theory]
[MemberData(nameof(ValidReflectedAttributeRouteModelsTestData))]
public void Combine_ValidReflectedAttributeRouteModels(
AttributeRouteModel left,
AttributeRouteModel right,
AttributeRouteModel expectedResult)
{
// Arrange & Act
var combined = AttributeRouteModel.CombineAttributeRouteModel(left, right);
// Assert
Assert.NotNull(combined);
Assert.Equal(expectedResult.Template, combined.Template);
}
[Theory]
[MemberData(nameof(NullOrNullTemplateReflectedAttributeRouteModelTestData))]
public void Combine_NullOrNullTemplateReflectedAttributeRouteModels(
AttributeRouteModel left,
AttributeRouteModel right)
{
// Arrange & Act
var combined = AttributeRouteModel.CombineAttributeRouteModel(left, right);
// Assert
Assert.Null(combined);
}
[Theory]
[MemberData(nameof(RightOverridesReflectedAttributeRouteModelTestData))]
public void Combine_RightOverridesReflectedAttributeRouteModel(
AttributeRouteModel left,
AttributeRouteModel right)
{
// Arrange
var expectedTemplate = AttributeRouteModel.CombineTemplates(null, right.Template);
// Act
var combined = AttributeRouteModel.CombineAttributeRouteModel(left, right);
// Assert
Assert.NotNull(combined);
Assert.Equal(expectedTemplate, combined.Template);
Assert.Equal(combined.Order, right.Order);
}
[Theory]
[MemberData(nameof(CombineNamesTestData))]
public void Combine_Names(
AttributeRouteModel left,
AttributeRouteModel right,
string expectedName)
{
// Arrange & Act
var combined = AttributeRouteModel.CombineAttributeRouteModel(left, right);
// Assert
Assert.NotNull(combined);
Assert.Equal(expectedName, combined.Name);
}
[Fact]
public void Combine_SetsSuppressLinkGenerationToFalse_IfNeitherIsTrue()
{
// Arrange
var left = new AttributeRouteModel
{
Template = "Template"
};
var right = new AttributeRouteModel();
var combined = AttributeRouteModel.CombineAttributeRouteModel(left, right);
// Assert
Assert.False(combined.SuppressLinkGeneration);
}
[Theory]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void Combine_SetsSuppressLinkGenerationToTrue_IfEitherIsTrue(bool leftSuppress, bool rightSuppress)
{
// Arrange
var left = new AttributeRouteModel
{
Template = "Template",
SuppressLinkGeneration = leftSuppress,
};
var right = new AttributeRouteModel
{
SuppressLinkGeneration = rightSuppress,
};
var combined = AttributeRouteModel.CombineAttributeRouteModel(left, right);
// Assert
Assert.True(combined.SuppressLinkGeneration);
}
[Fact]
public void Combine_SetsSuppressPathGenerationToFalse_IfNeitherIsTrue()
{
// Arrange
var left = new AttributeRouteModel
{
Template = "Template",
};
var right = new AttributeRouteModel();
var combined = AttributeRouteModel.CombineAttributeRouteModel(left, right);
// Assert
Assert.False(combined.SuppressPathMatching);
}
[Theory]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void Combine_SetsSuppressPathGenerationToTrue_IfEitherIsTrue(bool leftSuppress, bool rightSuppress)
{
// Arrange
var left = new AttributeRouteModel
{
Template = "Template",
SuppressPathMatching = leftSuppress,
};
var right = new AttributeRouteModel
{
SuppressPathMatching = rightSuppress,
};
var combined = AttributeRouteModel.CombineAttributeRouteModel(left, right);
// Assert
Assert.True(combined.SuppressPathMatching);
}
public static IEnumerable<object[]> CombineNamesTestData
{
get
{
// AttributeRoute on the controller, attribute route on the action, expected name.
var data = new TheoryData<AttributeRouteModel, AttributeRouteModel, string>();
// Combined name is null if no name is provided.
data.Add(Create(template: "/", order: null, name: null), null, null);
data.Add(Create(template: "~/", order: null, name: null), null, null);
data.Add(Create(template: "", order: null, name: null), null, null);
data.Add(Create(template: "home", order: null, name: null), null, null);
data.Add(Create(template: "/", order: 1, name: null), null, null);
data.Add(Create(template: "~/", order: 1, name: null), null, null);
data.Add(Create(template: "", order: 1, name: null), null, null);
data.Add(Create(template: "home", order: 1, name: null), null, null);
// Combined name is inherited if no right name is provided and the template is empty.
data.Add(Create(template: "/", order: null, name: "Named"), null, "Named");
data.Add(Create(template: "~/", order: null, name: "Named"), null, "Named");
data.Add(Create(template: "", order: null, name: "Named"), null, "Named");
data.Add(Create(template: "home", order: null, name: "Named"), null, "Named");
data.Add(Create(template: "home", order: null, name: "Named"), Create(null, null, null), "Named");
data.Add(Create(template: "", order: null, name: "Named"), Create("", null, null), "Named");
// Order doesn't matter for combining the name.
data.Add(Create(template: "", order: null, name: "Named"), Create("", 1, null), "Named");
data.Add(Create(template: "", order: 1, name: "Named"), Create("", 1, null), "Named");
data.Add(Create(template: "", order: 2, name: "Named"), Create("", 1, null), "Named");
data.Add(Create(template: "", order: null, name: "Named"), Create("index", 1, null), null);
data.Add(Create(template: "", order: 1, name: "Named"), Create("index", 1, null), null);
data.Add(Create(template: "", order: 2, name: "Named"), Create("index", 1, null), null);
data.Add(Create(template: "", order: null, name: "Named"), Create("", 1, "right"), "right");
data.Add(Create(template: "", order: 1, name: "Named"), Create("", 1, "right"), "right");
data.Add(Create(template: "", order: 2, name: "Named"), Create("", 1, "right"), "right");
// Combined name is not inherited if right name is provided or the template is not empty.
data.Add(Create(template: "/", order: null, name: "Named"), Create(null, null, "right"), "right");
data.Add(Create(template: "~/", order: null, name: "Named"), Create(null, null, "right"), "right");
data.Add(Create(template: "", order: null, name: "Named"), Create(null, null, "right"), "right");
data.Add(Create(template: "home", order: null, name: "Named"), Create(null, null, "right"), "right");
data.Add(Create(template: "home", order: null, name: "Named"), Create("index", null, null), null);
data.Add(Create(template: "home", order: null, name: "Named"), Create("/", null, null), null);
data.Add(Create(template: "home", order: null, name: "Named"), Create("~/", null, null), null);
data.Add(Create(template: "home", order: null, name: "Named"), Create("index", null, "right"), "right");
data.Add(Create(template: "home", order: null, name: "Named"), Create("/", null, "right"), "right");
data.Add(Create(template: "home", order: null, name: "Named"), Create("~/", null, "right"), "right");
data.Add(Create(template: "home", order: null, name: "Named"), Create("index", null, ""), "");
return data;
}
}
public static IEnumerable<object[]> CombineOrdersTestData
{
get
{
// AttributeRoute on the controller, attribute route on the action, expected order.
var data = new TheoryData<AttributeRouteModel, AttributeRouteModel, int?>();
data.Add(Create("", order: 1), Create("", order: 2), 2);
data.Add(Create("", order: 1), Create("", order: null), 1);
data.Add(Create("", order: 1), null, 1);
data.Add(Create("", order: 1), Create("/", order: 2), 2);
data.Add(Create("", order: 1), Create("/", order: null), null);
data.Add(Create("", order: null), Create("", order: 2), 2);
data.Add(Create("", order: null), Create("", order: null), null);
data.Add(Create("", order: null), null, null);
data.Add(Create("", order: null), Create("/", order: 2), 2);
data.Add(Create("", order: null), Create("/", order: null), null);
data.Add(null, Create("", order: 2), 2);
data.Add(null, Create("", order: null), null);
data.Add(null, Create("/", order: 2), 2);
data.Add(null, Create("/", order: null), null);
// We don't a test case for (left = null, right = null) as it is already tested in another test
// and will produce a null ReflectedAttributeRouteModel, which complicates the test case.
return data;
}
}
public static IEnumerable<object[]> RightOverridesReflectedAttributeRouteModelTestData
{
get
{
// AttributeRoute on the controller, attribute route on the action.
var data = new TheoryData<AttributeRouteModel, AttributeRouteModel>();
var leftModel = Create("Home", order: 3);
data.Add(leftModel, Create("/"));
data.Add(leftModel, Create("~/"));
data.Add(null, Create("/"));
data.Add(null, Create("~/"));
data.Add(Create(null), Create("/"));
data.Add(Create(null), Create("~/"));
return data;
}
}
public static IEnumerable<object[]> NullOrNullTemplateReflectedAttributeRouteModelTestData
{
get
{
// AttributeRoute on the controller, attribute route on the action.
var data = new TheoryData<AttributeRouteModel, AttributeRouteModel>();
data.Add(null, null);
data.Add(null, Create(null));
data.Add(Create(null), null);
data.Add(Create(null), Create(null));
return data;
}
}
public static IEnumerable<object[]> ValidReflectedAttributeRouteModelsTestData
{
get
{
// AttributeRoute on the controller, attribute route on the action, expected combined attribute route.
var data = new TheoryData<AttributeRouteModel, AttributeRouteModel, AttributeRouteModel>();
data.Add(null, Create("Index"), Create("Index"));
data.Add(Create(null), Create("Index"), Create("Index"));
data.Add(Create("Home"), null, Create("Home"));
data.Add(Create("Home"), Create(null), Create("Home"));
data.Add(Create("Home"), Create("Index"), Create("Home/Index"));
data.Add(Create("Blog"), Create("/Index"), Create("Index"));
return data;
}
}
public static IEnumerable<object[]> ReplaceTokens_ValueValuesData
{
get
{
yield return new object[]
{
"[controller]/[action]",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Home/Index"
};
yield return new object[]
{
"[controller]",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Home"
};
yield return new object[]
{
"[controller][[",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Home["
};
yield return new object[]
{
"[coNTroller]",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Home"
};
yield return new object[]
{
"thisisSomeText[action]",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"thisisSomeTextIndex"
};
yield return new object[]
{
"[[-]][[/[[controller]]",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"[-][/[controller]"
};
yield return new object[]
{
"[contr[[oller]/[act]]ion]",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "contr[oller", "Home" },
{ "act]ion", "Index" }
},
"Home/Index"
};
yield return new object[]
{
"[controller][action]",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"HomeIndex"
};
yield return new object[]
{
"[contr}oller]/[act{ion]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "contr}oller", "Home" },
{ "act{ion", "Index" }
},
"Home/Index/{id}"
};
yield return new object[]
{
"[controller]/[[[action]]]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Home/[Index]/{id}"
};
yield return new object[]
{
"[controller]/[[[[[action]]]]]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Home/[[Index]]/{id}"
};
yield return new object[]
{
"[controller]/[[[[[[[action]]]]]]]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Home/[[[Index]]]/{id}"
};
yield return new object[]
{
"[controller]/[[[[[action]]]]]]]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Home/[[Index]]]/{id}"
};
yield return new object[]
{
"[controller]/[[[[[[[action]]]]]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Home/[[[Index]]/{id}"
};
yield return new object[]
{
"[controller]/[[[action]]]]]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Home/[Index]]/{id}"
};
yield return new object[]
{
"[controller]/[[[[[[[action]]]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Home/[[[Index]/{id}"
};
}
}
public static IEnumerable<object[]> ReplaceTokens_InvalidFormatValuesData
{
get
{
yield return new object[]
{
"[",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase),
"A replacement token is not closed."
};
yield return new object[]
{
"text]",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase),
"Token delimiters ('[', ']') are imbalanced.",
};
yield return new object[]
{
"text]morecooltext",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase),
"Token delimiters ('[', ']') are imbalanced.",
};
yield return new object[]
{
"[action",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase),
"A replacement token is not closed.",
};
yield return new object[]
{
"[action]]][",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "action]", "Index" }
},
"A replacement token is not closed.",
};
yield return new object[]
{
"[action]]",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase),
"A replacement token is not closed."
};
yield return new object[]
{
"[ac[tion]",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase),
"An unescaped '[' token is not allowed inside of a replacement token. Use '[[' to escape."
};
yield return new object[]
{
"[]",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase),
"An empty replacement token ('[]') is not allowed.",
};
yield return new object[]
{
"[controller]/[[[action]]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Token delimiters ('[', ']') are imbalanced.",
};
yield return new object[]
{
"[controller]/[[[action]]]]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Token delimiters ('[', ']') are imbalanced.",
};
yield return new object[]
{
"[controller]/[[action]]]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Token delimiters ('[', ']') are imbalanced.",
};
yield return new object[]
{
"[controller]/[[[[[[[action]]]]]]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Token delimiters ('[', ']') are imbalanced.",
};
yield return new object[]
{
"[controller]/[[[[[[action]]]]]]]/{id}",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "controller", "Home" },
{ "action", "Index" }
},
"Token delimiters ('[', ']') are imbalanced.",
};
}
}
private static AttributeRouteModel Create(string template, int? order = null, string name = null)
{
return new AttributeRouteModel
{
Template = template,
Order = order,
Name = name
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using JabbR.Commands;
using JabbR.ContentProviders.Core;
using JabbR.Infrastructure;
using JabbR.Models;
using JabbR.Services;
using JabbR.ViewModels;
using Microsoft.AspNet.SignalR.Hubs;
using Newtonsoft.Json;
namespace JabbR
{
public class Chat : Hub, INotificationService
{
private readonly IJabbrRepository _repository;
private readonly IChatService _service;
private readonly ICache _cache;
private readonly IResourceProcessor _resourceProcessor;
private readonly IApplicationSettings _settings;
private static readonly Version _version = typeof(Chat).Assembly.GetName().Version;
private static readonly string _versionString = _version.ToString();
public Chat(IApplicationSettings settings, IResourceProcessor resourceProcessor, IChatService service, IJabbrRepository repository, ICache cache)
{
_settings = settings;
_resourceProcessor = resourceProcessor;
_service = service;
_repository = repository;
_cache = cache;
}
private string UserAgent
{
get
{
if (Context.Headers != null)
{
return Context.Headers["User-Agent"];
}
return null;
}
}
private bool OutOfSync
{
get
{
string version = Clients.Caller.version;
return String.IsNullOrEmpty(version) ||
new Version(version) != _version;
}
}
public bool Join()
{
SetVersion();
// Get the client state
ClientState clientState = GetClientState();
// Try to get the user from the client state
ChatUser user = _repository.GetUserById(clientState.UserId);
// Threre's no user being tracked
if (user == null)
{
return false;
}
// Migrate all users to use new auth
if (!String.IsNullOrEmpty(_settings.AuthApiKey) &&
String.IsNullOrEmpty(user.Identity))
{
return false;
}
// Update some user values
_service.UpdateActivity(user, Context.ConnectionId, UserAgent);
_repository.CommitChanges();
OnUserInitialize(clientState, user);
return true;
}
private void SetVersion()
{
// Set the version on the client
Clients.Caller.version = _versionString;
}
public bool CheckStatus()
{
bool outOfSync = OutOfSync;
SetVersion();
return outOfSync;
}
private void OnUserInitialize(ClientState clientState, ChatUser user)
{
// Update the active room on the client (only if it's still a valid room)
if (user.Rooms.Any(room => room.Name.Equals(clientState.ActiveRoom, StringComparison.OrdinalIgnoreCase)))
{
// Update the active room on the client (only if it's still a valid room)
Clients.Caller.activeRoom = clientState.ActiveRoom;
}
LogOn(user, Context.ConnectionId);
}
public bool Send(string content, string roomName)
{
var message = new ClientMessage
{
Content = content,
Id = Guid.NewGuid().ToString("d"),
Room = roomName
};
return Send(message);
}
public bool Send(ClientMessage message)
{
bool outOfSync = OutOfSync;
SetVersion();
// Sanitize the content (strip and bad html out)
message.Content = HttpUtility.HtmlEncode(message.Content);
// See if this is a valid command (starts with /)
if (TryHandleCommand(message.Content, message.Room))
{
return outOfSync;
}
string id = GetUserId();
ChatUser user = _repository.VerifyUserId(id);
ChatRoom room = _repository.VerifyUserRoom(_cache, user, message.Room);
// REVIEW: Is it better to use _repository.VerifyRoom(message.Room, mustBeOpen: false)
// here?
if (room.Closed)
{
throw new InvalidOperationException(String.Format("You cannot post messages to '{0}'. The room is closed.", message.Room));
}
// Update activity *after* ensuring the user, this forces them to be active
UpdateActivity(user, room);
HashSet<string> links;
var messageText = ParseChatMessageText(message.Content, out links);
ChatMessage chatMessage = _service.AddMessage(user, room, message.Id, messageText);
var messageViewModel = new MessageViewModel(chatMessage);
Clients.Group(room.Name).addMessage(messageViewModel, room.Name);
_repository.CommitChanges();
string clientMessageId = chatMessage.Id;
// Update the id on the message
chatMessage.Id = Guid.NewGuid().ToString("d");
_repository.CommitChanges();
if (!links.Any())
{
return outOfSync;
}
ProcessUrls(links, room.Name, clientMessageId, chatMessage.Id);
return outOfSync;
}
private string ParseChatMessageText(string content, out HashSet<string> links)
{
var textTransform = new TextTransform(_repository);
string message = textTransform.Parse(content);
return TextTransform.TransformAndExtractUrls(message, out links);
}
public UserViewModel GetUserInfo()
{
string id = GetUserId();
ChatUser user = _repository.VerifyUserId(id);
return new UserViewModel(user);
}
public override Task OnReconnected()
{
string id = GetUserId();
if (String.IsNullOrEmpty(id))
{
return null;
}
ChatUser user = _repository.VerifyUserId(id);
// Make sure this client is being tracked
_service.AddClient(user, Context.ConnectionId, UserAgent);
var currentStatus = (UserStatus)user.Status;
if (currentStatus == UserStatus.Offline)
{
// Mark the user as inactive
user.Status = (int)UserStatus.Inactive;
_repository.CommitChanges();
// If the user was offline that means they are not in the user list so we need to tell
// everyone the user is really in the room
var userViewModel = new UserViewModel(user);
foreach (var room in user.Rooms)
{
var isOwner = user.OwnedRooms.Contains(room);
// Tell the people in this room that you've joined
Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner).Wait();
// Add the caller to the group so they receive messages
Groups.Add(Context.ConnectionId, room.Name).Wait();
}
}
return base.OnReconnected();
}
public override Task OnDisconnected()
{
DisconnectClient(Context.ConnectionId);
return base.OnDisconnected();
}
public object GetCommands()
{
return CommandManager.GetCommandsMetaData();
}
public object GetShortcuts()
{
return new[] {
new { Name = "Tab or Shift + Tab", Category = "shortcut", Description = "Go to the next open room tab or Go to the previous open room tab." },
new { Name = "Alt + L", Category = "shortcut", Description = "Go to the Lobby."},
new { Name = "Alt + Number", Category = "shortcut", Description = "Go to specific Tab."}
};
}
public IEnumerable<RoomViewModel> GetRooms()
{
string id = GetUserId();
ChatUser user = _repository.VerifyUserId(id);
var rooms = _repository.GetAllowedRooms(user).Select(r => new RoomViewModel
{
Name = r.Name,
Count = r.Users.Count(u => u.Status != (int)UserStatus.Offline),
Private = r.Private,
Closed = r.Closed
}).ToList();
return rooms;
}
public IEnumerable<MessageViewModel> GetPreviousMessages(string messageId)
{
var previousMessages = (from m in _repository.GetPreviousMessages(messageId)
orderby m.When descending
select m).Take(100);
return previousMessages.AsEnumerable()
.Reverse()
.Select(m => new MessageViewModel(m));
}
public RoomViewModel GetRoomInfo(string roomName)
{
if (String.IsNullOrEmpty(roomName))
{
return null;
}
ChatRoom room = _repository.GetRoomByName(roomName);
if (room == null)
{
return null;
}
var recentMessages = (from m in _repository.GetMessagesByRoom(room)
orderby m.When descending
select m).Take(30).ToList();
// Reverse them since we want to get them in chronological order
recentMessages.Reverse();
// Get online users through the repository
IEnumerable<ChatUser> onlineUsers = _repository.GetOnlineUsers(room).ToList();
return new RoomViewModel
{
Name = room.Name,
Users = from u in onlineUsers
select new UserViewModel(u),
Owners = from u in room.Owners.Online()
select u.Name,
RecentMessages = recentMessages.Select(m => new MessageViewModel(m)),
Topic = ConvertUrlsAndRoomLinks(room.Topic ?? ""),
Welcome = ConvertUrlsAndRoomLinks(room.Welcome ?? ""),
Closed = room.Closed
};
}
private string ConvertUrlsAndRoomLinks(string message)
{
TextTransform textTransform = new TextTransform(_repository);
message = textTransform.ConvertHashtagsToRoomLinks(message);
HashSet<string> urls;
return TextTransform.TransformAndExtractUrls(message, out urls);
}
// TODO: Deprecate
public void Typing()
{
string roomName = Clients.Caller.activeRoom;
Typing(roomName);
}
public void Typing(string roomName)
{
string id = GetUserId();
ChatUser user = _repository.GetUserById(id);
if (user == null)
{
return;
}
ChatRoom room = _repository.VerifyUserRoom(_cache, user, roomName);
UpdateActivity(user, room);
var userViewModel = new UserViewModel(user);
Clients.Group(room.Name).setTyping(userViewModel, room.Name);
}
private void LogOn(ChatUser user, string clientId)
{
// Update the client state
Clients.Caller.id = user.Id;
Clients.Caller.name = user.Name;
Clients.Caller.hash = user.Hash;
var userViewModel = new UserViewModel(user);
var rooms = new List<RoomViewModel>();
var ownedRooms = user.OwnedRooms.Select(r => r.Key);
foreach (var room in user.Rooms)
{
var isOwner = ownedRooms.Contains(room.Key);
// Tell the people in this room that you've joined
Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner).Wait();
// Add the caller to the group so they receive messages
Groups.Add(clientId, room.Name).Wait();
// Add to the list of room names
rooms.Add(new RoomViewModel
{
Name = room.Name,
Private = room.Private,
Closed = room.Closed
});
}
// Initialize the chat with the rooms the user is in
Clients.Caller.logOn(rooms);
}
private void UpdateActivity(ChatUser user, ChatRoom room)
{
UpdateActivity(user);
OnUpdateActivity(user, room);
}
private void UpdateActivity(ChatUser user)
{
_service.UpdateActivity(user, Context.ConnectionId, UserAgent);
_repository.CommitChanges();
}
private void ProcessUrls(IEnumerable<string> links, string roomName, string clientMessageId, string messageId)
{
var contentTasks = links.Select(_resourceProcessor.ExtractResource).ToArray();
Task.Factory.ContinueWhenAll(contentTasks, tasks =>
{
foreach (var task in tasks)
{
if (task.IsFaulted)
{
Trace.TraceError(task.Exception.GetBaseException().Message);
continue;
}
if (task.Result == null || String.IsNullOrEmpty(task.Result.Content))
{
continue;
}
// Try to get content from each url we're resolved in the query
string extractedContent = "<p>" + task.Result.Content + "</p>";
// Notify the room
Clients.Group(roomName).addMessageContent(clientMessageId, extractedContent, roomName);
_service.AppendMessage(messageId, extractedContent);
}
});
}
private bool TryHandleCommand(string command, string room)
{
string clientId = Context.ConnectionId;
string userId = GetUserId();
var commandManager = new CommandManager(clientId, UserAgent, userId, room, _service, _repository, _cache, this);
return commandManager.TryHandleCommand(command);
}
private void DisconnectClient(string clientId)
{
string userId = _service.DisconnectClient(clientId);
if (String.IsNullOrEmpty(userId))
{
return;
}
// Query for the user to get the updated status
ChatUser user = _repository.GetUserById(userId);
// There's no associated user for this client id
if (user == null)
{
return;
}
// The user will be marked as offline if all clients leave
if (user.Status == (int)UserStatus.Offline)
{
foreach (var room in user.Rooms)
{
var userViewModel = new UserViewModel(user);
Clients.Group(room.Name).leave(userViewModel, room.Name).Wait();
}
}
}
private void OnUpdateActivity(ChatUser user, ChatRoom room)
{
var userViewModel = new UserViewModel(user);
Clients.Group(room.Name).updateActivity(userViewModel, room.Name);
}
private void LeaveRoom(ChatUser user, ChatRoom room)
{
var userViewModel = new UserViewModel(user);
Clients.Group(room.Name).leave(userViewModel, room.Name).Wait();
foreach (var client in user.ConnectedClients)
{
Groups.Remove(client.Id, room.Name).Wait();
}
OnRoomChanged(room);
}
void INotificationService.LogOn(ChatUser user, string clientId)
{
LogOn(user, clientId);
}
void INotificationService.ChangePassword()
{
Clients.Caller.changePassword();
}
void INotificationService.SetPassword()
{
Clients.Caller.setPassword();
}
void INotificationService.KickUser(ChatUser targetUser, ChatRoom room)
{
foreach (var client in targetUser.ConnectedClients)
{
// Kick the user from this room
Clients.Client(client.Id).kick(room.Name);
// Remove the user from this the room group so he doesn't get the leave message
Groups.Remove(client.Id, room.Name).Wait();
}
// Tell the room the user left
LeaveRoom(targetUser, room);
}
void INotificationService.OnUserCreated(ChatUser user)
{
// Set some client state
Clients.Caller.name = user.Name;
Clients.Caller.id = user.Id;
Clients.Caller.hash = user.Hash;
// Tell the client a user was created
Clients.Caller.userCreated();
}
void INotificationService.JoinRoom(ChatUser user, ChatRoom room)
{
var userViewModel = new UserViewModel(user);
var roomViewModel = new RoomViewModel
{
Name = room.Name,
Private = room.Private,
Welcome = ConvertUrlsAndRoomLinks(room.Welcome ?? ""),
Closed = room.Closed
};
var isOwner = user.OwnedRooms.Contains(room);
// Tell all clients to join this room
foreach (var client in user.ConnectedClients)
{
Clients.Client(client.Id).joinRoom(roomViewModel);
}
// Tell the people in this room that you've joined
Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner).Wait();
// Notify users of the room count change
OnRoomChanged(room);
foreach (var client in user.ConnectedClients)
{
// Add the caller to the group so they receive messages
Groups.Add(client.Id, room.Name).Wait();
}
}
void INotificationService.AllowUser(ChatUser targetUser, ChatRoom targetRoom)
{
foreach (var client in targetUser.ConnectedClients)
{
// Tell this client it's an owner
Clients.Client(client.Id).allowUser(targetRoom.Name);
}
// Tell the calling client the granting permission into the room was successful
Clients.Caller.userAllowed(targetUser.Name, targetRoom.Name);
}
void INotificationService.UnallowUser(ChatUser targetUser, ChatRoom targetRoom)
{
// Kick the user from the room when they are unallowed
((INotificationService)this).KickUser(targetUser, targetRoom);
foreach (var client in targetUser.ConnectedClients)
{
// Tell this client it's an owner
Clients.Client(client.Id).unallowUser(targetRoom.Name);
}
// Tell the calling client the granting permission into the room was successful
Clients.Caller.userUnallowed(targetUser.Name, targetRoom.Name);
}
void INotificationService.AddOwner(ChatUser targetUser, ChatRoom targetRoom)
{
foreach (var client in targetUser.ConnectedClients)
{
// Tell this client it's an owner
Clients.Client(client.Id).makeOwner(targetRoom.Name);
}
var userViewModel = new UserViewModel(targetUser);
// If the target user is in the target room.
// Tell everyone in the target room that a new owner was added
if (_repository.IsUserInRoom(_cache, targetUser, targetRoom))
{
Clients.Group(targetRoom.Name).addOwner(userViewModel, targetRoom.Name);
}
// Tell the calling client the granting of ownership was successful
Clients.Caller.ownerMade(targetUser.Name, targetRoom.Name);
}
void INotificationService.RemoveOwner(ChatUser targetUser, ChatRoom targetRoom)
{
foreach (var client in targetUser.ConnectedClients)
{
// Tell this client it's no longer an owner
Clients.Client(client.Id).demoteOwner(targetRoom.Name);
}
var userViewModel = new UserViewModel(targetUser);
// If the target user is in the target room.
// Tell everyone in the target room that the owner was removed
if (_repository.IsUserInRoom(_cache, targetUser, targetRoom))
{
Clients.Group(targetRoom.Name).removeOwner(userViewModel, targetRoom.Name);
}
// Tell the calling client the removal of ownership was successful
Clients.Caller.ownerRemoved(targetUser.Name, targetRoom.Name);
}
void INotificationService.ChangeGravatar(ChatUser user)
{
Clients.Caller.hash = user.Hash;
// Update the calling client
foreach (var client in user.ConnectedClients)
{
Clients.Client(client.Id).gravatarChanged();
}
// Create the view model
var userViewModel = new UserViewModel(user);
// Tell all users in rooms to change the gravatar
foreach (var room in user.Rooms)
{
Clients.Group(room.Name).changeGravatar(userViewModel, room.Name);
}
}
void INotificationService.OnSelfMessage(ChatRoom room, ChatUser user, string content)
{
Clients.Group(room.Name).sendMeMessage(user.Name, content, room.Name);
}
void INotificationService.SendPrivateMessage(ChatUser fromUser, ChatUser toUser, string messageText)
{
// Send a message to the sender and the sendee
foreach (var client in fromUser.ConnectedClients)
{
Clients.Client(client.Id).sendPrivateMessage(fromUser.Name, toUser.Name, messageText);
}
foreach (var client in toUser.ConnectedClients)
{
Clients.Client(client.Id).sendPrivateMessage(fromUser.Name, toUser.Name, messageText);
}
}
void INotificationService.PostNotification(ChatRoom room, ChatUser user, string message)
{
foreach (var client in user.ConnectedClients)
{
Clients.Client(client.Id).postNotification(message, room.Name);
}
}
void INotificationService.ListRooms(ChatUser user)
{
string userId = GetUserId();
var userModel = new UserViewModel(user);
Clients.Caller.showUsersRoomList(userModel, user.Rooms.Allowed(userId).Select(r => r.Name));
}
void INotificationService.ListUsers()
{
var users = _repository.Users.Online().Select(s => s.Name).OrderBy(s => s);
Clients.Caller.listUsers(users);
}
void INotificationService.ListUsers(IEnumerable<ChatUser> users)
{
Clients.Caller.listUsers(users.Select(s => s.Name));
}
void INotificationService.ListUsers(ChatRoom room, IEnumerable<string> names)
{
Clients.Caller.showUsersInRoom(room.Name, names);
}
void INotificationService.LockRoom(ChatUser targetUser, ChatRoom room)
{
var userViewModel = new UserViewModel(targetUser);
// Tell the room it's locked
Clients.All.lockRoom(userViewModel, room.Name);
// Tell the caller the room was successfully locked
Clients.Caller.roomLocked(room.Name);
// Notify people of the change
OnRoomChanged(room);
}
void INotificationService.CloseRoom(IEnumerable<ChatUser> users, ChatRoom room)
{
// notify all members of room that it is now closed
foreach (var user in users)
{
foreach (var client in user.ConnectedClients)
{
Clients.Client(client.Id).roomClosed(room.Name);
}
}
}
void INotificationService.UnCloseRoom(IEnumerable<ChatUser> users, ChatRoom room)
{
// notify all members of room that it is now re-opened
foreach (var user in users)
{
foreach (var client in user.ConnectedClients)
{
Clients.Client(client.Id).roomUnClosed(room.Name);
}
}
}
void INotificationService.LogOut(ChatUser user, string clientId)
{
DisconnectClient(clientId);
var rooms = user.Rooms.Select(r => r.Name);
Clients.Caller.logOut(rooms);
}
void INotificationService.ShowUserInfo(ChatUser user)
{
string userId = GetUserId();
Clients.Caller.showUserInfo(new
{
Name = user.Name,
OwnedRooms = user.OwnedRooms
.Allowed(userId)
.Where(r => !r.Closed)
.Select(r => r.Name),
Status = ((UserStatus)user.Status).ToString(),
LastActivity = user.LastActivity,
IsAfk = user.IsAfk,
AfkNote = user.AfkNote,
Note = user.Note,
Hash = user.Hash,
Rooms = user.Rooms.Allowed(userId).Select(r => r.Name)
});
}
void INotificationService.ShowHelp()
{
Clients.Caller.showCommands();
}
void INotificationService.Invite(ChatUser user, ChatUser targetUser, ChatRoom targetRoom)
{
var transform = new TextTransform(_repository);
string roomLink = transform.ConvertHashtagsToRoomLinks("#" + targetRoom.Name);
// Send the invite message to the sendee
foreach (var client in targetUser.ConnectedClients)
{
Clients.Client(client.Id).sendInvite(user.Name, targetUser.Name, roomLink);
}
// Send the invite notification to the sender
foreach (var client in user.ConnectedClients)
{
Clients.Client(client.Id).sendInvite(user.Name, targetUser.Name, roomLink);
}
}
void INotificationService.NugeUser(ChatUser user, ChatUser targetUser)
{
// Send a nudge message to the sender and the sendee
foreach (var client in targetUser.ConnectedClients)
{
Clients.Client(client.Id).nudge(user.Name, targetUser.Name);
}
foreach (var client in user.ConnectedClients)
{
Clients.Client(client.Id).sendPrivateMessage(user.Name, targetUser.Name, "nudged " + targetUser.Name);
}
}
void INotificationService.NudgeRoom(ChatRoom room, ChatUser user)
{
Clients.Group(room.Name).nudge(user.Name);
}
void INotificationService.LeaveRoom(ChatUser user, ChatRoom room)
{
LeaveRoom(user, room);
}
void INotificationService.OnUserNameChanged(ChatUser user, string oldUserName, string newUserName)
{
// Create the view model
var userViewModel = new UserViewModel(user);
// Tell the user's connected clients that the name changed
foreach (var client in user.ConnectedClients)
{
Clients.Client(client.Id).userNameChanged(userViewModel);
}
// Notify all users in the rooms
foreach (var room in user.Rooms)
{
Clients.Group(room.Name).changeUserName(oldUserName, userViewModel, room.Name);
}
}
void INotificationService.ChangeNote(ChatUser user)
{
bool isNoteCleared = user.Note == null;
// Update the calling client
foreach (var client in user.ConnectedClients)
{
Clients.Client(client.Id).noteChanged(user.IsAfk, isNoteCleared);
}
// Create the view model
var userViewModel = new UserViewModel(user);
// Tell all users in rooms to change the note
foreach (var room in user.Rooms)
{
Clients.Group(room.Name).changeNote(userViewModel, room.Name);
}
}
void INotificationService.ChangeFlag(ChatUser user)
{
bool isFlagCleared = String.IsNullOrWhiteSpace(user.Flag);
// Create the view model
var userViewModel = new UserViewModel(user);
// Update the calling client
foreach (var client in user.ConnectedClients)
{
Clients.Client(client.Id).flagChanged(isFlagCleared, userViewModel.Country);
}
// Tell all users in rooms to change the flag
foreach (var room in user.Rooms)
{
Clients.Group(room.Name).changeFlag(userViewModel, room.Name);
}
}
void INotificationService.ChangeTopic(ChatUser user, ChatRoom room)
{
bool isTopicCleared = String.IsNullOrWhiteSpace(room.Topic);
var parsedTopic = ConvertUrlsAndRoomLinks(room.Topic ?? "");
Clients.Group(room.Name).topicChanged(room.Name, isTopicCleared, parsedTopic, user.Name);
// Create the view model
var roomViewModel = new RoomViewModel
{
Name = room.Name,
Topic = parsedTopic,
Closed = room.Closed
};
Clients.Group(room.Name).changeTopic(roomViewModel);
}
void INotificationService.ChangeWelcome(ChatUser user, ChatRoom room)
{
bool isWelcomeCleared = String.IsNullOrWhiteSpace(room.Welcome);
var parsedWelcome = ConvertUrlsAndRoomLinks(room.Welcome ?? "");
foreach (var client in user.ConnectedClients)
{
Clients.Client(client.Id).welcomeChanged(isWelcomeCleared, parsedWelcome);
}
}
void INotificationService.AddAdmin(ChatUser targetUser)
{
foreach (var client in targetUser.ConnectedClients)
{
// Tell this client it's an owner
Clients.Client(client.Id).makeAdmin();
}
var userViewModel = new UserViewModel(targetUser);
// Tell all users in rooms to change the admin status
foreach (var room in targetUser.Rooms)
{
Clients.Group(room.Name).addAdmin(userViewModel, room.Name);
}
// Tell the calling client the granting of admin status was successful
Clients.Caller.adminMade(targetUser.Name);
}
void INotificationService.RemoveAdmin(ChatUser targetUser)
{
foreach (var client in targetUser.ConnectedClients)
{
// Tell this client it's no longer an owner
Clients.Client(client.Id).demoteAdmin();
}
var userViewModel = new UserViewModel(targetUser);
// Tell all users in rooms to change the admin status
foreach (var room in targetUser.Rooms)
{
Clients.Group(room.Name).removeAdmin(userViewModel, room.Name);
}
// Tell the calling client the removal of admin status was successful
Clients.Caller.adminRemoved(targetUser.Name);
}
void INotificationService.BroadcastMessage(ChatUser user, string messageText)
{
// Tell all users in all rooms about this message
foreach (var room in _repository.Rooms)
{
Clients.Group(room.Name).broadcastMessage(messageText, room.Name);
}
}
void INotificationService.ForceUpdate()
{
Clients.All.forceUpdate();
}
private void OnRoomChanged(ChatRoom room)
{
var roomViewModel = new RoomViewModel
{
Name = room.Name,
Private = room.Private,
Closed = room.Closed
};
// Update the room count
Clients.All.updateRoomCount(roomViewModel, _repository.GetOnlineUsers(room).Count());
}
private string GetUserId()
{
ClientState state = GetClientState();
return state.UserId;
}
private ClientState GetClientState()
{
// New client state
var jabbrState = GetCookieValue("jabbr.state");
ClientState clientState = null;
if (String.IsNullOrEmpty(jabbrState))
{
clientState = new ClientState();
}
else
{
clientState = JsonConvert.DeserializeObject<ClientState>(jabbrState);
}
// Read the id from the caller if there's no cookie
clientState.UserId = clientState.UserId ?? Clients.Caller.id;
return clientState;
}
private string GetCookieValue(string key)
{
var cookie = Context.RequestCookies[key];
string value = cookie != null ? cookie.Value : null;
return value != null ? HttpUtility.UrlDecode(value) : null;
}
void INotificationService.BanUser(ChatUser targetUser)
{
var rooms = targetUser.Rooms.Select(x => x.Name);
foreach (var room in rooms)
{
foreach (var client in targetUser.ConnectedClients)
{
// Kick the user from this room
Clients.Client(client.Id).kick(room);
// Remove the user from this the room group so he doesn't get the leave message
Groups.Remove(client.Id, room).Wait();
}
}
Clients.Client(targetUser.ConnectedClients.First().Id).logOut(rooms);
}
public override void Dispose()
{
_repository.Dispose();
}
}
}
| |
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
namespace WeifenLuo.WinFormsUI.Docking
{
partial class DockPanel
{
private class AutoHideWindowControl : Panel, ISplitterDragSource
{
private class SplitterControl : SplitterBase
{
public SplitterControl(AutoHideWindowControl autoHideWindow)
{
m_autoHideWindow = autoHideWindow;
}
private AutoHideWindowControl m_autoHideWindow;
private AutoHideWindowControl AutoHideWindow
{
get { return m_autoHideWindow; }
}
protected override int SplitterSize
{
get { return Measures.SplitterSize; }
}
protected override void StartDrag()
{
AutoHideWindow.DockPanel.BeginDrag(AutoHideWindow, AutoHideWindow.RectangleToScreen(Bounds));
}
}
#region consts
private const int ANIMATE_TIME = 100; // in mini-seconds
#endregion
private Timer m_timerMouseTrack;
private SplitterControl m_splitter;
public AutoHideWindowControl(DockPanel dockPanel)
{
m_dockPanel = dockPanel;
m_timerMouseTrack = new Timer();
m_timerMouseTrack.Tick += new EventHandler(TimerMouseTrack_Tick);
Visible = false;
m_splitter = new SplitterControl(this);
Controls.Add(m_splitter);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
m_timerMouseTrack.Dispose();
}
base.Dispose(disposing);
}
private DockPanel m_dockPanel = null;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
private DockPane m_activePane = null;
public DockPane ActivePane
{
get { return m_activePane; }
}
private void SetActivePane()
{
DockPane value = (ActiveContent == null ? null : ActiveContent.DockHandler.Pane);
if (value == m_activePane)
return;
m_activePane = value;
}
private static readonly object ActiveContentChangedEvent = new object();
public event EventHandler ActiveContentChanged
{
add { Events.AddHandler(ActiveContentChangedEvent, value); }
remove { Events.RemoveHandler(ActiveContentChangedEvent, value); }
}
protected virtual void OnActiveContentChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActiveContentChangedEvent];
if (handler != null)
handler(this, e);
}
private IDockContent m_activeContent = null;
public IDockContent ActiveContent
{
get { return m_activeContent; }
set
{
if (value == m_activeContent)
return;
if (value != null)
{
if (!DockHelper.IsDockStateAutoHide(value.DockHandler.DockState) || value.DockHandler.DockPanel != DockPanel)
throw (new InvalidOperationException(Strings.DockPanel_ActiveAutoHideContent_InvalidValue));
}
DockPanel.SuspendLayout();
if (m_activeContent != null)
{
if (m_activeContent.DockHandler.Form.ContainsFocus)
{
if (!Win32Helper.IsRunningOnMono)
{
DockPanel.ContentFocusManager.GiveUpFocus(m_activeContent);
}
}
AnimateWindow(false);
}
m_activeContent = value;
SetActivePane();
if (ActivePane != null)
ActivePane.ActiveContent = m_activeContent;
if (m_activeContent != null)
AnimateWindow(true);
DockPanel.ResumeLayout();
DockPanel.RefreshAutoHideStrip();
SetTimerMouseTrack();
OnActiveContentChanged(EventArgs.Empty);
}
}
public DockState DockState
{
get { return ActiveContent == null ? DockState.Unknown : ActiveContent.DockHandler.DockState; }
}
private bool m_flagAnimate = true;
private bool FlagAnimate
{
get { return m_flagAnimate; }
set { m_flagAnimate = value; }
}
private bool m_flagDragging = false;
internal bool FlagDragging
{
get { return m_flagDragging; }
set
{
if (m_flagDragging == value)
return;
m_flagDragging = value;
SetTimerMouseTrack();
}
}
private void AnimateWindow(bool show)
{
if (!FlagAnimate && Visible != show)
{
Visible = show;
return;
}
Parent.SuspendLayout();
Rectangle rectSource = GetRectangle(!show);
Rectangle rectTarget = GetRectangle(show);
int dxLoc, dyLoc;
int dWidth, dHeight;
dxLoc = dyLoc = dWidth = dHeight = 0;
if (DockState == DockState.DockTopAutoHide)
dHeight = show ? 1 : -1;
else if (DockState == DockState.DockLeftAutoHide)
dWidth = show ? 1 : -1;
else if (DockState == DockState.DockRightAutoHide)
{
dxLoc = show ? -1 : 1;
dWidth = show ? 1 : -1;
}
else if (DockState == DockState.DockBottomAutoHide)
{
dyLoc = (show ? -1 : 1);
dHeight = (show ? 1 : -1);
}
if (show)
{
Bounds = DockPanel.GetAutoHideWindowBounds(new Rectangle(-rectTarget.Width, -rectTarget.Height, rectTarget.Width, rectTarget.Height));
if (Visible == false)
Visible = true;
PerformLayout();
}
SuspendLayout();
LayoutAnimateWindow(rectSource);
if (Visible == false)
Visible = true;
int speedFactor = 1;
int totalPixels = (rectSource.Width != rectTarget.Width) ?
Math.Abs(rectSource.Width - rectTarget.Width) :
Math.Abs(rectSource.Height - rectTarget.Height);
int remainPixels = totalPixels;
DateTime startingTime = DateTime.Now;
while (rectSource != rectTarget)
{
DateTime startPerMove = DateTime.Now;
rectSource.X += dxLoc * speedFactor;
rectSource.Y += dyLoc * speedFactor;
rectSource.Width += dWidth * speedFactor;
rectSource.Height += dHeight * speedFactor;
if (Math.Sign(rectTarget.X - rectSource.X) != Math.Sign(dxLoc))
rectSource.X = rectTarget.X;
if (Math.Sign(rectTarget.Y - rectSource.Y) != Math.Sign(dyLoc))
rectSource.Y = rectTarget.Y;
if (Math.Sign(rectTarget.Width - rectSource.Width) != Math.Sign(dWidth))
rectSource.Width = rectTarget.Width;
if (Math.Sign(rectTarget.Height - rectSource.Height) != Math.Sign(dHeight))
rectSource.Height = rectTarget.Height;
LayoutAnimateWindow(rectSource);
if (Parent != null)
Parent.Update();
remainPixels -= speedFactor;
while (true)
{
TimeSpan time = new TimeSpan(0, 0, 0, 0, ANIMATE_TIME);
TimeSpan elapsedPerMove = DateTime.Now - startPerMove;
TimeSpan elapsedTime = DateTime.Now - startingTime;
if (((int)((time - elapsedTime).TotalMilliseconds)) <= 0)
{
speedFactor = remainPixels;
break;
}
else
speedFactor = remainPixels * (int)elapsedPerMove.TotalMilliseconds / (int)((time - elapsedTime).TotalMilliseconds);
if (speedFactor >= 1)
break;
}
}
ResumeLayout();
Parent.ResumeLayout();
}
private void LayoutAnimateWindow(Rectangle rect)
{
Bounds = DockPanel.GetAutoHideWindowBounds(rect);
Rectangle rectClient = ClientRectangle;
if (DockState == DockState.DockLeftAutoHide)
ActivePane.Location = new Point(rectClient.Right - 2 - Measures.SplitterSize - ActivePane.Width, ActivePane.Location.Y);
else if (DockState == DockState.DockTopAutoHide)
ActivePane.Location = new Point(ActivePane.Location.X, rectClient.Bottom - 2 - Measures.SplitterSize - ActivePane.Height);
}
private Rectangle GetRectangle(bool show)
{
if (DockState == DockState.Unknown)
return Rectangle.Empty;
Rectangle rect = DockPanel.AutoHideWindowRectangle;
if (show)
return rect;
if (DockState == DockState.DockLeftAutoHide)
rect.Width = 0;
else if (DockState == DockState.DockRightAutoHide)
{
rect.X += rect.Width;
rect.Width = 0;
}
else if (DockState == DockState.DockTopAutoHide)
rect.Height = 0;
else
{
rect.Y += rect.Height;
rect.Height = 0;
}
return rect;
}
private void SetTimerMouseTrack()
{
if (ActivePane == null || ActivePane.IsActivated || FlagDragging)
{
m_timerMouseTrack.Enabled = false;
return;
}
// start the timer
int hovertime = SystemInformation.MouseHoverTime ;
// assign a default value 400 in case of setting Timer.Interval invalid value exception
if (hovertime <= 0)
hovertime = 400;
m_timerMouseTrack.Interval = 2 * (int)hovertime;
m_timerMouseTrack.Enabled = true;
}
protected virtual Rectangle DisplayingRectangle
{
get
{
Rectangle rect = ClientRectangle;
// exclude the border and the splitter
if (DockState == DockState.DockBottomAutoHide)
{
rect.Y += 2 + Measures.SplitterSize;
rect.Height -= 2 + Measures.SplitterSize;
}
else if (DockState == DockState.DockRightAutoHide)
{
rect.X += 2 + Measures.SplitterSize;
rect.Width -= 2 + Measures.SplitterSize;
}
else if (DockState == DockState.DockTopAutoHide)
rect.Height -= 2 + Measures.SplitterSize;
else if (DockState == DockState.DockLeftAutoHide)
rect.Width -= 2 + Measures.SplitterSize;
return rect;
}
}
protected override void OnLayout(LayoutEventArgs levent)
{
DockPadding.All = 0;
if (DockState == DockState.DockLeftAutoHide)
{
DockPadding.Right = 2;
m_splitter.Dock = DockStyle.Right;
}
else if (DockState == DockState.DockRightAutoHide)
{
DockPadding.Left = 2;
m_splitter.Dock = DockStyle.Left;
}
else if (DockState == DockState.DockTopAutoHide)
{
DockPadding.Bottom = 2;
m_splitter.Dock = DockStyle.Bottom;
}
else if (DockState == DockState.DockBottomAutoHide)
{
DockPadding.Top = 2;
m_splitter.Dock = DockStyle.Top;
}
Rectangle rectDisplaying = DisplayingRectangle;
Rectangle rectHidden = new Rectangle(-rectDisplaying.Width, rectDisplaying.Y, rectDisplaying.Width, rectDisplaying.Height);
foreach (Control c in Controls)
{
DockPane pane = c as DockPane;
if (pane == null)
continue;
if (pane == ActivePane)
pane.Bounds = rectDisplaying;
else
pane.Bounds = rectHidden;
}
base.OnLayout(levent);
}
protected override void OnPaint(PaintEventArgs e)
{
// Draw the border
Graphics g = e.Graphics;
if (DockState == DockState.DockBottomAutoHide)
g.DrawLine(SystemPens.ControlLightLight, 0, 1, ClientRectangle.Right, 1);
else if (DockState == DockState.DockRightAutoHide)
g.DrawLine(SystemPens.ControlLightLight, 1, 0, 1, ClientRectangle.Bottom);
else if (DockState == DockState.DockTopAutoHide)
{
g.DrawLine(SystemPens.ControlDark, 0, ClientRectangle.Height - 2, ClientRectangle.Right, ClientRectangle.Height - 2);
g.DrawLine(SystemPens.ControlDarkDark, 0, ClientRectangle.Height - 1, ClientRectangle.Right, ClientRectangle.Height - 1);
}
else if (DockState == DockState.DockLeftAutoHide)
{
g.DrawLine(SystemPens.ControlDark, ClientRectangle.Width - 2, 0, ClientRectangle.Width - 2, ClientRectangle.Bottom);
g.DrawLine(SystemPens.ControlDarkDark, ClientRectangle.Width - 1, 0, ClientRectangle.Width - 1, ClientRectangle.Bottom);
}
base.OnPaint(e);
}
public void RefreshActiveContent()
{
if (ActiveContent == null)
return;
if (!DockHelper.IsDockStateAutoHide(ActiveContent.DockHandler.DockState))
{
FlagAnimate = false;
ActiveContent = null;
FlagAnimate = true;
}
}
public void RefreshActivePane()
{
SetTimerMouseTrack();
}
private void TimerMouseTrack_Tick(object sender, EventArgs e)
{
if (IsDisposed)
return;
if (ActivePane == null || ActivePane.IsActivated)
{
m_timerMouseTrack.Enabled = false;
return;
}
DockPane pane = ActivePane;
Point ptMouseInAutoHideWindow = PointToClient(Control.MousePosition);
Point ptMouseInDockPanel = DockPanel.PointToClient(Control.MousePosition);
Rectangle rectTabStrip = DockPanel.GetTabStripRectangle(pane.DockState);
if (!ClientRectangle.Contains(ptMouseInAutoHideWindow) && !rectTabStrip.Contains(ptMouseInDockPanel))
{
ActiveContent = null;
m_timerMouseTrack.Enabled = false;
}
}
#region ISplitterDragSource Members
void ISplitterDragSource.BeginDrag(Rectangle rectSplitter)
{
FlagDragging = true;
}
void ISplitterDragSource.EndDrag()
{
FlagDragging = false;
}
bool ISplitterDragSource.IsVertical
{
get { return (DockState == DockState.DockLeftAutoHide || DockState == DockState.DockRightAutoHide); }
}
Rectangle ISplitterDragSource.DragLimitBounds
{
get
{
Rectangle rectLimit = DockPanel.DockArea;
if ((this as ISplitterDragSource).IsVertical)
{
rectLimit.X += MeasurePane.MinSize;
rectLimit.Width -= 2 * MeasurePane.MinSize;
}
else
{
rectLimit.Y += MeasurePane.MinSize;
rectLimit.Height -= 2 * MeasurePane.MinSize;
}
return DockPanel.RectangleToScreen(rectLimit);
}
}
void ISplitterDragSource.MoveSplitter(int offset)
{
Rectangle rectDockArea = DockPanel.DockArea;
IDockContent content = ActiveContent;
if (DockState == DockState.DockLeftAutoHide && rectDockArea.Width > 0)
{
if (content.DockHandler.AutoHidePortion < 1)
content.DockHandler.AutoHidePortion += ((double)offset) / (double)rectDockArea.Width;
else
content.DockHandler.AutoHidePortion = Width + offset;
}
else if (DockState == DockState.DockRightAutoHide && rectDockArea.Width > 0)
{
if (content.DockHandler.AutoHidePortion < 1)
content.DockHandler.AutoHidePortion -= ((double)offset) / (double)rectDockArea.Width;
else
content.DockHandler.AutoHidePortion = Width - offset;
}
else if (DockState == DockState.DockBottomAutoHide && rectDockArea.Height > 0)
{
if (content.DockHandler.AutoHidePortion < 1)
content.DockHandler.AutoHidePortion -= ((double)offset) / (double)rectDockArea.Height;
else
content.DockHandler.AutoHidePortion = Height - offset;
}
else if (DockState == DockState.DockTopAutoHide && rectDockArea.Height > 0)
{
if (content.DockHandler.AutoHidePortion < 1)
content.DockHandler.AutoHidePortion += ((double)offset) / (double)rectDockArea.Height;
else
content.DockHandler.AutoHidePortion = Height + offset;
}
}
#region IDragSource Members
Control IDragSource.DragControl
{
get { return this; }
}
#endregion
#endregion
}
private AutoHideWindowControl AutoHideWindow
{
get { return m_autoHideWindow; }
}
internal Control AutoHideControl
{
get { return m_autoHideWindow; }
}
internal void RefreshActiveAutoHideContent()
{
AutoHideWindow.RefreshActiveContent();
}
internal Rectangle AutoHideWindowRectangle
{
get
{
DockState state = AutoHideWindow.DockState;
Rectangle rectDockArea = DockArea;
if (ActiveAutoHideContent == null)
return Rectangle.Empty;
if (Parent == null)
return Rectangle.Empty;
Rectangle rect = Rectangle.Empty;
double autoHideSize = ActiveAutoHideContent.DockHandler.AutoHidePortion;
if (state == DockState.DockLeftAutoHide)
{
if (autoHideSize < 1)
autoHideSize = rectDockArea.Width * autoHideSize;
if (autoHideSize > rectDockArea.Width - MeasurePane.MinSize)
autoHideSize = rectDockArea.Width - MeasurePane.MinSize;
rect.X = rectDockArea.X;
rect.Y = rectDockArea.Y;
rect.Width = (int)autoHideSize;
rect.Height = rectDockArea.Height;
}
else if (state == DockState.DockRightAutoHide)
{
if (autoHideSize < 1)
autoHideSize = rectDockArea.Width * autoHideSize;
if (autoHideSize > rectDockArea.Width - MeasurePane.MinSize)
autoHideSize = rectDockArea.Width - MeasurePane.MinSize;
rect.X = rectDockArea.X + rectDockArea.Width - (int)autoHideSize;
rect.Y = rectDockArea.Y;
rect.Width = (int)autoHideSize;
rect.Height = rectDockArea.Height;
}
else if (state == DockState.DockTopAutoHide)
{
if (autoHideSize < 1)
autoHideSize = rectDockArea.Height * autoHideSize;
if (autoHideSize > rectDockArea.Height - MeasurePane.MinSize)
autoHideSize = rectDockArea.Height - MeasurePane.MinSize;
rect.X = rectDockArea.X;
rect.Y = rectDockArea.Y;
rect.Width = rectDockArea.Width;
rect.Height = (int)autoHideSize;
}
else if (state == DockState.DockBottomAutoHide)
{
if (autoHideSize < 1)
autoHideSize = rectDockArea.Height * autoHideSize;
if (autoHideSize > rectDockArea.Height - MeasurePane.MinSize)
autoHideSize = rectDockArea.Height - MeasurePane.MinSize;
rect.X = rectDockArea.X;
rect.Y = rectDockArea.Y + rectDockArea.Height - (int)autoHideSize;
rect.Width = rectDockArea.Width;
rect.Height = (int)autoHideSize;
}
return rect;
}
}
internal Rectangle GetAutoHideWindowBounds(Rectangle rectAutoHideWindow)
{
if (DocumentStyle == DocumentStyle.SystemMdi ||
DocumentStyle == DocumentStyle.DockingMdi)
return (Parent == null) ? Rectangle.Empty : Parent.RectangleToClient(RectangleToScreen(rectAutoHideWindow));
else
return rectAutoHideWindow;
}
internal void RefreshAutoHideStrip()
{
AutoHideStripControl.RefreshChanges();
}
}
}
| |
// 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.Dynamic.Utils;
using System.Runtime.CompilerServices;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents an operation between an expression and a type.
/// </summary>
[DebuggerTypeProxy(typeof(TypeBinaryExpressionProxy))]
public sealed class TypeBinaryExpression : Expression
{
internal TypeBinaryExpression(Expression expression, Type typeOperand, ExpressionType nodeType)
{
Expression = expression;
TypeOperand = typeOperand;
NodeType = nodeType;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression"/> represents.
/// </summary>
/// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type => typeof(bool);
/// <summary>
/// Returns the node type of this Expression. Extension nodes should return
/// ExpressionType.Extension when overriding this method.
/// </summary>
/// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
public sealed override ExpressionType NodeType { get; }
/// <summary>
/// Gets the expression operand of a type test operation.
/// </summary>
public Expression Expression { get; }
/// <summary>
/// Gets the type operand of a type test operation.
/// </summary>
public Type TypeOperand { get; }
#region Reduce TypeEqual
internal Expression ReduceTypeEqual()
{
Type cType = Expression.Type;
if (cType.IsValueType || TypeOperand.IsPointer)
{
if (cType.IsNullableType())
{
// If the expression type is a nullable type, it will match if
// the value is not null and the type operand
// either matches or is its type argument (T to its T?).
if (cType.GetNonNullableType() != TypeOperand.GetNonNullableType())
{
return Expression.Block(Expression, Utils.Constant(value: false));
}
else
{
return Expression.NotEqual(Expression, Expression.Constant(null, Expression.Type));
}
}
else
{
// For other value types (including Void), we can
// determine the result now
return Expression.Block(Expression, Utils.Constant(cType == TypeOperand.GetNonNullableType()));
}
}
Debug.Assert(TypeUtils.AreReferenceAssignable(typeof(object), Expression.Type), "Expecting reference types only after this point.");
// Can check the value right now for constants.
if (Expression.NodeType == ExpressionType.Constant)
{
return ReduceConstantTypeEqual();
}
// expression is a ByVal parameter. Can safely reevaluate.
var parameter = Expression as ParameterExpression;
if (parameter != null && !parameter.IsByRef)
{
return ByValParameterTypeEqual(parameter);
}
// Create a temp so we only evaluate the left side once
parameter = Expression.Parameter(typeof(object));
return Expression.Block(
new TrueReadOnlyCollection<ParameterExpression>(parameter),
new TrueReadOnlyCollection<Expression>(
Expression.Assign(parameter, Expression),
ByValParameterTypeEqual(parameter)
)
);
}
// Helper that is used when re-eval of LHS is safe.
private Expression ByValParameterTypeEqual(ParameterExpression value)
{
Expression getType = Expression.Call(value, Object_GetType);
// In remoting scenarios, obj.GetType() can return an interface.
// But JIT32's optimized "obj.GetType() == typeof(ISomething)" codegen,
// causing it to always return false.
// We workaround this optimization by generating different, less optimal IL
// if TypeOperand is an interface.
if (TypeOperand.IsInterface)
{
ParameterExpression temp = Expression.Parameter(typeof(Type));
getType = Expression.Block(
new TrueReadOnlyCollection<ParameterExpression>(temp),
new TrueReadOnlyCollection<Expression>(
Expression.Assign(temp, getType),
temp
)
);
}
// We use reference equality when comparing to null for correctness
// (don't invoke a user defined operator), and reference equality
// on types for performance (so the JIT can optimize the IL).
return Expression.AndAlso(
Expression.ReferenceNotEqual(value, Utils.Null),
Expression.ReferenceEqual(
getType,
Expression.Constant(TypeOperand.GetNonNullableType(), typeof(Type))
)
);
}
private Expression ReduceConstantTypeEqual()
{
ConstantExpression ce = Expression as ConstantExpression;
//TypeEqual(null, T) always returns false.
if (ce.Value == null)
{
return Utils.Constant(value: false);
}
else
{
return Utils.Constant(TypeOperand.GetNonNullableType() == ce.Value.GetType());
}
}
#endregion
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitTypeBinary(this);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="expression">The <see cref="Expression"/> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public TypeBinaryExpression Update(Expression expression)
{
if (expression == Expression)
{
return this;
}
if (NodeType == ExpressionType.TypeIs)
{
return Expression.TypeIs(expression, TypeOperand);
}
return Expression.TypeEqual(expression, TypeOperand);
}
}
public partial class Expression
{
/// <summary>
/// Creates a <see cref="TypeBinaryExpression"/>.
/// </summary>
/// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param>
/// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param>
/// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="ExpressionType.TypeIs"/> and for which the <see cref="TypeBinaryExpression.Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns>
public static TypeBinaryExpression TypeIs(Expression expression, Type type)
{
ExpressionUtils.RequiresCanRead(expression, nameof(expression));
ContractUtils.RequiresNotNull(type, nameof(type));
if (type.IsByRef) throw Error.TypeMustNotBeByRef(nameof(type));
return new TypeBinaryExpression(expression, type, ExpressionType.TypeIs);
}
/// <summary>
/// Creates a <see cref="TypeBinaryExpression"/> that compares run-time type identity.
/// </summary>
/// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param>
/// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param>
/// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="ExpressionType.TypeEqual"/> and for which the <see cref="TypeBinaryExpression.Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns>
public static TypeBinaryExpression TypeEqual(Expression expression, Type type)
{
ExpressionUtils.RequiresCanRead(expression, nameof(expression));
ContractUtils.RequiresNotNull(type, nameof(type));
if (type.IsByRef) throw Error.TypeMustNotBeByRef(nameof(type));
return new TypeBinaryExpression(expression, type, ExpressionType.TypeEqual);
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Pathfinding.Util;
namespace Pathfinding {
[AddComponentMenu("Pathfinding/Modifiers/Simple Smooth")]
[System.Serializable]
[RequireComponent(typeof(Seeker))]
/** Modifier which smooths the path. This modifier can smooth a path by either moving the points closer together (Simple) or using Bezier curves (Bezier).\n
* \ingroup modifiers
* Attach this component to the same GameObject as a Seeker component.
* \n
* This component will hook in to the Seeker's path post-processing system and will post process any paths it searches for.
* Take a look at the Modifier Priorities settings on the Seeker component to determine where in the process this modifier should process the path.
* \n
* \n
* Several smoothing types are available, here follows a list of them and a short description of what they do, and how they work.
* But the best way is really to experiment with them yourself.\n
*
* - <b>Simple</b> Smooths the path by drawing all points close to each other. This results in paths that might cut corners if you are not careful.
* It will also subdivide the path to create more more points to smooth as otherwise it would still be quite rough.
* \shadowimage{smooth_simple.png}
* - <b>Bezier</b> Smooths the path using Bezier curves. This results a smooth path which will always pass through all points in the path, but make sure it doesn't turn too quickly.
* \shadowimage{smooth_bezier.png}
* - <b>OffsetSimple</b> An alternative to Simple smooth which will offset the path outwards in each step to minimize the corner-cutting.
* But be careful, if too high values are used, it will turn into loops and look really ugly.
* - <b>Curved Non Uniform</b> \shadowimage{smooth_curved_nonuniform.png}
*
* \note Modifies vectorPath array
* \todo Make the smooth modifier take the world geometry into account when smoothing
* */
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_simple_smooth_modifier.php")]
public class SimpleSmoothModifier : MonoModifier {
#if UNITY_EDITOR
[UnityEditor.MenuItem("CONTEXT/Seeker/Add Simple Smooth Modifier")]
public static void AddComp (UnityEditor.MenuCommand command) {
(command.context as Component).gameObject.AddComponent(typeof(SimpleSmoothModifier));
}
#endif
public override int Order { get { return 50; } }
/** Type of smoothing to use */
public SmoothType smoothType = SmoothType.Simple;
/** Number of times to subdivide when not using a uniform length */
[Tooltip("The number of times to subdivide (divide in half) the path segments. [0...inf] (recommended [1...10])")]
public int subdivisions = 2;
/** Number of times to apply smoothing */
[Tooltip("Number of times to apply smoothing")]
public int iterations = 2;
/** Determines how much smoothing to apply in each smooth iteration. 0.5 usually produces the nicest looking curves. */
[Tooltip("Determines how much smoothing to apply in each smooth iteration. 0.5 usually produces the nicest looking curves")]
[Range(0, 1)]
public float strength = 0.5F;
/** Toggle to divide all lines in equal length segments.
* \see #maxSegmentLength
*/
[Tooltip("Toggle to divide all lines in equal length segments")]
public bool uniformLength = true;
/** The length of the segments in the smoothed path when using #uniformLength.
* A high value yields rough paths and low value yields very smooth paths, but is slower */
[Tooltip("The length of each segment in the smoothed path. A high value yields rough paths and low value yields very smooth paths, but is slower")]
public float maxSegmentLength = 2F;
/** Length factor of the bezier curves' tangents' */
[Tooltip("Length factor of the bezier curves' tangents")]
public float bezierTangentLength = 0.4F;
/** Offset to apply in each smoothing iteration when using Offset Simple. \see #smoothType */
[Tooltip("Offset to apply in each smoothing iteration when using Offset Simple")]
public float offset = 0.2F;
/** Roundness factor used for CurvedNonuniform */
[Tooltip("How much to smooth the path. A higher value will give a smoother path, but might take the character far off the optimal path.")]
public float factor = 0.1F;
public enum SmoothType {
Simple,
Bezier,
OffsetSimple,
CurvedNonuniform
}
public override void Apply (Path p) {
// This should never trigger unless some other modifier has messed stuff up
if (p.vectorPath == null) {
Debug.LogWarning("Can't process NULL path (has another modifier logged an error?)");
return;
}
List<Vector3> path = null;
switch (smoothType) {
case SmoothType.Simple:
path = SmoothSimple(p.vectorPath); break;
case SmoothType.Bezier:
path = SmoothBezier(p.vectorPath); break;
case SmoothType.OffsetSimple:
path = SmoothOffsetSimple(p.vectorPath); break;
case SmoothType.CurvedNonuniform:
path = CurvedNonuniform(p.vectorPath); break;
}
if (path != p.vectorPath) {
ListPool<Vector3>.Release(ref p.vectorPath);
p.vectorPath = path;
}
}
public List<Vector3> CurvedNonuniform (List<Vector3> path) {
if (maxSegmentLength <= 0) {
Debug.LogWarning("Max Segment Length is <= 0 which would cause DivByZero-exception or other nasty errors (avoid this)");
return path;
}
int pointCounter = 0;
for (int i = 0; i < path.Count-1; i++) {
//pointCounter += Mathf.FloorToInt ((path[i]-path[i+1]).magnitude / maxSegmentLength)+1;
float dist = (path[i]-path[i+1]).magnitude;
//In order to avoid floating point errors as much as possible, and in lack of a better solution
//loop through it EXACTLY as the other code further down will
for (float t = 0; t <= dist; t += maxSegmentLength) {
pointCounter++;
}
}
List<Vector3> subdivided = ListPool<Vector3>.Claim(pointCounter);
// Set first velocity
Vector3 preEndVel = (path[1]-path[0]).normalized;
for (int i = 0; i < path.Count-1; i++) {
float dist = (path[i]-path[i+1]).magnitude;
Vector3 startVel1 = preEndVel;
Vector3 endVel1 = i < path.Count-2 ? ((path[i+2]-path[i+1]).normalized - (path[i]-path[i+1]).normalized).normalized : (path[i+1]-path[i]).normalized;
Vector3 startVel = startVel1 * dist * factor;
Vector3 endVel = endVel1 * dist * factor;
Vector3 start = path[i];
Vector3 end = path[i+1];
float onedivdist = 1F / dist;
for (float t = 0; t <= dist; t += maxSegmentLength) {
float t2 = t * onedivdist;
subdivided.Add(GetPointOnCubic(start, end, startVel, endVel, t2));
}
preEndVel = endVel1;
}
subdivided[subdivided.Count-1] = path[path.Count-1];
return subdivided;
}
public static Vector3 GetPointOnCubic (Vector3 a, Vector3 b, Vector3 tan1, Vector3 tan2, float t) {
float t2 = t*t, t3 = t2*t;
float h1 = 2*t3 - 3*t2 + 1; // calculate basis function 1
float h2 = -2*t3 + 3*t2; // calculate basis function 2
float h3 = t3 - 2*t2 + t; // calculate basis function 3
float h4 = t3 - t2; // calculate basis function 4
return h1*a + // multiply and sum all funtions
h2*b + // together to build the interpolated
h3*tan1 + // point along the curve.
h4*tan2;
}
public List<Vector3> SmoothOffsetSimple (List<Vector3> path) {
if (path.Count <= 2 || iterations <= 0) {
return path;
}
if (iterations > 12) {
Debug.LogWarning("A very high iteration count was passed, won't let this one through");
return path;
}
int maxLength = (path.Count-2)*(int)Mathf.Pow(2, iterations)+2;
List<Vector3> subdivided = ListPool<Vector3>.Claim(maxLength);
List<Vector3> subdivided2 = ListPool<Vector3>.Claim(maxLength);
for (int i = 0; i < maxLength; i++) { subdivided.Add(Vector3.zero); subdivided2.Add(Vector3.zero); }
for (int i = 0; i < path.Count; i++) {
subdivided[i] = path[i];
}
for (int iteration = 0; iteration < iterations; iteration++) {
int currentPathLength = (path.Count-2)*(int)Mathf.Pow(2, iteration)+2;
//Switch the arrays
List<Vector3> tmp = subdivided;
subdivided = subdivided2;
subdivided2 = tmp;
const float nextMultiplier = 1F;
for (int i = 0; i < currentPathLength-1; i++) {
Vector3 current = subdivided2[i];
Vector3 next = subdivided2[i+1];
Vector3 normal = Vector3.Cross(next-current, Vector3.up);
normal = normal.normalized;
bool firstRight = false;
bool secondRight = false;
bool setFirst = false;
bool setSecond = false;
if (i != 0 && !VectorMath.IsColinearXZ(current, next, subdivided2[i-1])) {
setFirst = true;
firstRight = VectorMath.RightOrColinearXZ(current, next, subdivided2[i-1]);
}
if (i < currentPathLength-1 && !VectorMath.IsColinearXZ(current, next, subdivided2[i+2])) {
setSecond = true;
secondRight = VectorMath.RightOrColinearXZ(current, next, subdivided2[i+2]);
}
if (setFirst) {
subdivided[i*2] = current + (firstRight ? normal*offset*nextMultiplier : -normal*offset*nextMultiplier);
} else {
subdivided[i*2] = current;
}
if (setSecond) {
subdivided[i*2+1] = next + (secondRight ? normal*offset*nextMultiplier : -normal*offset*nextMultiplier);
} else {
subdivided[i*2+1] = next;
}
}
subdivided[(path.Count-2)*(int)Mathf.Pow(2, iteration+1)+2-1] = subdivided2[currentPathLength-1];
}
ListPool<Vector3>.Release(ref subdivided2);
return subdivided;
}
public List<Vector3> SmoothSimple (List<Vector3> path) {
if (path.Count < 2) return path;
List<Vector3> subdivided;
if (uniformLength) {
// Clamp to a small value to avoid the path being divided into a huge number of segments
maxSegmentLength = Mathf.Max(maxSegmentLength, 0.005f);
float pathLength = 0;
for (int i = 0; i < path.Count-1; i++) {
pathLength += Vector3.Distance(path[i], path[i+1]);
}
int estimatedNumberOfSegments = Mathf.FloorToInt(pathLength / maxSegmentLength);
// Get a list with an initial capacity high enough so that we can add all points
subdivided = ListPool<Vector3>.Claim(estimatedNumberOfSegments+2);
float distanceAlong = 0;
// Sample points every [maxSegmentLength] world units along the path
for (int i = 0; i < path.Count-1; i++) {
var start = path[i];
var end = path[i+1];
float length = Vector3.Distance(start, end);
while (distanceAlong < length) {
subdivided.Add(Vector3.Lerp(start, end, distanceAlong / length));
distanceAlong += maxSegmentLength;
}
distanceAlong -= length;
}
// Make sure we get the exact position of the last point
subdivided.Add(path[path.Count-1]);
} else {
subdivisions = Mathf.Max(subdivisions, 0);
if (subdivisions > 10) {
Debug.LogWarning("Very large number of subdivisions. Cowardly refusing to subdivide every segment into more than " + (1 << subdivisions) + " subsegments");
subdivisions = 10;
}
int steps = 1 << subdivisions;
subdivided = ListPool<Vector3>.Claim((path.Count-1)*steps + 1);
Polygon.Subdivide(path, subdivided, steps);
}
if (strength > 0) {
for (int it = 0; it < iterations; it++) {
Vector3 prev = subdivided[0];
for (int i = 1; i < subdivided.Count-1; i++) {
Vector3 tmp = subdivided[i];
// prev is at this point set to the value that subdivided[i-1] had before this loop started
// Move the point closer to the average of the adjacent points
subdivided[i] = Vector3.Lerp(tmp, (prev+subdivided[i+1])/2F, strength);
prev = tmp;
}
}
}
return subdivided;
}
public List<Vector3> SmoothBezier (List<Vector3> path) {
if (subdivisions < 0) subdivisions = 0;
int subMult = 1 << subdivisions;
List<Vector3> subdivided = ListPool<Vector3>.Claim();
for (int i = 0; i < path.Count-1; i++) {
Vector3 tangent1;
Vector3 tangent2;
if (i == 0) {
tangent1 = path[i+1]-path[i];
} else {
tangent1 = path[i+1]-path[i-1];
}
if (i == path.Count-2) {
tangent2 = path[i]-path[i+1];
} else {
tangent2 = path[i]-path[i+2];
}
tangent1 *= bezierTangentLength;
tangent2 *= bezierTangentLength;
Vector3 v1 = path[i];
Vector3 v2 = v1+tangent1;
Vector3 v4 = path[i+1];
Vector3 v3 = v4+tangent2;
for (int j = 0; j < subMult; j++) {
subdivided.Add(AstarSplines.CubicBezier(v1, v2, v3, v4, (float)j/subMult));
}
}
// Assign the last point
subdivided.Add(path[path.Count-1]);
return subdivided;
}
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2016 Atif Aziz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
static partial class MoreEnumerable
{
/// <summary>
/// Returns the elements of the specified sequence or the specified
/// value in a singleton collection if the sequence is empty.
/// </summary>
/// <typeparam name="T">The type of the elements in the sequences.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="fallback">The value to return in a singleton
/// collection if <paramref name="source"/> is empty.</param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> that contains <paramref name="fallback"/>
/// if <paramref name="source"/> is empty; otherwise, <paramref name="source"/>.
/// </returns>
/// <example>
/// <code><![CDATA[
/// var numbers = new[] { 123, 456, 789 };
/// var result = numbers.Where(x => x == 100).FallbackIfEmpty(-1).Single();
/// ]]></code>
/// The <c>result</c> variable will contain <c>-1</c>.
/// </example>
public static IEnumerable<T> FallbackIfEmpty<T>(this IEnumerable<T> source, T fallback)
{
if (source == null) throw new ArgumentNullException(nameof(source));
return FallbackIfEmptyImpl(source, 1, fallback, default, default, default, null);
}
/// <summary>
/// Returns the elements of a sequence, but if it is empty then
/// returns an alternate sequence of values.
/// </summary>
/// <typeparam name="T">The type of the elements in the sequences.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="fallback1">First value of the alternate sequence that
/// is returned if <paramref name="source"/> is empty.</param>
/// <param name="fallback2">Second value of the alternate sequence that
/// is returned if <paramref name="source"/> is empty.</param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> that containing fallback values
/// if <paramref name="source"/> is empty; otherwise, <paramref name="source"/>.
/// </returns>
public static IEnumerable<T> FallbackIfEmpty<T>(this IEnumerable<T> source, T fallback1, T fallback2)
{
if (source == null) throw new ArgumentNullException(nameof(source));
return FallbackIfEmptyImpl(source, 2, fallback1, fallback2, default, default, null);
}
/// <summary>
/// Returns the elements of a sequence, but if it is empty then
/// returns an alternate sequence of values.
/// </summary>
/// <typeparam name="T">The type of the elements in the sequences.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="fallback1">First value of the alternate sequence that
/// is returned if <paramref name="source"/> is empty.</param>
/// <param name="fallback2">Second value of the alternate sequence that
/// is returned if <paramref name="source"/> is empty.</param>
/// <param name="fallback3">Third value of the alternate sequence that
/// is returned if <paramref name="source"/> is empty.</param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> that containing fallback values
/// if <paramref name="source"/> is empty; otherwise, <paramref name="source"/>.
/// </returns>
public static IEnumerable<T> FallbackIfEmpty<T>(this IEnumerable<T> source, T fallback1, T fallback2, T fallback3)
{
if (source == null) throw new ArgumentNullException(nameof(source));
return FallbackIfEmptyImpl(source, 3, fallback1, fallback2, fallback3, default, null);
}
/// <summary>
/// Returns the elements of a sequence, but if it is empty then
/// returns an alternate sequence of values.
/// </summary>
/// <typeparam name="T">The type of the elements in the sequences.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="fallback1">First value of the alternate sequence that
/// is returned if <paramref name="source"/> is empty.</param>
/// <param name="fallback2">Second value of the alternate sequence that
/// is returned if <paramref name="source"/> is empty.</param>
/// <param name="fallback3">Third value of the alternate sequence that
/// is returned if <paramref name="source"/> is empty.</param>
/// <param name="fallback4">Fourth value of the alternate sequence that
/// is returned if <paramref name="source"/> is empty.</param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> that containing fallback values
/// if <paramref name="source"/> is empty; otherwise, <paramref name="source"/>.
/// </returns>
public static IEnumerable<T> FallbackIfEmpty<T>(this IEnumerable<T> source, T fallback1, T fallback2, T fallback3, T fallback4)
{
if (source == null) throw new ArgumentNullException(nameof(source));
return FallbackIfEmptyImpl(source, 4, fallback1, fallback2, fallback3, fallback4, null);
}
/// <summary>
/// Returns the elements of a sequence, but if it is empty then
/// returns an alternate sequence from an array of values.
/// </summary>
/// <typeparam name="T">The type of the elements in the sequences.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="fallback">The array that is returned as the alternate
/// sequence if <paramref name="source"/> is empty.</param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> that containing fallback values
/// if <paramref name="source"/> is empty; otherwise, <paramref name="source"/>.
/// </returns>
public static IEnumerable<T> FallbackIfEmpty<T>(this IEnumerable<T> source, params T[] fallback)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (fallback == null) throw new ArgumentNullException(nameof(fallback));
return source.FallbackIfEmpty((IEnumerable<T>)fallback);
}
/// <summary>
/// Returns the elements of a sequence, but if it is empty then
/// returns an alternate sequence of values.
/// </summary>
/// <typeparam name="T">The type of the elements in the sequences.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="fallback">The alternate sequence that is returned
/// if <paramref name="source"/> is empty.</param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> that containing fallback values
/// if <paramref name="source"/> is empty; otherwise, <paramref name="source"/>.
/// </returns>
public static IEnumerable<T> FallbackIfEmpty<T>(this IEnumerable<T> source, IEnumerable<T> fallback)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (fallback == null) throw new ArgumentNullException(nameof(fallback));
return FallbackIfEmptyImpl(source, null, default, default, default, default, fallback);
}
static IEnumerable<T> FallbackIfEmptyImpl<T>(IEnumerable<T> source,
int? count, T? fallback1, T? fallback2, T? fallback3, T? fallback4,
IEnumerable<T>? fallback)
{
return source.TryGetCollectionCount() is {} collectionCount
? collectionCount == 0 ? Fallback() : source
: _();
IEnumerable<T> _()
{
using (var e = source.GetEnumerator())
{
if (e.MoveNext())
{
do { yield return e.Current; }
while (e.MoveNext());
yield break;
}
}
foreach (var item in Fallback())
yield return item;
}
IEnumerable<T> Fallback()
{
return fallback is {} seq ? seq : FallbackOnArgs();
IEnumerable<T> FallbackOnArgs()
{
Debug.Assert(count >= 1 && count <= 4);
yield return fallback1!;
if (count > 1) yield return fallback2!;
if (count > 2) yield return fallback3!;
if (count > 3) yield return fallback4!;
}
}
}
}
}
| |
// the includes. you might have to play around with these
using System;
using System.Data;
using System.Diagnostics;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Configuration;
// the code below would be placed in your code once you have created a blank aspx page, or
// in a windows program or wherever.
namespace WHATEVER_NAMESPACE_YOU_ARE_USING_IN_SAMPLECODE_CS {
class SampleCode {
// must be declared somewhere in code, or pulled from config file
// RC URI and RC Token
string strURI = "YOUR_RC_API_URI";
string strPostToken = "YOUR_RC_TOKEN";
// if pulling from web.config you could use the code below. i do this so i can easily switch between dev and production servers
// by just using different config files
string strURI = ConfigurationManager.AppSettings["RCURI"];
string strPostToken = ConfigurationManager.AppSettings["RCToken"];
//------------------------------
// // to get the above, this would be in your Web.config file in the <configuration> section.
// // sample shown in the Web.config file. Only if you want to do it this way.
// <appSettings>
// <add key="RCURI" value="YOUR_RC_API_URI" />
// <add key="RCToken" value="YOUR_RC_TOKEN" />
// </appSettings>
//------------------------------
// get any RC data. Need Token and strReturnCheck (to see if error in data returning). rest are optional
// strRecordsSelect: any records you want separated by ','; all records if ""
// strFields: Particular fields you want, separated by ','; all fields if ""
// strEvents: Particular events you want, separated by ','; all events if ""
// strForms: Particular forms you want, separated by ','; all forms if ""
// boolLabels: false=raw; true=label
// boolAccessGroups: false=no access group returned; true=access group returned (should be false, see note below)
// (note: can't import access group column if in your data table; ontology fields at the moment can't be imported too)
public DataTable GetTableFromAnyRC(string strPostToken, string strReturnCheck, string strRecordsSelect, string strFields,
string strEvents, string strForms, bool boolLabels, bool boolAccessGroups)
{
Debug.WriteLine("GetTableFromAnyRC()");
string strRecord;
CSVDoc csvDoc;
string strPostParameters = "";
int intReturnLength = strReturnCheck.Trim().Length;
DataTable dtDataTable = new DataTable();
DataRow drRecord;
strPostParameters = "&content=record&format=csv&type=flat&eventName=unique";
if (strReturnCheck == "")
{
throw new Exception("Error: " + "Must provide first field to check");
}
if (strRecordsSelect != "")
{
strPostParameters += "&records=" + strRecordsSelect;
}
if (strFields != "")
{
strPostParameters += "&fields=" + strFields;
}
if (strEvents != "")
{
strPostParameters += "&events=" + strEvents;
}
if (strForms != "")
{
strPostParameters += "&forms=" + strForms;
}
if (boolLabels)
strPostParameters += "&rawOrLabel=label";
else
strPostParameters += "&rawOrLabel=raw";
// probably should take out if you are going to import this exported data
if ( boolAccessGroups)
{
strPostParameters += "&exportDataAccessGroups=true";
}
byte[] bytePostData = Encoding.UTF8.GetBytes("token=" + strPostToken + strPostParameters);
string strResponse = responseHTTP(bytePostData);
// if no records found, there are no fields. new in RC 6 and greater
// have to deal with null DataTable in your call to this function
// if Rc < 6, then it will return field names without any rows of data
if (strResponse == "\n")
{
return (dtDataTable);
}
// should return the first field you expect. otherwise it is error
if (strResponse.Substring(0, intReturnLength) != strReturnCheck)
{
throw new Exception("RC Error: " + strResponse);
}
csvDoc = new CSVDoc(strResponse);
// first line of .csv is column names
strRecord = csvDoc.ReadLine();
// get column headers
string[] strColumnHeaders = strRecord.Split(',');
// set up table
for (int i = 0; i < strColumnHeaders.Length; i++)
{
dtDataTable.Columns.Add(strColumnHeaders[i].ToString(), typeof(string));
}
// now read all data and assign to data table
while ((strRecord = csvDoc.ReadLine()) != null)
{
CSVLine csvLine = new CSVLine(strRecord);
drRecord = dtDataTable.NewRow();
// now get fields
for (int i = 0; i < strColumnHeaders.Length; i++)
{
drRecord[i] = csvLine.ReadField();
}
dtDataTable.Rows.Add(drRecord);
}
return (dtDataTable);
}
// will return a csv string to import, given a data table
// if given any field string (like "studyid,redcap_event_name,field1,field2") will only put those fields in the csv string
public string GetCSVFromTable(DataTable dtData, string strFields)
{
Debug.WriteLine("GetCSVFromTable()");
string strCSVContents = "";
int i = 0;
int j = 0;
try
{
string[] strFieldsArray = strFields.Split(',');
//Write into csv format
for (i = 0; i < dtData.Columns.Count; i++)
{
if (strFields == "")
{
if (i > 0)
strCSVContents += ",";
strCSVContents += dtData.Columns[i].ColumnName;
}
else
{
if (InArray(strFieldsArray, dtData.Columns[i].ColumnName))
{
if (i > 0)
strCSVContents += ",";
strCSVContents += dtData.Columns[i].ColumnName;
}
}
}
strCSVContents += "\n";
for (i = 0; i < dtData.Rows.Count; i++)
{
for (j = 0; j < dtData.Columns.Count; j++)
{
if (strFields == "")
{
if (j > 0)
strCSVContents += ",";
// double quote all fields. replace any double quotes in field with escape clause.
// this allows things like inches (") to be put in fields, or any quote marks
strCSVContents += "\"" + dtData.Rows[i][j].ToString().Replace("\"", "\\\"") + "\"";
}
else
{
if (InArray(strFieldsArray, dtData.Columns[j].ColumnName))
{
if (j > 0)
strCSVContents += ",";
// double quote all fields. replace any double quotes in field with escape clause.
// this allows things like inches (") to be put in fields, or any quote marks
strCSVContents += "\"" + dtData.Rows[i][j].ToString().Replace("\"", "\\\"") + "\"";
}
}
}
strCSVContents += "\n";
}
}
catch (Exception ex)
{
throw new Exception("RC Error: " + ex.Message.ToString(), ex);
}
return (strCSVContents);
}
// if value found in array, will return true
private bool InArray(string[] strArray, string strText)
{
foreach (string strItem in strArray)
{
if (strItem == strText)
{
return true;
}
}
return false;
}
// will import a csv string into RC.
// remember that ONLY data exported in 'raw' mode can be imported (I think 'label' will not work)
public string RCImportCSVFlat(string strPostToken, string strCSVContents, bool boolOverwrite)
{
string strPostParameters = "&content=record&format=csv&type=flat&overwriteBehavior=overwrite&data=" + strCSVContents;
if ( boolOverwrite)
strPostParameters += "&overwriteBehavior=overwrite";
strPostParameters += "&data=" + strCSVContents;
byte[] bytePostData = Encoding.ASCII.GetBytes("token=" + strPostToken + strPostParameters);
string strResponse = responseHTTP(bytePostData);
// error if more than 9999 records (this num could change, but is just what I tried), or most likely, just has an error message.
if (strResponse.Length > 4)
{
throw new Exception("RC Error: " + strResponse);
}
return (strResponse);
}
// makes the API call and returns response from request
private string responseHTTP(byte[] bytePostData)
{
Debug.WriteLine("responseHTTP()");
string strResponse = "";
try
{
// added for mono on unix server. should not need if don't have this environment
// ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate,
// X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
HttpWebRequest webreqRedCap = (HttpWebRequest)WebRequest.Create(strURI);
webreqRedCap.Method = "POST";
webreqRedCap.ContentType = "application/x-www-form-urlencoded";
webreqRedCap.ContentLength = bytePostData.Length;
// Get the request stream and read it
Stream streamData = webreqRedCap.GetRequestStream();
streamData.Write(bytePostData, 0, bytePostData.Length);
streamData.Close();
HttpWebResponse webrespRedCap = (HttpWebResponse)webreqRedCap.GetResponse();
//Now, read the response (the string), and output it.
Stream streamResponse = webrespRedCap.GetResponseStream();
StreamReader readerResponse = new StreamReader(streamResponse);
strResponse = readerResponse.ReadToEnd();
}
catch (WebException exWE)
{
Stream streamWE = exWE.Response.GetResponseStream();
StringBuilder sbResponse = new StringBuilder("", 65536);
try
{
byte[] readBuffer = new byte[1000];
int intCnt = 0;
for (; ; )
{
intCnt = streamWE.Read(readBuffer, 0, readBuffer.Length);
if (intCnt == 0)
{
// EOF
break;
}
sbResponse.Append(System.Text.Encoding.UTF8.GetString(readBuffer, 0, intCnt));
}
}
finally
{
streamWE.Close();
strResponse = sbResponse.ToString();
}
}
catch (Exception ex)
{
strResponse = ex.Message.ToString();
//throw new Exception ( "RC Error. " + ex.Message.ToString(), ex);
}
return (strResponse);
}
//----------------------------------------------
/// Sample GetData code. gives you an idea of how to use above functions
public void GetData()
{
tbResults.Text = "";
DataTable dtRCTable = null;
DataRow drTableRow;
// say RC fields are: studyid, redcap_event_name, radio_button1
// remember, check_boxes come back as check_box___0 , check_box___1, etc.
string strField1="";
string strField2="";
string strField3="";
try
{
// the call below will expect 'studyid' as the 1st field (or errors out), asks for all records, all fields, all events, from form 'yourformname, raw data, all access groups
dtRCTable = dbAccess.GetTableFromAnyRC(strPostToken, "studyid", "", "", "", "yourformname", false, false);
for ( int i=0; i < dtRCTable.Rows.Count; i++)
{
// these will throw exceptions if the field name ("studyid") is not correct or not in the data returned
// when putting in Data Tables, noticed that empty fields sometimes have in them, so change it to blank ""
strField1 = dtRCTable.Rows[i]["studyid"].ToString().Trim().Replace(" ", "");
strField2 = dtRCTable.Rows[i]["redcap_event_name"].ToString().Trim().Replace(" ", ""); // this call should be removed if not longitudinal
strField3 = dtRCTable.Rows[i]["radio_button1"].ToString().Trim().Replace(" ", "");
// do whatever with the three fields you wanted
}
}
catch (Exception ex)
{
// whatever you want to do with exception
}
finally
{
// any actions needed here
}
}
// sample SetData code. gives you an idea of how to use the above functions
public void SetData ( DataTable dtData)
{
string strCSVContents = "";
try
{
// makes a csv string from all columns in data table
strCSVContents = GetCSVFromTable(dtData, "");
// imports this csv string to RC using API, with overwrite
RCImportCSVFlat(strPostToken, strCSVContents, true);
}
catch (Exception ex)
{
// whatever you want to do with exception
}
finally
{
// any actions needed here
}
}
}
}
| |
using BTDB.FieldHandler;
using BTDB.IL;
using BTDB.KVDBLayer;
using BTDB.ODBLayer;
using BTDB.StreamLayer;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using BTDB.Encrypted;
namespace BTDB.EventStoreLayer;
public delegate object Layer1Loader(ref SpanReader reader, ITypeBinaryDeserializerContext? ctx,
ITypeSerializersId2LoaderMapping mapping, ITypeDescriptor descriptor);
public delegate void Layer1SimpleSaver(ref SpanWriter writer, object value);
public delegate void Layer1ComplexSaver(ref SpanWriter writer, ITypeBinarySerializerContext ctx, object value);
public class TypeSerializers : ITypeSerializers
{
ITypeNameMapper _typeNameMapper;
readonly TypeSerializersOptions _options;
readonly
ConcurrentDictionary<ITypeDescriptor, Layer1Loader> _loaders =
new ConcurrentDictionary<ITypeDescriptor, Layer1Loader>(ReferenceEqualityComparer<ITypeDescriptor>.Instance);
readonly ConcurrentDictionary<(ITypeDescriptor, Type), Action<object, IDescriptorSerializerLiteContext>>
_newDescriptorSavers =
new ConcurrentDictionary<(ITypeDescriptor, Type), Action<object, IDescriptorSerializerLiteContext>>();
readonly ConcurrentDictionary<ITypeDescriptor, bool> _descriptorSet =
new ConcurrentDictionary<ITypeDescriptor, bool>(ReferenceEqualityComparer<ITypeDescriptor>.Instance);
ConcurrentDictionary<Type, ITypeDescriptor> _type2DescriptorMap =
new ConcurrentDictionary<Type, ITypeDescriptor>(ReferenceEqualityComparer<Type>.Instance);
readonly object _buildTypeLock = new object();
readonly ConcurrentDictionary<(ITypeDescriptor, Type), Layer1SimpleSaver> _simpleSavers =
new ConcurrentDictionary<(ITypeDescriptor, Type), Layer1SimpleSaver>();
readonly ConcurrentDictionary<(ITypeDescriptor, Type), Layer1ComplexSaver>
_complexSavers = new ConcurrentDictionary<(ITypeDescriptor, Type), Layer1ComplexSaver>();
readonly Func<ITypeDescriptor, Layer1Loader> _loaderFactoryAction;
readonly Func<Type, ITypeDescriptor> _buildFromTypeAction;
readonly ISymmetricCipher _symmetricCipher;
public TypeSerializers(ITypeNameMapper? typeNameMapper = null, TypeSerializersOptions? options = null)
{
ConvertorGenerator = DefaultTypeConvertorGenerator.Instance;
_typeNameMapper = typeNameMapper ?? new FullNameTypeMapper();
ForgotAllTypesAndSerializers();
_loaderFactoryAction = LoaderFactory;
_buildFromTypeAction = BuildFromType;
_options = options ?? TypeSerializersOptions.Default;
_symmetricCipher = _options.SymmetricCipher ?? new InvalidSymmetricCipher();
}
public void SetTypeNameMapper(ITypeNameMapper? typeNameMapper)
{
_typeNameMapper = typeNameMapper ?? new FullNameTypeMapper();
}
public ITypeDescriptor? DescriptorOf(object? obj)
{
if (obj == null) return null;
if (obj is IKnowDescriptor knowDescriptor) return knowDescriptor.GetDescriptor();
return DescriptorOf(obj.GetType());
}
public bool IsSafeToLoad(Type type)
{
return DescriptorOf(type) != null;
}
public ITypeConvertorGenerator ConvertorGenerator { get; private set; }
public ITypeNameMapper TypeNameMapper => _typeNameMapper;
public ITypeDescriptor? DescriptorOf(Type objType)
{
var res = _type2DescriptorMap.GetOrAdd(objType, _buildFromTypeAction);
if (res != null) _descriptorSet.GetOrAdd(res, true);
return res;
}
ITypeDescriptor? BuildFromType(Type type)
{
ITypeDescriptor result;
lock (_buildTypeLock)
{
var buildFromTypeCtx = new BuildFromTypeCtx(this, _type2DescriptorMap);
buildFromTypeCtx.Create(type);
buildFromTypeCtx.MergeTypesByShape();
buildFromTypeCtx.SetNewDescriptors();
result = buildFromTypeCtx.GetFinalDescriptor(type);
}
return result;
}
class BuildFromTypeCtx : ITypeDescriptorFactory
{
readonly TypeSerializers _typeSerializers;
readonly ConcurrentDictionary<Type, ITypeDescriptor> _type2DescriptorMap;
readonly Dictionary<Type, ITypeDescriptor> _temporaryMap = new Dictionary<Type, ITypeDescriptor>();
readonly Dictionary<ITypeDescriptor, ITypeDescriptor> _remap =
new Dictionary<ITypeDescriptor, ITypeDescriptor>(ReferenceEqualityComparer<ITypeDescriptor>.Instance);
public BuildFromTypeCtx(TypeSerializers typeSerializers,
ConcurrentDictionary<Type, ITypeDescriptor> type2DescriptorMap)
{
_typeSerializers = typeSerializers;
_type2DescriptorMap = type2DescriptorMap;
}
public ITypeDescriptor? Create(Type type)
{
if (_type2DescriptorMap.TryGetValue(type, out var result)) return result;
if (_temporaryMap.TryGetValue(type, out result)) return result;
if (!type.IsSubclassOf(typeof(Delegate)))
{
if (type.IsGenericType)
{
var typeAlternative = type.SpecializationOf(typeof(IDictionary<,>));
if (typeAlternative != null)
{
result = new DictionaryTypeDescriptor(_typeSerializers, type);
goto haveDescriptor;
}
typeAlternative = type.SpecializationOf(typeof(ICollection<>));
if (typeAlternative != null)
{
result = new ListTypeDescriptor(_typeSerializers, typeAlternative);
goto haveDescriptor;
}
if (_typeSerializers._options.IgnoreIIndirect &&
type.InheritsOrImplements(typeof(IIndirect<>)))
{
return null;
}
if (Nullable.GetUnderlyingType(type) != null)
{
result = new NullableTypeDescriptor(_typeSerializers, type);
goto haveDescriptor;
}
if (type.InheritsOrImplements(typeof(ITuple)))
{
result = new TupleTypeDescriptor(_typeSerializers, type);
goto haveDescriptor;
}
result = new ObjectTypeDescriptor(_typeSerializers, type);
}
else if (type.IsArray)
{
var typeAlternative = type.SpecializationOf(typeof(ICollection<>));
result = new ListTypeDescriptor(_typeSerializers, typeAlternative!);
}
else if (type.IsEnum)
{
result = new EnumTypeDescriptor(_typeSerializers, type);
}
else if (type.IsValueType)
{
throw new BTDBException($"Unsupported value type {type.Name}.");
}
else
{
result = new ObjectTypeDescriptor(_typeSerializers, type);
}
}
haveDescriptor:
_temporaryMap[type] = result;
if (result != null)
{
if (!result.FinishBuildFromType(this))
{
_temporaryMap.Remove(type);
return null;
}
}
return result;
}
public void MergeTypesByShape()
{
foreach (var typeDescriptor in _temporaryMap)
{
var d = typeDescriptor.Value;
foreach (var existingTypeDescriptor in _type2DescriptorMap)
{
if (d.Equals(existingTypeDescriptor.Value))
{
_remap[d] = existingTypeDescriptor.Value;
break;
}
}
}
foreach (var typeDescriptor in _temporaryMap)
{
var d = typeDescriptor.Value;
d.MapNestedTypes(desc =>
{
if (_remap.TryGetValue(desc, out var res)) return res;
return desc;
});
}
}
public ITypeDescriptor? GetFinalDescriptor(Type type)
{
if (_temporaryMap.TryGetValue(type, out var result))
{
if (_remap.TryGetValue(result, out var result2)) return result2;
return result;
}
return null;
}
public void SetNewDescriptors()
{
foreach (var typeDescriptor in _temporaryMap)
{
var d = typeDescriptor.Value;
if (_remap.TryGetValue(d, out _)) continue;
_type2DescriptorMap.TryAdd(d.GetPreferredType(), d);
}
}
}
public void ForgotAllTypesAndSerializers()
{
_loaders.Clear();
_newDescriptorSavers.Clear();
foreach (var p in _descriptorSet)
{
p.Key.ClearMappingToType();
}
_descriptorSet.Clear();
_type2DescriptorMap =
new ConcurrentDictionary<Type, ITypeDescriptor>(EnumDefaultTypes(),
ReferenceEqualityComparer<Type>.Instance);
}
static IEnumerable<KeyValuePair<Type, ITypeDescriptor>> EnumDefaultTypes()
{
foreach (var predefinedType in BasicSerializersFactory.TypeDescriptors)
{
yield return new KeyValuePair<Type, ITypeDescriptor>(predefinedType.GetPreferredType(), predefinedType);
var descriptorMultipleNativeTypes = predefinedType as ITypeDescriptorMultipleNativeTypes;
if (descriptorMultipleNativeTypes == null) continue;
foreach (var type in descriptorMultipleNativeTypes.GetNativeTypes())
{
yield return new KeyValuePair<Type, ITypeDescriptor>(type, predefinedType);
}
}
}
public Layer1Loader GetLoader(ITypeDescriptor descriptor)
{
return _loaders.GetOrAdd(descriptor, _loaderFactoryAction);
}
Layer1Loader LoaderFactory(ITypeDescriptor descriptor)
{
Type loadAsType = null;
try
{
loadAsType = LoadAsType(descriptor);
}
catch (EventSkippedException)
{
}
var methodBuilder = ILBuilder.Instance.NewMethod<Layer1Loader>("DeserializerFor" + descriptor.Name);
var il = methodBuilder.Generator;
if (descriptor.AnyOpNeedsCtx())
{
var localCtx = il.DeclareLocal(typeof(ITypeBinaryDeserializerContext), "ctx");
var haveCtx = il.DefineLabel();
il
.Ldarg(1)
.Dup()
.Stloc(localCtx)
.Brtrue(haveCtx)
.Ldarg(2)
// ReSharper disable once ObjectCreationAsStatement
.Newobj(() => new DeserializerCtx(null))
.Castclass(typeof(ITypeBinaryDeserializerContext))
.Stloc(localCtx)
.Mark(haveCtx);
if (loadAsType == null)
descriptor.GenerateSkip(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldloc(localCtx));
else
descriptor.GenerateLoad(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldloc(localCtx),
ilGen => ilGen.Ldarg(3), loadAsType);
}
else
{
if (loadAsType == null)
descriptor.GenerateSkip(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldarg(1));
else
descriptor.GenerateLoad(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldarg(1),
ilGen => ilGen.Ldarg(3), loadAsType);
}
if (loadAsType == null)
{
il.Ldnull();
}
else if (loadAsType.IsValueType)
{
il.Box(loadAsType);
}
else if (loadAsType != typeof(object))
{
il.Castclass(typeof(object));
}
il.Ret();
return methodBuilder.Create();
}
public Type LoadAsType(ITypeDescriptor descriptor)
{
return descriptor.GetPreferredType() ?? NameToType(descriptor.Name!) ?? typeof(object);
}
public Type LoadAsType(ITypeDescriptor descriptor, Type targetType)
{
return descriptor.GetPreferredType(targetType) ?? NameToType(descriptor.Name!) ?? typeof(object);
}
class DeserializerCtx : ITypeBinaryDeserializerContext
{
readonly ITypeSerializersId2LoaderMapping _mapping;
readonly List<object> _backRefs = new List<object>();
public DeserializerCtx(ITypeSerializersId2LoaderMapping mapping)
{
_mapping = mapping;
}
public object? LoadObject(ref SpanReader reader)
{
var typeId = reader.ReadVUInt32();
if (typeId == 0)
{
return null;
}
if (typeId == 1)
{
var backRefId = reader.ReadVUInt32();
return _backRefs[(int)backRefId];
}
return _mapping.Load(typeId, ref reader, this);
}
public void AddBackRef(object obj)
{
_backRefs.Add(obj);
}
public void SkipObject(ref SpanReader reader)
{
var typeId = reader.ReadVUInt32();
if (typeId == 0)
{
return;
}
if (typeId == 1)
{
var backRefId = reader.ReadVUInt32();
if (backRefId > _backRefs.Count) throw new InvalidDataException();
return;
}
_mapping.Load(typeId, ref reader, this);
}
public EncryptedString LoadEncryptedString(ref SpanReader reader)
{
var cipher = _mapping.GetSymmetricCipher();
var enc = reader.ReadByteArray();
var size = cipher!.CalcPlainSizeFor(enc);
var dec = new byte[size];
if (!cipher.Decrypt(enc, dec))
{
throw new CryptographicException();
}
var r = new SpanReader(dec);
return r.ReadString();
}
public void SkipEncryptedString(ref SpanReader reader)
{
reader.SkipByteArray();
}
}
public Layer1SimpleSaver GetSimpleSaver(ITypeDescriptor descriptor, Type type)
{
return _simpleSavers.GetOrAdd((descriptor, type), NewSimpleSaver);
}
static Layer1SimpleSaver? NewSimpleSaver((ITypeDescriptor descriptor, Type type) v)
{
var (descriptor, type) = v;
if (descriptor.AnyOpNeedsCtx()) return null;
var method =
ILBuilder.Instance.NewMethod<Layer1SimpleSaver>(descriptor.Name + "SimpleSaver");
var il = method.Generator;
descriptor.GenerateSave(il, ilgen => ilgen.Ldarg(0), null, ilgen =>
{
ilgen.Ldarg(1);
if (type != typeof(object))
{
ilgen.UnboxAny(type);
}
}, type);
il.Ret();
return method.Create();
}
public Layer1ComplexSaver GetComplexSaver(ITypeDescriptor descriptor, Type type)
{
return _complexSavers.GetOrAdd((descriptor, type), NewComplexSaver);
}
static Layer1ComplexSaver NewComplexSaver((ITypeDescriptor descriptor, Type type) v)
{
var (descriptor, type) = v;
var method = ILBuilder.Instance.NewMethod<Layer1ComplexSaver>(descriptor.Name + "ComplexSaver");
var il = method.Generator;
descriptor.GenerateSave(il, ilgen => ilgen.Ldarg(0), ilgen => ilgen.Ldarg(1), ilgen =>
{
ilgen.Ldarg(2);
if (type != typeof(object))
{
ilgen.UnboxAny(type);
}
}, type);
il.Ret();
return method.Create();
}
public Action<object, IDescriptorSerializerLiteContext>? GetNewDescriptorSaver(ITypeDescriptor descriptor,
Type preciseType)
{
return _newDescriptorSavers.GetOrAdd((descriptor, preciseType), NewDescriptorSaverFactory);
}
static Action<object, IDescriptorSerializerLiteContext>? NewDescriptorSaverFactory((ITypeDescriptor descriptor, Type type) pair)
{
var gen = pair.descriptor.BuildNewDescriptorGenerator();
if (gen == null)
{
return null;
}
var method =
ILBuilder.Instance.NewMethod<Action<object, IDescriptorSerializerLiteContext>>(
"GatherAllObjectsForTypeExtraction_" + pair.descriptor.Name);
var il = method.Generator;
gen.GenerateTypeIterator(il, ilgen => ilgen.Ldarg(0), ilgen => ilgen.Ldarg(1), pair.type);
il.Ret();
return method.Create();
}
public ITypeSerializersMapping CreateMapping()
{
return new TypeSerializersMapping(this);
}
public static void StoreDescriptor(ITypeDescriptor descriptor, ref SpanWriter writer, Func<ITypeDescriptor, uint> descriptor2Id)
{
switch (descriptor)
{
case ListTypeDescriptor:
writer.WriteUInt8((byte)TypeCategory.List);
break;
case DictionaryTypeDescriptor:
writer.WriteUInt8((byte)TypeCategory.Dictionary);
break;
case ObjectTypeDescriptor:
writer.WriteUInt8((byte)TypeCategory.Class);
break;
case EnumTypeDescriptor:
writer.WriteUInt8((byte)TypeCategory.Enum);
break;
case NullableTypeDescriptor:
writer.WriteUInt8((byte)TypeCategory.Nullable);
break;
case TupleTypeDescriptor:
writer.WriteUInt8((byte)TypeCategory.Tuple);
break;
default:
throw new ArgumentOutOfRangeException();
}
((IPersistTypeDescriptor)descriptor).Persist(ref writer, (ref SpanWriter w, ITypeDescriptor d) => w.WriteVUInt32(descriptor2Id(d)));
}
public ITypeDescriptor MergeDescriptor(ITypeDescriptor descriptor)
{
foreach (var (typeDescriptor, _) in _descriptorSet)
{
if (descriptor.Equals(typeDescriptor))
{
return typeDescriptor;
}
}
_descriptorSet.GetOrAdd(descriptor, true);
return descriptor;
}
public string TypeToName(Type type)
{
return _typeNameMapper.ToName(type);
}
Type? NameToType(string name)
{
return _typeNameMapper.ToType(name);
}
public ISymmetricCipher GetSymmetricCipher()
{
return _symmetricCipher;
}
}
| |
using UnityEngine;
using System.Collections;
[System.Serializable]
public class RagePixelRow {
public int pixelSizeX;
public int pixelSizeY;
public int newPixelSizeX;
public int newPixelSizeY;
public int key;
public string name;
[HideInInspector]
public string fontCharacter = "";
[HideInInspector]
public int fontYOffset = 0;
[SerializeField]
private RagePixelAnimation[] _animations;
public RagePixelAnimation[] animations
{
get
{
if (_animations == null)
{
_animations = new RagePixelAnimation[0];
}
return _animations;
}
set
{
_animations = value;
}
}
[SerializeField]
private RagePixelCell[] _cells;
public RagePixelCell[] cells
{
get
{
if (_cells == null)
{
_cells = new RagePixelCell[0];
}
return _cells;
}
set
{
_cells = value;
}
}
public RagePixelCell InsertCell(int index, int key)
{
RagePixelCell newCell = new RagePixelCell();
newCell.delay = 200;
newCell.uv = new Rect();
newCell.key = key;
RagePixelCell[] tmpArr = new RagePixelCell[cells.Length + 1];
for (int i = 0; i < tmpArr.Length; i++)
{
if (i < index)
{
tmpArr[i] = cells[i];
if (i == index - 1)
{
newCell.uv = cells[i].uv;
}
}
else if (i > index)
{
tmpArr[i] = cells[i - 1];
}
else
{
tmpArr[i] = newCell;
}
}
cells = tmpArr;
return newCell;
}
public void RemoveCellByKey(int key)
{
int toBeRemovedIndex = -1;
if (cells.Length > 1)
{
for (int i = 0; i < cells.Length; i++)
{
if (cells[i].key.Equals(key))
{
toBeRemovedIndex = i;
}
}
if (toBeRemovedIndex >= 0)
{
RemoveCellByIndex(toBeRemovedIndex);
}
}
else
{
Debug.Log("Error: Can't remove the last cell. Remove row instead");
}
}
public void MoveCell(int fromIndex, int toIndex)
{
if (fromIndex >= 0 && fromIndex < cells.Length && toIndex >= 0 && toIndex <= cells.Length)
{
RagePixelCell[] tmpArr = new RagePixelCell[cells.Length];
for (int i = 0; i < tmpArr.Length; i++)
{
if (i == toIndex)
{
tmpArr[toIndex] = cells[fromIndex];
}
else if (i < fromIndex && i < toIndex || i > fromIndex && i > toIndex)
{
tmpArr[i] = cells[i];
}
else if (i >= fromIndex && i < toIndex)
{
tmpArr[i] = cells[i + 1];
}
else if (i <= fromIndex && i > toIndex)
{
tmpArr[i] = cells[i - 1];
}
}
cells = tmpArr;
}
}
public int GetKey(int index)
{
if (cells.Length > index)
{
return cells[index].key;
}
Debug.Log("Error: Indvalid array size");
return cells[0].key;
}
public int GetIndex(int key)
{
if (cells.Length > 0)
{
for (int i = 0; i < cells.Length; i++)
{
if (cells[i].key.Equals(key))
{
return i;
}
}
}
return 0;
}
public RagePixelCell GetCell(int key)
{
if (cells.Length > 0)
{
for (int i = 0; i < cells.Length; i++)
{
if (cells[i].key.Equals(key))
{
return cells[i];
}
}
}
return cells[0];
}
public void RemoveCellByIndex(int index)
{
if (cells.Length > 0)
{
RagePixelCell[] tmpArr = new RagePixelCell[cells.Length - 1];
for (int i = 0; i < cells.Length; i++)
{
if (i < index)
{
tmpArr[i] = cells[i];
}
else if (i > index)
{
tmpArr[i-1] = cells[i];
}
}
cells = tmpArr;
}
}
public void AddAnimation()
{
RagePixelAnimation newAnim = new RagePixelAnimation();
newAnim.mode = RagePixelSprite.AnimationMode.PlayOnce;
newAnim.startIndex = 0;
newAnim.endIndex = cells.Length - 1;
newAnim.name = "New animation";
RagePixelAnimation[] tmpArr = new RagePixelAnimation[animations.Length + 1];
for (int i = 0; i < tmpArr.Length-1; i++)
{
tmpArr[i] = animations[i];
}
tmpArr[tmpArr.Length - 1] = newAnim;
animations = tmpArr;
}
public void RemoveAnimation(int index)
{
if (animations.Length > 0)
{
RagePixelAnimation[] tmpArr = new RagePixelAnimation[animations.Length - 1];
for (int i = 0; i < animations.Length; i++)
{
if (i < index)
{
tmpArr[i] = animations[i];
}
else if (i > index)
{
tmpArr[i - 1] = animations[i];
}
}
animations = tmpArr;
}
}
public RagePixelAnimation GetAnimationByName(string name)
{
if (animations.Length > 0)
{
for (int i = 0; i < animations.Length; i++)
{
if (animations[i].name.Equals(name))
{
return animations[i];
}
}
}
return null;
}
public void ClearUndoHistory()
{
for (int i = 0; i < cells.Length; i++)
{
if (cells[i].undoHistory == null)
{
cells[i].undoHistory = new ArrayList();
}
else
{
cells[i].undoHistory.Clear();
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function WorldEditor::onSelect( %this, %obj )
{
EditorTree.addSelection( %obj );
_setShadowVizLight( %obj );
//Inspector.inspect( %obj );
if ( isObject( %obj ) && %obj.isMethod( "onEditorSelect" ) )
%obj.onEditorSelect( %this.getSelectionSize() );
EditorGui.currentEditor.onObjectSelected( %obj );
// Inform the camera
commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid());
EditorGuiStatusBar.setSelectionObjectsByCount(%this.getSelectionSize());
// Update the materialEditorList
$Tools::materialEditorList = %obj.getId();
// Used to help the Material Editor( the M.E doesn't utilize its own TS control )
// so this dirty extension is used to fake it
if ( MaterialEditorPreviewWindow.isVisible() )
MaterialEditorGui.prepareActiveObject();
// Update the Transform Selection window
ETransformSelection.onSelectionChanged();
}
function WorldEditor::onMultiSelect( %this, %set )
{
// This is called when completing a drag selection ( on3DMouseUp )
// so we can avoid calling onSelect for every object. We can only
// do most of this stuff, like inspecting, on one object at a time anyway.
%count = %set.getCount();
%i = 0;
foreach( %obj in %set )
{
if ( %obj.isMethod( "onEditorSelect" ) )
%obj.onEditorSelect( %count );
%i ++;
EditorTree.addSelection( %obj, %i == %count );
EditorGui.currentEditor.onObjectSelected( %obj );
}
// Inform the camera
commandToServer( 'EditorOrbitCameraSelectChange', %count, %this.getSelectionCentroid() );
EditorGuiStatusBar.setSelectionObjectsByCount( EWorldEditor.getSelectionSize() );
// Update the Transform Selection window, if it is
// visible.
if( ETransformSelection.isVisible() )
ETransformSelection.onSelectionChanged();
}
function WorldEditor::onUnSelect( %this, %obj )
{
if ( isObject( %obj ) && %obj.isMethod( "onEditorUnselect" ) )
%obj.onEditorUnselect();
EditorGui.currentEditor.onObjectDeselected( %obj );
Inspector.removeInspect( %obj );
EditorTree.removeSelection(%obj);
// Inform the camera
commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid());
EditorGuiStatusBar.setSelectionObjectsByCount(%this.getSelectionSize());
// Update the Transform Selection window
ETransformSelection.onSelectionChanged();
}
function WorldEditor::onClearSelection( %this )
{
EditorGui.currentEditor.onSelectionCleared();
EditorTree.clearSelection();
// Inform the camera
commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid());
EditorGuiStatusBar.setSelectionObjectsByCount(%this.getSelectionSize());
// Update the Transform Selection window
ETransformSelection.onSelectionChanged();
}
function WorldEditor::onSelectionCentroidChanged( %this )
{
// Inform the camera
commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid());
// Refresh inspector.
Inspector.refresh();
}
function WorldEditor::setSceneAsDirty(%this)
{
EWorldEditor.isDirty = true;
}
//////////////////////////////////////////////////////////////////////////
function WorldEditor::init(%this)
{
// add objclasses which we do not want to collide with
%this.ignoreObjClass(Sky);
// editing modes
%this.numEditModes = 3;
%this.editMode[0] = "move";
%this.editMode[1] = "rotate";
%this.editMode[2] = "scale";
// context menu
new GuiControl(WEContextPopupDlg, EditorGuiGroup)
{
profile = "ToolsGuiModelessDialogProfile";
horizSizing = "width";
vertSizing = "height";
position = "0 0";
extent = "640 480";
minExtent = "8 8";
visible = "1";
setFirstResponder = "0";
modal = "1";
new GuiPopUpMenuCtrl(WEContextPopup)
{
profile = "ToolsGuiScrollProfile";
position = "0 0";
extent = "0 0";
minExtent = "0 0";
maxPopupHeight = "200";
command = "canvas.popDialog(WEContextPopupDlg);";
};
};
WEContextPopup.setVisible(false);
// Make sure we have an active selection set.
if( !%this.getActiveSelection() )
%this.setActiveSelection( new WorldEditorSelection( EWorldEditorSelection ) );
}
//------------------------------------------------------------------------------
function WorldEditor::onDblClick(%this, %obj)
{
// Commented out because making someone double click to do this is stupid
// and has the possibility of moving hte object
//Inspector.inspect(%obj);
//InspectorNameEdit.setValue(%obj.getName());
}
function WorldEditor::onClick( %this, %obj )
{
Inspector.inspect( %obj );
}
function WorldEditor::onEndDrag( %this, %obj )
{
Inspector.inspect( %obj );
Inspector.apply();
}
//------------------------------------------------------------------------------
function WorldEditor::export(%this)
{
getSaveFilename("~/editor/*.mac|mac file", %this @ ".doExport", "selection.mac");
}
function WorldEditor::doExport(%this, %file)
{
getRootScene().save("~/editor/" @ %file, true);
}
function WorldEditor::import(%this)
{
getLoadFilename("~/editor/*.mac|mac file", %this @ ".doImport");
}
function WorldEditor::doImport(%this, %file)
{
exec("~/editor/" @ %file);
}
function WorldEditor::onGuiUpdate(%this, %text)
{
}
function WorldEditor::getSelectionLockCount(%this)
{
%ret = 0;
for(%i = 0; %i < %this.getSelectionSize(); %i++)
{
%obj = %this.getSelectedObject(%i);
if(%obj.locked)
%ret++;
}
return %ret;
}
function WorldEditor::getSelectionHiddenCount(%this)
{
%ret = 0;
for(%i = 0; %i < %this.getSelectionSize(); %i++)
{
%obj = %this.getSelectedObject(%i);
if(%obj.hidden)
%ret++;
}
return %ret;
}
function WorldEditor::dropCameraToSelection(%this)
{
if(%this.getSelectionSize() == 0)
return;
%pos = %this.getSelectionCentroid();
%cam = LocalClientConnection.camera.getTransform();
// set the pnt
%cam = setWord(%cam, 0, getWord(%pos, 0));
%cam = setWord(%cam, 1, getWord(%pos, 1));
%cam = setWord(%cam, 2, getWord(%pos, 2));
LocalClientConnection.camera.setTransform(%cam);
}
/// Pastes the selection at the same place (used to move obj from a group to another)
function WorldEditor::moveSelectionInPlace(%this)
{
%saveDropType = %this.dropType;
%this.dropType = "atCentroid";
%this.copySelection();
%this.deleteSelection();
%this.pasteSelection();
%this.dropType = %saveDropType;
}
function WorldEditor::addSelectionToAddGroup(%this)
{
for(%i = 0; %i < %this.getSelectionSize(); %i++)
{
%obj = %this.getSelectedObject(%i);
$InstantGroup.add(%obj);
}
}
// resets the scale and rotation on the selection set
function WorldEditor::resetTransforms(%this)
{
%this.addUndoState();
for(%i = 0; %i < %this.getSelectionSize(); %i++)
{
%obj = %this.getSelectedObject(%i);
%transform = %obj.getTransform();
%transform = setWord(%transform, 3, "0");
%transform = setWord(%transform, 4, "0");
%transform = setWord(%transform, 5, "1");
%transform = setWord(%transform, 6, "0");
//
%obj.setTransform(%transform);
%obj.setScale("1 1 1");
}
}
function WorldEditorToolbarDlg::init(%this)
{
WorldEditorInspectorCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolInspectorGui" ) );
WorldEditorMissionAreaCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolMissionAreaGui" ) );
WorldEditorTreeCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolTreeViewGui" ) );
WorldEditorCreatorCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolCreatorGui" ) );
}
function WorldEditor::onAddSelected(%this,%obj)
{
EditorTree.addSelection(%obj);
}
function WorldEditor::onWorldEditorUndo( %this )
{
Inspector.refresh();
}
function Inspector::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue )
{
// The instant group will try to add our
// UndoAction if we don't disable it.
pushInstantGroup();
%nameOrClass = %object.getName();
if ( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%action = new InspectorFieldUndoAction()
{
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %oldValue;
arrayIndex = %arrayIndex;
inspectorGui = %this;
};
// If it's a datablock, initiate a retransmit. Don't do so
// immediately so as the actual field value will only be set
// by the inspector code after this method has returned.
if( %object.isMemberOfClass( "SimDataBlock" ) )
%object.schedule( 1, "reloadOnLocalClient" );
// Restore the instant group.
popInstantGroup();
%action.addToManager( Editor.getUndoManager() );
EWorldEditor.isDirty = true;
// Update the selection
if(EWorldEditor.getSelectionSize() > 0 && (%fieldName $= "position" || %fieldName $= "rotation" || %fieldName $= "scale"))
{
EWorldEditor.invalidateSelectionCentroid();
}
}
function Inspector::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc )
{
FieldInfoControl.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc );
}
// The following three methods are for fields that edit field value live and thus cannot record
// undo information during edits. For these fields, undo information is recorded in advance and
// then either queued or disarded when the field edit is finished.
function Inspector::onInspectorPreFieldModification( %this, %fieldName, %arrayIndex )
{
pushInstantGroup();
%undoManager = Editor.getUndoManager();
%numObjects = %this.getNumInspectObjects();
if( %numObjects > 1 )
%action = %undoManager.pushCompound( "Multiple Field Edit" );
for( %i = 0; %i < %numObjects; %i ++ )
{
%object = %this.getInspectObject( %i );
%nameOrClass = %object.getName();
if ( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%undo = new InspectorFieldUndoAction()
{
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %object.getFieldValue( %fieldName, %arrayIndex );
arrayIndex = %arrayIndex;
inspectorGui = %this;
};
if( %numObjects > 1 )
%undo.addToManager( %undoManager );
else
{
%action = %undo;
break;
}
}
%this.currentFieldEditAction = %action;
popInstantGroup();
}
function Inspector::onInspectorPostFieldModification( %this )
{
if( %this.currentFieldEditAction.isMemberOfClass( "CompoundUndoAction" ) )
{
// Finish multiple field edit.
Editor.getUndoManager().popCompound();
}
else
{
// Queue single field undo.
%this.currentFieldEditAction.addToManager( Editor.getUndoManager() );
}
%this.currentFieldEditAction = "";
EWorldEditor.isDirty = true;
}
function Inspector::onInspectorDiscardFieldModification( %this )
{
%this.currentFieldEditAction.undo();
if( %this.currentFieldEditAction.isMemberOfClass( "CompoundUndoAction" ) )
{
// Multiple field editor. Pop and discard.
Editor.getUndoManager().popCompound( true );
}
else
{
// Single field edit. Just kill undo action.
%this.currentFieldEditAction.delete();
}
%this.currentFieldEditAction = "";
}
function Inspector::inspect( %this, %obj )
{
//echo( "inspecting: " @ %obj );
%name = "";
if ( isObject( %obj ) )
%name = %obj.getName();
else
FieldInfoControl.setText( "" );
//InspectorNameEdit.setValue( %name );
Parent::inspect( %this, %obj );
}
function Inspector::onBeginCompoundEdit( %this )
{
Editor.getUndoManager().pushCompound( "Multiple Field Edit" );
}
function Inspector::onEndCompoundEdit( %this )
{
Editor.getUndoManager().popCompound();
}
function Inspector::onCancelCompoundEdit( %this )
{
Editor.getUndoManager().popCompound( true );
}
function foCollaps (%this, %tab){
switch$ (%tab){
case "container0":
%tab.visible = "0";
buttxon1.position = getWord(buttxon0.position, 0)+32 SPC getWord(buttxon1.position, 1);
buttxon2.position = getWord(buttxon1.position, 0)+32 SPC getWord(buttxon2.position, 1);
case "container1":
%tab.visible = "0";
case "container2":
%tab.visible = "0";
}
}
| |
// GHelper.cs
//
// Author:
// Atte Vuorinen <[email protected]>
//
// Copyright (c) 2014 Atte Vuorinen
//
// 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.
#if UNITY_EDITOR || (!UNITY_FLASH && !NETFX_CORE)
#define USE_FORMATTERS
#endif
using UnityEngine;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
#if USE_FORMATTERS
using System.Runtime.Serialization.Formatters.Binary;
#endif
using System.Xml.Serialization;
public static class GHelper
{
/// <summary>
/// Gets the component or add it if GameObject doesn't have it.
/// </summary>
/// <returns>The component.</returns>
/// <param name="go">Go.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public static T GetComponent<T>(GameObject go) where T : Component
{
T comp = go.GetComponent<T>();
if(comp == null)
{
comp = go.AddComponent<T>();
}
return comp;
}
/// <summary>
/// Gets the default material.
/// </summary>
/// <returns>The default material.</returns>
public static Material GetDefaultMaterial()
{
return Resources.Load<Material>("Materials/AGUI-Default");
}
/// <summary>
/// Determines if has flag the specified enumValue enumLookingValue.
/// </summary>
/// <returns><c>true</c> if has flag the specified enumValue enumLookingValue; otherwise, <c>false</c>.</returns>
/// <param name="enumValue">Enum value.</param>
/// <param name="enumLookingValue">Enum looking value.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public static bool HasFlag<T>(this T enumValue, T enumLookingValue) where T : System.IComparable
{
int value = (int) (object) enumValue;
int looking = (int) (object) enumLookingValue;
if( (value & looking) == looking)
{
return true;
}
return false;
}
public static T CreateInstance<T>(string name) where T : Component
{
GameObject go = new GameObject(name);
return go.AddComponent<T>();
}
public static T CreateStaticInstance<T>(string name) where T : Component
{
T instance = CreateInstance<T>(name);
GameObject.DontDestroyOnLoad(instance.gameObject);
return instance;
}
}
public static class GColorHelper
{
/// <summary>
/// Gets the color using GameObject to get GData.
/// </summary>
/// <returns>The color.</returns>
/// <param name="go">Go.</param>
/// <param name="shared">If set to <c>true</c> shared.</param>
public static Color GetColor(GameObject go, bool shared = false)
{
return GetColor(GData.GetData(go),shared);
}
/// <summary>
/// Gets the color using GData.
/// </summary>
/// <returns>The color.</returns>
/// <param name="data">Data.</param>
/// <param name="shared">If set to <c>true</c> shared.</param>
public static Color GetColor(GData data, bool shared = false)
{
if(data.aguiObject && !data.aguiObject.simulateNonAGUI)
{
return data.aguiObject.color;
}
else if(data.renderer)
{
if(shared)
{
return data.renderer.sharedMaterial.color;
}
else if(data.renderer.GetType() == typeof(SpriteRenderer) && data.aguiObject == null)
{
return (data.renderer as SpriteRenderer).color;
}
else
{
return data.renderer.material.color;
}
}
else if(data.light)
{
return data.light.color;
}
return Color.black;
}
/// <summary>
/// Sets the color using GameObject to get GData.
/// </summary>
/// <param name="go">Go.</param>
/// <param name="color">Color.</param>
/// <param name="shared">If set to <c>true</c> shared.</param>
public static void SetColor(GameObject go, Color color, bool shared = false)
{
SetColor(GData.GetData(go),color,shared);
}
/// <summary>
/// Sets the color using GData
/// </summary>
/// <param name="data">Data.</param>
/// <param name="color">Color.</param>
/// <param name="shared">If set to <c>true</c> shared.</param>
public static void SetColor(GData data, Color color, bool shared = false)
{
if(data.aguiPanel)
{
data.aguiPanel.alpha = color.a;
return;
}
else if(data.aguiObject && !data.aguiObject.simulateNonAGUI)
{
data.aguiObject.color = color;
}
else if(data.renderer)
{
if(shared)
{
data.renderer.sharedMaterial.color = color;
}
else if(data.renderer.GetType() == typeof(SpriteRenderer) && data.aguiObject == null)
{
(data.renderer as SpriteRenderer).color = color;
}
else
{
data.renderer.material.color = color;
}
}
if(data.light)
{
data.light.color = color;
}
}
}
public static class GSerialize
{
/*
* TODO
* - Create customize able saving and loading system.
*/
static GSerialize()
{
#if UNITY_IPHONE
System.Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");
#endif
}
public static void Save<T>(string playerPrefID, T data)
{
#if USE_FORMATTERS
BinaryFormatter binary = new BinaryFormatter();
MemoryStream memory = new MemoryStream();
binary.Serialize(memory,data);
PlayerPrefs.SetString(playerPrefID, System.Convert.ToBase64String(memory.GetBuffer()) );
#else
SaveXml<T>(playerPrefID, data);
#endif
}
public static void SaveXml<T>(string playerPrefID, T data)
{
XmlSerializer xml = new XmlSerializer(typeof(T));
MemoryStream memory = new MemoryStream();
xml.Serialize(memory,data);
PlayerPrefs.SetString(playerPrefID, System.Convert.ToBase64String(memory.ToArray()) );
}
public static bool Load<T>(string playerPrefID, ref T objectData)
{
if(PlayerPrefs.HasKey(playerPrefID))
{
#if USE_FORMATTERS
byte[] data = System.Convert.FromBase64String(PlayerPrefs.GetString(playerPrefID));
return Load<T>(data,ref objectData);
#else
return LoadXml<T>(playerPrefID, ref objectData);
#endif
}
return false;
}
public static bool LoadXml<T>(string playerPrefID, ref T objectData)
{
byte[] data = System.Convert.FromBase64String(PlayerPrefs.GetString(playerPrefID));
MemoryStream memory = new MemoryStream(data);
XmlSerializer xml = new XmlSerializer(typeof(T));
StreamReader reader = new StreamReader(memory);
objectData = (T)xml.Deserialize(reader);
return true;
}
public static bool Load<T>(byte[] rawData, ref T objectData)
{
BinaryFormatter binary = new BinaryFormatter();
MemoryStream memory = new MemoryStream(rawData);
objectData = (T)binary.Deserialize(memory);
return true;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Storage;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Feedback.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using Roslyn.VisualStudio.ProjectSystem;
using VSLangProj;
using VSLangProj140;
using OLEServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
/// <summary>
/// The Workspace for running inside Visual Studio.
/// </summary>
internal abstract class VisualStudioWorkspaceImpl : VisualStudioWorkspace
{
private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1);
private const string AppCodeFolderName = "App_Code";
protected readonly IServiceProvider ServiceProvider;
private readonly IVsUIShellOpenDocument _shellOpenDocument;
private readonly IVsTextManager _textManager;
// Not readonly because it needs to be set in the derived class' constructor.
private VisualStudioProjectTracker _projectTracker;
// document worker coordinator
private ISolutionCrawlerRegistrationService _registrationService;
private readonly ForegroundThreadAffinitizedObject _foregroundObject = new ForegroundThreadAffinitizedObject();
public VisualStudioWorkspaceImpl(
SVsServiceProvider serviceProvider,
WorkspaceBackgroundWork backgroundWork)
: base(
CreateHostServices(serviceProvider),
backgroundWork)
{
this.ServiceProvider = serviceProvider;
_textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager;
_shellOpenDocument = serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
// Ensure the options factory services are initialized on the UI thread
this.Services.GetService<IOptionService>();
}
internal static HostServices CreateHostServices(SVsServiceProvider serviceProvider)
{
var composition = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
return MefV1HostServices.Create(composition.DefaultExportProvider);
}
protected void InitializeStandardVisualStudioWorkspace(SVsServiceProvider serviceProvider, SaveEventsService saveEventsService)
{
var projectTracker = new VisualStudioProjectTracker(serviceProvider);
// Ensure the document tracking service is initialized on the UI thread
var documentTrackingService = this.Services.GetService<IDocumentTrackingService>();
var documentProvider = new RoslynDocumentProvider(projectTracker, serviceProvider, documentTrackingService);
var metadataReferenceProvider = this.Services.GetService<VisualStudioMetadataReferenceManager>();
var ruleSetFileProvider = this.Services.GetService<VisualStudioRuleSetManager>();
projectTracker.InitializeProviders(documentProvider, metadataReferenceProvider, ruleSetFileProvider);
this.SetProjectTracker(projectTracker);
var workspaceHost = new VisualStudioWorkspaceHost(this);
projectTracker.RegisterWorkspaceHost(workspaceHost);
projectTracker.StartSendingEventsToWorkspaceHost(workspaceHost);
saveEventsService.StartSendingSaveEvents();
// Ensure the options factory services are initialized on the UI thread
this.Services.GetService<IOptionService>();
}
/// <summary>NOTE: Call only from derived class constructor</summary>
protected void SetProjectTracker(VisualStudioProjectTracker projectTracker)
{
_projectTracker = projectTracker;
}
internal VisualStudioProjectTracker ProjectTracker
{
get
{
return _projectTracker;
}
}
internal void ClearReferenceCache()
{
_projectTracker.MetadataReferenceProvider.ClearCache();
}
internal IVisualStudioHostDocument GetHostDocument(DocumentId documentId)
{
var project = GetHostProject(documentId.ProjectId);
if (project != null)
{
return project.GetDocumentOrAdditionalDocument(documentId);
}
return null;
}
internal IVisualStudioHostProject GetHostProject(ProjectId projectId)
{
return this.ProjectTracker.GetProject(projectId);
}
private bool TryGetHostProject(ProjectId projectId, out IVisualStudioHostProject project)
{
project = GetHostProject(projectId);
return project != null;
}
internal override bool TryApplyChanges(
Microsoft.CodeAnalysis.Solution newSolution,
IProgressTracker progressTracker)
{
// first make sure we can edit the document we will be updating (check them out from source control, etc)
var changedDocs = newSolution.GetChanges(this.CurrentSolution).GetProjectChanges().SelectMany(pd => pd.GetChangedDocuments()).ToList();
if (changedDocs.Count > 0)
{
this.EnsureEditableDocuments(changedDocs);
}
return base.TryApplyChanges(newSolution, progressTracker);
}
public override bool CanOpenDocuments
{
get
{
return true;
}
}
internal override bool CanChangeActiveContextDocument
{
get
{
return true;
}
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
switch (feature)
{
case ApplyChangesKind.AddDocument:
case ApplyChangesKind.RemoveDocument:
case ApplyChangesKind.ChangeDocument:
case ApplyChangesKind.AddMetadataReference:
case ApplyChangesKind.RemoveMetadataReference:
case ApplyChangesKind.AddProjectReference:
case ApplyChangesKind.RemoveProjectReference:
case ApplyChangesKind.AddAnalyzerReference:
case ApplyChangesKind.RemoveAnalyzerReference:
case ApplyChangesKind.AddAdditionalDocument:
case ApplyChangesKind.RemoveAdditionalDocument:
case ApplyChangesKind.ChangeAdditionalDocument:
return true;
default:
return false;
}
}
private bool TryGetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project)
{
hierarchy = null;
project = null;
return this.TryGetHostProject(projectId, out hostProject)
&& this.TryGetHierarchy(projectId, out hierarchy)
&& hierarchy.TryGetProject(out project);
}
internal void GetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project)
{
if (!TryGetProjectData(projectId, out hostProject, out hierarchy, out project))
{
throw new ArgumentException(string.Format(ServicesVSResources.Could_not_find_project_0, projectId));
}
}
internal EnvDTE.Project TryGetDTEProject(ProjectId projectId)
{
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
return TryGetProjectData(projectId, out hostProject, out hierarchy, out project) ? project : null;
}
internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName)
{
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
try
{
GetProjectData(projectId, out hostProject, out hierarchy, out project);
}
catch (ArgumentException)
{
return false;
}
var vsProject = (VSProject)project.Object;
try
{
vsProject.References.Add(assemblyName);
}
catch (Exception)
{
return false;
}
return true;
}
private string GetAnalyzerPath(AnalyzerReference analyzerReference)
{
return analyzerReference.FullPath;
}
protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (analyzerReference == null)
{
throw new ArgumentNullException(nameof(analyzerReference));
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
string filePath = GetAnalyzerPath(analyzerReference);
if (filePath != null)
{
VSProject3 vsProject = (VSProject3)project.Object;
vsProject.AnalyzerReferences.Add(filePath);
}
}
protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (analyzerReference == null)
{
throw new ArgumentNullException(nameof(analyzerReference));
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
string filePath = GetAnalyzerPath(analyzerReference);
if (filePath != null)
{
VSProject3 vsProject = (VSProject3)project.Object;
vsProject.AnalyzerReferences.Remove(filePath);
}
}
private string GetMetadataPath(MetadataReference metadataReference)
{
var fileMetadata = metadataReference as PortableExecutableReference;
if (fileMetadata != null)
{
return fileMetadata.FilePath;
}
return null;
}
protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (metadataReference == null)
{
throw new ArgumentNullException(nameof(metadataReference));
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
string filePath = GetMetadataPath(metadataReference);
if (filePath != null)
{
VSProject vsProject = (VSProject)project.Object;
vsProject.References.Add(filePath);
}
}
protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (metadataReference == null)
{
throw new ArgumentNullException(nameof(metadataReference));
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
string filePath = GetMetadataPath(metadataReference);
if (filePath != null)
{
VSProject vsProject = (VSProject)project.Object;
Reference reference = vsProject.References.Find(filePath);
if (reference != null)
{
reference.Remove();
}
}
}
protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (projectReference == null)
{
throw new ArgumentNullException(nameof(projectReference));
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
IVisualStudioHostProject refHostProject;
IVsHierarchy refHierarchy;
EnvDTE.Project refProject;
GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject);
var vsProject = (VSProject)project.Object;
vsProject.References.AddProject(refProject);
}
protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (projectReference == null)
{
throw new ArgumentNullException(nameof(projectReference));
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
IVisualStudioHostProject refHostProject;
IVsHierarchy refHierarchy;
EnvDTE.Project refProject;
GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject);
var vsProject = (VSProject)project.Object;
foreach (Reference reference in vsProject.References)
{
if (reference.SourceProject == refProject)
{
reference.Remove();
}
}
}
protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text)
{
AddDocumentCore(info, text, isAdditionalDocument: false);
}
protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text)
{
AddDocumentCore(info, text, isAdditionalDocument: true);
}
private void AddDocumentCore(DocumentInfo info, SourceText initialText, bool isAdditionalDocument)
{
IVsHierarchy hierarchy;
EnvDTE.Project project;
IVisualStudioHostProject hostProject;
GetProjectData(info.Id.ProjectId, out hostProject, out hierarchy, out project);
// If the first namespace name matches the name of the project, then we don't want to
// generate a folder for that. The project is implicitly a folder with that name.
var folders = info.Folders.AsEnumerable();
if (folders.FirstOrDefault() == project.Name)
{
folders = folders.Skip(1);
}
folders = FilterFolderForProjectType(project, folders);
if (IsWebsite(project))
{
AddDocumentToFolder(hostProject, project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
}
else if (folders.Any())
{
AddDocumentToFolder(hostProject, project, info.Id, folders, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
}
else
{
AddDocumentToProject(hostProject, project, info.Id, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
}
}
private bool IsWebsite(EnvDTE.Project project)
{
return project.Kind == VsWebSite.PrjKind.prjKindVenusProject;
}
private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders)
{
foreach (var folder in folders)
{
var items = GetAllItems(project.ProjectItems);
var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0);
if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile)
{
yield return folder;
}
}
}
private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems)
{
if (projectItems == null)
{
return SpecializedCollections.EmptyEnumerable<ProjectItem>();
}
var items = projectItems.OfType<ProjectItem>();
return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems)));
}
#if false
protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders)
{
IVsHierarchy hierarchy;
EnvDTE.Project project;
IVisualStudioHostProject hostProject;
GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project);
// If the first namespace name matches the name of the project, then we don't want to
// generate a folder for that. The project is implicitly a folder with that name.
if (folders.FirstOrDefault() == project.Name)
{
folders = folders.Skip(1);
}
var name = Path.GetFileName(filePath);
if (folders.Any())
{
AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath);
}
else
{
AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath);
}
}
#endif
private ProjectItem AddDocumentToProject(
IVisualStudioHostProject hostProject,
EnvDTE.Project project,
DocumentId documentId,
string documentName,
SourceCodeKind sourceCodeKind,
SourceText initialText = null,
string filePath = null,
bool isAdditionalDocument = false)
{
string folderPath;
if (!project.TryGetFullPath(out folderPath))
{
// TODO(cyrusn): Throw an appropriate exception here.
throw new Exception(ServicesVSResources.Could_not_find_location_of_folder_on_disk);
}
return AddDocumentToProjectItems(hostProject, project.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument);
}
private ProjectItem AddDocumentToFolder(
IVisualStudioHostProject hostProject,
EnvDTE.Project project,
DocumentId documentId,
IEnumerable<string> folders,
string documentName,
SourceCodeKind sourceCodeKind,
SourceText initialText = null,
string filePath = null,
bool isAdditionalDocument = false)
{
var folder = project.FindOrCreateFolder(folders);
string folderPath;
if (!folder.TryGetFullPath(out folderPath))
{
// TODO(cyrusn): Throw an appropriate exception here.
throw new Exception(ServicesVSResources.Could_not_find_location_of_folder_on_disk);
}
return AddDocumentToProjectItems(hostProject, folder.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument);
}
private ProjectItem AddDocumentToProjectItems(
IVisualStudioHostProject hostProject,
ProjectItems projectItems,
DocumentId documentId,
string folderPath,
string documentName,
SourceCodeKind sourceCodeKind,
SourceText initialText,
string filePath,
bool isAdditionalDocument)
{
if (filePath == null)
{
var baseName = Path.GetFileNameWithoutExtension(documentName);
var extension = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind);
var uniqueName = projectItems.GetUniqueName(baseName, extension);
filePath = Path.Combine(folderPath, uniqueName);
}
if (initialText != null)
{
using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8))
{
initialText.Write(writer);
}
}
using (var documentIdHint = _projectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId))
{
return projectItems.AddFromFile(filePath);
}
}
protected void RemoveDocumentCore(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
var document = this.GetHostDocument(documentId);
if (document != null)
{
var project = document.Project.Hierarchy as IVsProject3;
var itemId = document.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// it is no longer part of the solution
return;
}
int result;
project.RemoveItem(0, itemId, out result);
}
}
protected override void ApplyDocumentRemoved(DocumentId documentId)
{
RemoveDocumentCore(documentId);
}
protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId)
{
RemoveDocumentCore(documentId);
}
public override void OpenDocument(DocumentId documentId, bool activate = true)
{
OpenDocumentCore(documentId, activate);
}
public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true)
{
OpenDocumentCore(documentId, activate);
}
public override void CloseDocument(DocumentId documentId)
{
CloseDocumentCore(documentId);
}
public override void CloseAdditionalDocument(DocumentId documentId)
{
CloseDocumentCore(documentId);
}
public bool TryGetInfoBarData(out IVsWindowFrame frame, out IVsInfoBarUIFactory factory)
{
frame = null;
factory = null;
var monitorSelectionService = ServiceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection;
object value = null;
// We want to get whichever window is currently in focus (including toolbars) as we could have had an exception thrown from the error list or interactive window
if (monitorSelectionService != null &&
ErrorHandler.Succeeded(monitorSelectionService.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_WindowFrame, out value)))
{
frame = value as IVsWindowFrame;
}
else
{
return false;
}
factory = ServiceProvider.GetService(typeof(SVsInfoBarUIFactory)) as IVsInfoBarUIFactory;
return frame != null && factory != null;
}
public void OpenDocumentCore(DocumentId documentId, bool activate = true)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (!_foregroundObject.IsForeground())
{
throw new InvalidOperationException(ServicesVSResources.This_workspace_only_supports_opening_documents_on_the_UI_thread);
}
var document = this.GetHostDocument(documentId);
if (document != null && document.Project != null)
{
IVsWindowFrame frame;
if (TryGetFrame(document, out frame))
{
if (activate)
{
frame.Show();
}
else
{
frame.ShowNoActivate();
}
}
}
}
private bool TryGetFrame(IVisualStudioHostDocument document, out IVsWindowFrame frame)
{
frame = null;
var itemId = document.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// If the ItemId is Nil, then IVsProject would not be able to open the
// document using its ItemId. Thus, we must use OpenDocumentViaProject, which only
// depends on the file path.
uint itemid;
IVsUIHierarchy uiHierarchy;
OLEServiceProvider oleServiceProvider;
return ErrorHandler.Succeeded(_shellOpenDocument.OpenDocumentViaProject(
document.FilePath,
VSConstants.LOGVIEWID.TextView_guid,
out oleServiceProvider,
out uiHierarchy,
out itemid,
out frame));
}
else
{
// If the ItemId is not Nil, then we should not call IVsUIShellDocument
// .OpenDocumentViaProject here because that simply takes a file path and opens the
// file within the context of the first project it finds. That would cause problems
// if the document we're trying to open is actually a linked file in another
// project. So, we get the project's hierarchy and open the document using its item
// ID.
// It's conceivable that IVsHierarchy might not implement IVsProject. However,
// OpenDocumentViaProject itself relies upon this QI working, so it should be OK to
// use here.
var vsProject = document.Project.Hierarchy as IVsProject;
return vsProject != null &&
ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame));
}
}
public void CloseDocumentCore(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (this.IsDocumentOpen(documentId))
{
var document = this.GetHostDocument(documentId);
if (document != null)
{
IVsUIHierarchy uiHierarchy;
IVsWindowFrame frame;
int isOpen;
if (ErrorHandler.Succeeded(_shellOpenDocument.IsDocumentOpen(null, 0, document.FilePath, Guid.Empty, 0, out uiHierarchy, null, out frame, out isOpen)))
{
// TODO: do we need save argument for CloseDocument?
frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
}
}
}
}
protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
{
EnsureEditableDocuments(documentId);
var hostDocument = GetHostDocument(documentId);
hostDocument.UpdateText(newText);
}
protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText)
{
EnsureEditableDocuments(documentId);
var hostDocument = GetHostDocument(documentId);
hostDocument.UpdateText(newText);
}
private static string GetPreferredExtension(IVisualStudioHostProject hostProject, SourceCodeKind sourceCodeKind)
{
// No extension was provided. Pick a good one based on the type of host project.
switch (hostProject.Language)
{
case LanguageNames.CSharp:
// TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325
//return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx";
return ".cs";
case LanguageNames.VisualBasic:
// TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325
//return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx";
return ".vb";
default:
throw new InvalidOperationException();
}
}
public override IVsHierarchy GetHierarchy(ProjectId projectId)
{
var project = this.GetHostProject(projectId);
if (project == null)
{
return null;
}
return project.Hierarchy;
}
internal override void SetDocumentContext(DocumentId documentId)
{
var hostDocument = GetHostDocument(documentId);
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// the document has been removed from the solution
return;
}
var hierarchy = hostDocument.Project.Hierarchy;
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId);
if (sharedHierarchy != null)
{
if (sharedHierarchy.SetProperty(
(uint)VSConstants.VSITEMID.Root,
(int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext,
ProjectTracker.GetProject(documentId.ProjectId).ProjectSystemName) == VSConstants.S_OK)
{
// The ASP.NET 5 intellisense project is now updated.
return;
}
else
{
// Universal Project shared files
// Change the SharedItemContextHierarchy of the project's parent hierarchy, then
// hierarchy events will trigger the workspace to update.
var hr = sharedHierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy, hierarchy);
}
}
else
{
// Regular linked files
// Transfer the item (open buffer) to the new hierarchy, and then hierarchy events
// will trigger the workspace to update.
var vsproj = hierarchy as IVsProject3;
var hr = vsproj.TransferItem(hostDocument.FilePath, hostDocument.FilePath, punkWindowFrame: null);
}
}
internal void UpdateDocumentContextIfContainsDocument(IVsHierarchy sharedHierarchy, DocumentId documentId)
{
// TODO: This is a very roundabout way to update the context
// The sharedHierarchy passed in has a new context, but we don't know what it is.
// The documentId passed in is associated with this sharedHierarchy, and this method
// will be called once for each such documentId. During this process, one of these
// documentIds will actually belong to the new SharedItemContextHierarchy. Once we
// find that one, we can map back to the open buffer and set its active context to
// the appropriate project.
// Note that if there is a single head project and it's in the process of being unloaded
// there might not be a host project.
var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker);
if (hostProject?.Hierarchy == sharedHierarchy)
{
return;
}
if (hostProject.Id != documentId.ProjectId)
{
// While this documentId is associated with one of the head projects for this
// sharedHierarchy, it is not associated with the new context hierarchy. Another
// documentId will be passed to this method and update the context.
return;
}
// This documentId belongs to the new SharedItemContextHierarchy. Update the associated
// buffer.
OnDocumentContextUpdated(documentId);
}
/// <summary>
/// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that
/// is in the current context. For regular files (non-shared and non-linked) and closed
/// linked files, this is always the provided <see cref="DocumentId"/>. For open linked
/// files and open shared files, the active context is already tracked by the
/// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the
/// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/>
/// is preferred.
/// </summary>
internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId)
{
// If the document is open, then the Workspace knows the current context for both
// linked and shared files
if (IsDocumentOpen(documentId))
{
return base.GetDocumentIdInCurrentContext(documentId);
}
var hostDocument = GetHostDocument(documentId);
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// An itemid is required to determine whether the file belongs to a Shared Project
return base.GetDocumentIdInCurrentContext(documentId);
}
// If this is a regular document or a closed linked (non-shared) document, then use the
// default logic for determining current context.
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId);
if (sharedHierarchy == null)
{
return base.GetDocumentIdInCurrentContext(documentId);
}
// This is a closed shared document, so we must determine the correct context.
var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker);
var matchingProject = CurrentSolution.GetProject(hostProject.Id);
if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy)
{
return base.GetDocumentIdInCurrentContext(documentId);
}
if (matchingProject.ContainsDocument(documentId))
{
// The provided documentId is in the current context project
return documentId;
}
// The current context document is from another project.
var linkedDocumentIds = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds();
var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id);
return matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId);
}
internal bool TryGetHierarchy(ProjectId projectId, out IVsHierarchy hierarchy)
{
hierarchy = this.GetHierarchy(projectId);
return hierarchy != null;
}
public override string GetFilePath(DocumentId documentId)
{
var document = this.GetHostDocument(documentId);
if (document == null)
{
return null;
}
else
{
return document.FilePath;
}
}
internal void StartSolutionCrawler()
{
if (_registrationService == null)
{
lock (this)
{
if (_registrationService == null)
{
_registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>();
_registrationService.Register(this);
}
}
}
}
internal void StopSolutionCrawler()
{
if (_registrationService != null)
{
lock (this)
{
if (_registrationService != null)
{
_registrationService.Unregister(this, blockingShutdown: true);
_registrationService = null;
}
}
}
}
protected override void Dispose(bool finalize)
{
// workspace is going away. unregister this workspace from work coordinator
StopSolutionCrawler();
base.Dispose(finalize);
}
public void EnsureEditableDocuments(IEnumerable<DocumentId> documents)
{
var queryEdit = (IVsQueryEditQuerySave2)ServiceProvider.GetService(typeof(SVsQueryEditQuerySave));
var fileNames = documents.Select(GetFilePath).ToArray();
uint editVerdict;
uint editResultFlags;
// TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn
int result = queryEdit.QueryEditFiles(
rgfQueryEdit: 0,
cFiles: fileNames.Length,
rgpszMkDocuments: fileNames,
rgrgf: new uint[fileNames.Length],
rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length],
pfEditVerdict: out editVerdict,
prgfMoreInfo: out editResultFlags);
if (ErrorHandler.Failed(result) ||
editVerdict != (uint)tagVSQueryEditResult.QER_EditOK)
{
throw new Exception("Unable to check out the files from source control.");
}
if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0)
{
throw new Exception("A file was reloaded during the source control checkout.");
}
}
public void EnsureEditableDocuments(params DocumentId[] documents)
{
this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents);
}
internal void OnDocumentTextUpdatedOnDisk(DocumentId documentId)
{
var vsDoc = this.GetHostDocument(documentId);
this.OnDocumentTextLoaderChanged(documentId, vsDoc.Loader);
}
internal void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId documentId)
{
var vsDoc = this.GetHostDocument(documentId);
this.OnAdditionalDocumentTextLoaderChanged(documentId, vsDoc.Loader);
}
public TInterface GetVsService<TService, TInterface>()
where TService : class
where TInterface : class
{
return this.ServiceProvider.GetService(typeof(TService)) as TInterface;
}
public object GetVsService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
public DTE GetVsDte()
{
return GetVsService<SDTE, DTE>();
}
internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject)
{
_foregroundObject.AssertIsForeground();
IVsHierarchy referencingHierarchy;
IVsHierarchy referencedHierarchy;
if (!TryGetHierarchy(referencingProject, out referencingHierarchy) ||
!TryGetHierarchy(referencedProject, out referencedHierarchy))
{
// Couldn't even get a hierarchy for this project. So we have to assume
// that adding a reference is disallowed.
return false;
}
// First we have to see if either project disallows the reference being added.
const int ContextFlags = (int)__VSQUERYFLAVORREFERENCESCONTEXT.VSQUERYFLAVORREFERENCESCONTEXT_RefreshReference;
uint canAddProjectReference = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN;
uint canBeReferenced = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN;
var referencingProjectFlavor3 = referencingHierarchy as IVsProjectFlavorReferences3;
if (referencingProjectFlavor3 != null)
{
string unused;
if (ErrorHandler.Failed(referencingProjectFlavor3.QueryAddProjectReferenceEx(referencedHierarchy, ContextFlags, out canAddProjectReference, out unused)))
{
// Something went wrong even trying to see if the reference would be allowed.
// Assume it won't be allowed.
return false;
}
if (canAddProjectReference == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY)
{
// Adding this project reference is not allowed.
return false;
}
}
var referencedProjectFlavor3 = referencedHierarchy as IVsProjectFlavorReferences3;
if (referencedProjectFlavor3 != null)
{
string unused;
if (ErrorHandler.Failed(referencedProjectFlavor3.QueryCanBeReferencedEx(referencingHierarchy, ContextFlags, out canBeReferenced, out unused)))
{
// Something went wrong even trying to see if the reference would be allowed.
// Assume it won't be allowed.
return false;
}
if (canBeReferenced == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY)
{
// Adding this project reference is not allowed.
return false;
}
}
// Neither project denied the reference being added. At this point, if either project
// allows the reference to be added, and the other doesn't block it, then we can add
// the reference.
if (canAddProjectReference == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW ||
canBeReferenced == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW)
{
return true;
}
// In both directions things are still unknown. Fallback to the reference manager
// to make the determination here.
var referenceManager = GetVsService<SVsReferenceManager, IVsReferenceManager>();
if (referenceManager == null)
{
// Couldn't get the reference manager. Have to assume it's not allowed.
return false;
}
// As long as the reference manager does not deny things, then we allow the
// reference to be added.
var result = referenceManager.QueryCanReferenceProject(referencingHierarchy, referencedHierarchy);
return result != (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY;
}
/// <summary>
/// A trivial implementation of <see cref="IVisualStudioWorkspaceHost" /> that just
/// forwards the calls down to the underlying Workspace.
/// </summary>
protected sealed class VisualStudioWorkspaceHost : IVisualStudioWorkspaceHost, IVisualStudioWorkspaceHost2, IVisualStudioWorkingFolder
{
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly Dictionary<DocumentId, uint> _documentIdToHierarchyEventsCookieMap = new Dictionary<DocumentId, uint>();
public VisualStudioWorkspaceHost(VisualStudioWorkspaceImpl workspace)
{
_workspace = workspace;
}
void IVisualStudioWorkspaceHost.OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions)
{
_workspace.OnCompilationOptionsChanged(projectId, compilationOptions);
_workspace.OnParseOptionsChanged(projectId, parseOptions);
}
void IVisualStudioWorkspaceHost.OnDocumentAdded(DocumentInfo documentInfo)
{
_workspace.OnDocumentAdded(documentInfo);
}
void IVisualStudioWorkspaceHost.OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext)
{
// TODO: Move this out to DocumentProvider. As is, this depends on being able to
// access the host document which will already be deleted in some cases, causing
// a crash. Until this is fixed, we will leak a HierarchyEventsSink every time a
// Mercury shared document is closed.
// UnsubscribeFromSharedHierarchyEvents(documentId);
using (_workspace.Services.GetService<IGlobalOperationNotificationService>().Start("Document Closed"))
{
_workspace.OnDocumentClosed(documentId, loader, updateActiveContext);
}
}
void IVisualStudioWorkspaceHost.OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool currentContext)
{
SubscribeToSharedHierarchyEvents(documentId);
_workspace.OnDocumentOpened(documentId, textBuffer.AsTextContainer(), currentContext);
}
private void SubscribeToSharedHierarchyEvents(DocumentId documentId)
{
// Todo: maybe avoid double alerts.
var hostDocument = _workspace.GetHostDocument(documentId);
if (hostDocument == null)
{
return;
}
var hierarchy = hostDocument.Project.Hierarchy;
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// the document has been removed from the solution
return;
}
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId);
if (sharedHierarchy != null)
{
uint cookie;
var eventSink = new HierarchyEventsSink(_workspace, sharedHierarchy, documentId);
var hr = sharedHierarchy.AdviseHierarchyEvents(eventSink, out cookie);
if (hr == VSConstants.S_OK && !_documentIdToHierarchyEventsCookieMap.ContainsKey(documentId))
{
_documentIdToHierarchyEventsCookieMap.Add(documentId, cookie);
}
}
}
private void UnsubscribeFromSharedHierarchyEvents(DocumentId documentId)
{
var hostDocument = _workspace.GetHostDocument(documentId);
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// the document has been removed from the solution
return;
}
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId);
if (sharedHierarchy != null)
{
uint cookie;
if (_documentIdToHierarchyEventsCookieMap.TryGetValue(documentId, out cookie))
{
var hr = sharedHierarchy.UnadviseHierarchyEvents(cookie);
_documentIdToHierarchyEventsCookieMap.Remove(documentId);
}
}
}
private void RegisterPrimarySolutionForPersistentStorage(SolutionId solutionId)
{
var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService;
if (service == null)
{
return;
}
service.RegisterPrimarySolution(solutionId);
}
private void UnregisterPrimarySolutionForPersistentStorage(SolutionId solutionId, bool synchronousShutdown)
{
var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService;
if (service == null)
{
return;
}
service.UnregisterPrimarySolution(solutionId, synchronousShutdown);
}
void IVisualStudioWorkspaceHost.OnDocumentRemoved(DocumentId documentId)
{
_workspace.OnDocumentRemoved(documentId);
}
void IVisualStudioWorkspaceHost.OnMetadataReferenceAdded(ProjectId projectId, PortableExecutableReference metadataReference)
{
_workspace.OnMetadataReferenceAdded(projectId, metadataReference);
}
void IVisualStudioWorkspaceHost.OnMetadataReferenceRemoved(ProjectId projectId, PortableExecutableReference metadataReference)
{
_workspace.OnMetadataReferenceRemoved(projectId, metadataReference);
}
void IVisualStudioWorkspaceHost.OnProjectAdded(ProjectInfo projectInfo)
{
using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Add Project"))
{
_workspace.OnProjectAdded(projectInfo);
}
}
void IVisualStudioWorkspaceHost.OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
{
_workspace.OnProjectReferenceAdded(projectId, projectReference);
}
void IVisualStudioWorkspaceHost.OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
{
_workspace.OnProjectReferenceRemoved(projectId, projectReference);
}
void IVisualStudioWorkspaceHost.OnProjectRemoved(ProjectId projectId)
{
using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Remove Project"))
{
_workspace.OnProjectRemoved(projectId);
}
}
void IVisualStudioWorkspaceHost.OnSolutionAdded(SolutionInfo solutionInfo)
{
RegisterPrimarySolutionForPersistentStorage(solutionInfo.Id);
_workspace.OnSolutionAdded(solutionInfo);
}
void IVisualStudioWorkspaceHost.OnSolutionRemoved()
{
var solutionId = _workspace.CurrentSolution.Id;
_workspace.OnSolutionRemoved();
_workspace.ClearReferenceCache();
UnregisterPrimarySolutionForPersistentStorage(solutionId, synchronousShutdown: false);
}
void IVisualStudioWorkspaceHost.ClearSolution()
{
_workspace.ClearSolution();
_workspace.ClearReferenceCache();
}
void IVisualStudioWorkspaceHost.OnDocumentTextUpdatedOnDisk(DocumentId id)
{
_workspace.OnDocumentTextUpdatedOnDisk(id);
}
void IVisualStudioWorkspaceHost.OnAssemblyNameChanged(ProjectId id, string assemblyName)
{
_workspace.OnAssemblyNameChanged(id, assemblyName);
}
void IVisualStudioWorkspaceHost.OnOutputFilePathChanged(ProjectId id, string outputFilePath)
{
_workspace.OnOutputFilePathChanged(id, outputFilePath);
}
void IVisualStudioWorkspaceHost.OnProjectNameChanged(ProjectId projectId, string name, string filePath)
{
_workspace.OnProjectNameChanged(projectId, name, filePath);
}
void IVisualStudioWorkspaceHost.OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference)
{
_workspace.OnAnalyzerReferenceAdded(projectId, analyzerReference);
}
void IVisualStudioWorkspaceHost.OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference)
{
_workspace.OnAnalyzerReferenceRemoved(projectId, analyzerReference);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentAdded(DocumentInfo documentInfo)
{
_workspace.OnAdditionalDocumentAdded(documentInfo);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentRemoved(DocumentId documentInfo)
{
_workspace.OnAdditionalDocumentRemoved(documentInfo);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext)
{
_workspace.OnAdditionalDocumentOpened(documentId, textBuffer.AsTextContainer(), isCurrentContext);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader)
{
_workspace.OnAdditionalDocumentClosed(documentId, loader);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id)
{
_workspace.OnAdditionalDocumentTextUpdatedOnDisk(id);
}
void IVisualStudioWorkspaceHost2.OnHasAllInformation(ProjectId projectId, bool hasAllInformation)
{
_workspace.OnHasAllInformationChanged(projectId, hasAllInformation);
}
void IVisualStudioWorkingFolder.OnBeforeWorkingFolderChange()
{
UnregisterPrimarySolutionForPersistentStorage(_workspace.CurrentSolution.Id, synchronousShutdown: true);
}
void IVisualStudioWorkingFolder.OnAfterWorkingFolderChange()
{
var solutionId = _workspace.CurrentSolution.Id;
_workspace.ProjectTracker.UpdateSolutionProperties(solutionId);
RegisterPrimarySolutionForPersistentStorage(solutionId);
}
}
}
}
| |
// 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;
public class ComparableRefType : IComparable, IEquatable<ComparableRefType>
{
public int Id;
public ComparableRefType(int id)
{
this.Id = id;
}
public int CompareTo(object other)
{
ComparableRefType o = (ComparableRefType)other;
if (o.Id == this.Id)
{
return 0;
}
else if (this.Id > o.Id)
{
return 1;
}
else
{
return -1;
}
}
public override string ToString()
{
return "C:" + Id;
}
public override bool Equals(object obj)
{
return obj is ComparableRefType && ((ComparableRefType)obj).Id == this.Id;
}
public bool Equals(ComparableRefType other)
{
return other.Id == this.Id;
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
}
public class ComparableValueType : IComparable, IEquatable<ComparableValueType>
{
public int Id;
public ComparableValueType(int id)
{
this.Id = id;
}
public int CompareTo(object other)
{
ComparableValueType o = (ComparableValueType)other;
if (o.Id == this.Id)
{
return 0;
}
else if (this.Id > o.Id)
{
return 1;
}
else
{
return -1;
}
}
public override string ToString()
{
return "S:" + Id;
}
public override bool Equals(object obj)
{
return obj is ComparableValueType && ((ComparableValueType)obj).Equals(this);
}
public bool Equals(ComparableValueType other)
{
return other.Id == this.Id;
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
}
public class RefTypeReverseComparer : IComparer
{
public int Compare(ComparableRefType x, ComparableRefType y)
{
return -1 * x.CompareTo(y);
}
public int Compare(object x, object y)
{
return Compare((ComparableRefType)x, (ComparableRefType)y);
}
}
public class RefTypeNormalComparer : IComparer
{
public int Compare(ComparableRefType x, ComparableRefType y)
{
return x.CompareTo(y);
}
public int Compare(object x, object y)
{
return Compare((ComparableRefType)x, (ComparableRefType)y);
}
}
public static class TestObjects
{
public static readonly ComparableRefType[] customRefTypeArray = new ComparableRefType[]
{
new ComparableRefType(-5),
new ComparableRefType(-4),
new ComparableRefType(-6),
new ComparableRefType(-8),
new ComparableRefType(-10),
new ComparableRefType(2),
new ComparableRefType(1),
new ComparableRefType(5),
new ComparableRefType(-11),
new ComparableRefType(-10),
};
public static readonly ComparableRefType[] sortedRefTypeArray = new ComparableRefType[]
{
new ComparableRefType(-11),
new ComparableRefType(-10),
new ComparableRefType(-10),
new ComparableRefType(-8),
new ComparableRefType(-6),
new ComparableRefType(-5),
new ComparableRefType(-4),
new ComparableRefType(1),
new ComparableRefType(2),
new ComparableRefType(5),
};
public static readonly ComparableValueType[] customValueTypeArray = new ComparableValueType[]
{
new ComparableValueType(-5),
new ComparableValueType(-4),
new ComparableValueType(-6),
new ComparableValueType(-8),
new ComparableValueType(-10),
new ComparableValueType(2),
new ComparableValueType(1),
new ComparableValueType(5),
new ComparableValueType(-11),
new ComparableValueType(-10),
};
public static readonly ComparableValueType[] sortedValueTypeArray = new ComparableValueType[]
{
new ComparableValueType(-11),
new ComparableValueType(-10),
new ComparableValueType(-10),
new ComparableValueType(-8),
new ComparableValueType(-6),
new ComparableValueType(-5),
new ComparableValueType(-4),
new ComparableValueType(1),
new ComparableValueType(2),
new ComparableValueType(5),
};
public static readonly Array integerArray = new int[] { 5, 4, 3, 2, -1, -3, 7, 6, 10, 9, 20, 15 };
public static Array stringArray = new string[] { "cat", "dog", "bird", "cookie", "cat-spider", "cat-bird", "alligator", "fox", "rabbit", "ferret", "frog", "squirrel" };
public static readonly Array sortedIntegerArray = new int[] { -3, -1, 2, 3, 4, 5, 6, 7, 9, 10, 15, 20 };
// Sort order for these strings assumes that the integer array was used as the sorting key with the above string array as the extra param.
public static readonly Array sortedStringArray = new string[] { "cat-bird", "cat-spider", "cookie", "bird", "dog", "cat", "fox", "alligator", "ferret", "rabbit", "squirrel", "frog" };
/// <summary>
/// Returns an array of random integers, between Int32.MinValue and Int32.MaxValue.
/// </summary>
/// <param name="random">The random number generator.</param>
/// <param name="length">The length of the array.</param>
/// <returns>The array.</returns>
public static Array GetRandomIntegerArray(Random random, int length)
{
Array array = new int[length];
for (int g = 0; g < length; g++)
{
array.SetValue(random.Next(int.MinValue, int.MaxValue), g);
}
return array;
}
/// <summary>
/// Returns an array of strings with length 4-8 and random lower-case chars filling it.
/// </summary>
/// <param name="random">The random number generator.</param>
/// <param name="length">The length of the array.</param>
/// <returns>The array.</returns>
public static Array GetRandomStringArray(Random random, int length)
{
Array array = new string[length];
for (int g = 0; g < length; g++)
{
string value = "";
for (int i = 0; i < random.Next(4, 8); i++)
{
value += (char)('a' + random.Next(0, 26));
}
array.SetValue(value, g);
}
return array;
}
}
public class RegularIntComparer : IComparer
{
public int Compare(object x, object y)
{
return ((int)x).CompareTo((int)y);
}
}
public class ReverseIntComparer : IComparer
{
public int Compare(object x, object y)
{
return -((int)x).CompareTo((int)y);
}
}
public class RegularStringComparer : IComparer
{
public int Compare(object x, object y)
{
return ((string)x).CompareTo((string)y);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyDateTime
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// Datetime operations.
/// </summary>
public partial interface IDatetime
{
/// <summary>
/// Get null datetime value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get invalid datetime value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get overflow datetime value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetOverflowWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get underflow datetime value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetUnderflowWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put max datetime value 9999-12-31T23:59:59.9999999Z
/// </summary>
/// <param name='datetimeBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutUtcMaxDateTimeWithHttpMessagesAsync(DateTime? datetimeBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get max datetime value 9999-12-31t23:59:59.9999999z
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetUtcLowercaseMaxDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get max datetime value 9999-12-31T23:59:59.9999999Z
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetUtcUppercaseMaxDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put max datetime value with positive numoffset
/// 9999-12-31t23:59:59.9999999+14:00
/// </summary>
/// <param name='datetimeBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutLocalPositiveOffsetMaxDateTimeWithHttpMessagesAsync(DateTime? datetimeBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31t23:59:59.9999999+14:00
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetLocalPositiveOffsetLowercaseMaxDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31T23:59:59.9999999+14:00
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetLocalPositiveOffsetUppercaseMaxDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put max datetime value with positive numoffset
/// 9999-12-31t23:59:59.9999999-14:00
/// </summary>
/// <param name='datetimeBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutLocalNegativeOffsetMaxDateTimeWithHttpMessagesAsync(DateTime? datetimeBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31T23:59:59.9999999-14:00
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetLocalNegativeOffsetUppercaseMaxDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31t23:59:59.9999999-14:00
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetLocalNegativeOffsetLowercaseMaxDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00Z
/// </summary>
/// <param name='datetimeBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutUtcMinDateTimeWithHttpMessagesAsync(DateTime? datetimeBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00Z
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetUtcMinDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00+14:00
/// </summary>
/// <param name='datetimeBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutLocalPositiveOffsetMinDateTimeWithHttpMessagesAsync(DateTime? datetimeBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00+14:00
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetLocalPositiveOffsetMinDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00-14:00
/// </summary>
/// <param name='datetimeBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutLocalNegativeOffsetMinDateTimeWithHttpMessagesAsync(DateTime? datetimeBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00-14:00
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<DateTime?>> GetLocalNegativeOffsetMinDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
/// <summary>
/// CopyTo(T[],System.Int32)
/// </summary>
public class QueueCopyTo
{
public static int Main()
{
QueueCopyTo test = new QueueCopyTo();
TestLibrary.TestFramework.BeginTestCase("QueueCopyTo");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Test whether CopyTo(T[],System.Int32) is successful when System.Int32 is zero.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = { "first", "second", "third", "fourth" };
TestQueue.CopyTo(TestArray, 0);
if (TestArray[0] != "one" || TestArray[1] != "two" || TestArray[2] != "third"
|| TestArray[3] != "fourth" || TestArray.GetLength(0) != 4)
{
TestLibrary.TestFramework.LogError("P01.1", "CopyTo(T[],System.Int32) failed when System.Int32 is zero!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Test whether CopyTo(T[],System.Int32) is successful when System.Int32 is greater than zero.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = { "first", "second", "", "" };
TestQueue.CopyTo(TestArray, 1);
if (TestArray.GetLength(0) != 4 || TestArray[0] != "first" || TestArray[1] != "one" || TestArray[2] != "two")
{
TestLibrary.TestFramework.LogError("P02.1", "CopyTo(T[],System.Int32) failed when System.Int32 is greater than zero!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P02.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException should be thrown when array is a null reference.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = null;
TestQueue.CopyTo(TestArray, 0);
TestLibrary.TestFramework.LogError("N01.1", "ArgumentNullException is not thrown when array is a null reference!");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N01.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException should be thrown when index is less than zero.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = { "first", "second", "", "" };
TestQueue.CopyTo(TestArray, -1);
TestLibrary.TestFramework.LogError("N02.1", "ArgumentOutOfRangeException is not thrown when index is less than zero!");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N02.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentException should be thrown when index is equal to the length of array.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = { "first", "second", "", "" };
TestQueue.CopyTo(TestArray, 4);
TestLibrary.TestFramework.LogError("N03.1", "ArgumentException is not thrown when index is equal to the length of array!");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N03.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentException should be thrown when index is greater than the length of array.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = { "first", "second", "", "" };
TestQueue.CopyTo(TestArray, 10);
TestLibrary.TestFramework.LogError("N04.1", "ArgumentException is not thrown when index is greater than the length of array!");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N04.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: ArgumentException should be thrown when the number of elements in the source Queue is greater than the available space from index to the end of the destination array.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = { "first", "second", "", "" };
TestQueue.CopyTo(TestArray, 3);
TestLibrary.TestFramework.LogError("N05.1", "ArgumentException is not thrown when the number of elements in the source Queue is greater than the available space from index to the end of the destination array!");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N05.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace JWPush.Server.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);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
**
** Purpose: Generic hash table implementation
**
** #DictionaryVersusHashtableThreadSafety
** Hashtable has multiple reader/single writer (MR/SW) thread safety built into
** certain methods and properties, whereas Dictionary doesn't. If you're
** converting framework code that formerly used Hashtable to Dictionary, it's
** important to consider whether callers may have taken a dependence on MR/SW
** thread safety. If a reader writer lock is available, then that may be used
** with a Dictionary to get the same thread safety guarantee.
**
** Reader writer locks don't exist in silverlight, so we do the following as a
** result of removing non-generic collections from silverlight:
** 1. If the Hashtable was fully synchronized, then we replace it with a
** Dictionary with full locks around reads/writes (same thread safety
** guarantee).
** 2. Otherwise, the Hashtable has the default MR/SW thread safety behavior,
** so we do one of the following on a case-by-case basis:
** a. If the race condition can be addressed by rearranging the code and using a temp
** variable (for example, it's only populated immediately after created)
** then we address the race condition this way and use Dictionary.
** b. If there's concern about degrading performance with the increased
** locking, we ifdef with FEATURE_NONGENERIC_COLLECTIONS so we can at
** least use Hashtable in the desktop build, but Dictionary with full
** locks in silverlight builds. Note that this is heavier locking than
** MR/SW, but this is the only option without rewriting (or adding back)
** the reader writer lock.
** c. If there's no performance concern (e.g. debug-only code) we
** consistently replace Hashtable with Dictionary plus full locks to
** reduce complexity.
** d. Most of serialization is dead code in silverlight. Instead of updating
** those Hashtable occurences in serialization, we carved out references
** to serialization such that this code doesn't need to build in
** silverlight.
===========================================================*/
namespace System.Collections.Generic {
using System;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Security.Permissions;
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.InteropServices.ComVisible(false)]
public class Dictionary<TKey,TValue>: IDictionary<TKey,TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback {
private struct Entry {
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
private int[] buckets;
private Entry[] entries;
private int count;
private int version;
private int freeList;
private int freeCount;
private IEqualityComparer<TKey> comparer;
private KeyCollection keys;
private ValueCollection values;
private Object _syncRoot;
// constants for serialization
private const String VersionName = "Version";
private const String HashSizeName = "HashSize"; // Must save buckets.Length
private const String KeyValuePairsName = "KeyValuePairs";
private const String ComparerName = "Comparer";
public Dictionary(): this(0, null) {}
public Dictionary(int capacity): this(capacity, null) {}
public Dictionary(IEqualityComparer<TKey> comparer): this(0, comparer) {}
public Dictionary(int capacity, IEqualityComparer<TKey> comparer) {
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
if (capacity > 0) Initialize(capacity);
this.comparer = comparer ?? EqualityComparer<TKey>.Default;
#if FEATURE_RANDOMIZED_STRING_HASHING && FEATURE_CORECLR
if (HashHelpers.s_UseRandomizedStringHashing && comparer == EqualityComparer<string>.Default)
{
this.comparer = (IEqualityComparer<TKey>) NonRandomizedStringEqualityComparer.Default;
}
#endif // FEATURE_RANDOMIZED_STRING_HASHING && FEATURE_CORECLR
}
public Dictionary(IDictionary<TKey,TValue> dictionary): this(dictionary, null) {}
public Dictionary(IDictionary<TKey,TValue> dictionary, IEqualityComparer<TKey> comparer):
this(dictionary != null? dictionary.Count: 0, comparer) {
if( dictionary == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
foreach (KeyValuePair<TKey,TValue> pair in dictionary) {
Add(pair.Key, pair.Value);
}
}
protected Dictionary(SerializationInfo info, StreamingContext context) {
//We can't do anything with the keys and values until the entire graph has been deserialized
//and we have a resonable estimate that GetHashCode is not going to fail. For the time being,
//we'll just cache this. The graph is not valid until OnDeserialization has been called.
HashHelpers.SerializationInfoTable.Add(this, info);
}
public IEqualityComparer<TKey> Comparer {
get {
return comparer;
}
}
public int Count {
get { return count - freeCount; }
}
public KeyCollection Keys {
get {
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys {
get {
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys {
get {
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
public ValueCollection Values {
get {
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (values == null) values = new ValueCollection(this);
return values;
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values {
get {
if (values == null) values = new ValueCollection(this);
return values;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values {
get {
if (values == null) values = new ValueCollection(this);
return values;
}
}
public TValue this[TKey key] {
get {
int i = FindEntry(key);
if (i >= 0) return entries[i].value;
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
set {
Insert(key, value, false);
}
}
public void Add(TKey key, TValue value) {
Insert(key, value, true);
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) {
Add(keyValuePair.Key, keyValuePair.Value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) {
int i = FindEntry(keyValuePair.Key);
if( i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) {
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) {
int i = FindEntry(keyValuePair.Key);
if( i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) {
Remove(keyValuePair.Key);
return true;
}
return false;
}
public void Clear() {
if (count > 0) {
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
Array.Clear(entries, 0, count);
freeList = -1;
count = 0;
freeCount = 0;
version++;
}
}
public bool ContainsKey(TKey key) {
return FindEntry(key) >= 0;
}
public bool ContainsValue(TValue value) {
if (value == null) {
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0 && entries[i].value == null) return true;
}
}
else {
EqualityComparer<TValue> c = EqualityComparer<TValue>.Default;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0 && c.Equals(entries[i].value, value)) return true;
}
}
return false;
}
private void CopyTo(KeyValuePair<TKey,TValue>[] array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length ) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = this.count;
Entry[] entries = this.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) {
array[index++] = new KeyValuePair<TKey,TValue>(entries[i].key, entries[i].value);
}
}
}
public Enumerator GetEnumerator() {
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() {
return new Enumerator(this, Enumerator.KeyValuePair);
}
[System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
}
info.AddValue(VersionName, version);
#if FEATURE_RANDOMIZED_STRING_HASHING
info.AddValue(ComparerName, HashHelpers.GetEqualityComparerForSerialization(comparer), typeof(IEqualityComparer<TKey>));
#else
info.AddValue(ComparerName, comparer, typeof(IEqualityComparer<TKey>));
#endif
info.AddValue(HashSizeName, buckets == null ? 0 : buckets.Length); //This is the length of the bucket array.
if( buckets != null) {
KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[Count];
CopyTo(array, 0);
info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[]));
}
}
private int FindEntry(TKey key) {
if( key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null) {
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
}
}
return -1;
}
private void Initialize(int capacity) {
int size = HashHelpers.GetPrime(capacity);
buckets = new int[size];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
entries = new Entry[size];
freeList = -1;
}
private void Insert(TKey key, TValue value, bool add) {
if( key == null ) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets == null) Initialize(0);
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int targetBucket = hashCode % buckets.Length;
#if FEATURE_RANDOMIZED_STRING_HASHING
int collisionCount = 0;
#endif
for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
if (add) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
entries[i].value = value;
version++;
return;
}
#if FEATURE_RANDOMIZED_STRING_HASHING
collisionCount++;
#endif
}
int index;
if (freeCount > 0) {
index = freeList;
freeList = entries[index].next;
freeCount--;
}
else {
if (count == entries.Length)
{
Resize();
targetBucket = hashCode % buckets.Length;
}
index = count;
count++;
}
entries[index].hashCode = hashCode;
entries[index].next = buckets[targetBucket];
entries[index].key = key;
entries[index].value = value;
buckets[targetBucket] = index;
version++;
#if FEATURE_RANDOMIZED_STRING_HASHING
#if FEATURE_CORECLR
// In case we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
// in this case will be EqualityComparer<string>.Default.
// Note, randomized string hashing is turned on by default on coreclr so EqualityComparer<string>.Default will
// be using randomized string hashing
if (collisionCount > HashHelpers.HashCollisionThreshold && comparer == NonRandomizedStringEqualityComparer.Default)
{
comparer = (IEqualityComparer<TKey>) EqualityComparer<string>.Default;
Resize(entries.Length, true);
}
#else
if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer))
{
comparer = (IEqualityComparer<TKey>) HashHelpers.GetRandomizedEqualityComparer(comparer);
Resize(entries.Length, true);
}
#endif // FEATURE_CORECLR
#endif
}
public virtual void OnDeserialization(Object sender) {
SerializationInfo siInfo;
HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo);
if (siInfo==null) {
// It might be necessary to call OnDeserialization from a container if the container object also implements
// OnDeserialization. However, remoting will call OnDeserialization again.
// We can return immediately if this function is called twice.
// Note we set remove the serialization info from the table at the end of this method.
return;
}
int realVersion = siInfo.GetInt32(VersionName);
int hashsize = siInfo.GetInt32(HashSizeName);
comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>));
if( hashsize != 0) {
buckets = new int[hashsize];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
entries = new Entry[hashsize];
freeList = -1;
KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[])
siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[]));
if (array==null) {
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys);
}
for (int i=0; i<array.Length; i++) {
if ( array[i].Key == null) {
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
}
Insert(array[i].Key, array[i].Value, true);
}
}
else {
buckets = null;
}
version = realVersion;
HashHelpers.SerializationInfoTable.Remove(this);
}
private void Resize() {
Resize(HashHelpers.ExpandPrime(count), false);
}
private void Resize(int newSize, bool forceNewHashCodes) {
Contract.Assert(newSize >= entries.Length);
int[] newBuckets = new int[newSize];
for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1;
Entry[] newEntries = new Entry[newSize];
Array.Copy(entries, 0, newEntries, 0, count);
if(forceNewHashCodes) {
for (int i = 0; i < count; i++) {
if(newEntries[i].hashCode != -1) {
newEntries[i].hashCode = (comparer.GetHashCode(newEntries[i].key) & 0x7FFFFFFF);
}
}
}
for (int i = 0; i < count; i++) {
if (newEntries[i].hashCode >= 0) {
int bucket = newEntries[i].hashCode % newSize;
newEntries[i].next = newBuckets[bucket];
newBuckets[bucket] = i;
}
}
buckets = newBuckets;
entries = newEntries;
}
public bool Remove(TKey key) {
if(key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null) {
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int bucket = hashCode % buckets.Length;
int last = -1;
for (int i = buckets[bucket]; i >= 0; last = i, i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
if (last < 0) {
buckets[bucket] = entries[i].next;
}
else {
entries[last].next = entries[i].next;
}
entries[i].hashCode = -1;
entries[i].next = freeList;
entries[i].key = default(TKey);
entries[i].value = default(TValue);
freeList = i;
freeCount++;
version++;
return true;
}
}
}
return false;
}
public bool TryGetValue(TKey key, out TValue value) {
int i = FindEntry(key);
if (i >= 0) {
value = entries[i].value;
return true;
}
value = default(TValue);
return false;
}
// This is a convenience method for the internal callers that were converted from using Hashtable.
// Many were combining key doesn't exist and key exists but null value (for non-value types) checks.
// This allows them to continue getting that behavior with minimal code delta. This is basically
// TryGetValue without the out param
internal TValue GetValueOrDefault(TKey key) {
int i = FindEntry(key);
if (i >= 0) {
return entries[i].value;
}
return default(TValue);
}
bool ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly {
get { return false; }
}
void ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[] array, int index) {
CopyTo(array, index);
}
void ICollection.CopyTo(Array array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if( array.GetLowerBound(0) != 0 ) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey,TValue>[] pairs = array as KeyValuePair<TKey,TValue>[];
if (pairs != null) {
CopyTo(pairs, index);
}
else if( array is DictionaryEntry[]) {
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
Entry[] entries = this.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) {
dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value);
}
}
}
else {
object[] objects = array as object[];
if (objects == null) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
try {
int count = this.count;
Entry[] entries = this.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) {
objects[index++] = new KeyValuePair<TKey,TValue>(entries[i].key, entries[i].value);
}
}
}
catch(ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
}
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(this, Enumerator.KeyValuePair);
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get {
if( _syncRoot == null) {
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
bool IDictionary.IsFixedSize {
get { return false; }
}
bool IDictionary.IsReadOnly {
get { return false; }
}
ICollection IDictionary.Keys {
get { return (ICollection)Keys; }
}
ICollection IDictionary.Values {
get { return (ICollection)Values; }
}
object IDictionary.this[object key] {
get {
if( IsCompatibleKey(key)) {
int i = FindEntry((TKey)key);
if (i >= 0) {
return entries[i].value;
}
}
return null;
}
set {
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try {
TKey tempKey = (TKey)key;
try {
this[tempKey] = (TValue)value;
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
}
private static bool IsCompatibleKey(object key) {
if( key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return (key is TKey);
}
void IDictionary.Add(object key, object value) {
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try {
TKey tempKey = (TKey)key;
try {
Add(tempKey, (TValue)value);
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
bool IDictionary.Contains(object key) {
if(IsCompatibleKey(key)) {
return ContainsKey((TKey)key);
}
return false;
}
IDictionaryEnumerator IDictionary.GetEnumerator() {
return new Enumerator(this, Enumerator.DictEntry);
}
void IDictionary.Remove(object key) {
if(IsCompatibleKey(key)) {
Remove((TKey)key);
}
}
[Serializable]
public struct Enumerator: IEnumerator<KeyValuePair<TKey,TValue>>,
IDictionaryEnumerator
{
private Dictionary<TKey,TValue> dictionary;
private int version;
private int index;
private KeyValuePair<TKey,TValue> current;
private int getEnumeratorRetType; // What should Enumerator.Current return?
internal const int DictEntry = 1;
internal const int KeyValuePair = 2;
internal Enumerator(Dictionary<TKey,TValue> dictionary, int getEnumeratorRetType) {
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
this.getEnumeratorRetType = getEnumeratorRetType;
current = new KeyValuePair<TKey, TValue>();
}
public bool MoveNext() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue
while ((uint)index < (uint)dictionary.count) {
if (dictionary.entries[index].hashCode >= 0) {
current = new KeyValuePair<TKey, TValue>(dictionary.entries[index].key, dictionary.entries[index].value);
index++;
return true;
}
index++;
}
index = dictionary.count + 1;
current = new KeyValuePair<TKey, TValue>();
return false;
}
public KeyValuePair<TKey,TValue> Current {
get { return current; }
}
public void Dispose() {
}
object IEnumerator.Current {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
if (getEnumeratorRetType == DictEntry) {
return new System.Collections.DictionaryEntry(current.Key, current.Value);
} else {
return new KeyValuePair<TKey, TValue>(current.Key, current.Value);
}
}
}
void IEnumerator.Reset() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
index = 0;
current = new KeyValuePair<TKey, TValue>();
}
DictionaryEntry IDictionaryEnumerator.Entry {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return new DictionaryEntry(current.Key, current.Value);
}
}
object IDictionaryEnumerator.Key {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return current.Key;
}
}
object IDictionaryEnumerator.Value {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return current.Value;
}
}
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class KeyCollection: ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private Dictionary<TKey,TValue> dictionary;
public KeyCollection(Dictionary<TKey,TValue> dictionary) {
if (dictionary == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
this.dictionary = dictionary;
}
public Enumerator GetEnumerator() {
return new Enumerator(dictionary);
}
public void CopyTo(TKey[] array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < dictionary.Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) array[index++] = entries[i].key;
}
}
public int Count {
get { return dictionary.Count; }
}
bool ICollection<TKey>.IsReadOnly {
get { return true; }
}
void ICollection<TKey>.Add(TKey item){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
void ICollection<TKey>.Clear(){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
bool ICollection<TKey>.Contains(TKey item){
return dictionary.ContainsKey(item);
}
bool ICollection<TKey>.Remove(TKey item){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
return false;
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() {
return new Enumerator(dictionary);
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(dictionary);
}
void ICollection.CopyTo(Array array, int index) {
if (array==null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if( array.GetLowerBound(0) != 0 ) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < dictionary.Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
TKey[] keys = array as TKey[];
if (keys != null) {
CopyTo(keys, index);
}
else {
object[] objects = array as object[];
if (objects == null) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
try {
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) objects[index++] = entries[i].key;
}
}
catch(ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
}
}
bool ICollection.IsSynchronized {
get { return false; }
}
Object ICollection.SyncRoot {
get { return ((ICollection)dictionary).SyncRoot; }
}
[Serializable]
public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> dictionary;
private int index;
private int version;
private TKey currentKey;
internal Enumerator(Dictionary<TKey, TValue> dictionary) {
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
currentKey = default(TKey);
}
public void Dispose() {
}
public bool MoveNext() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
while ((uint)index < (uint)dictionary.count) {
if (dictionary.entries[index].hashCode >= 0) {
currentKey = dictionary.entries[index].key;
index++;
return true;
}
index++;
}
index = dictionary.count + 1;
currentKey = default(TKey);
return false;
}
public TKey Current {
get {
return currentKey;
}
}
Object System.Collections.IEnumerator.Current {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return currentKey;
}
}
void System.Collections.IEnumerator.Reset() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
index = 0;
currentKey = default(TKey);
}
}
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class ValueCollection: ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private Dictionary<TKey,TValue> dictionary;
public ValueCollection(Dictionary<TKey,TValue> dictionary) {
if (dictionary == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
this.dictionary = dictionary;
}
public Enumerator GetEnumerator() {
return new Enumerator(dictionary);
}
public void CopyTo(TValue[] array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < dictionary.Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) array[index++] = entries[i].value;
}
}
public int Count {
get { return dictionary.Count; }
}
bool ICollection<TValue>.IsReadOnly {
get { return true; }
}
void ICollection<TValue>.Add(TValue item){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Remove(TValue item){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
return false;
}
void ICollection<TValue>.Clear(){
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Contains(TValue item){
return dictionary.ContainsValue(item);
}
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() {
return new Enumerator(dictionary);
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(dictionary);
}
void ICollection.CopyTo(Array array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if( array.GetLowerBound(0) != 0 ) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
TValue[] values = array as TValue[];
if (values != null) {
CopyTo(values, index);
}
else {
object[] objects = array as object[];
if (objects == null) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
try {
for (int i = 0; i < count; i++) {
if (entries[i].hashCode >= 0) objects[index++] = entries[i].value;
}
}
catch(ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
}
}
bool ICollection.IsSynchronized {
get { return false; }
}
Object ICollection.SyncRoot {
get { return ((ICollection)dictionary).SyncRoot; }
}
[Serializable]
public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> dictionary;
private int index;
private int version;
private TValue currentValue;
internal Enumerator(Dictionary<TKey, TValue> dictionary) {
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
currentValue = default(TValue);
}
public void Dispose() {
}
public bool MoveNext() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
while ((uint)index < (uint)dictionary.count) {
if (dictionary.entries[index].hashCode >= 0) {
currentValue = dictionary.entries[index].value;
index++;
return true;
}
index++;
}
index = dictionary.count + 1;
currentValue = default(TValue);
return false;
}
public TValue Current {
get {
return currentValue;
}
}
Object System.Collections.IEnumerator.Current {
get {
if( index == 0 || (index == dictionary.count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return currentValue;
}
}
void System.Collections.IEnumerator.Reset() {
if (version != dictionary.version) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
index = 0;
currentValue = default(TValue);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.Tests
{
public class EnvironmentTests : RemoteExecutorTestBase
{
[Fact]
public void CurrentDirectory_Null_Path_Throws_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => Environment.CurrentDirectory = null);
}
[Fact]
public void CurrentDirectory_Empty_Path_Throws_ArgumentException()
{
AssertExtensions.Throws<ArgumentException>("value", null, () => Environment.CurrentDirectory = string.Empty);
}
[Fact]
public void CurrentDirectory_SetToNonExistentDirectory_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() => Environment.CurrentDirectory = GetTestFilePath());
}
[Fact]
public void CurrentDirectory_SetToValidOtherDirectory()
{
RemoteInvoke(() =>
{
Environment.CurrentDirectory = TestDirectory;
Assert.Equal(Directory.GetCurrentDirectory(), Environment.CurrentDirectory);
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current
// directory to a symlinked path will result in GetCurrentDirectory returning the absolute
// path that followed the symlink.
Assert.Equal(TestDirectory, Directory.GetCurrentDirectory());
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void CurrentManagedThreadId_Idempotent()
{
Assert.Equal(Environment.CurrentManagedThreadId, Environment.CurrentManagedThreadId);
}
[Fact]
public void CurrentManagedThreadId_DifferentForActiveThreads()
{
var ids = new HashSet<int>();
Barrier b = new Barrier(10);
Task.WaitAll((from i in Enumerable.Range(0, b.ParticipantCount)
select Task.Factory.StartNew(() =>
{
b.SignalAndWait();
lock (ids) ids.Add(Environment.CurrentManagedThreadId);
b.SignalAndWait();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray());
Assert.Equal(b.ParticipantCount, ids.Count);
}
[Fact]
public void HasShutdownStarted_FalseWhileExecuting()
{
Assert.False(Environment.HasShutdownStarted);
}
[Fact]
public void Is64BitProcess_MatchesIntPtrSize()
{
Assert.Equal(IntPtr.Size == 8, Environment.Is64BitProcess);
}
[Fact]
public void Is64BitOperatingSystem_TrueIf64BitProcess()
{
if (Environment.Is64BitProcess)
{
Assert.True(Environment.Is64BitOperatingSystem);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
public void Is64BitOperatingSystem_Unix_TrueIff64BitProcess()
{
Assert.Equal(Environment.Is64BitProcess, Environment.Is64BitOperatingSystem);
}
[Fact]
public void OSVersion_Idempotent()
{
Assert.Same(Environment.OSVersion, Environment.OSVersion);
}
[Fact]
public void OSVersion_MatchesPlatform()
{
PlatformID id = Environment.OSVersion.Platform;
Assert.Equal(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? PlatformID.Win32NT : PlatformID.Unix,
id);
}
[Fact]
public void OSVersion_ValidVersion()
{
Version version = Environment.OSVersion.Version;
string versionString = Environment.OSVersion.VersionString;
Assert.False(string.IsNullOrWhiteSpace(versionString), "Expected non-empty version string");
Assert.True(version.Major > 0);
Assert.Contains(version.ToString(2), versionString);
Assert.Contains(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" : "Unix", versionString);
}
[Fact]
public void SystemPageSize_Valid()
{
int pageSize = Environment.SystemPageSize;
Assert.Equal(pageSize, Environment.SystemPageSize);
Assert.True(pageSize > 0, "Expected positive page size");
Assert.True((pageSize & (pageSize - 1)) == 0, "Expected power-of-2 page size");
}
[Fact]
public void UserInteractive_True()
{
Assert.True(Environment.UserInteractive);
}
[Fact]
public void UserName_Valid()
{
Assert.False(string.IsNullOrWhiteSpace(Environment.UserName));
}
[Fact]
public void UserDomainName_Valid()
{
Assert.False(string.IsNullOrWhiteSpace(Environment.UserDomainName));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
public void UserDomainName_Unix_MatchesMachineName()
{
Assert.Equal(Environment.MachineName, Environment.UserDomainName);
}
[Fact]
public void Version_MatchesFixedVersion()
{
Assert.Equal(new Version(4, 0, 30319, 42000), Environment.Version);
}
[Fact]
public void WorkingSet_Valid()
{
Assert.True(Environment.WorkingSet > 0, "Expected positive WorkingSet value");
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process
[OuterLoop]
[Fact]
[ActiveIssue("https://github.com/dotnet/corefx/issues/21404", TargetFrameworkMonikers.Uap)]
public void FailFast_ExpectFailureExitCode()
{
using (Process p = RemoteInvoke(() => { Environment.FailFast("message"); return SuccessExitCode; }).Process)
{
p.WaitForExit();
Assert.NotEqual(SuccessExitCode, p.ExitCode);
}
using (Process p = RemoteInvoke(() => { Environment.FailFast("message", new Exception("uh oh")); return SuccessExitCode; }).Process)
{
p.WaitForExit();
Assert.NotEqual(SuccessExitCode, p.ExitCode);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
public void GetFolderPath_Unix_PersonalIsHomeAndUserProfile()
{
Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.Personal));
Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
}
[Fact]
public void GetSystemDirectory()
{
if (PlatformDetection.IsWindowsNanoServer)
{
// https://github.com/dotnet/corefx/issues/19110
// On Windows Nano, ShGetKnownFolderPath currently doesn't give
// the correct result for SystemDirectory.
// Assert that it's wrong, so that if it's fixed, we don't forget to
// enable this test for Nano.
Assert.NotEqual(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory);
return;
}
Assert.Equal(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory);
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
[InlineData(Environment.SpecialFolder.UserProfile, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.Personal, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.CommonTemplates, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.Desktop, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.DesktopDirectory, Environment.SpecialFolderOption.DoNotVerify)]
// Not set on Unix (amongst others)
//[InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.Templates, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.MyVideos, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.MyMusic, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.MyPictures, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.Fonts, Environment.SpecialFolderOption.DoNotVerify)]
public void GetFolderPath_Unix_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option)
{
Assert.NotEmpty(Environment.GetFolderPath(folder, option));
if (option == Environment.SpecialFolderOption.None)
{
Assert.NotEmpty(Environment.GetFolderPath(folder));
}
}
[Theory]
[PlatformSpecific(TestPlatforms.OSX)] // Tests OS-specific environment
[InlineData(Environment.SpecialFolder.Favorites, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.InternetCache, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.None)]
public void GetFolderPath_OSX_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option)
{
Assert.NotEmpty(Environment.GetFolderPath(folder, option));
if (option == Environment.SpecialFolderOption.None)
{
Assert.NotEmpty(Environment.GetFolderPath(folder));
}
}
// The commented out folders aren't set on all systems.
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))] // https://github.com/dotnet/corefx/issues/19110
[ActiveIssue(20782, TargetFrameworkMonikers.Uap)]
[InlineData(Environment.SpecialFolder.ApplicationData, false)]
[InlineData(Environment.SpecialFolder.CommonApplicationData, false)]
[InlineData(Environment.SpecialFolder.LocalApplicationData, true)]
[InlineData(Environment.SpecialFolder.Cookies, true)]
[InlineData(Environment.SpecialFolder.Desktop, false)]
[InlineData(Environment.SpecialFolder.Favorites, false)]
[InlineData(Environment.SpecialFolder.History, true)]
[InlineData(Environment.SpecialFolder.InternetCache, true)]
[InlineData(Environment.SpecialFolder.Programs, true)]
// [InlineData(Environment.SpecialFolder.MyComputer)]
[InlineData(Environment.SpecialFolder.MyMusic, false)]
[InlineData(Environment.SpecialFolder.MyPictures, false)]
[InlineData(Environment.SpecialFolder.MyVideos, false)]
[InlineData(Environment.SpecialFolder.Recent, false)]
[InlineData(Environment.SpecialFolder.SendTo, false)]
[InlineData(Environment.SpecialFolder.StartMenu, false)]
[InlineData(Environment.SpecialFolder.Startup, true)]
[InlineData(Environment.SpecialFolder.System, true)]
[InlineData(Environment.SpecialFolder.Templates, false)]
[InlineData(Environment.SpecialFolder.DesktopDirectory, false)]
[InlineData(Environment.SpecialFolder.Personal, false)]
[InlineData(Environment.SpecialFolder.ProgramFiles, true)]
[InlineData(Environment.SpecialFolder.CommonProgramFiles, true)]
[InlineData(Environment.SpecialFolder.AdminTools, true)]
[InlineData(Environment.SpecialFolder.CDBurning, false)]
[InlineData(Environment.SpecialFolder.CommonAdminTools, false)]
[InlineData(Environment.SpecialFolder.CommonDocuments, false)]
[InlineData(Environment.SpecialFolder.CommonMusic, false)]
// [InlineData(Environment.SpecialFolder.CommonOemLinks)]
[InlineData(Environment.SpecialFolder.CommonPictures, false)]
[InlineData(Environment.SpecialFolder.CommonStartMenu, false)]
[InlineData(Environment.SpecialFolder.CommonPrograms, false)]
[InlineData(Environment.SpecialFolder.CommonStartup, false)]
[InlineData(Environment.SpecialFolder.CommonDesktopDirectory, false)]
[InlineData(Environment.SpecialFolder.CommonTemplates, false)]
[InlineData(Environment.SpecialFolder.CommonVideos, false)]
[InlineData(Environment.SpecialFolder.Fonts, true)]
[InlineData(Environment.SpecialFolder.NetworkShortcuts, false)]
// [InlineData(Environment.SpecialFolder.PrinterShortcuts)]
[InlineData(Environment.SpecialFolder.UserProfile, false)]
[InlineData(Environment.SpecialFolder.CommonProgramFilesX86, true)]
[InlineData(Environment.SpecialFolder.ProgramFilesX86, true)]
[InlineData(Environment.SpecialFolder.Resources, true)]
// [InlineData(Environment.SpecialFolder.LocalizedResources)]
[InlineData(Environment.SpecialFolder.SystemX86, true)]
[InlineData(Environment.SpecialFolder.Windows, true)]
[PlatformSpecific(TestPlatforms.Windows)] // Tests OS-specific environment
public unsafe void GetFolderPath_Windows(Environment.SpecialFolder folder, bool existsInAppContainer = true)
{
string knownFolder = Environment.GetFolderPath(folder);
// If you are not executing inside an AppContainer or the folder is allowed in it the path must not be empty.
if (!PlatformDetection.IsWinRT || existsInAppContainer)
{
Assert.NotEmpty(knownFolder);
}
else
{
// If you hit this assert it means that SHGetFolderPath inside a UWP has been fixed.
// Check the value is reasonable and update the test data to expect a path from now on.
Assert.Empty(knownFolder);
}
// Call the older folder API to compare our results.
char* buffer = stackalloc char[260];
SHGetFolderPathW(IntPtr.Zero, (int)folder, IntPtr.Zero, 0, buffer);
string folderPath = new string(buffer);
Assert.Equal(folderPath, knownFolder);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes
public void GetLogicalDrives_Unix_AtLeastOneIsRoot()
{
string[] drives = Environment.GetLogicalDrives();
Assert.NotNull(drives);
Assert.True(drives.Length > 0, "Expected at least one drive");
Assert.All(drives, d => Assert.NotNull(d));
Assert.Contains(drives, d => d == "/");
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
public void GetLogicalDrives_Windows_MatchesExpectedLetters()
{
string[] drives = Environment.GetLogicalDrives();
uint mask = (uint)GetLogicalDrives();
var bits = new BitArray(new[] { (int)mask });
Assert.Equal(bits.Cast<bool>().Count(b => b), drives.Length);
for (int bit = 0, d = 0; bit < bits.Length; bit++)
{
if (bits[bit])
{
Assert.Contains((char)('A' + bit), drives[d++]);
}
}
}
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern int GetLogicalDrives();
[DllImport("shell32.dll", SetLastError = false, BestFitMapping = false, ExactSpelling = true)]
internal static extern unsafe int SHGetFolderPathW(
IntPtr hwndOwner,
int nFolder,
IntPtr hToken,
uint dwFlags,
char* pszPath);
public static IEnumerable<object[]> EnvironmentVariableTargets
{
get
{
yield return new object[] { EnvironmentVariableTarget.Process };
yield return new object[] { EnvironmentVariableTarget.User };
yield return new object[] { EnvironmentVariableTarget.Machine };
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class ParallelEnumerableTests
{
//
// Null query
//
[Fact]
public static void NullQuery()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).AsParallel());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable)null).AsParallel());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((Partitioner<int>)null).AsParallel());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((int[])null).AsParallel());
AssertExtensions.Throws<ArgumentNullException>("source", () => ParallelEnumerable.AsOrdered((ParallelQuery<int>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ParallelEnumerable.AsOrdered((ParallelQuery)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ParallelEnumerable.AsUnordered<int>((ParallelQuery<int>)null));
}
//
// Range
//
public static IEnumerable<object[]> RangeData()
{
int[] datapoints = { 0, 1, 2, 16, };
foreach (int sign in new[] { -1, 1 })
{
foreach (int start in datapoints)
{
foreach (int count in datapoints)
{
yield return new object[] { start * sign, count };
}
}
}
yield return new object[] { int.MaxValue, 0 };
yield return new object[] { int.MaxValue, 1 };
yield return new object[] { int.MaxValue - 8, 8 + 1 };
yield return new object[] { int.MinValue, 0 };
yield return new object[] { int.MinValue, 1 };
}
[Theory]
[MemberData(nameof(RangeData))]
public static void Range_UndefinedOrder(int start, int count)
{
ParallelQuery<int> query = ParallelEnumerable.Range(start, count);
IntegerRangeSet seen = new IntegerRangeSet(start, count);
Assert.All(query, x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(RangeData))]
public static void Range_AsOrdered(int start, int count)
{
ParallelQuery<int> query = ParallelEnumerable.Range(start, count).AsOrdered();
int current = start;
Assert.All(query, x => Assert.Equal(unchecked(current++), x));
Assert.Equal(count, unchecked(current - start));
}
[Theory]
[MemberData(nameof(RangeData))]
public static void Range_AsSequential(int start, int count)
{
IEnumerable<int> query = ParallelEnumerable.Range(start, count).AsSequential();
int current = start;
Assert.All(query, x => Assert.Equal(unchecked(current++), x));
Assert.Equal(count, unchecked(current - start));
}
[Theory]
[MemberData(nameof(RangeData))]
public static void Range_First(int start, int count)
{
ParallelQuery<int> query = ParallelEnumerable.Range(start, count);
if (count == 0)
{
Assert.Throws<InvalidOperationException>(() => query.First());
}
else
{
Assert.Equal(start, query.First());
}
}
[Theory]
[MemberData(nameof(RangeData))]
public static void Range_FirstOrDefault(int start, int count)
{
ParallelQuery<int> query = ParallelEnumerable.Range(start, count);
Assert.Equal(count == 0 ? 0 : start, query.FirstOrDefault());
}
[Theory]
[MemberData(nameof(RangeData))]
public static void Range_Last(int start, int count)
{
ParallelQuery<int> query = ParallelEnumerable.Range(start, count);
if (count == 0)
{
Assert.Throws<InvalidOperationException>(() => query.Last());
}
else
{
Assert.Equal(start + (count - 1), query.Last());
}
}
[Theory]
[MemberData(nameof(RangeData))]
public static void Range_LastOrDefault(int start, int count)
{
ParallelQuery<int> query = ParallelEnumerable.Range(start, count);
Assert.Equal(count == 0 ? 0 : start + (count - 1), query.LastOrDefault());
}
[Theory]
[MemberData(nameof(RangeData))]
public static void Range_Take(int start, int count)
{
ParallelQuery<int> query = ParallelEnumerable.Range(start, count).Take(count / 2);
// Elements are taken from the first half of the list, but order is indeterminate.
IntegerRangeSet seen = new IntegerRangeSet(start, count / 2);
Assert.All(query, x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(RangeData))]
public static void Range_Skip(int start, int count)
{
ParallelQuery<int> query = ParallelEnumerable.Range(start, count).Skip(count / 2);
// Skips over the first half of the list, but order is indeterminate.
IntegerRangeSet seen = new IntegerRangeSet(start + count / 2, (count + 1) / 2);
Assert.All(query, x => seen.Add(x));
seen.AssertComplete();
Assert.Empty(ParallelEnumerable.Range(start, count).Skip(count + 1));
}
[Fact]
public static void Range_Exception()
{
Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Range(0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Range(-8, -8));
Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Range(int.MaxValue, 2));
}
//
// Repeat
//
public static IEnumerable<object[]> RepeatData()
{
int[] datapoints = new[] { 0, 1, 2, 16, 128, 1024 };
foreach (int count in datapoints)
{
foreach (int element in datapoints)
{
yield return new object[] { element, count };
yield return new object[] { (long)element, count };
yield return new object[] { (double)element, count };
// [ActiveIssue("https://github.com/xunit/xunit/issues/1771")]
//yield return new object[] { (decimal)element, count };
yield return new object[] { "" + element, count };
}
yield return new object[] { (object)null, count };
yield return new object[] { (string)null, count };
}
}
[Theory]
[MemberData(nameof(RepeatData))]
public static void Repeat<T>(T element, int count)
{
ParallelQuery<T> query = ParallelEnumerable.Repeat(element, count);
int counted = 0;
Assert.All(query, e => { counted++; Assert.Equal(element, e); });
Assert.Equal(count, counted);
}
[Theory]
[MemberData(nameof(RepeatData))]
public static void Repeat_Select<T>(T element, int count)
{
ParallelQuery<T> query = ParallelEnumerable.Repeat(element, count).Select(i => i);
int counted = 0;
Assert.All(query, e => { counted++; Assert.Equal(element, e); });
Assert.Equal(count, counted);
}
[Fact]
public static void Repeat_Exception()
{
Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat(1, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat((long)1024, -1024));
Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat(2.0, -2));
Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat((decimal)8, -8));
Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat("fail", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat((string)null, -1));
}
[Fact]
public static void Repeat_Reset()
{
const int Value = 42;
const int Iterations = 3;
ParallelQuery<int> q = ParallelEnumerable.Repeat(Value, Iterations);
IEnumerator<int> e = q.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int count = 0;
while (e.MoveNext())
{
Assert.Equal(Value, e.Current);
count++;
}
Assert.False(e.MoveNext());
Assert.Equal(Iterations, count);
e.Reset();
}
}
//
// Empty
//
[Fact]
public static void EmptyStruct() => Empty<int>();
[Fact]
public static void EmptyClass() => Empty<string>();
private static void Empty<T>()
{
Assert.Empty(ParallelEnumerable.Empty<T>());
Assert.False(ParallelEnumerable.Empty<T>().Any(x => true));
Assert.False(ParallelEnumerable.Empty<T>().Contains(default(T)));
Assert.Equal(0, ParallelEnumerable.Empty<T>().Count());
Assert.Equal(0, ParallelEnumerable.Empty<T>().LongCount());
Assert.Equal(new T[0], ParallelEnumerable.Empty<T>().ToArray());
Assert.Equal(new Dictionary<T, T>(), ParallelEnumerable.Empty<T>().ToDictionary(x => x));
Assert.Equal(new List<T>(), ParallelEnumerable.Empty<T>().ToList());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<T>().First());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<T>().Last());
}
}
}
| |
// 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;
using System.Runtime.InteropServices;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal
{
internal sealed partial class CertificatePal : IDisposable, ICertificatePal
{
public static ICertificatePal FromBlob(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
return FromBlobOrFile(rawData, null, password, keyStorageFlags);
}
public static ICertificatePal FromFile(string fileName, string password, X509KeyStorageFlags keyStorageFlags)
{
return FromBlobOrFile(null, fileName, password, keyStorageFlags);
}
private static ICertificatePal FromBlobOrFile(byte[] rawData, string fileName, string password, X509KeyStorageFlags keyStorageFlags)
{
Debug.Assert(rawData != null || fileName != null);
bool loadFromFile = (fileName != null);
PfxCertStoreFlags pfxCertStoreFlags = MapKeyStorageFlags(keyStorageFlags);
bool persistKeySet = (0 != (keyStorageFlags & X509KeyStorageFlags.PersistKeySet));
CertEncodingType msgAndCertEncodingType;
ContentType contentType;
FormatType formatType;
SafeCertStoreHandle hCertStore = null;
SafeCryptMsgHandle hCryptMsg = null;
SafeCertContextHandle pCertContext = null;
try
{
unsafe
{
fixed (byte* pRawData = rawData)
{
fixed (char* pFileName = fileName)
{
CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB(loadFromFile ? 0 : rawData.Length, pRawData);
CertQueryObjectType objectType = loadFromFile ? CertQueryObjectType.CERT_QUERY_OBJECT_FILE : CertQueryObjectType.CERT_QUERY_OBJECT_BLOB;
void* pvObject = loadFromFile ? (void*)pFileName : (void*)&certBlob;
bool success = Interop.crypt32.CryptQueryObject(
objectType,
pvObject,
X509ExpectedContentTypeFlags,
X509ExpectedFormatTypeFlags,
0,
out msgAndCertEncodingType,
out contentType,
out formatType,
out hCertStore,
out hCryptMsg,
out pCertContext
);
if (!success)
{
int hr = Marshal.GetHRForLastWin32Error();
throw hr.ToCryptographicException();
}
}
}
if (contentType == ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED || contentType == ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED)
{
pCertContext = GetSignerInPKCS7Store(hCertStore, hCryptMsg);
}
else if (contentType == ContentType.CERT_QUERY_CONTENT_PFX)
{
if (loadFromFile)
rawData = File.ReadAllBytes(fileName);
pCertContext = FilterPFXStore(rawData, password, pfxCertStoreFlags);
}
CertificatePal pal = new CertificatePal(pCertContext, deleteKeyContainer: !persistKeySet);
pCertContext = null;
return pal;
}
}
finally
{
if (hCertStore != null)
hCertStore.Dispose();
if (hCryptMsg != null)
hCryptMsg.Dispose();
if (pCertContext != null)
pCertContext.Dispose();
}
}
private static SafeCertContextHandle GetSignerInPKCS7Store(SafeCertStoreHandle hCertStore, SafeCryptMsgHandle hCryptMsg)
{
// make sure that there is at least one signer of the certificate store
int dwSigners;
int cbSigners = sizeof(int);
if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_COUNT_PARAM, 0, out dwSigners, ref cbSigners))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
if (dwSigners == 0)
throw ErrorCode.CRYPT_E_SIGNER_NOT_FOUND.ToCryptographicException();
// get the first signer from the store, and use that as the loaded certificate
int cbData = 0;
if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_INFO_PARAM, 0, null, ref cbData))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
byte[] cmsgSignerBytes = new byte[cbData];
if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_INFO_PARAM, 0, cmsgSignerBytes, ref cbData))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
CERT_INFO certInfo = default(CERT_INFO);
unsafe
{
fixed (byte* pCmsgSignerBytes = cmsgSignerBytes)
{
CMSG_SIGNER_INFO_Partial* pCmsgSignerInfo = (CMSG_SIGNER_INFO_Partial*)pCmsgSignerBytes;
certInfo.Issuer.cbData = pCmsgSignerInfo->Issuer.cbData;
certInfo.Issuer.pbData = pCmsgSignerInfo->Issuer.pbData;
certInfo.SerialNumber.cbData = pCmsgSignerInfo->SerialNumber.cbData;
certInfo.SerialNumber.pbData = pCmsgSignerInfo->SerialNumber.pbData;
}
SafeCertContextHandle pCertContext = null;
if (!Interop.crypt32.CertFindCertificateInStore(hCertStore, CertFindType.CERT_FIND_SUBJECT_CERT, &certInfo, ref pCertContext))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
return pCertContext;
}
}
private static SafeCertContextHandle FilterPFXStore(byte[] rawData, string password, PfxCertStoreFlags pfxCertStoreFlags)
{
SafeCertStoreHandle hStore;
unsafe
{
fixed (byte* pbRawData = rawData)
{
CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB(rawData.Length, pbRawData);
hStore = Interop.crypt32.PFXImportCertStore(ref certBlob, password, pfxCertStoreFlags);
if (hStore.IsInvalid)
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
}
}
try
{
// Find the first cert with private key. If none, then simply take the very first cert. Along the way, delete the keycontainers
// of any cert we don't accept.
SafeCertContextHandle pCertContext = SafeCertContextHandle.InvalidHandle;
SafeCertContextHandle pEnumContext = null;
while (Interop.crypt32.CertEnumCertificatesInStore(hStore, ref pEnumContext))
{
if (pEnumContext.ContainsPrivateKey)
{
if ((!pCertContext.IsInvalid) && pCertContext.ContainsPrivateKey)
{
// We already found our chosen one. Free up this one's key and move on.
SafeCertContextHandleWithKeyContainerDeletion.DeleteKeyContainer(pEnumContext);
}
else
{
// Found our first cert that has a private key. Set him up as our chosen one but keep iterating
// as we need to free up the keys of any remaining certs.
pCertContext.Dispose();
pCertContext = pEnumContext.Duplicate();
}
}
else
{
if (pCertContext.IsInvalid)
pCertContext = pEnumContext.Duplicate(); // Doesn't have a private key but hang on to it anyway in case we don't find any certs with a private key.
}
}
if (pCertContext.IsInvalid)
{
// For compat, setting "hr" to ERROR_INVALID_PARAMETER even though ERROR_INVALID_PARAMETER is not actually an HRESULT.
throw ErrorCode.ERROR_INVALID_PARAMETER.ToCryptographicException();
}
return pCertContext;
}
finally
{
hStore.Dispose();
}
}
private static PfxCertStoreFlags MapKeyStorageFlags(X509KeyStorageFlags keyStorageFlags)
{
if ((keyStorageFlags & (X509KeyStorageFlags)~0x1F) != 0)
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(keyStorageFlags));
PfxCertStoreFlags pfxCertStoreFlags = 0;
if ((keyStorageFlags & X509KeyStorageFlags.UserKeySet) == X509KeyStorageFlags.UserKeySet)
pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_USER_KEYSET;
else if ((keyStorageFlags & X509KeyStorageFlags.MachineKeySet) == X509KeyStorageFlags.MachineKeySet)
pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_MACHINE_KEYSET;
if ((keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable)
pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_EXPORTABLE;
if ((keyStorageFlags & X509KeyStorageFlags.UserProtected) == X509KeyStorageFlags.UserProtected)
pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_USER_PROTECTED;
// In the full .NET Framework loading a PFX then adding the key to the Windows Certificate Store would
// enable a native application compiled against CAPI to find that private key and interoperate with it.
//
// For CoreFX this behavior is being retained.
//
// For .NET Native (UWP) the API used to delete the private key (if it wasn't added to a store) is not
// allowed to be called if the key is stored in CAPI. So for UWP force the key to be stored in the
// CNG Key Storage Provider, then deleting the key with CngKey.Delete will clean up the file on disk, too.
#if NETNATIVE
pfxCertStoreFlags |= PfxCertStoreFlags.PKCS12_ALWAYS_CNG_KSP;
#endif
return pfxCertStoreFlags;
}
private const ExpectedContentTypeFlags X509ExpectedContentTypeFlags =
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_CERT |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PFX;
private const ExpectedFormatTypeFlags X509ExpectedFormatTypeFlags = ExpectedFormatTypeFlags.CERT_QUERY_FORMAT_FLAG_ALL;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using MiniOa.Areas.HelpPage.ModelDescriptions;
using MiniOa.Areas.HelpPage.Models;
namespace MiniOa.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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.PortsTests;
using System.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class SerialStream_Read_byte_int_int : PortsTest
{
// The number of random bytes to receive for read method testing
private const int numRndBytesToRead = 16;
// The number of random bytes to receive for large input buffer testing
private const int largeNumRndBytesToRead = 2048;
// When we test Read and do not care about actually reading anything we must still
// create an byte array to pass into the method the following is the size of the
// byte array used in this situation
private const int defaultByteArraySize = 1;
private const int defaultByteOffset = 0;
private const int defaultByteCount = 1;
// The maximum buffer size when an exception occurs
private const int maxBufferSizeForException = 255;
// The maximum buffer size when an exception is not expected
private const int maxBufferSize = 8;
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void Buffer_Null()
{
VerifyReadException(null, 0, 1, typeof(ArgumentNullException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_NEG1()
{
VerifyReadException(new byte[defaultByteArraySize], -1, defaultByteCount, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_NEGRND()
{
var rndGen = new Random(-55);
VerifyReadException(new byte[defaultByteArraySize], rndGen.Next(int.MinValue, 0), defaultByteCount, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_MinInt()
{
VerifyReadException(new byte[defaultByteArraySize], int.MinValue, defaultByteCount, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_NEG1()
{
VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, -1, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_NEGRND()
{
var rndGen = new Random(-55);
VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_MinInt()
{
VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, int.MinValue, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void OffsetCount_EQ_Length_Plus_1()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = rndGen.Next(0, bufferLength);
int count = bufferLength + 1 - offset;
Type expectedException = typeof(ArgumentException);
VerifyReadException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void OffsetCount_GT_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = rndGen.Next(0, bufferLength);
int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue);
Type expectedException = typeof(ArgumentException);
VerifyReadException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_GT_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = rndGen.Next(bufferLength, int.MaxValue);
int count = defaultByteCount;
Type expectedException = typeof(ArgumentException);
VerifyReadException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_GT_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = defaultByteOffset;
int count = rndGen.Next(bufferLength + 1, int.MaxValue);
Type expectedException = typeof(ArgumentException);
VerifyReadException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasNullModem))]
public void OffsetCount_EQ_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = rndGen.Next(0, bufferLength - 1);
int count = bufferLength - offset;
VerifyRead(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasNullModem))]
public void Offset_EQ_Length_Minus_1()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = bufferLength - 1;
var count = 1;
VerifyRead(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasNullModem))]
public void Count_EQ_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSize);
var offset = 0;
int count = bufferLength;
VerifyRead(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasNullModem))]
public void LargeInputBuffer()
{
int bufferLength = largeNumRndBytesToRead;
var offset = 0;
int count = bufferLength;
VerifyRead(new byte[bufferLength], offset, count, largeNumRndBytesToRead);
}
#endregion
#region Verification for Test Cases
private void VerifyReadException(byte[] buffer, int offset, int count, Type expectedException)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
int bufferLength = null == buffer ? 0 : buffer.Length;
Debug.WriteLine("Verifying read method throws {0} buffer.Lenght={1}, offset={2}, count={3}",
expectedException, bufferLength, offset, count);
com.Open();
Assert.Throws(expectedException, () => com.BaseStream.Read(buffer, offset, count));
}
}
private void VerifyRead(byte[] buffer, int offset, int count)
{
VerifyRead(buffer, offset, count, numRndBytesToRead);
}
private void VerifyRead(byte[] buffer, int offset, int count, int numberOfBytesToRead)
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
var bytesToWrite = new byte[numberOfBytesToRead];
// Generate random bytes
for (var i = 0; i < bytesToWrite.Length; i++)
{
var randByte = (byte)rndGen.Next(0, 256);
bytesToWrite[i] = randByte;
}
// Generate some random bytes in the buffer
for (var i = 0; i < buffer.Length; i++)
{
var randByte = (byte)rndGen.Next(0, 256);
buffer[i] = randByte;
}
Debug.WriteLine(
"Verifying read method buffer.Lenght={0}, offset={1}, count={2} with {3} random chars",
buffer.Length, offset, count, bytesToWrite.Length);
com1.ReadTimeout = 500;
com1.Open();
com2.Open();
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, buffer, offset, count);
}
}
private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count)
{
var buffer = new byte[bytesToWrite.Length];
int totalBytesRead;
int bytesToRead;
var oldRcvBuffer = (byte[])rcvBuffer.Clone();
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 500;
Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250);
totalBytesRead = 0;
bytesToRead = com1.BytesToRead;
while (true)
{
int bytesRead;
try
{
bytesRead = com1.BaseStream.Read(rcvBuffer, offset, count);
}
catch (TimeoutException)
{
break;
}
// While their are more characters to be read
if ((bytesToRead > bytesRead && count != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead))
{
// If we have not read all of the characters that we should have
Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer");
}
if (bytesToWrite.Length < totalBytesRead + bytesRead)
{
// If we have read in more characters then we expect
Fail("ERROR!!!: We have received more characters then were sent");
}
VerifyBuffer(rcvBuffer, oldRcvBuffer, offset, bytesRead);
Array.Copy(rcvBuffer, offset, buffer, totalBytesRead, bytesRead);
totalBytesRead += bytesRead;
if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead);
}
oldRcvBuffer = (byte[])rcvBuffer.Clone();
bytesToRead = com1.BytesToRead;
}
// Compare the bytes that were written with the ones we read
Assert.Equal(bytesToWrite, buffer);
}
private void VerifyBuffer(byte[] actualBuffer, byte[] expectedBuffer, int offset, int count)
{
// Verify all character before the offset
for (var i = 0; i < offset; i++)
{
if (actualBuffer[i] != expectedBuffer[i])
{
Fail("ERROR!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]);
}
}
// Verify all character after the offset + count
for (int i = offset + count; i < actualBuffer.Length; i++)
{
if (actualBuffer[i] != expectedBuffer[i])
{
Fail("ERROR!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]);
}
}
}
#endregion
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// 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.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.12.9: initializing or chaning internal state information, reliable. Needs manual intervention to fix padding on variable datums. UNFINISHED
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(FixedDatum))]
[XmlInclude(typeof(VariableDatum))]
public partial class SetDataReliablePdu : SimulationManagementWithReliabilityFamilyPdu, IEquatable<SetDataReliablePdu>
{
/// <summary>
/// level of reliability service used for this transaction
/// </summary>
private byte _requiredReliabilityService;
/// <summary>
/// padding
/// </summary>
private ushort _pad1;
/// <summary>
/// padding
/// </summary>
private byte _pad2;
/// <summary>
/// Request ID
/// </summary>
private uint _requestID;
/// <summary>
/// Fixed datum record count
/// </summary>
private uint _numberOfFixedDatumRecords;
/// <summary>
/// variable datum record count
/// </summary>
private uint _numberOfVariableDatumRecords;
/// <summary>
/// Fixed datum records
/// </summary>
private List<FixedDatum> _fixedDatumRecords = new List<FixedDatum>();
/// <summary>
/// Variable datum records
/// </summary>
private List<VariableDatum> _variableDatumRecords = new List<VariableDatum>();
/// <summary>
/// Initializes a new instance of the <see cref="SetDataReliablePdu"/> class.
/// </summary>
public SetDataReliablePdu()
{
PduType = (byte)59;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(SetDataReliablePdu left, SetDataReliablePdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(SetDataReliablePdu left, SetDataReliablePdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += 1; // this._requiredReliabilityService
marshalSize += 2; // this._pad1
marshalSize += 1; // this._pad2
marshalSize += 4; // this._requestID
marshalSize += 4; // this._numberOfFixedDatumRecords
marshalSize += 4; // this._numberOfVariableDatumRecords
for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++)
{
FixedDatum listElement = (FixedDatum)this._fixedDatumRecords[idx];
marshalSize += listElement.GetMarshalledSize();
}
for (int idx = 0; idx < this._variableDatumRecords.Count; idx++)
{
VariableDatum listElement = (VariableDatum)this._variableDatumRecords[idx];
marshalSize += listElement.GetMarshalledSize();
}
return marshalSize;
}
/// <summary>
/// Gets or sets the level of reliability service used for this transaction
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "requiredReliabilityService")]
public byte RequiredReliabilityService
{
get
{
return this._requiredReliabilityService;
}
set
{
this._requiredReliabilityService = value;
}
}
/// <summary>
/// Gets or sets the padding
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "pad1")]
public ushort Pad1
{
get
{
return this._pad1;
}
set
{
this._pad1 = value;
}
}
/// <summary>
/// Gets or sets the padding
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "pad2")]
public byte Pad2
{
get
{
return this._pad2;
}
set
{
this._pad2 = value;
}
}
/// <summary>
/// Gets or sets the Request ID
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "requestID")]
public uint RequestID
{
get
{
return this._requestID;
}
set
{
this._requestID = value;
}
}
/// <summary>
/// Gets or sets the Fixed datum record count
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getnumberOfFixedDatumRecords method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(uint), ElementName = "numberOfFixedDatumRecords")]
public uint NumberOfFixedDatumRecords
{
get
{
return this._numberOfFixedDatumRecords;
}
set
{
this._numberOfFixedDatumRecords = value;
}
}
/// <summary>
/// Gets or sets the variable datum record count
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getnumberOfVariableDatumRecords method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(uint), ElementName = "numberOfVariableDatumRecords")]
public uint NumberOfVariableDatumRecords
{
get
{
return this._numberOfVariableDatumRecords;
}
set
{
this._numberOfVariableDatumRecords = value;
}
}
/// <summary>
/// Gets the Fixed datum records
/// </summary>
[XmlElement(ElementName = "fixedDatumRecordsList", Type = typeof(List<FixedDatum>))]
public List<FixedDatum> FixedDatumRecords
{
get
{
return this._fixedDatumRecords;
}
}
/// <summary>
/// Gets the Variable datum records
/// </summary>
[XmlElement(ElementName = "variableDatumRecordsList", Type = typeof(List<VariableDatum>))]
public List<VariableDatum> VariableDatumRecords
{
get
{
return this._variableDatumRecords;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
dos.WriteUnsignedByte((byte)this._requiredReliabilityService);
dos.WriteUnsignedShort((ushort)this._pad1);
dos.WriteUnsignedByte((byte)this._pad2);
dos.WriteUnsignedInt((uint)this._requestID);
dos.WriteUnsignedInt((uint)this._fixedDatumRecords.Count);
dos.WriteUnsignedInt((uint)this._variableDatumRecords.Count);
for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++)
{
FixedDatum aFixedDatum = (FixedDatum)this._fixedDatumRecords[idx];
aFixedDatum.Marshal(dos);
}
for (int idx = 0; idx < this._variableDatumRecords.Count; idx++)
{
VariableDatum aVariableDatum = (VariableDatum)this._variableDatumRecords[idx];
aVariableDatum.Marshal(dos);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._requiredReliabilityService = dis.ReadUnsignedByte();
this._pad1 = dis.ReadUnsignedShort();
this._pad2 = dis.ReadUnsignedByte();
this._requestID = dis.ReadUnsignedInt();
this._numberOfFixedDatumRecords = dis.ReadUnsignedInt();
this._numberOfVariableDatumRecords = dis.ReadUnsignedInt();
for (int idx = 0; idx < this.NumberOfFixedDatumRecords; idx++)
{
FixedDatum anX = new FixedDatum();
anX.Unmarshal(dis);
this._fixedDatumRecords.Add(anX);
}
for (int idx = 0; idx < this.NumberOfVariableDatumRecords; idx++)
{
VariableDatum anX = new VariableDatum();
anX.Unmarshal(dis);
this._variableDatumRecords.Add(anX);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<SetDataReliablePdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<requiredReliabilityService type=\"byte\">" + this._requiredReliabilityService.ToString(CultureInfo.InvariantCulture) + "</requiredReliabilityService>");
sb.AppendLine("<pad1 type=\"ushort\">" + this._pad1.ToString(CultureInfo.InvariantCulture) + "</pad1>");
sb.AppendLine("<pad2 type=\"byte\">" + this._pad2.ToString(CultureInfo.InvariantCulture) + "</pad2>");
sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>");
sb.AppendLine("<fixedDatumRecords type=\"uint\">" + this._fixedDatumRecords.Count.ToString(CultureInfo.InvariantCulture) + "</fixedDatumRecords>");
sb.AppendLine("<variableDatumRecords type=\"uint\">" + this._variableDatumRecords.Count.ToString(CultureInfo.InvariantCulture) + "</variableDatumRecords>");
for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++)
{
sb.AppendLine("<fixedDatumRecords" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"FixedDatum\">");
FixedDatum aFixedDatum = (FixedDatum)this._fixedDatumRecords[idx];
aFixedDatum.Reflection(sb);
sb.AppendLine("</fixedDatumRecords" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
for (int idx = 0; idx < this._variableDatumRecords.Count; idx++)
{
sb.AppendLine("<variableDatumRecords" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"VariableDatum\">");
VariableDatum aVariableDatum = (VariableDatum)this._variableDatumRecords[idx];
aVariableDatum.Reflection(sb);
sb.AppendLine("</variableDatumRecords" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
sb.AppendLine("</SetDataReliablePdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as SetDataReliablePdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(SetDataReliablePdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (this._requiredReliabilityService != obj._requiredReliabilityService)
{
ivarsEqual = false;
}
if (this._pad1 != obj._pad1)
{
ivarsEqual = false;
}
if (this._pad2 != obj._pad2)
{
ivarsEqual = false;
}
if (this._requestID != obj._requestID)
{
ivarsEqual = false;
}
if (this._numberOfFixedDatumRecords != obj._numberOfFixedDatumRecords)
{
ivarsEqual = false;
}
if (this._numberOfVariableDatumRecords != obj._numberOfVariableDatumRecords)
{
ivarsEqual = false;
}
if (this._fixedDatumRecords.Count != obj._fixedDatumRecords.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++)
{
if (!this._fixedDatumRecords[idx].Equals(obj._fixedDatumRecords[idx]))
{
ivarsEqual = false;
}
}
}
if (this._variableDatumRecords.Count != obj._variableDatumRecords.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._variableDatumRecords.Count; idx++)
{
if (!this._variableDatumRecords[idx].Equals(obj._variableDatumRecords[idx]))
{
ivarsEqual = false;
}
}
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._requiredReliabilityService.GetHashCode();
result = GenerateHash(result) ^ this._pad1.GetHashCode();
result = GenerateHash(result) ^ this._pad2.GetHashCode();
result = GenerateHash(result) ^ this._requestID.GetHashCode();
result = GenerateHash(result) ^ this._numberOfFixedDatumRecords.GetHashCode();
result = GenerateHash(result) ^ this._numberOfVariableDatumRecords.GetHashCode();
if (this._fixedDatumRecords.Count > 0)
{
for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++)
{
result = GenerateHash(result) ^ this._fixedDatumRecords[idx].GetHashCode();
}
}
if (this._variableDatumRecords.Count > 0)
{
for (int idx = 0; idx < this._variableDatumRecords.Count; idx++)
{
result = GenerateHash(result) ^ this._variableDatumRecords[idx].GetHashCode();
}
}
return result;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Client.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Org.Apache.Http.Client
{
/// <summary>
/// <para>A handler for determining if an HttpRequest should be retried after a recoverable exception during execution.</para><para>Classes implementing this interface must synchronize access to shared data as methods of this interfrace may be executed from multiple threads </para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/HttpRequestRetryHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/client/HttpRequestRetryHandler", AccessFlags = 1537)]
public partial interface IHttpRequestRetryHandler
/* scope: __dot42__ */
{
/// <summary>
/// <para>Determines if a method should be retried after an IOException occurs during execution.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the method should be retried, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// retryRequest
/// </java-name>
[Dot42.DexImport("retryRequest", "(Ljava/io/IOException;ILorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)]
bool RetryRequest(global::System.IO.IOException exception, int executionCount, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Abstract credentials provider.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/CredentialsProvider
/// </java-name>
[Dot42.DexImport("org/apache/http/client/CredentialsProvider", AccessFlags = 1537)]
public partial interface ICredentialsProvider
/* scope: __dot42__ */
{
/// <summary>
/// <para>Sets the credentials for the given authentication scope. Any previous credentials for the given scope will be overwritten.</para><para><para>getCredentials(AuthScope) </para></para>
/// </summary>
/// <java-name>
/// setCredentials
/// </java-name>
[Dot42.DexImport("setCredentials", "(Lorg/apache/http/auth/AuthScope;Lorg/apache/http/auth/Credentials;)V", AccessFlags = 1025)]
void SetCredentials(global::Org.Apache.Http.Auth.AuthScope authscope, global::Org.Apache.Http.Auth.ICredentials credentials) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Get the credentials for the given authentication scope.</para><para><para>setCredentials(AuthScope, Credentials) </para></para>
/// </summary>
/// <returns>
/// <para>the credentials</para>
/// </returns>
/// <java-name>
/// getCredentials
/// </java-name>
[Dot42.DexImport("getCredentials", "(Lorg/apache/http/auth/AuthScope;)Lorg/apache/http/auth/Credentials;", AccessFlags = 1025)]
global::Org.Apache.Http.Auth.ICredentials GetCredentials(global::Org.Apache.Http.Auth.AuthScope authscope) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Clears all credentials. </para>
/// </summary>
/// <java-name>
/// clear
/// </java-name>
[Dot42.DexImport("clear", "()V", AccessFlags = 1025)]
void Clear() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Handler that encapsulates the process of generating a response object from a HttpResponse.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/ResponseHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/client/ResponseHandler", AccessFlags = 1537, Signature = "<T:Ljava/lang/Object;>Ljava/lang/Object;")]
public partial interface IResponseHandler<T>
/* scope: __dot42__ */
{
/// <summary>
/// <para>Processes an HttpResponse and returns some value corresponding to that response.</para><para></para>
/// </summary>
/// <returns>
/// <para>A value determined by the response</para>
/// </returns>
/// <java-name>
/// handleResponse
/// </java-name>
[Dot42.DexImport("handleResponse", "(Lorg/apache/http/HttpResponse;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "(Lorg/apache/http/HttpResponse;)TT;")]
T HandleResponse(global::Org.Apache.Http.IHttpResponse response) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Signals an error in the HTTP protocol. </para>
/// </summary>
/// <java-name>
/// org/apache/http/client/ClientProtocolException
/// </java-name>
[Dot42.DexImport("org/apache/http/client/ClientProtocolException", AccessFlags = 33)]
public partial class ClientProtocolException : global::System.IO.IOException
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public ClientProtocolException() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public ClientProtocolException(string @string) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/Throwable;)V", AccessFlags = 1)]
public ClientProtocolException(global::System.Exception exception) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public ClientProtocolException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Signals failure to retry the request due to non-repeatable request entity.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/NonRepeatableRequestException
/// </java-name>
[Dot42.DexImport("org/apache/http/client/NonRepeatableRequestException", AccessFlags = 33)]
public partial class NonRepeatableRequestException : global::Org.Apache.Http.ProtocolException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new NonRepeatableEntityException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public NonRepeatableRequestException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new NonRepeatableEntityException with the specified detail message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public NonRepeatableRequestException(string message) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>A client-side request director. The director decides which steps are necessary to execute a request. It establishes connections and optionally processes redirects and authentication challenges. The director may therefore generate and send a sequence of requests in order to execute one initial request.</para><para><br></br><b>Note:</b> It is most likely that implementations of this interface will allocate connections, and return responses that depend on those connections for reading the response entity. Such connections MUST be released, but that is out of the scope of a request director.</para><para><para></para><para></para><title>Revision:</title><para>676020 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/RequestDirector
/// </java-name>
[Dot42.DexImport("org/apache/http/client/RequestDirector", AccessFlags = 1537)]
public partial interface IRequestDirector
/* scope: __dot42__ */
{
/// <summary>
/// <para>Executes a request. <br></br><b>Note:</b> For the time being, a new director is instantiated for each request. This is the same behavior as for <code>HttpMethodDirector</code> in HttpClient 3.</para><para></para>
/// </summary>
/// <returns>
/// <para>the final response to the request. This is never an intermediate response with status code 1xx.</para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" +
"/HttpContext;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)]
global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Interface for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication, connection management, and other features. Thread safety of HTTP clients depends on the implementation and configuration of the specific client.</para><para><para></para><para></para><title>Revision:</title><para>676020 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/HttpClient
/// </java-name>
[Dot42.DexImport("org/apache/http/client/HttpClient", AccessFlags = 1537)]
public partial interface IHttpClient
/* scope: __dot42__ */
{
/// <summary>
/// <para>Obtains the parameters for this client. These parameters will become defaults for all requests being executed with this client, and for the parameters of dependent objects in this client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the default parameters </para>
/// </returns>
/// <java-name>
/// getParams
/// </java-name>
[Dot42.DexImport("getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams GetParams() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the connection manager used by this client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the connection manager </para>
/// </returns>
/// <java-name>
/// getConnectionManager
/// </java-name>
[Dot42.DexImport("getConnectionManager", "()Lorg/apache/http/conn/ClientConnectionManager;", AccessFlags = 1025)]
global::Org.Apache.Http.Conn.IClientConnectionManager GetConnectionManager() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request using the default context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)]
global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/protocol/HttpCon" +
"text;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)]
global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;)Lorg/apache/http/HttpRes" +
"ponse;", AccessFlags = 1025)]
global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost request, global::Org.Apache.Http.IHttpRequest context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request to the target using the given context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" +
"/HttpContext;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)]
global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/client/ResponseH" +
"andler;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache" +
"/http/client/ResponseHandler<+TT;>;)TT;")]
T Execute<T>(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request to the target using the given context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/client/ResponseH" +
"andler;Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache" +
"/http/client/ResponseHandler<+TT;>;Lorg/apache/http/protocol/HttpContext;)TT;")]
T Execute<T>(global::Org.Apache.Http.Client.Methods.IHttpUriRequest target, global::Org.Apache.Http.Client.IResponseHandler<T> request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request to the target using the given context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/client/R" +
"esponseHandler;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lor" +
"g/apache/http/client/ResponseHandler<+TT;>;)TT;")]
T Execute<T>(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request to the target using the given context and processes the response using the given response handler.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response object as generated by the response handler. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/client/R" +
"esponseHandler;Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lor" +
"g/apache/http/client/ResponseHandler<+TT;>;Lorg/apache/http/protocol/HttpContext" +
";)TT;")]
T Execute<T>(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> responseHandler, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>A handler for determining if an HTTP request should be redirected to a new location in response to an HTTP response received from the target server.</para><para>Classes implementing this interface must synchronize access to shared data as methods of this interfrace may be executed from multiple threads </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/RedirectHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/client/RedirectHandler", AccessFlags = 1537)]
public partial interface IRedirectHandler
/* scope: __dot42__ */
{
/// <summary>
/// <para>Determines if a request should be redirected to a new location given the response from the target server.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the request should be redirected, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isRedirectRequested
/// </java-name>
[Dot42.DexImport("isRedirectRequested", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)]
bool IsRedirectRequested(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Determines the location request is expected to be redirected to given the response from the target server and the current request execution context.</para><para></para>
/// </summary>
/// <returns>
/// <para>redirect URI </para>
/// </returns>
/// <java-name>
/// getLocationURI
/// </java-name>
[Dot42.DexImport("getLocationURI", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/net/U" +
"RI;", AccessFlags = 1025)]
global::System.Uri GetLocationURI(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>A handler for determining if the given execution context is user specific or not. The token object returned by this handler is expected to uniquely identify the current user if the context is user specific or to be <code>null</code> if the context does not contain any resources or details specific to the current user. </para><para>The user token will be used to ensure that user specific resouces will not shared with or reused by other users.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/UserTokenHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/client/UserTokenHandler", AccessFlags = 1537)]
public partial interface IUserTokenHandler
/* scope: __dot42__ */
{
/// <summary>
/// <para>The token object returned by this method is expected to uniquely identify the current user if the context is user specific or to be <code>null</code> if it is not.</para><para></para>
/// </summary>
/// <returns>
/// <para>user token that uniquely identifies the user or <code>null</null> if the context is not user specific. </code></para>
/// </returns>
/// <java-name>
/// getUserToken
/// </java-name>
[Dot42.DexImport("getUserToken", "(Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025)]
object GetUserToken(global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Abstract cookie store.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/CookieStore
/// </java-name>
[Dot42.DexImport("org/apache/http/client/CookieStore", AccessFlags = 1537)]
public partial interface ICookieStore
/* scope: __dot42__ */
{
/// <summary>
/// <para>Adds an HTTP cookie, replacing any existing equivalent cookies. If the given cookie has already expired it will not be added, but existing values will still be removed.</para><para></para>
/// </summary>
/// <java-name>
/// addCookie
/// </java-name>
[Dot42.DexImport("addCookie", "(Lorg/apache/http/cookie/Cookie;)V", AccessFlags = 1025)]
void AddCookie(global::Org.Apache.Http.Cookie.ICookie cookie) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns all cookies contained in this store.</para><para></para>
/// </summary>
/// <returns>
/// <para>all cookies </para>
/// </returns>
/// <java-name>
/// getCookies
/// </java-name>
[Dot42.DexImport("getCookies", "()Ljava/util/List;", AccessFlags = 1025, Signature = "()Ljava/util/List<Lorg/apache/http/cookie/Cookie;>;")]
global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> GetCookies() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Removes all of cookies in this store that have expired by the specified date.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if any cookies were purged. </para>
/// </returns>
/// <java-name>
/// clearExpired
/// </java-name>
[Dot42.DexImport("clearExpired", "(Ljava/util/Date;)Z", AccessFlags = 1025)]
bool ClearExpired(global::Java.Util.Date date) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Clears all cookies. </para>
/// </summary>
/// <java-name>
/// clear
/// </java-name>
[Dot42.DexImport("clear", "()V", AccessFlags = 1025)]
void Clear() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Signals a circular redirect</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/CircularRedirectException
/// </java-name>
[Dot42.DexImport("org/apache/http/client/CircularRedirectException", AccessFlags = 33)]
public partial class CircularRedirectException : global::Org.Apache.Http.Client.RedirectException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new CircularRedirectException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CircularRedirectException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new CircularRedirectException with the specified detail message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CircularRedirectException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new CircularRedirectException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public CircularRedirectException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/AuthenticationHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/client/AuthenticationHandler", AccessFlags = 1537)]
public partial interface IAuthenticationHandler
/* scope: __dot42__ */
{
/// <java-name>
/// isAuthenticationRequested
/// </java-name>
[Dot42.DexImport("isAuthenticationRequested", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)]
bool IsAuthenticationRequested(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
/// <java-name>
/// getChallenges
/// </java-name>
[Dot42.DexImport("getChallenges", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/util/" +
"Map;", AccessFlags = 1025, Signature = "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/util/" +
"Map<Ljava/lang/String;Lorg/apache/http/Header;>;")]
global::Java.Util.IMap<string, global::Org.Apache.Http.IHeader> GetChallenges(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
/// <java-name>
/// selectScheme
/// </java-name>
[Dot42.DexImport("selectScheme", "(Ljava/util/Map;Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpConte" +
"xt;)Lorg/apache/http/auth/AuthScheme;", AccessFlags = 1025, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/Header;>;Lorg/apache/http/Http" +
"Response;Lorg/apache/http/protocol/HttpContext;)Lorg/apache/http/auth/AuthScheme" +
";")]
global::Org.Apache.Http.Auth.IAuthScheme SelectScheme(global::Java.Util.IMap<string, global::Org.Apache.Http.IHeader> challenges, global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Signals violation of HTTP specification caused by an invalid redirect</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/RedirectException
/// </java-name>
[Dot42.DexImport("org/apache/http/client/RedirectException", AccessFlags = 33)]
public partial class RedirectException : global::Org.Apache.Http.ProtocolException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new RedirectException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public RedirectException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new RedirectException with the specified detail message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public RedirectException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new RedirectException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public RedirectException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Signals a non 2xx HTTP response. </para>
/// </summary>
/// <java-name>
/// org/apache/http/client/HttpResponseException
/// </java-name>
[Dot42.DexImport("org/apache/http/client/HttpResponseException", AccessFlags = 33)]
public partial class HttpResponseException : global::Org.Apache.Http.Client.ClientProtocolException
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(ILjava/lang/String;)V", AccessFlags = 1)]
public HttpResponseException(int statusCode, string s) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getStatusCode
/// </java-name>
[Dot42.DexImport("getStatusCode", "()I", AccessFlags = 1)]
public virtual int GetStatusCode() /* MethodBuilder.Create */
{
return default(int);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal HttpResponseException() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getStatusCode
/// </java-name>
public int StatusCode
{
[Dot42.DexImport("getStatusCode", "()I", AccessFlags = 1)]
get{ return GetStatusCode(); }
}
}
}
| |
// 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.Dynamic.Utils;
using System.Reflection;
namespace System.Linq.Expressions.Interpreter
{
internal abstract class GreaterThanInstruction : Instruction
{
private readonly object _nullValue;
private static Instruction s_SByte, s_Int16, s_Char, s_Int32, s_Int64, s_Byte, s_UInt16, s_UInt32, s_UInt64, s_Single, s_Double;
private static Instruction s_liftedToNullSByte, s_liftedToNullInt16, s_liftedToNullChar, s_liftedToNullInt32, s_liftedToNullInt64, s_liftedToNullByte, s_liftedToNullUInt16, s_liftedToNullUInt32, s_liftedToNullUInt64, s_liftedToNullSingle, s_liftedToNullDouble;
public override int ConsumedStack => 2;
public override int ProducedStack => 1;
public override string InstructionName => "GreaterThan";
private GreaterThanInstruction(object nullValue)
{
_nullValue = nullValue;
}
private sealed class GreaterThanSByte : GreaterThanInstruction
{
public GreaterThanSByte(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((sbyte)left > (sbyte)right);
}
return 1;
}
}
private sealed class GreaterThanInt16 : GreaterThanInstruction
{
public GreaterThanInt16(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((short)left > (short)right);
}
return 1;
}
}
private sealed class GreaterThanChar : GreaterThanInstruction
{
public GreaterThanChar(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((char)left > (char)right);
}
return 1;
}
}
private sealed class GreaterThanInt32 : GreaterThanInstruction
{
public GreaterThanInt32(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((int)left > (int)right);
}
return 1;
}
}
private sealed class GreaterThanInt64 : GreaterThanInstruction
{
public GreaterThanInt64(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((long)left > (long)right);
}
return 1;
}
}
private sealed class GreaterThanByte : GreaterThanInstruction
{
public GreaterThanByte(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((byte)left > (byte)right);
}
return 1;
}
}
private sealed class GreaterThanUInt16 : GreaterThanInstruction
{
public GreaterThanUInt16(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((ushort)left > (ushort)right);
}
return 1;
}
}
private sealed class GreaterThanUInt32 : GreaterThanInstruction
{
public GreaterThanUInt32(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((uint)left > (uint)right);
}
return 1;
}
}
private sealed class GreaterThanUInt64 : GreaterThanInstruction
{
public GreaterThanUInt64(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((ulong)left > (ulong)right);
}
return 1;
}
}
private sealed class GreaterThanSingle : GreaterThanInstruction
{
public GreaterThanSingle(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((float)left > (float)right);
}
return 1;
}
}
private sealed class GreaterThanDouble : GreaterThanInstruction
{
public GreaterThanDouble(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((double)left > (double)right);
}
return 1;
}
}
public static Instruction Create(Type type, bool liftedToNull = false)
{
Debug.Assert(!type.IsEnum);
if (liftedToNull)
{
switch (type.GetNonNullableType().GetTypeCode())
{
case TypeCode.SByte: return s_liftedToNullSByte ?? (s_liftedToNullSByte = new GreaterThanSByte(null));
case TypeCode.Int16: return s_liftedToNullInt16 ?? (s_liftedToNullInt16 = new GreaterThanInt16(null));
case TypeCode.Char: return s_liftedToNullChar ?? (s_liftedToNullChar = new GreaterThanChar(null));
case TypeCode.Int32: return s_liftedToNullInt32 ?? (s_liftedToNullInt32 = new GreaterThanInt32(null));
case TypeCode.Int64: return s_liftedToNullInt64 ?? (s_liftedToNullInt64 = new GreaterThanInt64(null));
case TypeCode.Byte: return s_liftedToNullByte ?? (s_liftedToNullByte = new GreaterThanByte(null));
case TypeCode.UInt16: return s_liftedToNullUInt16 ?? (s_liftedToNullUInt16 = new GreaterThanUInt16(null));
case TypeCode.UInt32: return s_liftedToNullUInt32 ?? (s_liftedToNullUInt32 = new GreaterThanUInt32(null));
case TypeCode.UInt64: return s_liftedToNullUInt64 ?? (s_liftedToNullUInt64 = new GreaterThanUInt64(null));
case TypeCode.Single: return s_liftedToNullSingle ?? (s_liftedToNullSingle = new GreaterThanSingle(null));
case TypeCode.Double: return s_liftedToNullDouble ?? (s_liftedToNullDouble = new GreaterThanDouble(null));
default:
throw ContractUtils.Unreachable;
}
}
else
{
switch (type.GetNonNullableType().GetTypeCode())
{
case TypeCode.SByte: return s_SByte ?? (s_SByte = new GreaterThanSByte(Utils.BoxedFalse));
case TypeCode.Int16: return s_Int16 ?? (s_Int16 = new GreaterThanInt16(Utils.BoxedFalse));
case TypeCode.Char: return s_Char ?? (s_Char = new GreaterThanChar(Utils.BoxedFalse));
case TypeCode.Int32: return s_Int32 ?? (s_Int32 = new GreaterThanInt32(Utils.BoxedFalse));
case TypeCode.Int64: return s_Int64 ?? (s_Int64 = new GreaterThanInt64(Utils.BoxedFalse));
case TypeCode.Byte: return s_Byte ?? (s_Byte = new GreaterThanByte(Utils.BoxedFalse));
case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new GreaterThanUInt16(Utils.BoxedFalse));
case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new GreaterThanUInt32(Utils.BoxedFalse));
case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new GreaterThanUInt64(Utils.BoxedFalse));
case TypeCode.Single: return s_Single ?? (s_Single = new GreaterThanSingle(Utils.BoxedFalse));
case TypeCode.Double: return s_Double ?? (s_Double = new GreaterThanDouble(Utils.BoxedFalse));
default:
throw ContractUtils.Unreachable;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
namespace SOS
{
internal class SymbolReader
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct DebugInfo
{
public int lineNumber;
public int ilOffset;
public string fileName;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MethodDebugInfo
{
public IntPtr points;
public int size;
public IntPtr locals;
public int localsSize;
}
/// <summary>
/// Read memory callback
/// </summary>
/// <returns>number of bytes read or 0 for error</returns>
internal unsafe delegate int ReadMemoryDelegate(ulong address, byte* buffer, int count);
private sealed class OpenedReader : IDisposable
{
public readonly MetadataReaderProvider Provider;
public readonly MetadataReader Reader;
public OpenedReader(MetadataReaderProvider provider, MetadataReader reader)
{
Debug.Assert(provider != null);
Debug.Assert(reader != null);
Provider = provider;
Reader = reader;
}
public void Dispose() => Provider.Dispose();
}
/// <summary>
/// Stream implementation to read debugger target memory for in-memory PDBs
/// </summary>
private class TargetStream : Stream
{
readonly ulong _address;
readonly ReadMemoryDelegate _readMemory;
public override long Position { get; set; }
public override long Length { get; }
public override bool CanSeek { get { return true; } }
public override bool CanRead { get { return true; } }
public override bool CanWrite { get { return false; } }
public TargetStream(ulong address, int size, ReadMemoryDelegate readMemory)
: base()
{
_address = address;
_readMemory = readMemory;
Length = size;
Position = 0;
}
public override int Read(byte[] buffer, int offset, int count)
{
if (Position + count > Length)
{
throw new ArgumentOutOfRangeException();
}
unsafe
{
fixed (byte* p = &buffer[offset])
{
int read = _readMemory(_address + (ulong)Position, p, count);
Position += read;
return read;
}
}
}
public override long Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
Position = offset;
break;
case SeekOrigin.End:
Position = Length + offset;
break;
case SeekOrigin.Current:
Position += offset;
break;
}
return Position;
}
public override void Flush()
{
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Quick fix for Path.GetFileName which incorrectly handles Windows-style paths on Linux
/// </summary>
/// <param name="pathName"> File path to be processed </param>
/// <returns>Last component of path</returns>
private static string GetFileName(string pathName)
{
int pos = pathName.LastIndexOfAny(new char[] { '/', '\\'});
if (pos < 0)
return pathName;
return pathName.Substring(pos + 1);
}
/// <summary>
/// Checks availability of debugging information for given assembly.
/// </summary>
/// <param name="assemblyPath">
/// File path of the assembly or null if the module is in-memory or dynamic (generated by Reflection.Emit)
/// </param>
/// <param name="isFileLayout">type of in-memory PE layout, if true, file based layout otherwise, loaded layout</param>
/// <param name="loadedPeAddress">
/// Loaded PE image address or zero if the module is dynamic (generated by Reflection.Emit).
/// Dynamic modules have their PDBs (if any) generated to an in-memory stream
/// (pointed to by <paramref name="inMemoryPdbAddress"/> and <paramref name="inMemoryPdbSize"/>).
/// </param>
/// <param name="loadedPeSize">loaded PE image size</param>
/// <param name="inMemoryPdbAddress">in memory PDB address or zero</param>
/// <param name="inMemoryPdbSize">in memory PDB size</param>
/// <returns>Symbol reader handle or zero if error</returns>
internal static IntPtr LoadSymbolsForModule(string assemblyPath, bool isFileLayout, ulong loadedPeAddress, int loadedPeSize,
ulong inMemoryPdbAddress, int inMemoryPdbSize, ReadMemoryDelegate readMemory)
{
try
{
TargetStream peStream = null;
if (assemblyPath == null && loadedPeAddress != 0)
{
peStream = new TargetStream(loadedPeAddress, loadedPeSize, readMemory);
}
TargetStream pdbStream = null;
if (inMemoryPdbAddress != 0)
{
pdbStream = new TargetStream(inMemoryPdbAddress, inMemoryPdbSize, readMemory);
}
OpenedReader openedReader = GetReader(assemblyPath, isFileLayout, peStream, pdbStream);
if (openedReader != null)
{
GCHandle gch = GCHandle.Alloc(openedReader);
return GCHandle.ToIntPtr(gch);
}
}
catch
{
}
return IntPtr.Zero;
}
/// <summary>
/// Cleanup and dispose of symbol reader handle
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
internal static void Dispose(IntPtr symbolReaderHandle)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
try
{
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
((OpenedReader)gch.Target).Dispose();
gch.Free();
}
catch
{
}
}
/// <summary>
/// Returns method token and IL offset for given source line number.
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
/// <param name="filePath">source file name and path</param>
/// <param name="lineNumber">source line number</param>
/// <param name="methodToken">method token return</param>
/// <param name="ilOffset">IL offset return</param>
/// <returns> true if information is available</returns>
internal static bool ResolveSequencePoint(IntPtr symbolReaderHandle, string filePath, int lineNumber, out int methodToken, out int ilOffset)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
methodToken = 0;
ilOffset = 0;
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
MetadataReader reader = ((OpenedReader)gch.Target).Reader;
try
{
string fileName = GetFileName(filePath);
foreach (MethodDebugInformationHandle methodDebugInformationHandle in reader.MethodDebugInformation)
{
MethodDebugInformation methodDebugInfo = reader.GetMethodDebugInformation(methodDebugInformationHandle);
SequencePointCollection sequencePoints = methodDebugInfo.GetSequencePoints();
foreach (SequencePoint point in sequencePoints)
{
string sourceName = reader.GetString(reader.GetDocument(point.Document).Name);
if (point.StartLine == lineNumber && GetFileName(sourceName) == fileName)
{
methodToken = MetadataTokens.GetToken(methodDebugInformationHandle.ToDefinitionHandle());
ilOffset = point.Offset;
return true;
}
}
}
}
catch
{
}
return false;
}
/// <summary>
/// Returns source line number and source file name for given IL offset and method token.
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
/// <param name="methodToken">method token</param>
/// <param name="ilOffset">IL offset</param>
/// <param name="lineNumber">source line number return</param>
/// <param name="fileName">source file name return</param>
/// <returns> true if information is available</returns>
internal static bool GetLineByILOffset(IntPtr symbolReaderHandle, int methodToken, long ilOffset, out int lineNumber, out IntPtr fileName)
{
lineNumber = 0;
fileName = IntPtr.Zero;
string sourceFileName = null;
if (!GetSourceLineByILOffset(symbolReaderHandle, methodToken, ilOffset, out lineNumber, out sourceFileName))
{
return false;
}
fileName = Marshal.StringToBSTR(sourceFileName);
sourceFileName = null;
return true;
}
/// <summary>
/// Helper method to return source line number and source file name for given IL offset and method token.
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
/// <param name="methodToken">method token</param>
/// <param name="ilOffset">IL offset</param>
/// <param name="lineNumber">source line number return</param>
/// <param name="fileName">source file name return</param>
/// <returns> true if information is available</returns>
private static bool GetSourceLineByILOffset(IntPtr symbolReaderHandle, int methodToken, long ilOffset, out int lineNumber, out string fileName)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
lineNumber = 0;
fileName = null;
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
MetadataReader reader = ((OpenedReader)gch.Target).Reader;
try
{
Handle handle = MetadataTokens.Handle(methodToken);
if (handle.Kind != HandleKind.MethodDefinition)
return false;
MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
MethodDebugInformation methodDebugInfo = reader.GetMethodDebugInformation(methodDebugHandle);
SequencePointCollection sequencePoints = methodDebugInfo.GetSequencePoints();
SequencePoint nearestPoint = sequencePoints.GetEnumerator().Current;
foreach (SequencePoint point in sequencePoints)
{
if (point.Offset < ilOffset)
{
nearestPoint = point;
}
else
{
if (point.Offset == ilOffset)
nearestPoint = point;
if (nearestPoint.StartLine == 0 || nearestPoint.StartLine == SequencePoint.HiddenLine)
return false;
lineNumber = nearestPoint.StartLine;
fileName = reader.GetString(reader.GetDocument(nearestPoint.Document).Name);
return true;
}
}
}
catch
{
}
return false;
}
/// <summary>
/// Returns local variable name for given local index and IL offset.
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
/// <param name="methodToken">method token</param>
/// <param name="localIndex">local variable index</param>
/// <param name="localVarName">local variable name return</param>
/// <returns>true if name has been found</returns>
internal static bool GetLocalVariableName(IntPtr symbolReaderHandle, int methodToken, int localIndex, out IntPtr localVarName)
{
localVarName = IntPtr.Zero;
string localVar = null;
if (!GetLocalVariableByIndex(symbolReaderHandle, methodToken, localIndex, out localVar))
return false;
localVarName = Marshal.StringToBSTR(localVar);
localVar = null;
return true;
}
/// <summary>
/// Helper method to return local variable name for given local index and IL offset.
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
/// <param name="methodToken">method token</param>
/// <param name="localIndex">local variable index</param>
/// <param name="localVarName">local variable name return</param>
/// <returns>true if name has been found</returns>
internal static bool GetLocalVariableByIndex(IntPtr symbolReaderHandle, int methodToken, int localIndex, out string localVarName)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
localVarName = null;
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
MetadataReader reader = ((OpenedReader)gch.Target).Reader;
try
{
Handle handle = MetadataTokens.Handle(methodToken);
if (handle.Kind != HandleKind.MethodDefinition)
return false;
MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
LocalScopeHandleCollection localScopes = reader.GetLocalScopes(methodDebugHandle);
foreach (LocalScopeHandle scopeHandle in localScopes)
{
LocalScope scope = reader.GetLocalScope(scopeHandle);
LocalVariableHandleCollection localVars = scope.GetLocalVariables();
foreach (LocalVariableHandle varHandle in localVars)
{
LocalVariable localVar = reader.GetLocalVariable(varHandle);
if (localVar.Index == localIndex)
{
if (localVar.Attributes == LocalVariableAttributes.DebuggerHidden)
return false;
localVarName = reader.GetString(localVar.Name);
return true;
}
}
}
}
catch
{
}
return false;
}
internal static bool GetLocalsInfoForMethod(string assemblyPath, int methodToken, out List<string> locals)
{
locals = null;
OpenedReader openedReader = GetReader(assemblyPath, isFileLayout: true, peStream: null, pdbStream: null);
if (openedReader == null)
return false;
using (openedReader)
{
try
{
Handle handle = MetadataTokens.Handle(methodToken);
if (handle.Kind != HandleKind.MethodDefinition)
return false;
locals = new List<string>();
MethodDebugInformationHandle methodDebugHandle =
((MethodDefinitionHandle)handle).ToDebugInformationHandle();
LocalScopeHandleCollection localScopes = openedReader.Reader.GetLocalScopes(methodDebugHandle);
foreach (LocalScopeHandle scopeHandle in localScopes)
{
LocalScope scope = openedReader.Reader.GetLocalScope(scopeHandle);
LocalVariableHandleCollection localVars = scope.GetLocalVariables();
foreach (LocalVariableHandle varHandle in localVars)
{
LocalVariable localVar = openedReader.Reader.GetLocalVariable(varHandle);
if (localVar.Attributes == LocalVariableAttributes.DebuggerHidden)
continue;
locals.Add(openedReader.Reader.GetString(localVar.Name));
}
}
}
catch
{
return false;
}
}
return true;
}
/// <summary>
/// Returns source name, line numbers and IL offsets for given method token.
/// </summary>
/// <param name="assemblyPath">file path of the assembly</param>
/// <param name="methodToken">method token</param>
/// <param name="debugInfo">structure with debug information return</param>
/// <returns>true if information is available</returns>
/// <remarks>used by the gdb JIT support (not SOS). Does not support in-memory PEs or PDBs</remarks>
internal static bool GetInfoForMethod(string assemblyPath, int methodToken, ref MethodDebugInfo debugInfo)
{
try
{
List<DebugInfo> points = null;
List<string> locals = null;
if (!GetDebugInfoForMethod(assemblyPath, methodToken, out points))
{
return false;
}
if (!GetLocalsInfoForMethod(assemblyPath, methodToken, out locals))
{
return false;
}
var structSize = Marshal.SizeOf<DebugInfo>();
debugInfo.size = points.Count;
var ptr = debugInfo.points;
foreach (var info in points)
{
Marshal.StructureToPtr(info, ptr, false);
ptr = (IntPtr)(ptr.ToInt64() + structSize);
}
debugInfo.localsSize = locals.Count;
debugInfo.locals = Marshal.AllocHGlobal(debugInfo.localsSize * Marshal.SizeOf<IntPtr>());
IntPtr ptrLocals = debugInfo.locals;
foreach (string s in locals)
{
Marshal.WriteIntPtr(ptrLocals, Marshal.StringToHGlobalUni(s));
ptrLocals += Marshal.SizeOf<IntPtr>();
}
return true;
}
catch
{
}
return false;
}
/// <summary>
/// Helper method to return source name, line numbers and IL offsets for given method token.
/// </summary>
/// <param name="assemblyPath">file path of the assembly</param>
/// <param name="methodToken">method token</param>
/// <param name="points">list of debug information for each sequence point return</param>
/// <returns>true if information is available</returns>
/// <remarks>used by the gdb JIT support (not SOS). Does not support in-memory PEs or PDBs</remarks>
private static bool GetDebugInfoForMethod(string assemblyPath, int methodToken, out List<DebugInfo> points)
{
points = null;
OpenedReader openedReader = GetReader(assemblyPath, isFileLayout: true, peStream: null, pdbStream: null);
if (openedReader == null)
return false;
using (openedReader)
{
try
{
Handle handle = MetadataTokens.Handle(methodToken);
if (handle.Kind != HandleKind.MethodDefinition)
return false;
points = new List<DebugInfo>();
MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
MethodDebugInformation methodDebugInfo = openedReader.Reader.GetMethodDebugInformation(methodDebugHandle);
SequencePointCollection sequencePoints = methodDebugInfo.GetSequencePoints();
foreach (SequencePoint point in sequencePoints)
{
DebugInfo debugInfo = new DebugInfo();
debugInfo.lineNumber = point.StartLine;
debugInfo.fileName = GetFileName(openedReader.Reader.GetString(openedReader.Reader.GetDocument(point.Document).Name));
debugInfo.ilOffset = point.Offset;
points.Add(debugInfo);
}
}
catch
{
return false;
}
}
return true;
}
/// <summary>
/// Returns the portable PDB reader for the assembly path
/// </summary>
/// <param name="assemblyPath">file path of the assembly or null if the module is in-memory or dynamic</param>
/// <param name="isFileLayout">type of in-memory PE layout, if true, file based layout otherwise, loaded layout</param>
/// <param name="peStream">optional in-memory PE stream</param>
/// <param name="pdbStream">optional in-memory PDB stream</param>
/// <returns>reader/provider wrapper instance</returns>
/// <remarks>
/// Assumes that neither PE image nor PDB loaded into memory can be unloaded or moved around.
/// </remarks>
private static OpenedReader GetReader(string assemblyPath, bool isFileLayout, Stream peStream, Stream pdbStream)
{
return (pdbStream != null) ? TryOpenReaderForInMemoryPdb(pdbStream) : TryOpenReaderFromAssembly(assemblyPath, isFileLayout, peStream);
}
private static OpenedReader TryOpenReaderForInMemoryPdb(Stream pdbStream)
{
Debug.Assert(pdbStream != null);
byte[] buffer = new byte[sizeof(uint)];
if (pdbStream.Read(buffer, 0, sizeof(uint)) != sizeof(uint))
{
return null;
}
uint signature = BitConverter.ToUInt32(buffer, 0);
// quick check to avoid throwing exceptions below in common cases:
const uint ManagedMetadataSignature = 0x424A5342;
if (signature != ManagedMetadataSignature)
{
// not a Portable PDB
return null;
}
OpenedReader result = null;
MetadataReaderProvider provider = null;
try
{
pdbStream.Position = 0;
provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream);
result = new OpenedReader(provider, provider.GetMetadataReader());
}
catch (Exception e) when (e is BadImageFormatException || e is IOException)
{
return null;
}
finally
{
if (result == null)
{
provider?.Dispose();
}
}
return result;
}
private static OpenedReader TryOpenReaderFromAssembly(string assemblyPath, bool isFileLayout, Stream peStream)
{
if (assemblyPath == null && peStream == null)
return null;
PEStreamOptions options = isFileLayout ? PEStreamOptions.Default : PEStreamOptions.IsLoadedImage;
if (peStream == null)
{
peStream = TryOpenFile(assemblyPath);
if (peStream == null)
return null;
options = PEStreamOptions.Default;
}
try
{
using (var peReader = new PEReader(peStream, options))
{
DebugDirectoryEntry codeViewEntry, embeddedPdbEntry;
ReadPortableDebugTableEntries(peReader, out codeViewEntry, out embeddedPdbEntry);
// First try .pdb file specified in CodeView data (we prefer .pdb file on disk over embedded PDB
// since embedded PDB needs decompression which is less efficient than memory-mapping the file).
if (codeViewEntry.DataSize != 0)
{
var result = TryOpenReaderFromCodeView(peReader, codeViewEntry, assemblyPath);
if (result != null)
{
return result;
}
}
// if it failed try Embedded Portable PDB (if available):
if (embeddedPdbEntry.DataSize != 0)
{
return TryOpenReaderFromEmbeddedPdb(peReader, embeddedPdbEntry);
}
}
}
catch (Exception e) when (e is BadImageFormatException || e is IOException)
{
// nop
}
return null;
}
private static void ReadPortableDebugTableEntries(PEReader peReader, out DebugDirectoryEntry codeViewEntry, out DebugDirectoryEntry embeddedPdbEntry)
{
// See spec: https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/PE-COFF.md
codeViewEntry = default(DebugDirectoryEntry);
embeddedPdbEntry = default(DebugDirectoryEntry);
foreach (DebugDirectoryEntry entry in peReader.ReadDebugDirectory())
{
if (entry.Type == DebugDirectoryEntryType.CodeView)
{
const ushort PortableCodeViewVersionMagic = 0x504d;
if (entry.MinorVersion != PortableCodeViewVersionMagic)
{
continue;
}
codeViewEntry = entry;
}
else if (entry.Type == DebugDirectoryEntryType.EmbeddedPortablePdb)
{
embeddedPdbEntry = entry;
}
}
}
private static OpenedReader TryOpenReaderFromCodeView(PEReader peReader, DebugDirectoryEntry codeViewEntry, string assemblyPath)
{
OpenedReader result = null;
MetadataReaderProvider provider = null;
try
{
var data = peReader.ReadCodeViewDebugDirectoryData(codeViewEntry);
string pdbPath = data.Path;
if (assemblyPath != null)
{
try
{
pdbPath = Path.Combine(Path.GetDirectoryName(assemblyPath), GetFileName(pdbPath));
}
catch
{
// invalid characters in CodeView path
return null;
}
}
var pdbStream = TryOpenFile(pdbPath);
if (pdbStream == null)
{
return null;
}
provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream);
var reader = provider.GetMetadataReader();
// Validate that the PDB matches the assembly version
if (data.Age == 1 && new BlobContentId(reader.DebugMetadataHeader.Id) == new BlobContentId(data.Guid, codeViewEntry.Stamp))
{
result = new OpenedReader(provider, reader);
}
}
catch (Exception e) when (e is BadImageFormatException || e is IOException)
{
return null;
}
finally
{
if (result == null)
{
provider?.Dispose();
}
}
return result;
}
private static OpenedReader TryOpenReaderFromEmbeddedPdb(PEReader peReader, DebugDirectoryEntry embeddedPdbEntry)
{
OpenedReader result = null;
MetadataReaderProvider provider = null;
try
{
// TODO: We might want to cache this provider globally (across stack traces),
// since decompressing embedded PDB takes some time.
provider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embeddedPdbEntry);
result = new OpenedReader(provider, provider.GetMetadataReader());
}
catch (Exception e) when (e is BadImageFormatException || e is IOException)
{
return null;
}
finally
{
if (result == null)
{
provider?.Dispose();
}
}
return result;
}
private static Stream TryOpenFile(string path)
{
if (!File.Exists(path))
{
return null;
}
try
{
return File.OpenRead(path);
}
catch
{
return null;
}
}
}
}
| |
/*
** Copyright (c) Microsoft. All rights reserved.
** Licensed under the MIT license.
** See LICENSE file in the project root for full license information.
**
** This program was translated to C# and adapted for xunit-performance.
** New variants of several tests were added to compare class versus
** struct and to compare jagged arrays vs multi-dimensional arrays.
*/
/*
** BYTEmark (tm)
** BYTE Magazine's Native Mode benchmarks
** Rick Grehan, BYTE Magazine
**
** Create:
** Revision: 3/95
**
** DISCLAIMER
** The source, executable, and documentation files that comprise
** the BYTEmark benchmarks are made available on an "as is" basis.
** This means that we at BYTE Magazine have made every reasonable
** effort to verify that the there are no errors in the source and
** executable code. We cannot, however, guarantee that the programs
** are error-free. Consequently, McGraw-HIll and BYTE Magazine make
** no claims in regard to the fitness of the source code, executable
** code, and documentation of the BYTEmark.
**
** Furthermore, BYTE Magazine, McGraw-Hill, and all employees
** of McGraw-Hill cannot be held responsible for any damages resulting
** from the use of this code or the results obtained from using
** this code.
*/
using System;
/***********************
** LU DECOMPOSITION **
** (Linear Equations) **
************************
** These routines come from "Numerical Recipes in Pascal".
** Note that, as in the assignment algorithm, though we
** separately define LUARRAYROWS and LUARRAYCOLS, the two
** must be the same value (this routine depends on a square
** matrix).
*/
internal class LUDecomp : LUStruct
{
private const int MAXLUARRAYS = 1000;
private static double[] s_LUtempvv;
public override string Name()
{
return "LU DECOMPOSITION";
}
public override double Run()
{
double[][] a;
double[] b;
double[][][] abase = null;
double[][] bbase = null;
int n;
int i;
long accumtime;
double iterations;
/*
** Our first step is to build a "solvable" problem. This
** will become the "seed" set that all others will be
** derived from. (I.E., we'll simply copy these arrays
** into the others.
*/
a = new double[global.LUARRAYROWS][];
for (int j = 0; j < global.LUARRAYROWS; j++)
{
a[j] = new double[global.LUARRAYCOLS];
}
b = new double[global.LUARRAYROWS];
n = global.LUARRAYROWS;
s_LUtempvv = new double[global.LUARRAYROWS];
build_problem(a, n, b);
if (this.adjust == 0)
{
for (i = 1; i <= MAXLUARRAYS; i++)
{
abase = new double[i + 1][][];
for (int j = 0; j < i + 1; j++)
{
abase[j] = new double[global.LUARRAYROWS][];
for (int k = 0; k < global.LUARRAYROWS; k++)
{
abase[j][k] = new double[global.LUARRAYCOLS];
}
}
bbase = new double[i + 1][];
for (int j = 0; j < i + 1; j++)
{
bbase[j] = new double[global.LUARRAYROWS];
}
if (DoLUIteration(a, b, abase, bbase, i) > global.min_ticks)
{
this.numarrays = i;
break;
}
}
if (this.numarrays == 0)
{
throw new Exception("FPU:LU -- Array limit reached");
}
}
else
{
abase = new double[this.numarrays][][];
for (int j = 0; j < this.numarrays; j++)
{
abase[j] = new double[global.LUARRAYROWS][];
for (int k = 0; k < global.LUARRAYROWS; k++)
{
abase[j][k] = new double[global.LUARRAYCOLS];
}
}
bbase = new double[this.numarrays][];
for (int j = 0; j < this.numarrays; j++)
{
bbase[j] = new double[global.LUARRAYROWS];
}
}
accumtime = 0;
iterations = 0.0;
do
{
accumtime += DoLUIteration(a, b, abase, bbase, this.numarrays);
iterations += (double)this.numarrays;
} while (ByteMark.TicksToSecs(accumtime) < this.request_secs);
if (this.adjust == 0) this.adjust = 1;
return iterations / ByteMark.TicksToFracSecs(accumtime);
}
private static long DoLUIteration(double[][] a, double[] b, double[][][] abase, double[][] bbase, int numarrays)
{
double[][] locabase;
double[] locbbase;
long elapsed;
int k, j, i;
for (j = 0; j < numarrays; j++)
{
locabase = abase[j];
locbbase = bbase[j];
for (i = 0; i < global.LUARRAYROWS; i++)
for (k = 0; k < global.LUARRAYCOLS; k++)
locabase[i][k] = a[i][k];
for (i = 0; i < global.LUARRAYROWS; i++)
locbbase[i] = b[i];
}
elapsed = ByteMark.StartStopwatch();
for (i = 0; i < numarrays; i++)
{
locabase = abase[i];
locbbase = bbase[i];
lusolve(locabase, global.LUARRAYROWS, locbbase);
}
return (ByteMark.StopStopwatch(elapsed));
}
private static void build_problem(double[][] a, int n, double[] b)
{
int i, j, k, k1;
double rcon;
ByteMark.randnum(13);
for (i = 0; i < n; i++)
{
b[i] = (double)(ByteMark.abs_randwc(100) + 1);
for (j = 0; j < n; j++)
if (i == j)
a[i][j] = (double)(ByteMark.abs_randwc(1000) + 1);
else
a[i][j] = (double)0.0;
}
for (i = 0; i < 8 * n; i++)
{
k = ByteMark.abs_randwc(n);
k1 = ByteMark.abs_randwc(n);
if (k != k1)
{
if (k < k1) rcon = 1.0;
else rcon = -1.0;
for (j = 0; j < n; j++)
a[k][j] += a[k1][j] * rcon;
b[k] += b[k1] * rcon;
}
}
}
private static int ludcmp(double[][] a, int n, int[] indx, out int d)
{
double big;
double sum;
double dum;
int i, j, k;
int imax = 0;
double tiny;
tiny = 1.0e-20;
d = 1;
for (i = 0; i < n; i++)
{
big = 0.0;
for (j = 0; j < n; j++)
if (Math.Abs(a[i][j]) > big)
big = Math.Abs(a[i][j]);
if (big == 0.0) return 0;
s_LUtempvv[i] = 1.0 / big;
}
for (j = 0; j < n; j++)
{
if (j != 0)
for (i = 0; i < j; i++)
{
sum = a[i][j];
if (i != 0)
for (k = 0; k < i; k++)
sum -= a[i][k] * a[k][j];
a[i][j] = sum;
}
big = 0.0;
for (i = j; i < n; i++)
{
sum = a[i][j];
if (j != 0)
for (k = 0; k < j; k++)
sum -= a[i][k] * a[k][j];
a[i][j] = sum;
dum = s_LUtempvv[i] * Math.Abs(sum);
if (dum >= big)
{
big = dum;
imax = i;
}
}
if (j != imax)
{
for (k = 0; k < n; k++)
{
dum = a[imax][k];
a[imax][k] = a[j][k];
a[j][k] = dum;
}
d = -d;
dum = s_LUtempvv[imax];
s_LUtempvv[imax] = s_LUtempvv[j];
s_LUtempvv[j] = dum;
}
indx[j] = imax;
if (a[j][j] == 0.0)
a[j][j] = tiny;
if (j != (n - 1))
{
dum = 1.0 / a[j][j];
for (i = j + 1; i < n; i++)
a[i][j] = a[i][j] * dum;
}
}
return 1;
}
private static void lubksb(double[][] a, int n, int[] indx, double[] b)
{
int i, j;
int ip;
int ii;
double sum;
ii = -1;
for (i = 0; i < n; i++)
{
ip = indx[i];
sum = b[ip];
b[ip] = b[i];
if (ii != -1)
for (j = ii; j < i; j++)
sum = sum - a[i][j] * b[j];
else
if (sum != (double)0.0)
ii = i;
b[i] = sum;
}
for (i = (n - 1); i >= 0; i--)
{
sum = b[i];
if (i != (n - 1))
for (j = (i + 1); j < n; j++)
sum = sum - a[i][j] * b[j];
b[i] = sum / a[i][i];
}
}
private static int lusolve(double[][] a, int n, double[] b)
{
int[] indx = new int[global.LUARRAYROWS];
int d;
if (ludcmp(a, n, indx, out d) == 0) return 0;
lubksb(a, n, indx, b);
return 1;
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Diagnostics;
namespace Irony.Parsing {
// CoreParser class implements LALR parser automaton. Its behavior is controlled by the state transition graph
// with root in Data.InitialState. Each state contains a dictionary of parser actions indexed by input
// element (terminal or non-terminal).
public partial class CoreParser {
#region Constructors
public CoreParser(Parser parser) {
Parser = parser;
Data = parser.Language.ParserData;
_grammar = Data.Language.Grammar;
}
#endregion
#region Properties and fields: Parser, Data, _grammar
public readonly Parser Parser;
public readonly ParserData Data;
Grammar _grammar;
bool _traceEnabled;
private ParsingContext Context {
get { return Parser.Context; }
}
#endregion
internal void Reset() {
}
#region Parse method
public void Parse() {
//main loop
Context.Status = ParserStatus.Parsing;
while(Context.Status == ParserStatus.Parsing) {
ExecuteAction();
}
}//Parse
#endregion
#region reading input
private void ReadInput() {
if (Context.ParserInputStack.Count > 0)
Context.ParserInputStack.Pop();
if (Context.ParserInputStack.Count > 0) {
Context.CurrentParserInput = Context.ParserInputStack.Top;
return;
}
FetchToken();
}
private void FetchToken() {
var token = GetScannerToken();
if (token.Terminal.Flags.IsSet(TermFlags.IsBrace))
token = CheckBraceToken(token);
Context.CurrentParserInput = new ParseTreeNode(token);
//attach comments if any accumulated to content token
if (Context.CurrentCommentBlock != null && token.Terminal.Category == TokenCategory.Content) {
Context.CurrentParserInput.Comments = Context.CurrentCommentBlock;
Context.CurrentCommentBlock = null;
}
Context.ParserInputStack.Push(Context.CurrentParserInput);
}
// Reads token from scanner, skips all non-grammar tokens but accumulates comment tokens in CurrentCommentBlock
private Token GetScannerToken() {
Token token;
Terminal term;
do {
token = Parser.Scanner.GetToken();
term = token.Terminal;
if (term.Category == TokenCategory.Comment) {
if (Context.CurrentCommentBlock == null) Context.CurrentCommentBlock = new CommentBlock();
Context.CurrentCommentBlock.Tokens.Add(token);
}
} while (term.Flags.IsSet(TermFlags.IsNonGrammar) && term != _grammar.Eof);
return token;
}
#endregion
#region execute actions
private void ExecuteAction() {
_traceEnabled = Context.Options.IsSet(ParseOptions.TraceParser);
//Read input only if DefaultReduceAction is null - in this case the state does not contain ExpectedSet,
// so parser cannot assist scanner when it needs to select terminal and therefore can fail
if (Context.CurrentParserInput == null && Context.CurrentParserState.DefaultAction == null)
ReadInput();
//Check scanner error
if (Context.CurrentParserInput != null && Context.CurrentParserInput.IsError) {
ProcessParserError();
return;
}
//Try getting action
var action = FindActionForStateAndInput();
if (action == null) {
if (CheckPartialInputCompleted())
return;
ProcessParserError();
return;
}
//We have action. First, write trace
if (_traceEnabled) Context.AddTrace("{0}", action);
//Execute it
switch (action.ActionType) {
case ParserActionType.Shift: ExecuteShift(action); break;
case ParserActionType.Operator: ExecuteOperatorAction(action); break;
case ParserActionType.Reduce: ExecuteReduce(action); break;
case ParserActionType.Code: ExecuteConflictAction(action); break;
case ParserActionType.Accept: ExecuteAccept(action); break;
}
}
private bool CheckPartialInputCompleted() {
bool partialCompleted = (Context.Mode == ParseMode.CommandLine && Context.CurrentParserInput.Term == _grammar.Eof);
if (!partialCompleted) return false;
Context.Status = ParserStatus.AcceptedPartial;
// clean up EOF in input so we can continue parsing next line
Context.CurrentParserInput = null;
Context.ParserInputStack.Pop();
return true;
}
private ParserAction FindActionForStateAndInput() {
if (Context.CurrentParserState.DefaultAction != null)
return Context.CurrentParserState.DefaultAction;
ParserAction action;
//First try as keyterm/key symbol; for example if token text = "while", then first try it as a keyword "while";
// if this does not work, try as an identifier that happens to match a keyword but is in fact identifier
Token inputToken = Context.CurrentParserInput.Token;
if (inputToken != null && inputToken.KeyTerm != null) {
var keyTerm = inputToken.KeyTerm;
if (Context.CurrentParserState.Actions.TryGetValue(keyTerm, out action)) {
#region comments
// Ok, we found match as a key term (keyword or special symbol)
// Backpatch the token's term. For example in most cases keywords would be recognized as Identifiers by Scanner.
// Identifier would also check with SymbolTerms table and set AsSymbol field to SymbolTerminal if there exist
// one for token content. So we first find action by Symbol if there is one; if we find action, then we
// patch token's main terminal to AsSymbol value. This is important for recognizing keywords (for colorizing),
// and for operator precedence algorithm to work when grammar uses operators like "AND", "OR", etc.
//TODO: This might be not quite correct action, and we can run into trouble with some languages that have keywords that
// are not reserved words. But proper implementation would require substantial addition to parser code:
// when running into errors, we need to check the stack for places where we made this "interpret as Symbol"
// decision, roll back the stack and try to reinterpret as identifier
#endregion
inputToken.SetTerminal(keyTerm);
Context.CurrentParserInput.Term = keyTerm;
Context.CurrentParserInput.Precedence = keyTerm.Precedence;
Context.CurrentParserInput.Associativity = keyTerm.Associativity;
return action;
}
}
//Try to get by main Terminal, only if it is not the same as symbol
if (Context.CurrentParserState.Actions.TryGetValue(Context.CurrentParserInput.Term, out action))
return action;
//If input is EOF and NewLineBeforeEof flag is set, try injecting NewLine into input
if (Context.CurrentParserInput.Term == _grammar.Eof && _grammar.LanguageFlags.IsSet(LanguageFlags.NewLineBeforeEOF) &&
Context.CurrentParserState.Actions.TryGetValue(_grammar.NewLine, out action)) {
InjectNewLineToken();
return action;
}//if
return null;
}
private void InjectNewLineToken() {
var newLineToken = new Token(_grammar.NewLine, Context.CurrentParserInput.Token.Location, "\r\n", null);
var newLineNode = new ParseTreeNode(newLineToken);
Context.ParserInputStack.Push(newLineNode);
Context.CurrentParserInput = newLineNode;
}
private void ExecuteShift(ParserAction action) {
Context.ParserStack.Push(Context.CurrentParserInput, action.NewState);
Context.CurrentParserState = action.NewState;
Context.CurrentParserInput = null;
if (action.NewState.DefaultAction == null) //read only if new state is NOT single-reduce state
ReadInput();
}
#region ExecuteReduce
private void ExecuteReduce(ParserAction action) {
var reduceProduction = action.ReduceProduction;
ParseTreeNode resultNode;
if(reduceProduction.IsSet(ProductionFlags.IsListBuilder))
resultNode = ReduceExistingList(action);
else if(reduceProduction.LValue.Flags.IsSet(TermFlags.IsListContainer))
resultNode = ReduceListContainer(action);
else if (reduceProduction.LValue.Flags.IsSet(TermFlags.IsTransient))
resultNode = ReduceTransientNonTerminal(action);
else
resultNode = ReduceRegularNode(action);
//final reduce actions ----------------------------------------------------------
Context.ParserStack.Pop(reduceProduction.RValues.Count);
//Push new node into stack and move to new state
//First read the state from top of the stack
Context.CurrentParserState = Context.ParserStack.Top.State;
if (_traceEnabled) Context.AddTrace(Resources.MsgTracePoppedState, reduceProduction.LValue.Name);
// Shift to new state (LALR) - execute shift over non-terminal
var shift = Context.CurrentParserState.Actions[reduceProduction.LValue];
Context.ParserStack.Push(resultNode, shift.NewState);
Context.CurrentParserState = shift.NewState;
//Copy comment block from first child; if comments precede child node, they precede the parent as well.
if (resultNode.ChildNodes.Count > 0)
resultNode.Comments = resultNode.ChildNodes[0].Comments;
//Invoke event
reduceProduction.LValue.OnReduced(Context, reduceProduction, resultNode);
}
private ParseTreeNode ReduceExistingList(ParserAction action) {
int childCount = action.ReduceProduction.RValues.Count;
int firstChildIndex = Context.ParserStack.Count - childCount;
var listNode = Context.ParserStack[firstChildIndex]; //get the list already created - it is the first child node
listNode.Span = ComputeNewNodeSpan(childCount);
var listMember = Context.ParserStack.Top; //next list member is the last child - at the top of the stack
if (ShouldSkipChildNode(listMember))
return listNode;
CheckCreateAstNode(listMember);
listNode.ChildNodes.Add(listMember);
return listNode;
}
// Skip punctuation and empty transient nodes
private bool ShouldSkipChildNode(ParseTreeNode childNode) {
if (childNode.Term.Flags.IsSet(TermFlags.IsPunctuation))
return true;
if (childNode.Term.Flags.IsSet(TermFlags.IsTransient) && childNode.ChildNodes.Count == 0)
return true;
return false;
}
//List container is created by MakePlusRule, MakeStarRule with allowTrailingDelimiter = true
// it is a special case for parser. The "real" list in grammar is the "container", but list members had been accumulated under
// the transient "plus-list" which is a child of this container. So we need to copy all "grandchildren" from child to parent.
private ParseTreeNode ReduceListContainer(ParserAction action) {
int childCount = action.ReduceProduction.RValues.Count;
int firstChildIndex = Context.ParserStack.Count - childCount;
var span = ComputeNewNodeSpan(childCount);
var newNode = new ParseTreeNode(action.ReduceProduction, span);
if(childCount > 0) { //if it is not empty production - might happen for MakeStarRule
var listNode = Context.ParserStack[firstChildIndex]; //get the transient list with all members - it is the first child node
newNode.ChildNodes.AddRange(listNode.ChildNodes); //copy all list members
}
return newNode;
}
private ParseTreeNode ReduceTransientNonTerminal(ParserAction action) {
var topIndex = Context.ParserStack.Count - 1;
var childCount = action.ReduceProduction.RValues.Count;
for(int i = 0; i < childCount; i++) {
var child = Context.ParserStack[topIndex - i];
if (ShouldSkipChildNode(child)) continue;
CheckCreateAstNode(child);
return child;
}
//Otherwise return an empty transient node; if it is part of the list, the list will skip it
var span = ComputeNewNodeSpan(childCount);
return new ParseTreeNode(action.ReduceProduction, span);
}
// Note that we create AST nodes
private ParseTreeNode ReduceRegularNode(ParserAction action) {
var childCount = action.ReduceProduction.RValues.Count;
int firstChildIndex = Context.ParserStack.Count - childCount;
var span = ComputeNewNodeSpan(childCount);
var newNode = new ParseTreeNode(action.ReduceProduction, span);
var newIsOp = newNode.Term.Flags.IsSet(TermFlags.IsOperator);
for(int i = 0; i < childCount; i++) {
var childNode = Context.ParserStack[firstChildIndex + i];
if(ShouldSkipChildNode(childNode))
continue; //skip punctuation or empty transient nodes
//AST nodes are created when we pop the (child) parse node from the stack, not when we push it into the stack.
// See more in comments to CheckCreateAstNode method
CheckCreateAstNode(childNode);
//Inherit precedence and associativity, to cover a standard case: BinOp->+|-|*|/;
// BinOp node should inherit precedence from underlying operator symbol. Keep in mind special case of SQL operator "NOT LIKE" which consists
// of 2 tokens. We therefore inherit "max" precedence from any children
if(newIsOp && childNode.Precedence != BnfTerm.NoPrecedence && childNode.Precedence > newNode.Precedence) {
newNode.Precedence = childNode.Precedence;
newNode.Associativity = childNode.Associativity;
}
newNode.ChildNodes.Add(childNode);
}//for i
return newNode;
}
private SourceSpan ComputeNewNodeSpan(int childCount) {
if(childCount == 0)
return new SourceSpan(Context.CurrentParserInput.Span.Location, 0);
var first = Context.ParserStack[Context.ParserStack.Count - childCount];
var last = Context.ParserStack.Top;
return new SourceSpan(first.Span.Location, last.Span.EndPosition - first.Span.Location.Position);
}
//Note that we create AST objects for parse nodes only when we pop the node from the stack (when it is a child being added to to its parent).
// So only when we form a parent node, we run thru children in the stack top and check/create their AST nodes.
// This is done to provide correct initialization of List nodes (created with Plus or Star operation).
// We create a parse tree node for a list non-terminal very early, when we encounter its first element. We push the newly created list node into
// the stack. At this moment it is too early to create the AST node for the list. We should wait until all child nodes are parsed and accumulated
// in the stack. Only then, when list construction is finished, we can create AST node and provide it with all list elements.
private void CheckCreateAstNode(ParseTreeNode parseNode) {
try {
//Check preconditions
if (!_grammar.LanguageFlags.IsSet(LanguageFlags.CreateAst))
return;
if (parseNode.AstNode != null || parseNode.Term.Flags.IsSet(TermFlags.IsTransient)
|| parseNode.Term.Flags.IsSet(TermFlags.NoAstNode)) return;
if (Context.Status != ParserStatus.Parsing || Context.HasErrors) return;
//Prepare mapped child node list
CheckCreateMappedChildNodeList(parseNode);
//Actually create node
_grammar.CreateAstNode(Context, parseNode);
if (parseNode.AstNode != null)
parseNode.Term.OnAstNodeCreated(parseNode);
} catch (Exception ex) {
Context.AddParserMessage(ParserErrorLevel.Error, parseNode.Span.Location, Resources.ErrFailedCreateNode, parseNode.Term.Name, ex.Message);
}
}
private bool CheckCreateMappedChildNodeList(ParseTreeNode parseTreeNode) {
var term = parseTreeNode.Term;
if (term.AstPartsMap == null) return false;
parseTreeNode.MappedChildNodes = new ParseTreeNodeList();
foreach (var index in term.AstPartsMap)
parseTreeNode.MappedChildNodes.Add(parseTreeNode.ChildNodes[index]);
return true;
}
#endregion
private void ExecuteConflictAction(ParserAction action) {
var args = action.ResolveConflict(_grammar, Context);
switch(args.Result) {
case ParserActionType.Reduce:
ExecuteReduce(new ParserAction(ParserActionType.Reduce, null, args.ReduceProduction));
break;
case ParserActionType.Operator:
ExecuteOperatorAction(new ParserAction(ParserActionType.Operator, action.NewState, args.ReduceProduction));
break;
case ParserActionType.Shift:
default:
ExecuteShift(action);
break;
}
if (_traceEnabled) Context.AddTrace(Resources.MsgTraceConflictResolved);
}
private void ExecuteAccept(ParserAction action) {
var root = Context.ParserStack.Pop(); //Pop root
CheckCreateAstNode(root);
Context.CurrentParseTree.Root = root;
Context.Status = ParserStatus.Accepted;
}
private void ExecuteOperatorAction(ParserAction action) {
var realActionType = GetActionTypeForOperation(action);
if (_traceEnabled) Context.AddTrace(Resources.MsgTraceOpResolved, realActionType);
switch (realActionType) {
case ParserActionType.Shift: ExecuteShift(action); break;
case ParserActionType.Reduce: ExecuteReduce(action); break;
}//switch
}
private ParserActionType GetActionTypeForOperation(ParserAction action) {
for (int i = Context.ParserStack.Count - 1; i >= 0; i--) {
var prevNode = Context.ParserStack[i];
if (prevNode == null) continue;
if (prevNode.Precedence == BnfTerm.NoPrecedence) continue;
ParserActionType result;
//if previous operator has the same precedence then use associativity
var input = Context.CurrentParserInput;
if (prevNode.Precedence == input.Precedence)
result = input.Associativity == Associativity.Left ? ParserActionType.Reduce : ParserActionType.Shift;
else
result = prevNode.Precedence > input.Precedence ? ParserActionType.Reduce : ParserActionType.Shift;
return result;
}
//If no operators found on the stack, do simple shift
return ParserActionType.Shift;
}
#endregion
#region Braces handling
private Token CheckBraceToken(Token token) {
if (token.Terminal.Flags.IsSet(TermFlags.IsOpenBrace)) {
Context.OpenBraces.Push(token);
return token;
}
//it is closing brace; check if we have opening brace
if (Context.OpenBraces.Count == 0)
return CreateBraceMismatchErrorToken(token);
//check that braces match
var lastBrace = Context.OpenBraces.Peek();
if (lastBrace.Terminal.IsPairFor != token.Terminal)
return CreateBraceMismatchErrorToken(token);
//Link both tokens, pop the stack and return true
Token.LinkMatchingBraces(lastBrace, token);
Context.OpenBraces.Pop();
return token;
}
private Token CreateBraceMismatchErrorToken(Token closingBrace) {
return new Token(_grammar.SyntaxError, closingBrace.Location, closingBrace.Text,
string.Format(Resources.ErrUnmatchedCloseBrace, closingBrace.Text));
}
#endregion
}//class
}//namespace
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email [email protected] |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Reporting.Rdl
{
/// <summary>
/// A simple lexer that is used by PageTextHtml to break an HTML command into name value pairs.
/// </summary>
internal class PageTextHtmlCmdLexer
{
private CharReader reader;
/// <summary>
/// Initializes a new instance of the Lexer class with the specified
/// TextReader to lex.
/// </summary>
/// <param name="source">A TextReader to lex.</param>
internal PageTextHtmlCmdLexer(string htmlcmd)
{
// read the file contents
reader = new CharReader(htmlcmd);
}
/// <summary>
/// Breaks the input stream onto the tokens list and returns a hash table with the name value pairs.
/// </summary>
/// <returns>The hash table.</returns>
internal Hashtable Lex()
{
Hashtable ht = new Hashtable();
while(true)
{
string cmd = GetNextToken();
if (cmd == null)
return ht;
if (GetNextToken() != "=")
return ht;
string val = GetNextToken();
if (val == null)
return ht;
ht.Add(cmd, val);
}
}
private string GetNextToken()
{
while(!reader.EndOfInput())
{
char ch = reader.GetNext();
// skipping whitespaces at front of token
if(Char.IsWhiteSpace(ch))
continue;
switch(ch)
{
case '\'':
case '"':
return ReadQuoted(ch);
default:
return ReadWord(ch);
} // end of switch
}
return null;
}
// Read html command string
private string ReadQuoted(char firstc)
{
char qChar = firstc;
StringBuilder lt = new StringBuilder();
while(!reader.EndOfInput())
{
char ch = reader.GetNext();
if (ch == qChar)
break;
lt.Append(ch);
}
return lt.ToString();
}
// Read to next white space or to specified character
private string ReadWord(char ch)
{
if (ch == '=')
return "=";
StringBuilder lt = new StringBuilder();
lt.Append(ch);
while(!reader.EndOfInput())
{
ch = reader.GetNext();
if (Char.IsWhiteSpace(ch) || ch == '=')
{
reader.UnGet(); // put it back on the stack
break;
}
lt.Append(ch);
}
return lt.ToString();
}
class CharReader
{
string file = null;
int ptr = 0;
/// <summary>
/// Initializes a new instance of the CharReader class.
/// </summary>
internal CharReader(string text)
{
file = text;
}
/// <summary>
/// Returns the next char from the stream.
/// </summary>
internal char GetNext()
{
if (EndOfInput())
{
return '\0';
}
char ch = file[ptr++];
return ch;
}
/// <summary>
/// Returns the next char from the stream without removing it.
/// </summary>
internal char Peek()
{
if (EndOfInput()) // ok to peek at end of file
return '\0';
return file[ptr];
}
/// <summary>
/// Undoes the extracting of the last char.
/// </summary>
internal void UnGet()
{
--ptr;
if (ptr < 0)
throw new Exception("error : ungetted first char");
char ch = file[ptr];
}
/// <summary>
/// Returns True if end of input was reached; otherwise False.
/// </summary>
internal bool EndOfInput()
{
return ptr >= file.Length;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
public class VehicleController : MonoBehaviour {
public bool IsAI;
public Camera TailCamera;
public Camera FireCamera;
public TireController Tires;
public CupolaController Cupola;
public float Speed = 0.5f;
public float RotSpeed = 5f;
public bool IsTank;
public bool IsAntiTurn;
public GameObject TailPos;
bool isMoving;
bool isForwarding;
float maxCameraDist = 3f;
float curtDist = 0f;
float mouseX, mouseY;
float cameraDistUnit = 0.05f;
// Use this for initialization
void Start()
{
if (!IsAI)
{
ResetUserControl(true);
}
}
public void ResetUserControl(bool status = false)
{
IsAI = !status;
FireCamera.enabled = status;
TailCamera.enabled = status;
FireCamera.gameObject.SetActive(status);
TailCamera.gameObject.SetActive(status);
}
// Update is called once per frame
void Update()
{
mouseX = Input.GetAxisRaw("Mouse X");
mouseY = Input.GetAxisRaw("Mouse Y");
ProcessMouseAction(mouseX, mouseY);
ProcessKeyAction();
}
private void ProcessMouseAction(float angle, float angleY)
{
if (Cupola != null && !IsAI)
{
Cupola.Turn(angle);
Cupola.Hold(-angleY);
}
Cupola.ProcessFire();
}
void OnCollisionEnter(Collision collision)
{
//Debug.Log(collision.collider.name + " hit " + collision.contacts.Length);
}
void OnCollisionExit(Collision collision)
{
//Debug.Log(collision.collider.name + "Through");
}
void ProcessKeyAction()
{
if (!IsAI)
{
isMoving = false;
isForwarding = false;
if (Input.GetKey(KeyCode.Alpha1))
{
if (TailCamera != null)
{
TailCamera.enabled = false;
}
FireCamera.enabled = true;
}
else if (Input.GetKey(KeyCode.Alpha2))
{
if (TailCamera != null)
{
TailCamera.enabled = true;
}
FireCamera.enabled = false;
}
if (Input.GetKey(KeyCode.W))
{
Forward();
}
else if (Input.GetKey(KeyCode.S))
{
Backward();
}
if (Input.GetKey(KeyCode.UpArrow))
{
Forward();
}
else if (Input.GetKey(KeyCode.DownArrow))
{
Backward();
}
if (Input.GetKey(KeyCode.A))
{
//Tires.TurnLeft();
SteelLeft();
}
else if (Input.GetKey(KeyCode.D))
{
//Tires.TurnRight();
SteelRight();
}
else
{
Tires.Restore();
RestoreCamera();
}
}
}
public void Forward()
{
Tires.Forward();
isMoving = true;
isForwarding = true;
transform.Translate(0, 0, Speed);
}
public void Backward()
{
Tires.Backward();
isMoving = true;
isForwarding = false;
transform.Translate(0, 0, -Speed);
}
public void SteelLeft()
{
if (isMoving || IsTank)
{
float angle = -RotSpeed * (isForwarding || !isMoving ? 1 : -1);
Steel(angle);
}
}
public void SteelRight()
{
if (isMoving || IsTank)
{
float angle = RotSpeed * (isForwarding || !isMoving ? 1 : -1);
Steel(angle);
}
}
private void Steel(float angle)
{
if (isForwarding)
{
if (angle < 0)
{
Tires.TurnLeft();
}
else if (angle > 0)
{
Tires.TurnRight();
}
}
else
{
if (angle < 0)
{
Tires.TurnRight();
}
else if (angle > 0)
{
Tires.TurnLeft();
}
}
if (TailPos != null)
{
transform.RotateAround(TailPos.transform.position, Vector3.up, angle);
}
else
{
transform.Rotate(Vector3.up, angle);
}
if (IsAntiTurn)
{
ProcessMouseAction(-angle, 0);
}
TurnCamera(angle);
}
private void RestoreCamera()
{
float angle = 0f;
if (Mathf.Abs(curtDist) > cameraDistUnit)
{
if (curtDist > 0)
{
angle = -1f;
}
else if (curtDist < 0)
{
angle = 1f;
}
TurnCamera(angle);
}
}
private void TurnCamera(float angle)
{
if (TailCamera != null && angle != 0)
{
float dist = 0f;
if (angle > 0)
{
dist = cameraDistUnit;
}
else
{
dist = -cameraDistUnit;
}
curtDist += dist;
if (Mathf.Abs(curtDist) < Mathf.Abs(maxCameraDist))
{
TailCamera.transform.Translate(dist, 0, 0);
}
else
{
curtDist -= dist;
}
}
}
}
| |
// Copyright (c) 2012 Calvin Rien
// http://the.darktable.com
//
// This software is provided 'as-is', without any express or implied warranty. In
// no event will the authors be held liable for any damages arising from the use
// of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not claim
// that you wrote the original software. If you use this software in a product,
// an acknowledgment in the product documentation would be appreciated but is not
// required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
using System.Collections;
using System.Collections.Generic;
namespace UnityEngine {
public class UnityNameValuePair<V> : UnityKeyValuePair<string, V> {
public string name = null;
override public string Key {
get { return name; }
set { name = value; }
}
public UnityNameValuePair() : base() {
}
public UnityNameValuePair(string key, V value) : base(key, value) {
}
}
public class UnityKeyValuePair<K, V> {
virtual public K Key {
get;
set;
}
virtual public V Value {
get;
set;
}
public UnityKeyValuePair() {
Key = default(K);
Value = default(V);
}
public UnityKeyValuePair(K key, V value) {
Key = key;
Value = value;
}
}
public abstract class UnityDictionary<K,V> : IDictionary<K,V> {
abstract protected List<UnityKeyValuePair<K,V>> KeyValuePairs {
get;
set;
}
protected abstract void SetKeyValuePair(K k, V v); /* {
var index = Collection.FindIndex(x => {return x.Key == k;});
if (index != -1) {
if (v == null) {
Collection.RemoveAt(index);
return;
}
values[index] = new UnityKeyValuePair(key, value);
return;
}
values.Add(new UnityKeyValuePair(key, value));
} */
virtual public V this[K key] {
get {
var result = KeyValuePairs.Find(x => {
return x.Key.Equals(key);});
if (result == null) {
return default(V);
}
return result.Value;
}
set {
if (key == null) {
return;
}
SetKeyValuePair(key, value);
}
}
#region IDictionary interface
public void Add(K key, V value) {
this[key] = value;
}
public void Add(KeyValuePair<K, V> kvp) {
this[kvp.Key] = kvp.Value;
}
public bool TryGetValue(K key, out V value) {
if (!this.ContainsKey(key)) {
value = default(V);
return false;
}
value = this[key];
return true;
}
public bool Remove(KeyValuePair<K, V> item) {
return Remove(item.Key);
}
public bool Remove(K key) {
var list = KeyValuePairs;
var index = list.FindIndex(x => {
return x.Key.Equals(key);});
if (index == -1) {
return false;
}
list.RemoveAt(index);
KeyValuePairs = list;
return true;
}
public void Clear() {
var list = KeyValuePairs;
list.Clear();
KeyValuePairs = list;
}
public bool ContainsKey(K key) {
return KeyValuePairs.FindIndex(x => {
return x.Key.Equals(key);}) != -1;
}
public bool Contains(KeyValuePair<K, V> kvp) {
return this[kvp.Key].Equals(kvp.Value);
}
public int Count {
get {
return KeyValuePairs.Count;
}
}
public void CopyTo(KeyValuePair<K, V>[] array, int index) {
var copy = KeyValuePairs.ConvertAll<KeyValuePair<K, V>>(
new System.Converter<UnityKeyValuePair<K, V>, KeyValuePair<K, V>>(
x => {
return new KeyValuePair<K, V>(x.Key, (V) x.Value);
}));
copy.CopyTo(array, index);
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator() as IEnumerator;
}
public IEnumerator<KeyValuePair<K, V>> GetEnumerator() {
return new UnityDictionaryEnumerator(this);
}
public ICollection<K> Keys {
get {
return KeyValuePairs.ConvertAll(new System.Converter<UnityKeyValuePair<K,V>, K>(x => {
return x.Key;}));
}
}
public ICollection<V> Values {
get {
return KeyValuePairs.ConvertAll(new System.Converter<UnityKeyValuePair<K,V>, V>(x => {
return x.Value;}));
}
}
public ICollection<KeyValuePair<K, V>> Items {
get {
return KeyValuePairs.ConvertAll<KeyValuePair<K, V>>(new System.Converter<UnityKeyValuePair<K,V>, KeyValuePair<K, V>>(x => {
return new KeyValuePair<K, V>(x.Key, x.Value);}));
}
}
public V SyncRoot {
get { return default(V); }
}
public bool IsFixedSize {
get { return false; }
}
public bool IsReadOnly {
get { return false; }
}
public bool IsSynchronized {
get { return false; }
}
internal sealed class UnityDictionaryEnumerator : IEnumerator<KeyValuePair<K, V>> {
// A copy of the SimpleDictionary T's key/value pairs.
KeyValuePair<K, V>[] items;
int index = -1;
internal UnityDictionaryEnumerator() {
}
internal UnityDictionaryEnumerator(UnityDictionary<K,V> ud) {
// Make a copy of the dictionary entries currently in the SimpleDictionary T.
items = new KeyValuePair<K, V>[ud.Count];
ud.CopyTo(items, 0);
}
object IEnumerator.Current {
get { return Current; }
}
public KeyValuePair<K, V> Current {
get {
ValidateIndex();
return items[index];
}
}
// Return the current dictionary entry.
public KeyValuePair<K, V> Entry {
get { return (KeyValuePair<K, V>) Current; }
}
public void Dispose() {
index = -1;
items = null;
}
// Return the key of the current item.
public K Key {
get {
ValidateIndex();
return items[index].Key;
}
}
// Return the value of the current item.
public V Value {
get {
ValidateIndex();
return items[index].Value;
}
}
// Advance to the next item.
public bool MoveNext() {
if (index < items.Length - 1) {
index++;
return true;
}
return false;
}
// Validate the enumeration index and throw an exception if the index is out of range.
private void ValidateIndex() {
if (index < 0 || index >= items.Length) {
throw new System.InvalidOperationException("Enumerator is before or after the collection.");
}
}
// Reset the index to restart the enumeration.
public void Reset() {
index = -1;
}
#endregion
}
}
public abstract class UnityDictionary<V> : UnityDictionary<string, V> {
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.MemoryTests
{
public static partial class MemoryTests
{
[Theory]
[InlineData(new int[0], 1, new int[0])]
[InlineData(new int[] { 1 }, 1, new int[0])]
[InlineData(new int[] { 2 }, 1, new int[] { 2 })]
[InlineData(new int[] { 1, 2, 1 }, 1, new int[] { 2, 1 })]
[InlineData(new int[] { 1, 1, 2, 1 }, 1, new int[] { 2, 1 })]
[InlineData(new int[] { 1, 1, 2, 1 }, 2, new int[] { 1, 1, 2, 1 })]
[InlineData(new int[] { 1, 1, 2, 1 }, 3, new int[] { 1, 1, 2, 1 })]
[InlineData(new int[] { 1, 1, 1, 2 }, 1, new int[] { 2 })]
[InlineData(new int[] { 1, 1, 1, 1 }, 1, new int[0])]
public static void MemoryExtensions_TrimStart_Single(int[] values, int trim, int[] expected)
{
Memory<int> memory = new Memory<int>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<int> rom = new ReadOnlyMemory<int>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<int> span = new Span<int>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<int> ros = new ReadOnlySpan<int>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Theory]
[InlineData(new int[0], 1, new int[0])]
[InlineData(new int[] { 1 }, 1, new int[0])]
[InlineData(new int[] { 2 }, 1, new int[] { 2 })]
[InlineData(new int[] { 1, 2, 1 }, 1, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 1, 1 }, 1, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 1, 1 }, 2, new int[] { 1, 2, 1, 1 })]
[InlineData(new int[] { 1, 2, 1, 1 }, 3, new int[] { 1, 2, 1, 1 })]
[InlineData(new int[] { 2, 1, 1, 1 }, 1, new int[] { 2 })]
[InlineData(new int[] { 1, 1, 1, 1 }, 1, new int[0])]
public static void MemoryExtensions_TrimEnd_Single(int[] values, int trim, int[] expected)
{
Memory<int> memory = new Memory<int>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<int> rom = new ReadOnlyMemory<int>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<int> span = new Span<int>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<int> ros = new ReadOnlySpan<int>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Theory]
[InlineData(new int[0], 1, new int[0])]
[InlineData(new int[] { 1 }, 1, new int[0])]
[InlineData(new int[] { 2 }, 1, new int[] { 2 })]
[InlineData(new int[] { 1, 2, 1 }, 1, new int[] { 2 })]
[InlineData(new int[] { 1, 2, 1, 1 }, 1, new int[] { 2 })]
[InlineData(new int[] { 1, 2, 1, 1 }, 2, new int[] { 1, 2, 1, 1 })]
[InlineData(new int[] { 1, 2, 1, 1 }, 3, new int[] { 1, 2, 1, 1 })]
[InlineData(new int[] { 2, 1, 1, 1 }, 1, new int[] { 2 })]
[InlineData(new int[] { 1, 1, 1, 2 }, 1, new int[] { 2 })]
[InlineData(new int[] { 1, 1, 1, 1 }, 1, new int[0])]
public static void MemoryExtensions_Trim_Single(int[] values, int trim, int[] expected)
{
Memory<int> memory = new Memory<int>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<int> rom = new ReadOnlyMemory<int>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<int> span = new Span<int>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<int> ros = new ReadOnlySpan<int>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Theory]
[InlineData(new int[0], new int[0], new int[0])]
[InlineData(new int[0], new int[] { 1 }, new int[0])]
[InlineData(new int[] { 1 }, new int[0], new int[] { 1 })]
[InlineData(new int[] { 1 }, new int[] { 1 }, new int[0])]
[InlineData(new int[] { 2 }, new int[] { 1 }, new int[] { 2 })]
[InlineData(new int[] { 1, 2, 1 }, new int[] { 1 }, new int[] { 2, 1 })]
[InlineData(new int[] { 1, 1, 2, 1 }, new int[] { 1 }, new int[] { 2, 1 })]
[InlineData(new int[] { 1, 1, 2, 1 }, new int[] { 2 }, new int[] { 1, 1, 2, 1 })]
[InlineData(new int[] { 1, 1, 2, 1 }, new int[] { 3 }, new int[] { 1, 1, 2, 1 })]
[InlineData(new int[] { 1, 1, 2, 1 }, new int[] { 1, 2 }, new int[0])]
[InlineData(new int[] { 1, 1, 2, 3 }, new int[] { 1, 2 }, new int[] { 3 })]
[InlineData(new int[] { 1, 1, 2, 3 }, new int[] { 1, 2, 4 }, new int[] { 3 })]
[InlineData(new int[] { 1, 1, 1, 2 }, new int[] { 1 }, new int[] { 2 })]
[InlineData(new int[] { 1, 1, 1, 1 }, new int[] { 1 }, new int[0])]
public static void MemoryExtensions_TrimStart_Multi(int[] values, int[] trims, int[] expected)
{
Memory<int> memory = new Memory<int>(values).TrimStart(trims);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<int> rom = new ReadOnlyMemory<int>(values).TrimStart(trims);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<int> span = new Span<int>(values).TrimStart(trims);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<int> ros = new ReadOnlySpan<int>(values).TrimStart(trims);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Theory]
[InlineData(new int[0], new int[0], new int[0])]
[InlineData(new int[0], new int[] { 1 }, new int[0])]
[InlineData(new int[] { 1 }, new int[0], new int[] { 1 })]
[InlineData(new int[] { 1 }, new int[] { 1 }, new int[0])]
[InlineData(new int[] { 2 }, new int[] { 1 }, new int[] { 2 })]
[InlineData(new int[] { 1, 2, 1 }, new int[] { 1 }, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 1, 1 }, new int[] { 1 }, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 1, 1 }, new int[] { 2 }, new int[] { 1, 2, 1, 1 })]
[InlineData(new int[] { 1, 2, 1, 1 }, new int[] { 3 }, new int[] { 1, 2, 1, 1 })]
[InlineData(new int[] { 1, 2, 1, 1 }, new int[] { 1, 2 }, new int[0])]
[InlineData(new int[] { 3, 2, 1, 1 }, new int[] { 1, 2 }, new int[] { 3 })]
[InlineData(new int[] { 3, 2, 1, 1 }, new int[] { 1, 2, 4 }, new int[] { 3 })]
[InlineData(new int[] { 2, 1, 1, 1 }, new int[] { 1 }, new int[] { 2 })]
[InlineData(new int[] { 1, 1, 1, 1 }, new int[] { 1 }, new int[0])]
public static void MemoryExtensions_TrimEnd_Multi(int[] values, int[] trims, int[] expected)
{
Memory<int> memory = new Memory<int>(values).TrimEnd(trims);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<int> rom = new ReadOnlyMemory<int>(values).TrimEnd(trims);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<int> span = new Span<int>(values).TrimEnd(trims);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<int> ros = new ReadOnlySpan<int>(values).TrimEnd(trims);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Theory]
[InlineData(new int[0], new int[0], new int[0])]
[InlineData(new int[0], new int[] { 1 }, new int[0])]
[InlineData(new int[] { 1 }, new int[0], new int[] { 1 })]
[InlineData(new int[] { 1 }, new int[] { 1 }, new int[0])]
[InlineData(new int[] { 2 }, new int[] { 1 }, new int[] { 2 })]
[InlineData(new int[] { 1, 2, 1 }, new int[] { 1 }, new int[] { 2 })]
[InlineData(new int[] { 1, 2, 1, 1 }, new int[] { 1 }, new int[] { 2 })]
[InlineData(new int[] { 1, 2, 1, 1 }, new int[] { 2 }, new int[] { 1, 2, 1, 1 })]
[InlineData(new int[] { 1, 2, 1, 1 }, new int[] { 3 }, new int[] { 1, 2, 1, 1 })]
[InlineData(new int[] { 1, 2, 1, 1 }, new int[] { 1, 2 }, new int[0])]
[InlineData(new int[] { 2, 1, 3, 2, 1, 1 }, new int[] { 1, 2 }, new int[] { 3 })]
[InlineData(new int[] { 2, 1, 3, 2, 1, 1 }, new int[] { 1, 2, 4 }, new int[] { 3 })]
[InlineData(new int[] { 1, 2, 1, 1, 1 }, new int[] { 1 }, new int[] { 2 })]
[InlineData(new int[] { 1, 1, 1, 1 }, new int[] { 1 }, new int[0])]
public static void MemoryExtensions_Trim_Multi(int[] values, int[] trims, int[] expected)
{
Memory<int> memory = new Memory<int>(values).Trim(trims);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<int> rom = new ReadOnlyMemory<int>(values).Trim(trims);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<int> span = new Span<int>(values).Trim(trims);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<int> ros = new ReadOnlySpan<int>(values).Trim(trims);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
public sealed class Foo : IEquatable<Foo>
{
public int Value { get; set; }
public bool Equals(Foo other)
{
if (this == null && other == null)
return true;
if (other == null)
return false;
return Value == other.Value;
}
public static implicit operator Foo(int value) => new Foo { Value = value };
public static implicit operator int? (Foo foo) => foo?.Value;
}
public static IEnumerable<object[]> IdempotentValues => new object[][]
{
new object[1] { new Foo[] { } },
new object[1] { new Foo[] { null, 1, 2, 3, null, 2, 1, null } }
};
[Theory]
[MemberData(nameof(IdempotentValues))]
public static void MemoryExtensions_TrimStart_Idempotent(Foo[] values)
{
Foo[] expected = values;
Foo[] trim = null;
Memory<Foo> memory = new Memory<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<Foo> rom = new ReadOnlyMemory<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<Foo> span = new Span<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<Foo> ros = new ReadOnlySpan<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
trim = new Foo[] { };
memory = new Memory<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
rom = new ReadOnlyMemory<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
span = new Span<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ros = new ReadOnlySpan<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Theory]
[MemberData(nameof(IdempotentValues))]
public static void MemoryExtensions_TrimEnd_Idempotent(Foo[] values)
{
Foo[] expected = values;
Foo[] trim = null;
Memory<Foo> memory = new Memory<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<Foo> rom = new ReadOnlyMemory<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<Foo> span = new Span<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<Foo> ros = new ReadOnlySpan<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
trim = new Foo[] { };
memory = new Memory<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
rom = new ReadOnlyMemory<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
span = new Span<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ros = new ReadOnlySpan<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Theory]
[MemberData(nameof(IdempotentValues))]
public static void MemoryExtensions_Trim_Idempotent(Foo[] values)
{
Foo[] expected = values;
Foo[] trim = null;
Memory<Foo> memory = new Memory<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<Foo> rom = new ReadOnlyMemory<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<Foo> span = new Span<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<Foo> ros = new ReadOnlySpan<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
trim = new Foo[] { };
memory = new Memory<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
rom = new ReadOnlyMemory<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
span = new Span<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ros = new ReadOnlySpan<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Fact]
public static void MemoryExtensions_TrimStart_Single_Null()
{
var values = new Foo[] { null, null, 1, 2, null, null };
Foo trim = null;
var expected = new Foo[] { 1, 2, null, null };
Memory<Foo> memory = new Memory<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<Foo> rom = new ReadOnlyMemory<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<Foo> span = new Span<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<Foo> ros = new ReadOnlySpan<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Fact]
public static void MemoryExtensions_TrimStart_Multi_Null()
{
var values = new Foo[] { null, 1, 2, 3, null, 2, 1, null };
var trim = new Foo[] { null, 1, 2 };
var expected = new Foo[] { 3, null, 2, 1, null };
Memory<Foo> memory = new Memory<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<Foo> rom = new ReadOnlyMemory<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<Foo> span = new Span<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<Foo> ros = new ReadOnlySpan<Foo>(values).TrimStart(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Fact]
public static void MemoryExtensions_TrimEnd_Single_Null()
{
var values = new Foo[] { null, null, 1, 2, null, null };
Foo trim = null;
var expected = new Foo[] { null, null, 1, 2 };
Memory<Foo> memory = new Memory<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<Foo> rom = new ReadOnlyMemory<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<Foo> span = new Span<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<Foo> ros = new ReadOnlySpan<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Fact]
public static void MemoryExtensions_TrimEnd_Multi_Null()
{
var values = new Foo[] { null, 1, 2, 3, null, 2, 1, null };
var trim = new Foo[] { null, 1, 2 };
var expected = new Foo[] { null, 1, 2, 3 };
Memory<Foo> memory = new Memory<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<Foo> rom = new ReadOnlyMemory<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<Foo> span = new Span<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<Foo> ros = new ReadOnlySpan<Foo>(values).TrimEnd(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Fact]
public static void MemoryExtensions_Trim_Single_Null()
{
var values = new Foo[] { null, null, 1, 2, null, null };
Foo trim = null;
var expected = new Foo[] { 1, 2 };
Memory<Foo> memory = new Memory<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<Foo> rom = new ReadOnlyMemory<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<Foo> span = new Span<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<Foo> ros = new ReadOnlySpan<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
[Fact]
public static void MemoryExtensions_Trim_Multi_Null()
{
var values = new Foo[] { null, 1, 2, 3, null, 2, 1, null };
var trim = new Foo[] { null, 1, 2 };
var expected = new Foo[] { 3 };
Memory<Foo> memory = new Memory<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, memory.ToArray()));
ReadOnlyMemory<Foo> rom = new ReadOnlyMemory<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, rom.ToArray()));
Span<Foo> span = new Span<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, span.ToArray()));
ReadOnlySpan<Foo> ros = new ReadOnlySpan<Foo>(values).Trim(trim);
Assert.True(System.Linq.Enumerable.SequenceEqual(expected, ros.ToArray()));
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.27.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Google Cloud Speech API Version v1beta1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://cloud.google.com/speech/'>Google Cloud Speech API</a>
* <tr><th>API Version<td>v1beta1
* <tr><th>API Rev<td>20170705 (916)
* <tr><th>API Docs
* <td><a href='https://cloud.google.com/speech/'>
* https://cloud.google.com/speech/</a>
* <tr><th>Discovery Name<td>speech
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Google Cloud Speech API can be found at
* <a href='https://cloud.google.com/speech/'>https://cloud.google.com/speech/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Speech.v1beta1
{
/// <summary>The Speech Service.</summary>
public class SpeechService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1beta1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public SpeechService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public SpeechService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
operations = new OperationsResource(this);
speech = new SpeechResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "speech"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://speech.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://speech.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Google Cloud Speech API.</summary>
public class Scope
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
private readonly OperationsResource operations;
/// <summary>Gets the Operations resource.</summary>
public virtual OperationsResource Operations
{
get { return operations; }
}
private readonly SpeechResource speech;
/// <summary>Gets the Speech resource.</summary>
public virtual SpeechResource Speech
{
get { return speech; }
}
}
///<summary>A base abstract class for Speech requests.</summary>
public abstract class SpeechBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new SpeechBaseServiceRequest instance.</summary>
protected SpeechBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>OAuth bearer token.</summary>
[Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string BearerToken { get; set; }
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Pretty-print response.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Pp { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Speech parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"bearer_token", new Google.Apis.Discovery.Parameter
{
Name = "bearer_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pp", new Google.Apis.Discovery.Parameter
{
Name = "pp",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "operations" collection of methods.</summary>
public class OperationsResource
{
private const string Resource = "operations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public OperationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether
/// the cancellation succeeded or whether the operation completed despite cancellation. On successful
/// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value
/// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.</summary>
/// <param name="name">The name of the operation resource to be cancelled.</param>
public virtual CancelRequest Cancel(string name)
{
return new CancelRequest(service, name);
}
/// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether
/// the cancellation succeeded or whether the operation completed despite cancellation. On successful
/// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value
/// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.</summary>
public class CancelRequest : SpeechBaseServiceRequest<Google.Apis.Speech.v1beta1.Data.Empty>
{
/// <summary>Constructs a new Cancel request.</summary>
public CancelRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource to be cancelled.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "cancel"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1beta1/operations/{+name}:cancel"; }
}
/// <summary>Initializes Cancel parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^[^/]+$",
});
}
}
/// <summary>Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`.</summary>
/// <param name="name">The name of the operation resource to be deleted.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`.</summary>
public class DeleteRequest : SpeechBaseServiceRequest<Google.Apis.Speech.v1beta1.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource to be deleted.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1beta1/operations/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^[^/]+$",
});
}
}
/// <summary>Gets the latest state of a long-running operation. Clients can use this method to poll the
/// operation result at intervals as recommended by the API service.</summary>
/// <param name="name">The name of the operation resource.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets the latest state of a long-running operation. Clients can use this method to poll the
/// operation result at intervals as recommended by the API service.</summary>
public class GetRequest : SpeechBaseServiceRequest<Google.Apis.Speech.v1beta1.Data.Operation>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1beta1/operations/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^[^/]+$",
});
}
}
/// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`.
///
/// NOTE: the `name` binding allows API services to override the binding to use different resource name schemes,
/// such as `users/operations`. To override the binding, API services can add a binding such as
/// `"/v1/{name=users}/operations"` to their service configuration. For backwards compatibility, the default
/// name includes the operations collection id, however overriding users must ensure the name binding is the
/// parent resource, without the operations collection id.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`.
///
/// NOTE: the `name` binding allows API services to override the binding to use different resource name schemes,
/// such as `users/operations`. To override the binding, API services can add a binding such as
/// `"/v1/{name=users}/operations"` to their service configuration. For backwards compatibility, the default
/// name includes the operations collection id, however overriding users must ensure the name binding is the
/// parent resource, without the operations collection id.</summary>
public class ListRequest : SpeechBaseServiceRequest<Google.Apis.Speech.v1beta1.Data.ListOperationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>The standard list page token.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>The name of the operation's parent resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Name { get; set; }
/// <summary>The standard list page size.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The standard list filter.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1beta1/operations"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>The "speech" collection of methods.</summary>
public class SpeechResource
{
private const string Resource = "speech";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public SpeechResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Performs asynchronous speech recognition: receive results via the [google.longrunning.Operations]
/// (/speech/reference/rest/v1beta1/operations#Operation) interface. Returns either an `Operation.error` or an
/// `Operation.response` which contains an `AsyncRecognizeResponse` message.</summary>
/// <param name="body">The body of the request.</param>
public virtual AsyncrecognizeRequest Asyncrecognize(Google.Apis.Speech.v1beta1.Data.AsyncRecognizeRequest body)
{
return new AsyncrecognizeRequest(service, body);
}
/// <summary>Performs asynchronous speech recognition: receive results via the [google.longrunning.Operations]
/// (/speech/reference/rest/v1beta1/operations#Operation) interface. Returns either an `Operation.error` or an
/// `Operation.response` which contains an `AsyncRecognizeResponse` message.</summary>
public class AsyncrecognizeRequest : SpeechBaseServiceRequest<Google.Apis.Speech.v1beta1.Data.Operation>
{
/// <summary>Constructs a new Asyncrecognize request.</summary>
public AsyncrecognizeRequest(Google.Apis.Services.IClientService service, Google.Apis.Speech.v1beta1.Data.AsyncRecognizeRequest body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Speech.v1beta1.Data.AsyncRecognizeRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "asyncrecognize"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1beta1/speech:asyncrecognize"; }
}
/// <summary>Initializes Asyncrecognize parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>Performs synchronous speech recognition: receive results after all audio has been sent and
/// processed.</summary>
/// <param name="body">The body of the request.</param>
public virtual SyncrecognizeRequest Syncrecognize(Google.Apis.Speech.v1beta1.Data.SyncRecognizeRequest body)
{
return new SyncrecognizeRequest(service, body);
}
/// <summary>Performs synchronous speech recognition: receive results after all audio has been sent and
/// processed.</summary>
public class SyncrecognizeRequest : SpeechBaseServiceRequest<Google.Apis.Speech.v1beta1.Data.SyncRecognizeResponse>
{
/// <summary>Constructs a new Syncrecognize request.</summary>
public SyncrecognizeRequest(Google.Apis.Services.IClientService service, Google.Apis.Speech.v1beta1.Data.SyncRecognizeRequest body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Speech.v1beta1.Data.SyncRecognizeRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "syncrecognize"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1beta1/speech:syncrecognize"; }
}
/// <summary>Initializes Syncrecognize parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
}
namespace Google.Apis.Speech.v1beta1.Data
{
/// <summary>The top-level message sent by the client for the `AsyncRecognize` method.</summary>
public class AsyncRecognizeRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>*Required* The audio data to be recognized.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audio")]
public virtual RecognitionAudio Audio { get; set; }
/// <summary>*Required* Provides information to the recognizer that specifies how to process the
/// request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("config")]
public virtual RecognitionConfig Config { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A
/// typical example is to use it as the request or the response type of an API method. For instance:
///
/// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
///
/// The JSON representation for `Empty` is empty JSON object `{}`.</summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Operations.ListOperations.</summary>
public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of operations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("operations")]
public virtual System.Collections.Generic.IList<Operation> Operations { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This resource represents a long-running operation that is the result of a network API call.</summary>
public class Operation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>If the value is `false`, it means the operation is still in progress. If true, the operation is
/// completed, and either `error` or `response` is available.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>The error result of the operation in case of failure or cancellation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual Status Error { get; set; }
/// <summary>Service-specific metadata associated with the operation. It typically contains progress
/// information and common metadata such as create time. Some services might not provide such metadata. Any
/// method that returns a long-running operation should document the metadata type, if any.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string,object> Metadata { get; set; }
/// <summary>The server-assigned name, which is only unique within the same service that originally returns it.
/// If you use the default HTTP mapping, the `name` should have the format of
/// `operations/some/unique/name`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The normal response of the operation in case of success. If the original method returns no data on
/// success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have
/// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name
/// is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string,object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Contains audio data in the encoding specified in the `RecognitionConfig`. Either `content` or `uri`
/// must be supplied. Supplying both or neither returns google.rpc.Code.INVALID_ARGUMENT. See [audio
/// limits](https://cloud.google.com/speech/limits#content).</summary>
public class RecognitionAudio : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The audio data bytes encoded as specified in `RecognitionConfig`. Note: as with all bytes fields,
/// protobuffers use a pure binary representation, whereas JSON representations use base64.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("content")]
public virtual string Content { get; set; }
/// <summary>URI that points to a file that contains audio data bytes as specified in `RecognitionConfig`.
/// Currently, only Google Cloud Storage URIs are supported, which must be specified in the following format:
/// `gs://bucket_name/object_name` (other URI formats return google.rpc.Code.INVALID_ARGUMENT). For more
/// information, see [Request URIs](https://cloud.google.com/storage/docs/reference-uris).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("uri")]
public virtual string Uri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Provides information to the recognizer that specifies how to process the request.</summary>
public class RecognitionConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>*Required* Encoding of audio data sent in all `RecognitionAudio` messages.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("encoding")]
public virtual string Encoding { get; set; }
/// <summary>*Optional* The language of the supplied audio as a BCP-47 language tag. Example: "en-GB"
/// https://www.rfc-editor.org/rfc/bcp/bcp47.txt If omitted, defaults to "en-US". See [Language
/// Support](https://cloud.google.com/speech/docs/languages) for a list of the currently supported language
/// codes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>*Optional* Maximum number of recognition hypotheses to be returned. Specifically, the maximum
/// number of `SpeechRecognitionAlternative` messages within each `SpeechRecognitionResult`. The server may
/// return fewer than `max_alternatives`. Valid values are `0`-`30`. A value of `0` or `1` will return a maximum
/// of one. If omitted, will return a maximum of one.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("maxAlternatives")]
public virtual System.Nullable<int> MaxAlternatives { get; set; }
/// <summary>*Optional* If set to `true`, the server will attempt to filter out profanities, replacing all but
/// the initial character in each filtered word with asterisks, e.g. "f***". If set to `false` or omitted,
/// profanities won't be filtered out.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("profanityFilter")]
public virtual System.Nullable<bool> ProfanityFilter { get; set; }
/// <summary>*Required* Sample rate in Hertz of the audio data sent in all `RecognitionAudio` messages. Valid
/// values are: 8000-48000. 16000 is optimal. For best results, set the sampling rate of the audio source to
/// 16000 Hz. If that's not possible, use the native sample rate of the audio source (instead of re-
/// sampling).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sampleRate")]
public virtual System.Nullable<int> SampleRate { get; set; }
/// <summary>*Optional* A means to provide context to assist the speech recognition.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("speechContext")]
public virtual SpeechContext SpeechContext { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Provides "hints" to the speech recognizer to favor specific words and phrases in the results.</summary>
public class SpeechContext : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>*Optional* A list of strings containing words and phrases "hints" so that the speech recognition is
/// more likely to recognize them. This can be used to improve the accuracy for specific words and phrases, for
/// example, if specific commands are typically spoken by the user. This can also be used to add additional
/// words to the vocabulary of the recognizer. See [usage
/// limits](https://cloud.google.com/speech/limits#content).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("phrases")]
public virtual System.Collections.Generic.IList<string> Phrases { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Alternative hypotheses (a.k.a. n-best list).</summary>
public class SpeechRecognitionAlternative : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>*Output-only* The confidence estimate between 0.0 and 1.0. A higher number indicates an estimated
/// greater likelihood that the recognized words are correct. This field is typically provided only for the top
/// hypothesis, and only for `is_final=true` results. Clients should not rely on the `confidence` field as it is
/// not guaranteed to be accurate, or even set, in any of the results. The default of 0.0 is a sentinel value
/// indicating `confidence` was not set.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("confidence")]
public virtual System.Nullable<float> Confidence { get; set; }
/// <summary>*Output-only* Transcript text representing the words that the user spoke.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("transcript")]
public virtual string Transcript { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A speech recognition result corresponding to a portion of the audio.</summary>
public class SpeechRecognitionResult : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>*Output-only* May contain one or more recognition hypotheses (up to the maximum specified in
/// `max_alternatives`).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("alternatives")]
public virtual System.Collections.Generic.IList<SpeechRecognitionAlternative> Alternatives { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The `Status` type defines a logical error model that is suitable for different programming
/// environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model
/// is designed to be:
///
/// - Simple to use and understand for most users - Flexible enough to meet unexpected needs
///
/// # Overview
///
/// The `Status` message contains three pieces of data: error code, error message, and error details. The error code
/// should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error
/// message should be a developer-facing English message that helps developers *understand* and *resolve* the error.
/// If a localized user-facing error message is needed, put the localized message in the error details or localize
/// it in the client. The optional error details may contain arbitrary information about the error. There is a
/// predefined set of error detail types in the package `google.rpc` that can be used for common error conditions.
///
/// # Language mapping
///
/// The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire
/// format. When the `Status` message is exposed in different client libraries and different wire protocols, it can
/// be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped
/// to some error codes in C.
///
/// # Other uses
///
/// The error model and the `Status` message can be used in a variety of environments, either with or without APIs,
/// to provide a consistent developer experience across different environments.
///
/// Example uses of this error model include:
///
/// - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the
/// normal response to indicate the partial errors.
///
/// - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error
/// reporting.
///
/// - Batch operations. If a client uses batch request and batch response, the `Status` message should be used
/// directly inside batch response, one for each error sub-response.
///
/// - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of
/// those operations should be represented directly using the `Status` message.
///
/// - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any
/// stripping needed for security/privacy reasons.</summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>A list of messages that carry the error details. There will be a common set of message types for
/// APIs to use.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> Details { get; set; }
/// <summary>A developer-facing error message, which should be in English. Any user-facing error message should
/// be localized and sent in the google.rpc.Status.details field, or localized by the client.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The top-level message sent by the client for the `SyncRecognize` method.</summary>
public class SyncRecognizeRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>*Required* The audio data to be recognized.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audio")]
public virtual RecognitionAudio Audio { get; set; }
/// <summary>*Required* Provides information to the recognizer that specifies how to process the
/// request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("config")]
public virtual RecognitionConfig Config { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The only message returned to the client by `SyncRecognize`. method. It contains the result as zero or
/// more sequential `SpeechRecognitionResult` messages.</summary>
public class SyncRecognizeResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>*Output-only* Sequential list of transcription results corresponding to sequential portions of
/// audio.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("results")]
public virtual System.Collections.Generic.IList<SpeechRecognitionResult> Results { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Versions;
using Microsoft.VisualStudio.Designer.Interfaces;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.DesignerAttribute
{
internal abstract partial class AbstractDesignerAttributeIncrementalAnalyzer : ForegroundThreadAffinitizedObject
{
private readonly IOptionService _optionService;
private readonly IForegroundNotificationService _notificationService;
private readonly IServiceProvider _serviceProvider;
private readonly DesignerAttributeState _state;
private readonly IAsynchronousOperationListener _listener;
/// <summary>
/// cache designer from UI thread
///
/// access this field through <see cref="GetDesignerFromForegroundThread"/>
/// </summary>
private IVSMDDesignerService _dotNotAccessDirectlyDesigner;
public AbstractDesignerAttributeIncrementalAnalyzer(
IServiceProvider serviceProvider,
IOptionService optionService,
IForegroundNotificationService notificationService,
IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
{
_serviceProvider = serviceProvider;
Contract.ThrowIfNull(_serviceProvider);
_optionService = optionService;
_notificationService = notificationService;
_listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.DesignerAttribute);
_state = new DesignerAttributeState();
}
protected abstract bool ProcessOnlyFirstTypeDefined();
protected abstract IEnumerable<SyntaxNode> GetAllTopLevelTypeDefined(SyntaxNode root);
protected abstract bool HasAttributesOrBaseTypeOrIsPartial(SyntaxNode typeNode);
public System.Threading.Tasks.Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
{
_state.Remove(document.Id);
return _state.PersistAsync(document, new Data(VersionStamp.Default, VersionStamp.Default, designerAttributeArgument: string.Empty), cancellationToken);
}
public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e)
{
return false;
}
public async System.Threading.Tasks.Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(document.IsFromPrimaryBranch());
cancellationToken.ThrowIfCancellationRequested();
if (!_optionService.GetOption(InternalFeatureOnOffOptions.DesignerAttributes))
{
return;
}
// use tree version so that things like compiler option changes are considered
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
var semanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
var existingData = await _state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
if (existingData != null)
{
// check whether we can use the data as it is (can happen when re-using persisted data from previous VS session)
if (CheckVersions(document, textVersion, projectVersion, semanticVersion, existingData))
{
var workspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl;
RegisterDesignerAttribute(workspace, document.Id, existingData.DesignerAttributeArgument);
return;
}
}
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
// Delay getting any of these until we need them, but hold on to them once we have them.
string designerAttributeArgument = null;
Compilation compilation = null;
INamedTypeSymbol designerAttribute = null;
SemanticModel model = null;
// get type defined in current tree
foreach (var typeNode in GetAllTopLevelTypeDefined(root))
{
cancellationToken.ThrowIfCancellationRequested();
if (HasAttributesOrBaseTypeOrIsPartial(typeNode))
{
if (designerAttribute == null)
{
if (compilation == null)
{
compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
}
designerAttribute = compilation.DesignerCategoryAttributeType();
if (designerAttribute == null)
{
// The DesignerCategoryAttribute doesn't exist.
InvalidateDocument(document);
return;
}
}
if (model == null)
{
model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
}
var definedType = model.GetDeclaredSymbol(typeNode, cancellationToken) as INamedTypeSymbol;
if (definedType == null)
{
continue;
}
// walk up type chain
foreach (var type in definedType.GetBaseTypesAndThis())
{
cancellationToken.ThrowIfCancellationRequested();
// if it has designer attribute, set it
var attribute = type.GetAttributes().Where(d => designerAttribute.Equals(d.AttributeClass)).FirstOrDefault();
if (attribute != null && attribute.ConstructorArguments.Length == 1)
{
designerAttributeArgument = GetArgumentString(attribute.ConstructorArguments[0]);
await RegisterDesignerAttributeAndSaveStateAsync(document, textVersion, semanticVersion, designerAttributeArgument, existingData, cancellationToken).ConfigureAwait(false);
return;
}
}
}
// check only first type
if (ProcessOnlyFirstTypeDefined())
{
break;
}
}
await RegisterDesignerAttributeAndSaveStateAsync(document, textVersion, semanticVersion, designerAttributeArgument, existingData, cancellationToken).ConfigureAwait(false);
}
private bool CheckVersions(
Document document, VersionStamp textVersion, VersionStamp dependentProjectVersion, VersionStamp dependentSemanticVersion, Data existingData)
{
// first check full version to see whether we can reuse data in same session, if we can't, check timestamp only version to see whether
// we can use it cross-session.
return document.CanReusePersistedTextVersion(textVersion, existingData.TextVersion) &&
document.Project.CanReusePersistedDependentSemanticVersion(dependentProjectVersion, dependentSemanticVersion, existingData.SemanticVersion);
}
private static string GetArgumentString(TypedConstant argument)
{
if (argument.Type == null ||
argument.Type.SpecialType != SpecialType.System_String ||
argument.IsNull)
{
return null;
}
return ((string)argument.Value).Trim();
}
private async System.Threading.Tasks.Task RegisterDesignerAttributeAndSaveStateAsync(
Document document, VersionStamp textVersion, VersionStamp semanticVersion, string designerAttributeArgument,
Data existingData, CancellationToken cancellationToken)
{
if (existingData != null && string.Equals(existingData.DesignerAttributeArgument, designerAttributeArgument, StringComparison.OrdinalIgnoreCase))
{
return;
}
var data = new Data(textVersion, semanticVersion, designerAttributeArgument);
await _state.PersistAsync(document, data, cancellationToken).ConfigureAwait(false);
var workspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl;
RegisterDesignerAttribute(workspace, document.Id, designerAttributeArgument);
}
private void RegisterDesignerAttribute(Document document, string designerAttributeArgument)
{
var workspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl;
RegisterDesignerAttribute(workspace, document.Id, designerAttributeArgument);
}
private void RegisterDesignerAttribute(VisualStudioWorkspaceImpl workspace, DocumentId documentId, string designerAttributeArgument)
{
if (workspace == null)
{
return;
}
_notificationService.RegisterNotification(() =>
{
var vsDocument = workspace.GetHostDocument(documentId);
if (vsDocument == null)
{
return;
}
uint itemId = vsDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// it is no longer part of the solution
return;
}
object currentValue;
if (ErrorHandler.Succeeded(vsDocument.Project.Hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_ItemSubType, out currentValue)))
{
var currentStringValue = string.IsNullOrEmpty(currentValue as string) ? null : (string)currentValue;
if (string.Equals(currentStringValue, designerAttributeArgument, StringComparison.OrdinalIgnoreCase))
{
// PERF: Avoid sending the message if the project system already has the current value.
return;
}
}
try
{
var designer = GetDesignerFromForegroundThread();
if (designer != null)
{
designer.RegisterDesignViewAttribute(vsDocument.Project.Hierarchy, (int)itemId, dwClass: 0, pwszAttributeValue: designerAttributeArgument);
}
}
catch
{
// DevDiv # 933717
// turns out RegisterDesignViewAttribute can throw in certain cases such as a file failed to be checked out by source control
// or IVSHierarchy failed to set a property for this project
//
// just swallow it. don't crash VS.
}
}, _listener.BeginAsyncOperation("RegisterDesignerAttribute"));
}
private IVSMDDesignerService GetDesignerFromForegroundThread()
{
if (_dotNotAccessDirectlyDesigner != null)
{
return _dotNotAccessDirectlyDesigner;
}
AssertIsForeground();
_dotNotAccessDirectlyDesigner = _serviceProvider.GetService(typeof(SVSMDDesignerService)) as IVSMDDesignerService;
return _dotNotAccessDirectlyDesigner;
}
private void InvalidateDocument(Document document)
{
_state.Remove(document.Id);
RegisterDesignerAttribute(document, designerAttributeArgument: null);
}
public void RemoveDocument(DocumentId documentId)
{
_state.Remove(documentId);
}
private class Data
{
public readonly VersionStamp TextVersion;
public readonly VersionStamp SemanticVersion;
public readonly string DesignerAttributeArgument;
public Data(VersionStamp textVersion, VersionStamp semanticVersion, string designerAttributeArgument)
{
this.TextVersion = textVersion;
this.SemanticVersion = semanticVersion;
this.DesignerAttributeArgument = designerAttributeArgument;
}
}
#region unused
public System.Threading.Tasks.Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public System.Threading.Tasks.Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public System.Threading.Tasks.Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public System.Threading.Tasks.Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public void RemoveProject(ProjectId projectId)
{
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="CloudAnchorsExampleController.cs" company="Google">
//
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore.Examples.CloudAnchors
{
using GoogleARCore;
using UnityEngine;
using UnityEngine.Networking;
#if UNITY_EDITOR
// Set up touch input propagation while using Instant Preview in the editor.
using Input = GoogleARCore.InstantPreviewInput;
#endif
/// <summary>
/// Controller for the Cloud Anchors Example. Handles the ARCore lifecycle.
/// </summary>
public class CloudAnchorsExampleController : MonoBehaviour
{
[Header("ARCore")]
/// <summary>
/// The UI Controller.
/// </summary>
public NetworkManagerUIController UIController;
/// <summary>
/// The root for ARCore-specific GameObjects in the scene.
/// </summary>
public GameObject ARCoreRoot;
/// <summary>
/// The helper that will calculate the World Origin offset when performing a raycast or
/// generating planes.
/// </summary>
public ARCoreWorldOriginHelper ARCoreWorldOriginHelper;
[Header("ARKit")]
/// <summary>
/// The root for ARKit-specific GameObjects in the scene.
/// </summary>
public GameObject ARKitRoot;
/// <summary>
/// The first-person camera used to render the AR background texture for ARKit.
/// </summary>
public Camera ARKitFirstPersonCamera;
/// <summary>
/// A helper object to ARKit functionality.
/// </summary>
private ARKitHelper m_ARKit = new ARKitHelper();
/// <summary>
/// Indicates whether the Origin of the new World Coordinate System, i.e. the Cloud Anchor,
/// was placed.
/// </summary>
private bool m_IsOriginPlaced = false;
/// <summary>
/// Indicates whether the Anchor was already instantiated.
/// </summary>
private bool m_AnchorAlreadyInstantiated = false;
/// <summary>
/// Indicates whether the Cloud Anchor finished hosting.
/// </summary>
private bool m_AnchorFinishedHosting = false;
/// <summary>
/// True if the app is in the process of quitting due to an ARCore connection error,
/// otherwise false.
/// </summary>
private bool m_IsQuitting = false;
/// <summary>
/// The anchor component that defines the shared world origin.
/// </summary>
private Component m_WorldOriginAnchor = null;
/// <summary>
/// The last pose of the hit point from AR hit test.
/// </summary>
private Pose? m_LastHitPose = null;
/// <summary>
/// The current cloud anchor mode.
/// </summary>
private ApplicationMode m_CurrentMode = ApplicationMode.Ready;
/// <summary>
/// The Network Manager.
/// </summary>
#pragma warning disable 618
private NetworkManager m_NetworkManager;
#pragma warning restore 618
private bool m_MatchStarted = false;
/// <summary>
/// Enumerates modes the example application can be in.
/// </summary>
public enum ApplicationMode
{
Ready,
Hosting,
Resolving,
}
/// <summary>
/// The Unity Start() method.
/// </summary>
public void Start()
{
#pragma warning disable 618
m_NetworkManager = UIController.GetComponent<NetworkManager>();
#pragma warning restore 618
// A Name is provided to the Game Object so it can be found by other Scripts
// instantiated as prefabs in the scene.
gameObject.name = "CloudAnchorsExampleController";
ARCoreRoot.SetActive(false);
ARKitRoot.SetActive(false);
_ResetStatus();
}
/// <summary>
/// The Unity Update() method.
/// </summary>
public void Update()
{
_UpdateApplicationLifecycle();
// If we are neither in hosting nor resolving mode then the update is complete.
if (m_CurrentMode != ApplicationMode.Hosting &&
m_CurrentMode != ApplicationMode.Resolving)
{
return;
}
// If the origin anchor has not been placed yet, then update in resolving mode is
// complete.
if (m_CurrentMode == ApplicationMode.Resolving && !m_IsOriginPlaced)
{
return;
}
// If the player has not touched the screen then the update is complete.
Touch touch;
if (Input.touchCount < 1 || (touch = Input.GetTouch(0)).phase != TouchPhase.Began)
{
return;
}
TrackableHit arcoreHitResult = new TrackableHit();
m_LastHitPose = null;
// Raycast against the location the player touched to search for planes.
if (Application.platform != RuntimePlatform.IPhonePlayer)
{
if (ARCoreWorldOriginHelper.Raycast(touch.position.x, touch.position.y,
TrackableHitFlags.PlaneWithinPolygon, out arcoreHitResult))
{
m_LastHitPose = arcoreHitResult.Pose;
}
}
else
{
Pose hitPose;
if (m_ARKit.RaycastPlane(
ARKitFirstPersonCamera, touch.position.x, touch.position.y, out hitPose))
{
m_LastHitPose = hitPose;
}
}
// If there was an anchor placed, then instantiate the corresponding object.
if (m_LastHitPose != null)
{
// The first touch on the Hosting mode will instantiate the origin anchor. Any
// subsequent touch will instantiate a star, both in Hosting and Resolving modes.
if (_CanPlaceStars())
{
_InstantiateStar();
}
else if (!m_IsOriginPlaced && m_CurrentMode == ApplicationMode.Hosting)
{
if (Application.platform != RuntimePlatform.IPhonePlayer)
{
m_WorldOriginAnchor =
arcoreHitResult.Trackable.CreateAnchor(arcoreHitResult.Pose);
}
else
{
m_WorldOriginAnchor = m_ARKit.CreateAnchor(m_LastHitPose.Value);
}
SetWorldOrigin(m_WorldOriginAnchor.transform);
_InstantiateAnchor();
OnAnchorInstantiated(true);
}
}
}
/// <summary>
/// Sets the apparent world origin so that the Origin of Unity's World Coordinate System
/// coincides with the Anchor. This function needs to be called once the Cloud Anchor is
/// either hosted or resolved.
/// </summary>
/// <param name="anchorTransform">Transform of the Cloud Anchor.</param>
public void SetWorldOrigin(Transform anchorTransform)
{
if (m_IsOriginPlaced)
{
Debug.LogWarning("The World Origin can be set only once.");
return;
}
m_IsOriginPlaced = true;
if (Application.platform != RuntimePlatform.IPhonePlayer)
{
ARCoreWorldOriginHelper.SetWorldOrigin(anchorTransform);
}
else
{
m_ARKit.SetWorldOrigin(anchorTransform);
}
}
/// <summary>
/// Handles user intent to enter a mode where they can place an anchor to host or to exit
/// this mode if already in it.
/// </summary>
public void OnEnterHostingModeClick()
{
if (m_CurrentMode == ApplicationMode.Hosting)
{
m_CurrentMode = ApplicationMode.Ready;
_ResetStatus();
return;
}
m_CurrentMode = ApplicationMode.Hosting;
_SetPlatformActive();
}
/// <summary>
/// Handles a user intent to enter a mode where they can input an anchor to be resolved or
/// exit this mode if already in it.
/// </summary>
public void OnEnterResolvingModeClick()
{
if (m_CurrentMode == ApplicationMode.Resolving)
{
m_CurrentMode = ApplicationMode.Ready;
_ResetStatus();
return;
}
m_CurrentMode = ApplicationMode.Resolving;
_SetPlatformActive();
}
/// <summary>
/// Callback indicating that the Cloud Anchor was instantiated and the host request was
/// made.
/// </summary>
/// <param name="isHost">Indicates whether this player is the host.</param>
public void OnAnchorInstantiated(bool isHost)
{
if (m_AnchorAlreadyInstantiated)
{
return;
}
m_AnchorAlreadyInstantiated = true;
UIController.OnAnchorInstantiated(isHost);
}
/// <summary>
/// Callback indicating that the Cloud Anchor was hosted.
/// </summary>
/// <param name="success">If set to <c>true</c> indicates the Cloud Anchor was hosted
/// successfully.</param>
/// <param name="response">The response string received.</param>
public void OnAnchorHosted(bool success, string response)
{
m_AnchorFinishedHosting = success;
UIController.OnAnchorHosted(success, response);
}
/// <summary>
/// Callback indicating that the Cloud Anchor was resolved.
/// </summary>
/// <param name="success">If set to <c>true</c> indicates the Cloud Anchor was resolved
/// successfully.</param>
/// <param name="response">The response string received.</param>
public void OnAnchorResolved(bool success, string response)
{
UIController.OnAnchorResolved(success, response);
}
/// <summary>
/// Instantiates the anchor object at the pose of the m_LastPlacedAnchor Anchor. This will
/// host the Cloud Anchor.
/// </summary>
private void _InstantiateAnchor()
{
// The anchor will be spawned by the host, so no networking Command is needed.
GameObject.Find("LocalPlayer").GetComponent<LocalPlayerController>()
.SpawnAnchor(Vector3.zero, Quaternion.identity, m_WorldOriginAnchor);
}
/// <summary>
/// Instantiates a star object that will be synchronized over the network to other clients.
/// </summary>
private void _InstantiateStar()
{
// Star must be spawned in the server so a networking Command is used.
GameObject.Find("LocalPlayer").GetComponent<LocalPlayerController>()
.CmdSpawnStar(m_LastHitPose.Value.position, m_LastHitPose.Value.rotation);
}
/// <summary>
/// Sets the corresponding platform active.
/// </summary>
private void _SetPlatformActive()
{
if (Application.platform != RuntimePlatform.IPhonePlayer)
{
ARCoreRoot.SetActive(true);
ARKitRoot.SetActive(false);
}
else
{
ARCoreRoot.SetActive(false);
ARKitRoot.SetActive(true);
}
}
/// <summary>
/// Indicates whether a star can be placed.
/// </summary>
/// <returns><c>true</c>, if stars can be placed, <c>false</c> otherwise.</returns>
private bool _CanPlaceStars()
{
if (m_CurrentMode == ApplicationMode.Resolving)
{
return m_IsOriginPlaced;
}
if (m_CurrentMode == ApplicationMode.Hosting)
{
return m_IsOriginPlaced && m_AnchorFinishedHosting;
}
return false;
}
/// <summary>
/// Resets the internal status.
/// </summary>
private void _ResetStatus()
{
// Reset internal status.
m_CurrentMode = ApplicationMode.Ready;
if (m_WorldOriginAnchor != null)
{
Destroy(m_WorldOriginAnchor.gameObject);
}
m_WorldOriginAnchor = null;
}
/// <summary>
/// Check and update the application lifecycle.
/// </summary>
private void _UpdateApplicationLifecycle()
{
if (!m_MatchStarted && m_NetworkManager.IsClientConnected())
{
m_MatchStarted = true;
}
// Exit the app when the 'back' button is pressed.
if (Input.GetKey(KeyCode.Escape))
{
Application.Quit();
}
var sleepTimeout = SleepTimeout.NeverSleep;
#if !UNITY_IOS
// Only allow the screen to sleep when not tracking.
if (Session.Status != SessionStatus.Tracking)
{
const int lostTrackingSleepTimeout = 15;
sleepTimeout = lostTrackingSleepTimeout;
}
#endif
Screen.sleepTimeout = sleepTimeout;
if (m_IsQuitting)
{
return;
}
// Quit if ARCore was unable to connect and give Unity some time for the toast to
// appear.
if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
{
UIController.ShowErrorMessage(
"Camera permission is needed to run this application.");
m_IsQuitting = true;
Invoke("_DoQuit", 5.0f);
}
else if (Session.Status.IsError())
{
UIController.ShowErrorMessage(
"ARCore encountered a problem connecting. Please start the app again.");
m_IsQuitting = true;
Invoke("_DoQuit", 5.0f);
}
else if (m_MatchStarted && !m_NetworkManager.IsClientConnected())
{
UIController.ShowErrorMessage(
"Network session disconnected! Please start the app again.");
m_IsQuitting = true;
Invoke("_DoQuit", 5.0f);
}
}
/// <summary>
/// Actually quit the application.
/// </summary>
private void _DoQuit()
{
Application.Quit();
}
}
}
| |
using System;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Provider;
using PowerShellDBDrive.Drives;
using PowerShellDBDrive.DataModel;
namespace PowerShellDBDrive
{
[CmdletProvider("DatabaseProvider", ProviderCapabilities.None)]
public class DatabaseProvider : NavigationCmdletProvider
{
#region Drive Manipulation
/// <summary>
/// The Windows PowerShell engine calls this method when the New-Drive
/// cmdlet is run. This provider creates a connection to the database
/// file and sets the Connection property in the PSDriveInfo.
/// </summary>
/// <param name="drive">
/// Information describing the drive to create.
/// </param>
/// <returns>An object that describes the new drive.</returns>
protected override PSDriveInfo NewDrive(PSDriveInfo drive)
{
// Check to see if the supplied drive object is null.
if (drive == null)
{
WriteError(new ErrorRecord(
new ArgumentNullException("drive"),
"NullDrive",
ErrorCategory.InvalidArgument,
null));
return null;
}
if (drive.Root.Equals(DatabaseUtils.PATH_SEPARATOR))
{
WriteError(new ErrorRecord(new ArgumentException("Root cannot be path separator"), "BadRoot", ErrorCategory.InvalidArgument, null));
return null;
}
var driveParams = this.DynamicParameters as DatabaseParameters;
DatabaseDriveInfo driveInfo = DatabaseDriveInfoFactory.NewInstance(drive, driveParams);
WriteDebug(String.Format("Parsed Connection String : {0}", driveInfo.ParsedConnectionString));
return driveInfo;
}
/// <summary>
/// The Windows PowerShell engine calls this method when the
/// Remove-Drive cmdlet is run.
/// </summary>
/// <param name="drive">The drive to remove.</param>
/// <returns>The drive to be removed.</returns>
protected override PSDriveInfo RemoveDrive(PSDriveInfo drive)
{
// Check to see if the supplied drive object is null.
if (drive == null)
{
WriteError(new ErrorRecord(new ArgumentNullException("drive"), "NullDrive", ErrorCategory.InvalidArgument, drive));
return null;
}
DatabaseDriveInfo driveInfo = drive as DatabaseDriveInfo;
if (driveInfo == null)
{
return null;
}
return driveInfo;
}
protected override object NewDriveDynamicParameters()
{
return new DatabaseParameters();
}
#endregion Drive Manipulation
#region Item Methods
/// <summary>
/// The Windows PowerShell engine calls this method when the Get-Item
/// cmdlet is run.
/// </summary>
/// <param name="path">The path to the item to return.</param>
protected override void GetItem(string path)
{
WriteVerbose(string.Format("GetItem: <- Path='{0}'", path));
DatabaseDriveInfo di = PSDriveInfo as DatabaseDriveInfo;
if (di == null)
{
return;
}
PathDescriptor pathDescriptor = new PathDescriptor(path);
switch (pathDescriptor.PathType)
{
case PathType.Database:
WriteVerbose("GetItem: -> Database");
WriteItemObject(PSDriveInfo, di.GetRootDrive(), true);
break;
case PathType.Schema:
IDatabaseSchemaInfo schema = di.GetSchema(pathDescriptor.SchemaName);
WriteVerbose("GetItem: -> Schema");
WriteItemObject(schema, path, true);
break;
case PathType.ObjectType:
WriteVerbose("GetItem: -> ObjectType");
WriteItemObject(pathDescriptor.DatabaseObjectType, path, true);
break;
case PathType.Object:
switch (pathDescriptor.DatabaseObjectType)
{
case ObjectType.TABLE:
{
IDatabaseTableInfo table = di.GetTable(pathDescriptor.SchemaName, pathDescriptor.ObjectPath[0]);
WriteVerbose("GetItem: -> Object - Table");
WriteItemObject(table, path, true);
break;
}
case ObjectType.VIEW:
{
IDatabaseViewInfo table = di.GetView(pathDescriptor.SchemaName, pathDescriptor.ObjectPath[0]);
WriteVerbose("GetItem: -> Object - View");
WriteItemObject(table, path, true);
break;
}
default:
ThrowTerminatingInvalidPathException(path);
break;
}
break;
case PathType.Row:
WriteVerbose("GetItem: -> Row");
/// WriteItemObject(row, path, false);
break;
default:
ThrowTerminatingInvalidPathException(path);
break;
}
}
/// <summary>
/// Test to see if the specified path is syntactically valid.
/// </summary>
/// <param name="path">The path to validate.</param>
/// <returns>True if the specified path is valid.</returns>
protected override bool IsValidPath(string path)
{
// Check to see if the path is null or empty.
WriteVerbose(string.Format("IsValidPath:{0}", path));
if (string.IsNullOrEmpty(path))
{
return false;
}
return DatabaseUtils.PATH_VALIDATOR.IsMatch(path);
}
/// <summary>
/// Test to see if the specified item exists.
/// </summary>
/// <param name="path">The path to the item to verify.</param>
/// <returns>True if the item is found.</returns>
protected override bool ItemExists(string path)
{
WriteVerbose(string.Format("ItemExists: <- Path='{0}'", path));
DatabaseDriveInfo di = PSDriveInfo as DatabaseDriveInfo;
if (di == null)
{
WriteVerbose("ItemExists: -> false");
return false;
}
PathDescriptor pathDescriptor = new PathDescriptor(path);
switch (pathDescriptor.PathType)
{
case PathType.Database:
{
WriteVerbose("ItemExists: {PathType.Database} -> true");
return true;
}
case PathType.Schema:
{
bool result = di.IsSchemaExist(pathDescriptor.SchemaName);
WriteVerbose(string.Format("ItemExists: {{PathType.Schema}} -> {0}", result));
return result;
}
case PathType.ObjectType:
{
WriteVerbose("ItemExists: {PathType.ObjectType} -> true");
return true;
}
case PathType.Object:
{
bool result = di.IsObjectExist(pathDescriptor.SchemaName, pathDescriptor.DatabaseObjectType, pathDescriptor.ObjectPath);
WriteVerbose(string.Format("ItemExists: {{PathType.Object}} -> {0},{1}", pathDescriptor.ObjectPath, result));
return result;
}
case PathType.Row:
{
WriteVerbose("ItemExists: {PathType.Row} -> false");
return false;
}
default:
WriteVerbose("ItemExists: {PathType.Invalid} -> false");
return false;
}
}
/// <summary>
/// Checks to see if the table name is valid.
/// </summary>
/// <param name="tableName">Table name to validate</param>
/// <remarks>Helps to check for SQL injection attacks</remarks>
/// <returns>A Boolean value indicating true if the name is valid.</returns>
private bool TableNameIsValid(string tableName)
{
if (!DatabaseUtils.NameIsValid(tableName))
{
WriteError(new ErrorRecord(
new ArgumentException("Table name not valid"),
"TableNameNotValid",
ErrorCategory.InvalidArgument,
tableName));
return false;
}
return true;
}
/// <summary>
/// Checks to see if the schema name is valid.
/// </summary>
/// <param name="schemaName">Schema name to validate</param>
/// <remarks>Helps to check for SQL injection attacks</remarks>
/// <returns>A Boolean value indicating true if the name is valid.</returns>
private bool SchemaNameIsValid(string schemaName)
{
if (!DatabaseUtils.NameIsValid(schemaName))
{
WriteError(new ErrorRecord(
new ArgumentException("Schema name not valid"),
"SchemaNameNotValid",
ErrorCategory.InvalidArgument,
schemaName));
return false;
}
return true;
}
#endregion Item Methods
#region Container Methods
/// <summary>
/// The Windows PowerShell engine calls this method when the Get-ChildItem
/// cmdlet is run. This provider returns either the tables in the database
/// or the rows of the table.
/// </summary>
/// <param name="path">The path to the parent item.</param>
/// <param name="recurse">A Boolean value that indicates true to return all
/// child items recursively.
/// </param>
protected override void GetChildItems(string path, bool recurse)
{
WriteVerbose(string.Format("GetChildItems: <- Path='{0}', Recurse='{1}'", path, recurse));
DatabaseDriveInfo di = PSDriveInfo as DatabaseDriveInfo;
if (di == null)
{
return;
}
PathDescriptor pathDescriptor = new PathDescriptor(path);
switch (pathDescriptor.PathType)
{
case PathType.Database:
WriteVerbose("GetChildItems: -- Database");
foreach (IDatabaseSchemaInfo schema in di.GetSchemas())
{
WriteVerbose(string.Format("GetChildItems: ---> Database schema '{0}'", schema.SchemaName));
string outputPath = di.GetRootDrive() + schema.SchemaName;
WriteItemObject(schema, outputPath, true);
if (recurse)
{
GetChildItems(outputPath, recurse);
}
}
WriteVerbose("GetChildItems: -- Database Done");
break;
case PathType.Schema:
WriteVerbose("GetChildItems: -- Schema");
foreach (ObjectType objectType in di.GetSupportedObjectTypes(pathDescriptor.SchemaName))
{
string outputPath = di.GetRootDrive() + pathDescriptor.SchemaName + DatabaseUtils.PATH_SEPARATOR + objectType;
WriteItemObject(objectType, outputPath, false);
}
WriteVerbose("GetChildItems: -- Schema Done");
break;
case PathType.ObjectType:
WriteVerbose("GetChildItems: -- ObjectType");
foreach (IDatabaseTableInfo table in di.GetTables(pathDescriptor.SchemaName))
{
WriteVerbose(string.Format("GetChildItems: ---> Database table '{0}'", table.TableName));
string outputPath = di.GetRootDrive() + pathDescriptor.SchemaName + DatabaseUtils.PATH_SEPARATOR + pathDescriptor.DatabaseObjectType + DatabaseUtils.PATH_SEPARATOR + table.TableName;
WriteItemObject(table, outputPath, true);
if (recurse)
{
GetChildItems(outputPath, recurse);
}
}
WriteVerbose("GetChildItems: -- ObjectType Done");
break;
case PathType.Object:
WriteVerbose("GetChildItems: -- Table");
foreach (PSObject row in di.GetRows(pathDescriptor.SchemaName, pathDescriptor.ObjectPath[0]))
{
WriteItemObject(row, path, false);
}
WriteVerbose("GetChildItems: -- Table Done");
break;
default:
ThrowTerminatingInvalidPathException(path);
break;
}
}
/// <summary>
/// Return the names of all child items.
/// </summary>
/// <param name="path">The root path.</param>
/// <param name="returnContainers">This parameter is not used.</param>
protected override void GetChildNames(string path, ReturnContainers returnContainers)
{
WriteVerbose(string.Format("GetChildNames: <- Path='{0}'", path));
DatabaseDriveInfo di = PSDriveInfo as DatabaseDriveInfo;
if (di == null)
{
return;
}
PathDescriptor pathDescriptor = new PathDescriptor(path);
switch (pathDescriptor.PathType)
{
case PathType.Database:
{
foreach (IDatabaseSchemaInfo schema in di.GetSchemas())
{
WriteItemObject(schema.SchemaName, path, true);
}
break;
}
case PathType.Schema:
{
foreach (IDatabaseTableInfo table in di.GetTables(pathDescriptor.SchemaName))
{
WriteItemObject(table.TableName, path, true);
}
break;
}
case PathType.ObjectType:
{
foreach (ObjectType objectType in di.GetSupportedObjectTypes(pathDescriptor.SchemaName))
{
WriteItemObject(objectType.GetTypeCode(), path, true);
}
break;
}
case PathType.Object:
foreach (PSObject row in di.GetRows(pathDescriptor.SchemaName, pathDescriptor.ObjectPath[0]))
{
/// TODO WriteItemObject(row.Properties[], path, false);
}
break;
case PathType.Row:
break;
default:
ThrowTerminatingInvalidPathException(path);
break;
}
}
/// <summary>
/// Determines if the specified path has child items.
/// </summary>
/// <param name="path">The path to examine.</param>
/// <returns>
/// True if the specified path has child items.
/// </returns>
protected override bool HasChildItems(string path)
{
WriteVerbose(string.Format("HasChildItems: <- Path='{0}'", path));
PathDescriptor pathDescriptor = new PathDescriptor(path);
switch(pathDescriptor.PathType)
{
case PathType.Root:
case PathType.Database:
case PathType.Schema:
case PathType.ObjectType:
return true;
case PathType.Object:
return true;
}
return false;
}
#endregion Container Methods
#region Navigation Methods
/// <summary>
/// Determine if the path specified is that of a container.
/// </summary>
/// <param name="path">The path to check.</param>
/// <returns>True if the path specifies a container.</returns>
protected override bool IsItemContainer(string path)
{
WriteVerbose(string.Format("IsItemContainer: <- Path='{0}'", path));
PathDescriptor pathDescriptor = new PathDescriptor(path);
if (pathDescriptor.PathType == PathType.Row)
{
WriteVerbose("IsItemContainer: -> false");
return false;
}
WriteVerbose("IsItemContainer: -> true");
return true;
}
/// <summary>
/// Gets the name of the leaf element in the specified path.
/// </summary>
/// <param name="path">
/// The full or partial provider specific path.
/// </param>
/// <returns>
/// The leaf element in the path.
/// </returns>
/*protected override string GetChildName(string path)
{
WriteVerbose(string.Format("GetChildName: <- Path='{0}'", path));
path = path.Replace("*", string.Empty);
PathDescriptor pathDescription = new PathDescriptor(path);
switch (pathDescription.PathType)
{
case PathType.Database:
WriteVerbose(string.Format("GetChildName: -> {{Database}} Name='{0}'", path));
return path;
case PathType.Schema:
WriteVerbose(string.Format("GetChildName: -> {{Schema}} Name='{0}'", pathDescription.SchemaName));
return pathDescription.SchemaName;
case PathType.ObjectType:
WriteVerbose(string.Format("GetChildName: -> {{DatabaseObjectType}} Name='{0}'", pathDescription.DatabaseObjectType));
return pathDescription.DatabaseObjectType.ToString();
case PathType.Object:
WriteVerbose(string.Format("GetChildName: -> {{Object}} Name='{0}'", pathDescription.ObjectPath[0]));
return pathDescription.ObjectPath[0];
case PathType.Row:
/// WriteVerbose(string.Format("GetChildName: -> {{Row}} Name='{0}'", key));
/// return key;
default:
ThrowTerminatingInvalidPathException(path);
break;
}
return null;
}*/
/// <summary>
/// Returns the parent portion of the path, removing the child
/// segment of the path.
/// </summary>
/// <param name="path">
/// A full or partial provider specific path. The path may be to an
/// item that may or may not exist.
/// </param>
/// <param name="root">
/// The fully qualified path to the root of a drive. This parameter
/// may be null or empty if a mounted drive is not in use for this
/// operation. If this parameter is not null or empty the result
/// of the method should not be a path to a container that is a
/// parent or in a different tree than the root.
/// </param>
/// <returns>The parent portion of the path.</returns>
protected override string GetParentPath(string path, string root)
{
// If the root is specified then the path has to contain
// the root. If not nothing should be returned.
WriteVerbose(string.Format("GetParentPath: <- Path='{0}', Root='{1}'", path, root));
DatabaseDriveInfo di = PSDriveInfo as DatabaseDriveInfo;
if (di == null)
{
return null;
}
if (path.Equals(di.GetRootDrive()))
{
return string.Empty;
}
path = path.Replace(di.GetRootDrive(), string.Empty);
if (!string.IsNullOrEmpty(root))
{
if (!path.Contains(root))
{
WriteVerbose(string.Format("GetParentPath: -> '{0}'", root));
return root;
}
}
if (!path.Contains(DatabaseUtils.PATH_SEPARATOR))
{
WriteVerbose(string.Format("GetParentPath: -> '{0}'", di.GetRootDrive()));
return di.GetRootDrive();
}
string result = path.Substring(0, path.LastIndexOf(DatabaseUtils.PATH_SEPARATOR, StringComparison.OrdinalIgnoreCase));
WriteVerbose(string.Format("GetParentPath: -> '{0}'", result));
return result;
}
/// <summary>
/// Normalizes the path so that it is a relative path to the
/// basePath that was passed.
/// </summary>
/// <param name="path">
/// A fully qualified provider specific path to an item. The item
/// should exist or the provider should write out an error.
/// </param>
/// <param name="basepath">
/// The path that the return value should be relative to.
/// </param>
/// <returns>
/// A normalized path that is relative to the basePath that was
/// passed. The provider should parse the path parameter, normalize
/// the path, and then return the normalized path relative to the
/// basePath.
/// </returns>
protected override string NormalizeRelativePath(string path, string basepath)
{
WriteVerbose(string.Format("NormalizeRelativePath: <- Path='{0}', Basepath='{1}'", path, basepath));
DatabaseDriveInfo di = PSDriveInfo as DatabaseDriveInfo;
// Normalize the paths first.
string normalPath = DatabaseUtils.NormalizePath(path);
normalPath = DatabaseUtils.RemoveDriveFromPath(normalPath, di.GetRootDrive());
string normalBasePath = DatabaseUtils.NormalizePath(basepath);
normalBasePath = DatabaseUtils.RemoveDriveFromPath(normalBasePath, di.GetRootDrive());
if (string.IsNullOrEmpty(normalBasePath))
{
return normalPath;
}
else
{
if (!normalPath.Contains(normalBasePath))
{
return null;
}
return normalPath.Substring(normalBasePath.Length + DatabaseUtils.PATH_SEPARATOR.Length);
}
}
/// <summary>
/// Joins two strings with a provider specific path separator.
/// </summary>
/// <param name="parent">
/// The parent segment of a path to be joined with the child.
/// </param>
/// <param name="child">
/// The child segment of a path to be joined with the parent.
/// </param>
/// <returns>
/// A string that contains the parent and child segments of the path
/// joined by a path separator.
/// </returns>
protected override string MakePath(string parent, string child)
{
WriteVerbose(string.Format("MakePath: <- Parent='{0}', Child='{1}'", parent, child));
DatabaseDriveInfo di = PSDriveInfo as DatabaseDriveInfo;
string result;
string normalParent = DatabaseUtils.NormalizePath(parent);
if (normalParent.EndsWith(DatabaseUtils.PATH_SEPARATOR))
{
normalParent = normalParent.Remove(normalParent.Length - 1);
}
string normalChild = DatabaseUtils.NormalizePath(child);
if (normalChild.StartsWith(DatabaseUtils.PATH_SEPARATOR))
{
normalChild = normalChild.Substring(1);
}
if (String.IsNullOrEmpty(normalParent))
{
if (String.IsNullOrEmpty(normalChild))
{
result = String.Empty;
}
else
{
result = normalChild;
}
}
else
{
if (String.IsNullOrEmpty(normalChild))
{
result = normalParent + DatabaseUtils.PATH_SEPARATOR;
}
else
{
result = normalParent + DatabaseUtils.PATH_SEPARATOR + normalChild;
}
}
WriteVerbose(string.Format("MakePath: -> {0}", result));
return result;
}
#endregion Navigation Methods
#region Provider Capabilities
/**protected override string[] ExpandPath(string path)
{
DatabaseDriveInfo di = PSDriveInfo as DatabaseDriveInfo;
if (di == null)
{
return null;
}
path = path.Replace("*", string.Empty);
PathDescriptor pathDescriptor = new PathDescriptor(path);
switch (pathDescriptor.PathType)
{
case PathType.Database:
return di.GetSchemasNames("").ToArray();
case PathType.Schema:
return di.GetSchemasNames("^" + pathDescriptor.SchemaName + ".*").ToArray();
case PathType.Object:
return di.GetTablesNames("^" + pathDescriptor.ObjectPath[0] + ".*").ToArray();
}
return null;
}*/
#endregion Provider Capabilities
private void ThrowTerminatingInvalidPathException(string path)
{
throw new ArgumentException(string.Format("Path must represent either a table or a row : {0}", path));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
namespace System.Net.Security
{
//
// Used when working with SSPI APIs, like SafeSspiAuthDataHandle(). Holds the pointer to the auth data blob.
//
#if DEBUG
internal sealed class SafeSspiAuthDataHandle : DebugSafeHandle
{
#else
internal sealed class SafeSspiAuthDataHandle : SafeHandleZeroOrMinusOneIsInvalid
{
#endif
public SafeSspiAuthDataHandle() : base(true)
{
}
protected override bool ReleaseHandle()
{
return Interop.SspiCli.SspiFreeAuthIdentity(handle) == Interop.SecurityStatus.OK;
}
}
//
// A set of Safe Handles that depend on native FreeContextBuffer finalizer.
//
#if DEBUG
internal abstract class SafeFreeContextBuffer : DebugSafeHandle
{
#else
internal abstract class SafeFreeContextBuffer : SafeHandleZeroOrMinusOneIsInvalid
{
#endif
protected SafeFreeContextBuffer() : base(true) { }
// This must be ONLY called from this file.
internal void Set(IntPtr value)
{
this.handle = value;
}
internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray)
{
int res = -1;
SafeFreeContextBuffer_SECURITY pkgArray_SECURITY = null;
res = Interop.SspiCli.EnumerateSecurityPackagesW(out pkgnum, out pkgArray_SECURITY);
pkgArray = pkgArray_SECURITY;
if (res != 0 && pkgArray != null)
{
pkgArray.SetHandleAsInvalid();
}
return res;
}
internal static SafeFreeContextBuffer CreateEmptyHandle()
{
return new SafeFreeContextBuffer_SECURITY();
}
//
// After PInvoke call the method will fix the refHandle.handle with the returned value.
// The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned.
//
// This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and
// reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.)
//
public unsafe static int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle)
{
return QueryContextAttributes_SECURITY(phContext, contextAttribute, buffer, refHandle);
}
private unsafe static int QueryContextAttributes_SECURITY(
SafeDeleteContext phContext,
Interop.SspiCli.ContextAttribute contextAttribute,
byte* buffer,
SafeHandle refHandle)
{
int status = (int)Interop.SecurityStatus.InvalidHandle;
try
{
bool ignore = false;
phContext.DangerousAddRef(ref ignore);
status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer);
}
finally
{
phContext.DangerousRelease();
}
if (status == 0 && refHandle != null)
{
if (refHandle is SafeFreeContextBuffer)
{
((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer);
}
else
{
((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer);
}
}
if (status != 0 && refHandle != null)
{
refHandle.SetHandleAsInvalid();
}
return status;
}
public static int SetContextAttributes(
SafeDeleteContext phContext,
Interop.SspiCli.ContextAttribute contextAttribute, byte[] buffer)
{
return SetContextAttributes_SECURITY(phContext, contextAttribute, buffer);
}
private static int SetContextAttributes_SECURITY(
SafeDeleteContext phContext,
Interop.SspiCli.ContextAttribute contextAttribute,
byte[] buffer)
{
try
{
bool ignore = false;
phContext.DangerousAddRef(ref ignore);
return Interop.SspiCli.SetContextAttributesW(ref phContext._handle, contextAttribute, buffer, buffer.Length);
}
finally
{
phContext.DangerousRelease();
}
}
}
internal sealed class SafeFreeContextBuffer_SECURITY : SafeFreeContextBuffer
{
internal SafeFreeContextBuffer_SECURITY() : base() { }
protected override bool ReleaseHandle()
{
return Interop.SspiCli.FreeContextBuffer(handle) == 0;
}
}
//
// Implementation of handles required CertFreeCertificateContext
//
#if DEBUG
internal sealed class SafeFreeCertContext : DebugSafeHandle
{
#else
internal sealed class SafeFreeCertContext : SafeHandleZeroOrMinusOneIsInvalid
{
#endif
internal SafeFreeCertContext() : base(true) { }
// This must be ONLY called from this file.
internal void Set(IntPtr value)
{
this.handle = value;
}
private const uint CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040;
protected override bool ReleaseHandle()
{
Interop.Crypt32.CertFreeCertificateContext(handle);
return true;
}
}
//
// Implementation of handles dependable on FreeCredentialsHandle
//
#if DEBUG
internal abstract class SafeFreeCredentials : DebugSafeHandle
{
#else
internal abstract class SafeFreeCredentials : SafeHandle
{
#endif
internal Interop.SspiCli.SSPIHandle _handle; //should be always used as by ref in PInvokes parameters
protected SafeFreeCredentials() : base(IntPtr.Zero, true)
{
_handle = new Interop.SspiCli.SSPIHandle();
}
#if TRACE_VERBOSE
public override string ToString()
{
return "0x" + _handle.ToString();
}
#endif
public override bool IsInvalid
{
get { return IsClosed || _handle.IsZero; }
}
#if DEBUG
public new IntPtr DangerousGetHandle()
{
Debug.Fail("This method should never be called for this type");
throw NotImplemented.ByDesign;
}
#endif
public unsafe static int AcquireCredentialsHandle(
string package,
Interop.SspiCli.CredentialUse intent,
ref Interop.SspiCli.AuthIdentity authdata,
out SafeFreeCredentials outCredential)
{
bool globalLogEnabled = GlobalLog.IsEnabled;
if (globalLogEnabled)
{
GlobalLog.Print("SafeFreeCredentials::AcquireCredentialsHandle#1("
+ package + ", "
+ intent + ", "
+ authdata + ")");
}
int errorCode = -1;
long timeStamp;
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.SspiCli.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
ref authdata,
null,
null,
ref outCredential._handle,
out timeStamp);
#if TRACE_VERBOSE
if (globalLogEnabled)
{
GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x"
+ String.Format("{0:x}", errorCode)
+ ", handle = " + outCredential.ToString());
}
#endif
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
public unsafe static int AcquireDefaultCredential(
string package,
Interop.SspiCli.CredentialUse intent,
out SafeFreeCredentials outCredential)
{
bool globalLogEnabled = GlobalLog.IsEnabled;
if (globalLogEnabled)
{
GlobalLog.Print("SafeFreeCredentials::AcquireDefaultCredential("
+ package + ", "
+ intent + ")");
}
int errorCode = -1;
long timeStamp;
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.SspiCli.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
IntPtr.Zero,
null,
null,
ref outCredential._handle,
out timeStamp);
#if TRACE_VERBOSE
if (globalLogEnabled)
{
GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x"
+ errorCode.ToString("x")
+ ", handle = " + outCredential.ToString());
}
#endif
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
public unsafe static int AcquireCredentialsHandle(
string package,
Interop.SspiCli.CredentialUse intent,
ref SafeSspiAuthDataHandle authdata,
out SafeFreeCredentials outCredential)
{
int errorCode = -1;
long timeStamp;
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.SspiCli.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
authdata,
null,
null,
ref outCredential._handle,
out timeStamp);
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
public unsafe static int AcquireCredentialsHandle(
string package,
Interop.SspiCli.CredentialUse intent,
ref Interop.SspiCli.SecureCredential authdata,
out SafeFreeCredentials outCredential)
{
bool globalLogEnabled = GlobalLog.IsEnabled;
if (globalLogEnabled)
{
GlobalLog.Print("SafeFreeCredentials::AcquireCredentialsHandle#2("
+ package + ", "
+ intent + ", "
+ authdata + ")");
}
int errorCode = -1;
long timeStamp;
// If there is a certificate, wrap it into an array.
// Not threadsafe.
IntPtr copiedPtr = authdata.certContextArray;
try
{
IntPtr certArrayPtr = new IntPtr(&copiedPtr);
if (copiedPtr != IntPtr.Zero)
{
authdata.certContextArray = certArrayPtr;
}
outCredential = new SafeFreeCredential_SECURITY();
errorCode = Interop.SspiCli.AcquireCredentialsHandleW(
null,
package,
(int)intent,
null,
ref authdata,
null,
null,
ref outCredential._handle,
out timeStamp);
}
finally
{
authdata.certContextArray = copiedPtr;
}
#if TRACE_VERBOSE
if (globalLogEnabled)
{
GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x"
+ errorCode.ToString("x")
+ ", handle = " + outCredential.ToString());
}
#endif
if (errorCode != 0)
{
outCredential.SetHandleAsInvalid();
}
return errorCode;
}
}
//
// This is a class holding a Credential handle reference, used for static handles cache
//
#if DEBUG
internal sealed class SafeCredentialReference : DebugCriticalHandleMinusOneIsInvalid
{
#else
internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid
{
#endif
//
// Static cache will return the target handle if found the reference in the table.
//
internal SafeFreeCredentials Target;
internal static SafeCredentialReference CreateReference(SafeFreeCredentials target)
{
SafeCredentialReference result = new SafeCredentialReference(target);
if (result.IsInvalid)
{
return null;
}
return result;
}
private SafeCredentialReference(SafeFreeCredentials target) : base()
{
// Bumps up the refcount on Target to signify that target handle is statically cached so
// its dispose should be postponed
bool ignore = false;
target.DangerousAddRef(ref ignore);
Target = target;
SetHandle(new IntPtr(0)); // make this handle valid
}
protected override bool ReleaseHandle()
{
SafeFreeCredentials target = Target;
if (target != null)
{
target.DangerousRelease();
}
Target = null;
return true;
}
}
internal sealed class SafeFreeCredential_SECURITY : SafeFreeCredentials
{
public SafeFreeCredential_SECURITY() : base() { }
protected override bool ReleaseHandle()
{
return Interop.SspiCli.FreeCredentialsHandle(ref _handle) == 0;
}
}
//
// Implementation of handles that are dependent on DeleteSecurityContext
//
#if DEBUG
internal abstract class SafeDeleteContext : DebugSafeHandle
{
#else
internal abstract class SafeDeleteContext : SafeHandle
{
#endif
private const string dummyStr = " ";
private static readonly byte[] s_dummyBytes = new byte[] { 0 };
//
// ATN: _handle is internal since it is used on PInvokes by other wrapper methods.
// However all such wrappers MUST manually and reliably adjust refCounter of SafeDeleteContext handle.
//
internal Interop.SspiCli.SSPIHandle _handle;
protected SafeFreeCredentials _EffectiveCredential;
protected SafeDeleteContext() : base(IntPtr.Zero, true)
{
_handle = new Interop.SspiCli.SSPIHandle();
}
public override bool IsInvalid
{
get
{
return IsClosed || _handle.IsZero;
}
}
public override string ToString()
{
return _handle.ToString();
}
#if DEBUG
//This method should never be called for this type
public new IntPtr DangerousGetHandle()
{
throw new InvalidOperationException();
}
#endif
//-------------------------------------------------------------------
internal unsafe static int InitializeSecurityContext(
ref SafeFreeCredentials inCredentials,
ref SafeDeleteContext refContext,
string targetName,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
SecurityBuffer inSecBuffer,
SecurityBuffer[] inSecBuffers,
SecurityBuffer outSecBuffer,
ref Interop.SspiCli.ContextFlags outFlags)
{
bool globalLogEnabled = GlobalLog.IsEnabled;
#if TRACE_VERBOSE
if (globalLogEnabled)
{
GlobalLog.Enter("SafeDeleteContext::InitializeSecurityContext");
GlobalLog.Print(" credential = " + inCredentials.ToString());
GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext));
GlobalLog.Print(" targetName = " + targetName);
GlobalLog.Print(" inFlags = " + inFlags);
GlobalLog.Print(" reservedI = 0x0");
GlobalLog.Print(" endianness = " + endianness);
if (inSecBuffers == null)
{
GlobalLog.Print(" inSecBuffers = (null)");
}
else
{
GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
}
}
#endif
if (globalLogEnabled)
{
if (outSecBuffer == null)
{
GlobalLog.Assert("SafeDeleteContext::InitializeSecurityContext()|outSecBuffer != null");
}
if (inSecBuffer != null && inSecBuffers != null)
{
GlobalLog.Assert("SafeDeleteContext::InitializeSecurityContext()|inSecBuffer == null || inSecBuffers == null");
}
}
if (inCredentials == null)
{
throw new ArgumentNullException("inCredentials");
}
Interop.SspiCli.SecurityBufferDescriptor inSecurityBufferDescriptor = null;
if (inSecBuffer != null)
{
inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(1);
}
else if (inSecBuffers != null)
{
inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(inSecBuffers.Length);
}
Interop.SspiCli.SecurityBufferDescriptor outSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(1);
// Actually, this is returned in outFlags.
bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false;
int errorCode = -1;
Interop.SspiCli.SSPIHandle contextHandle = new Interop.SspiCli.SSPIHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
GCHandle pinnedOutBytes = new GCHandle();
// Optional output buffer that may need to be freed.
SafeFreeContextBuffer outFreeContextBuffer = null;
try
{
pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
Interop.SspiCli.SecurityBufferStruct[] inUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
if (inSecurityBufferDescriptor != null)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index)
{
securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index];
if (securityBuffer != null)
{
// Copy the SecurityBuffer content into unmanaged place holder.
inUnmanagedBuffer[index].count = securityBuffer.size;
inUnmanagedBuffer[index].type = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].token = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
if (globalLogEnabled)
{
GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
}
#endif
}
}
}
Interop.SspiCli.SecurityBufferStruct[] outUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[1];
fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr;
outUnmanagedBuffer[0].count = outSecBuffer.size;
outUnmanagedBuffer[0].type = outSecBuffer.type;
if (outSecBuffer.token == null || outSecBuffer.token.Length == 0)
{
outUnmanagedBuffer[0].token = IntPtr.Zero;
}
else
{
outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);
}
if (isSspiAllocated)
{
outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle();
}
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
if (targetName == null || targetName.Length == 0)
{
targetName = dummyStr;
}
fixed (char* namePtr = targetName)
{
errorCode = MustRunInitializeSecurityContext_SECURITY(
ref inCredentials,
contextHandle.IsZero ? null : &contextHandle,
(byte*)(((object)targetName == (object)dummyStr) ? null : namePtr),
inFlags,
endianness,
inSecurityBufferDescriptor,
refContext,
outSecurityBufferDescriptor,
ref outFlags,
outFreeContextBuffer);
}
if (globalLogEnabled)
{
GlobalLog.Print("SafeDeleteContext:InitializeSecurityContext Marshalling OUT buffer");
}
// Get unmanaged buffer with index 0 as the only one passed into PInvoke.
outSecBuffer.size = outUnmanagedBuffer[0].count;
outSecBuffer.type = outUnmanagedBuffer[0].type;
if (outSecBuffer.size > 0)
{
outSecBuffer.token = new byte[outSecBuffer.size];
Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size);
}
else
{
outSecBuffer.token = null;
}
}
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
if (pinnedOutBytes.IsAllocated)
{
pinnedOutBytes.Free();
}
if (outFreeContextBuffer != null)
{
outFreeContextBuffer.Dispose();
}
}
if (globalLogEnabled)
{
GlobalLog.Leave("SafeDeleteContext::InitializeSecurityContext() unmanaged InitializeSecurityContext()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext));
}
return errorCode;
}
//
// After PInvoke call the method will fix the handleTemplate.handle with the returned value.
// The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned.
//
private static unsafe int MustRunInitializeSecurityContext_SECURITY(
ref SafeFreeCredentials inCredentials,
void* inContextPtr,
byte* targetName,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
Interop.SspiCli.SecurityBufferDescriptor inputBuffer,
SafeDeleteContext outContext,
Interop.SspiCli.SecurityBufferDescriptor outputBuffer,
ref Interop.SspiCli.ContextFlags attributes,
SafeFreeContextBuffer handleTemplate)
{
int errorCode = (int)Interop.SecurityStatus.InvalidHandle;
try
{
bool ignore = false;
inCredentials.DangerousAddRef(ref ignore);
outContext.DangerousAddRef(ref ignore);
Interop.SspiCli.SSPIHandle credentialHandle = inCredentials._handle;
long timeStamp;
errorCode = Interop.SspiCli.InitializeSecurityContextW(
ref credentialHandle,
inContextPtr,
targetName,
inFlags,
0,
endianness,
inputBuffer,
0,
ref outContext._handle,
outputBuffer,
ref attributes,
out timeStamp);
}
finally
{
//
// When a credential handle is first associated with the context we keep credential
// ref count bumped up to ensure ordered finalization.
// If the credential handle has been changed we de-ref the old one and associate the
// context with the new cred handle but only if the call was successful.
if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0)
{
// Disassociate the previous credential handle
if (outContext._EffectiveCredential != null)
{
outContext._EffectiveCredential.DangerousRelease();
}
outContext._EffectiveCredential = inCredentials;
}
else
{
inCredentials.DangerousRelease();
}
outContext.DangerousRelease();
}
// The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer.
if (handleTemplate != null)
{
//ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes
handleTemplate.Set(((Interop.SspiCli.SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token);
if (handleTemplate.IsInvalid)
{
handleTemplate.SetHandleAsInvalid();
}
}
if (inContextPtr == null && (errorCode & 0x80000000) != 0)
{
// an error on the first call, need to set the out handle to invalid value
outContext._handle.SetToInvalid();
}
return errorCode;
}
//-------------------------------------------------------------------
internal unsafe static int AcceptSecurityContext(
ref SafeFreeCredentials inCredentials,
ref SafeDeleteContext refContext,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
SecurityBuffer inSecBuffer,
SecurityBuffer[] inSecBuffers,
SecurityBuffer outSecBuffer,
ref Interop.SspiCli.ContextFlags outFlags)
{
bool globalLogEnabled = GlobalLog.IsEnabled;
#if TRACE_VERBOSE
if (globalLogEnabled)
{
GlobalLog.Enter("SafeDeleteContext::AcceptSecurityContex");
GlobalLog.Print(" credential = " + inCredentials.ToString());
GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext));
GlobalLog.Print(" inFlags = " + inFlags);
if (inSecBuffers == null)
{
GlobalLog.Print(" inSecBuffers = (null)");
}
else
{
GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
}
}
#endif
if (globalLogEnabled)
{
if (outSecBuffer == null)
{
GlobalLog.Assert("SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null");
}
if (inSecBuffer != null && inSecBuffers != null)
{
GlobalLog.Assert("SafeDeleteContext::AcceptSecurityContext()|inSecBuffer == null || inSecBuffers == null");
}
}
if (inCredentials == null)
{
throw new ArgumentNullException("inCredentials");
}
Interop.SspiCli.SecurityBufferDescriptor inSecurityBufferDescriptor = null;
if (inSecBuffer != null)
{
inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(1);
}
else if (inSecBuffers != null)
{
inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(inSecBuffers.Length);
}
Interop.SspiCli.SecurityBufferDescriptor outSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(1);
// Actually, this is returned in outFlags.
bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false;
int errorCode = -1;
Interop.SspiCli.SSPIHandle contextHandle = new Interop.SspiCli.SSPIHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
GCHandle pinnedOutBytes = new GCHandle();
// Optional output buffer that may need to be freed.
SafeFreeContextBuffer outFreeContextBuffer = null;
try
{
pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
var inUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
if (inSecurityBufferDescriptor != null)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index)
{
securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index];
if (securityBuffer != null)
{
// Copy the SecurityBuffer content into unmanaged place holder.
inUnmanagedBuffer[index].count = securityBuffer.size;
inUnmanagedBuffer[index].type = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].token = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
if (globalLogEnabled)
{
GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
}
#endif
}
}
}
var outUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[1];
fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr;
// Copy the SecurityBuffer content into unmanaged place holder.
outUnmanagedBuffer[0].count = outSecBuffer.size;
outUnmanagedBuffer[0].type = outSecBuffer.type;
if (outSecBuffer.token == null || outSecBuffer.token.Length == 0)
{
outUnmanagedBuffer[0].token = IntPtr.Zero;
}
else
{
outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);
}
if (isSspiAllocated)
{
outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle();
}
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
errorCode = MustRunAcceptSecurityContext_SECURITY(
ref inCredentials,
contextHandle.IsZero ? null : &contextHandle,
inSecurityBufferDescriptor,
inFlags,
endianness,
refContext,
outSecurityBufferDescriptor,
ref outFlags,
outFreeContextBuffer);
if (globalLogEnabled)
{
GlobalLog.Print("SafeDeleteContext:AcceptSecurityContext Marshalling OUT buffer");
}
// Get unmanaged buffer with index 0 as the only one passed into PInvoke.
outSecBuffer.size = outUnmanagedBuffer[0].count;
outSecBuffer.type = outUnmanagedBuffer[0].type;
if (outSecBuffer.size > 0)
{
outSecBuffer.token = new byte[outSecBuffer.size];
Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size);
}
else
{
outSecBuffer.token = null;
}
}
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
if (pinnedOutBytes.IsAllocated)
{
pinnedOutBytes.Free();
}
if (outFreeContextBuffer != null)
{
outFreeContextBuffer.Dispose();
}
}
if (globalLogEnabled)
{
GlobalLog.Leave("SafeDeleteContext::AcceptSecurityContex() unmanaged AcceptSecurityContex()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext));
}
return errorCode;
}
//
// After PInvoke call the method will fix the handleTemplate.handle with the returned value.
// The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned.
//
private static unsafe int MustRunAcceptSecurityContext_SECURITY(
ref SafeFreeCredentials inCredentials,
void* inContextPtr,
Interop.SspiCli.SecurityBufferDescriptor inputBuffer,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
SafeDeleteContext outContext,
Interop.SspiCli.SecurityBufferDescriptor outputBuffer,
ref Interop.SspiCli.ContextFlags outFlags,
SafeFreeContextBuffer handleTemplate)
{
int errorCode = (int)Interop.SecurityStatus.InvalidHandle;
// Run the body of this method as a non-interruptible block.
try
{
bool ignore = false;
inCredentials.DangerousAddRef(ref ignore);
outContext.DangerousAddRef(ref ignore);
Interop.SspiCli.SSPIHandle credentialHandle = inCredentials._handle;
long timeStamp;
errorCode = Interop.SspiCli.AcceptSecurityContext(
ref credentialHandle,
inContextPtr,
inputBuffer,
inFlags,
endianness,
ref outContext._handle,
outputBuffer,
ref outFlags,
out timeStamp);
}
finally
{
//
// When a credential handle is first associated with the context we keep credential
// ref count bumped up to ensure ordered finalization.
// If the credential handle has been changed we de-ref the old one and associate the
// context with the new cred handle but only if the call was successful.
if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0)
{
// Disassociate the previous credential handle.
if (outContext._EffectiveCredential != null)
{
outContext._EffectiveCredential.DangerousRelease();
}
outContext._EffectiveCredential = inCredentials;
}
else
{
inCredentials.DangerousRelease();
}
outContext.DangerousRelease();
}
// The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer.
if (handleTemplate != null)
{
//ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes.
handleTemplate.Set(((Interop.SspiCli.SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token);
if (handleTemplate.IsInvalid)
{
handleTemplate.SetHandleAsInvalid();
}
}
if (inContextPtr == null && (errorCode & 0x80000000) != 0)
{
// An error on the first call, need to set the out handle to invalid value.
outContext._handle.SetToInvalid();
}
return errorCode;
}
internal unsafe static int CompleteAuthToken(
ref SafeDeleteContext refContext,
SecurityBuffer[] inSecBuffers)
{
bool globalLogEnabled = GlobalLog.IsEnabled;
if (globalLogEnabled)
{
GlobalLog.Enter("SafeDeleteContext::CompleteAuthToken");
GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext));
#if TRACE_VERBOSE
GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
#endif
if (inSecBuffers == null)
{
GlobalLog.Assert("SafeDeleteContext::CompleteAuthToken()|inSecBuffers == null");
}
}
var inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(inSecBuffers.Length);
int errorCode = (int)Interop.SecurityStatus.InvalidHandle;
// These are pinned user byte arrays passed along with SecurityBuffers.
GCHandle[] pinnedInBytes = null;
var inUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[inSecurityBufferDescriptor.Count];
fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
{
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr;
pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count];
SecurityBuffer securityBuffer;
for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index)
{
securityBuffer = inSecBuffers[index];
if (securityBuffer != null)
{
inUnmanagedBuffer[index].count = securityBuffer.size;
inUnmanagedBuffer[index].type = securityBuffer.type;
// Use the unmanaged token if it's not null; otherwise use the managed buffer.
if (securityBuffer.unmanagedToken != null)
{
inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle();
}
else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
{
inUnmanagedBuffer[index].token = IntPtr.Zero;
}
else
{
pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
if (globalLogEnabled)
{
GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
}
#endif
}
}
Interop.SspiCli.SSPIHandle contextHandle = new Interop.SspiCli.SSPIHandle();
if (refContext != null)
{
contextHandle = refContext._handle;
}
try
{
if (refContext == null || refContext.IsInvalid)
{
refContext = new SafeDeleteContext_SECURITY();
}
try
{
bool ignore = false;
refContext.DangerousAddRef(ref ignore);
errorCode = Interop.SspiCli.CompleteAuthToken(contextHandle.IsZero ? null : &contextHandle, inSecurityBufferDescriptor);
}
finally
{
refContext.DangerousRelease();
}
}
finally
{
if (pinnedInBytes != null)
{
for (int index = 0; index < pinnedInBytes.Length; index++)
{
if (pinnedInBytes[index].IsAllocated)
{
pinnedInBytes[index].Free();
}
}
}
}
}
if (globalLogEnabled)
{
GlobalLog.Leave("SafeDeleteContext::CompleteAuthToken() unmanaged CompleteAuthToken()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext));
}
return errorCode;
}
}
internal sealed class SafeDeleteContext_SECURITY : SafeDeleteContext
{
internal SafeDeleteContext_SECURITY() : base() { }
protected override bool ReleaseHandle()
{
if (this._EffectiveCredential != null)
{
this._EffectiveCredential.DangerousRelease();
}
return Interop.SspiCli.DeleteSecurityContext(ref _handle) == 0;
}
}
// Based on SafeFreeContextBuffer.
internal abstract class SafeFreeContextBufferChannelBinding : ChannelBinding
{
private int _size;
public override int Size
{
get { return _size; }
}
public override bool IsInvalid
{
get { return handle == new IntPtr(0) || handle == new IntPtr(-1); }
}
internal unsafe void Set(IntPtr value)
{
this.handle = value;
}
internal static SafeFreeContextBufferChannelBinding CreateEmptyHandle()
{
return new SafeFreeContextBufferChannelBinding_SECURITY();
}
public unsafe static int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle)
{
return QueryContextChannelBinding_SECURITY(phContext, contextAttribute, buffer, refHandle);
}
private unsafe static int QueryContextChannelBinding_SECURITY(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle)
{
int status = (int)Interop.SecurityStatus.InvalidHandle;
// SCHANNEL only supports SECPKG_ATTR_ENDPOINT_BINDINGS and SECPKG_ATTR_UNIQUE_BINDINGS which
// map to our enum ChannelBindingKind.Endpoint and ChannelBindingKind.Unique.
if (contextAttribute != Interop.SspiCli.ContextAttribute.EndpointBindings &&
contextAttribute != Interop.SspiCli.ContextAttribute.UniqueBindings)
{
return status;
}
try
{
bool ignore = false;
phContext.DangerousAddRef(ref ignore);
status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer);
}
finally
{
phContext.DangerousRelease();
}
if (status == 0 && refHandle != null)
{
refHandle.Set((*buffer).pBindings);
refHandle._size = (*buffer).BindingsLength;
}
if (status != 0 && refHandle != null)
{
refHandle.SetHandleAsInvalid();
}
return status;
}
}
internal sealed class SafeFreeContextBufferChannelBinding_SECURITY : SafeFreeContextBufferChannelBinding
{
protected override bool ReleaseHandle()
{
return Interop.SspiCli.FreeContextBuffer(handle) == 0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace System.ComponentModel.DataAnnotations
{
/// <summary>
/// Cache of <see cref="ValidationAttribute" />s
/// </summary>
/// <remarks>
/// This internal class serves as a cache of validation attributes and [Display] attributes.
/// It exists both to help performance as well as to abstract away the differences between
/// Reflection and TypeDescriptor.
/// </remarks>
internal class ValidationAttributeStore
{
private static readonly ValidationAttributeStore _singleton = new ValidationAttributeStore();
private readonly Dictionary<Type, TypeStoreItem> _typeStoreItems = new Dictionary<Type, TypeStoreItem>();
/// <summary>
/// Gets the singleton <see cref="ValidationAttributeStore" />
/// </summary>
internal static ValidationAttributeStore Instance
{
get { return _singleton; }
}
/// <summary>
/// Retrieves the type level validation attributes for the given type.
/// </summary>
/// <param name="validationContext">The context that describes the type. It cannot be null.</param>
/// <returns>The collection of validation attributes. It could be empty.</returns>
internal IEnumerable<ValidationAttribute> GetTypeValidationAttributes(ValidationContext validationContext)
{
EnsureValidationContext(validationContext);
var item = GetTypeStoreItem(validationContext.ObjectType);
return item.ValidationAttributes;
}
/// <summary>
/// Retrieves the <see cref="DisplayAttribute" /> associated with the given type. It may be null.
/// </summary>
/// <param name="validationContext">The context that describes the type. It cannot be null.</param>
/// <returns>The display attribute instance, if present.</returns>
internal DisplayAttribute GetTypeDisplayAttribute(ValidationContext validationContext)
{
EnsureValidationContext(validationContext);
var item = GetTypeStoreItem(validationContext.ObjectType);
return item.DisplayAttribute;
}
/// <summary>
/// Retrieves the set of validation attributes for the property
/// </summary>
/// <param name="validationContext">The context that describes the property. It cannot be null.</param>
/// <returns>The collection of validation attributes. It could be empty.</returns>
internal IEnumerable<ValidationAttribute> GetPropertyValidationAttributes(ValidationContext validationContext)
{
EnsureValidationContext(validationContext);
var typeItem = GetTypeStoreItem(validationContext.ObjectType);
var item = typeItem.GetPropertyStoreItem(validationContext.MemberName);
return item.ValidationAttributes;
}
/// <summary>
/// Retrieves the <see cref="DisplayAttribute" /> associated with the given property
/// </summary>
/// <param name="validationContext">The context that describes the property. It cannot be null.</param>
/// <returns>The display attribute instance, if present.</returns>
internal DisplayAttribute GetPropertyDisplayAttribute(ValidationContext validationContext)
{
EnsureValidationContext(validationContext);
var typeItem = GetTypeStoreItem(validationContext.ObjectType);
var item = typeItem.GetPropertyStoreItem(validationContext.MemberName);
return item.DisplayAttribute;
}
/// <summary>
/// Retrieves the Type of the given property.
/// </summary>
/// <param name="validationContext">The context that describes the property. It cannot be null.</param>
/// <returns>The type of the specified property</returns>
internal Type GetPropertyType(ValidationContext validationContext)
{
EnsureValidationContext(validationContext);
var typeItem = GetTypeStoreItem(validationContext.ObjectType);
var item = typeItem.GetPropertyStoreItem(validationContext.MemberName);
return item.PropertyType;
}
/// <summary>
/// Determines whether or not a given <see cref="ValidationContext" />'s
/// <see cref="ValidationContext.MemberName" /> references a property on
/// the <see cref="ValidationContext.ObjectType" />.
/// </summary>
/// <param name="validationContext">The <see cref="ValidationContext" /> to check.</param>
/// <returns><c>true</c> when the <paramref name="validationContext" /> represents a property, <c>false</c> otherwise.</returns>
internal bool IsPropertyContext(ValidationContext validationContext)
{
EnsureValidationContext(validationContext);
var typeItem = GetTypeStoreItem(validationContext.ObjectType);
PropertyStoreItem item;
return typeItem.TryGetPropertyStoreItem(validationContext.MemberName, out item);
}
/// <summary>
/// Retrieves or creates the store item for the given type
/// </summary>
/// <param name="type">The type whose store item is needed. It cannot be null</param>
/// <returns>The type store item. It will not be null.</returns>
private TypeStoreItem GetTypeStoreItem(Type type)
{
Debug.Assert(type != null);
lock (_typeStoreItems)
{
TypeStoreItem item = null;
if (!_typeStoreItems.TryGetValue(type, out item))
{
// use CustomAttributeExtensions.GetCustomAttributes() to get inherited attributes as well as direct ones
var attributes = CustomAttributeExtensions.GetCustomAttributes(type, true);
item = new TypeStoreItem(type, attributes);
_typeStoreItems[type] = item;
}
return item;
}
}
/// <summary>
/// Throws an ArgumentException of the validation context is null
/// </summary>
/// <param name="validationContext">The context to check</param>
private static void EnsureValidationContext(ValidationContext validationContext)
{
if (validationContext == null)
{
throw new ArgumentNullException(nameof(validationContext));
}
}
internal static bool IsPublic(PropertyInfo p)
{
return (p.GetMethod != null && p.GetMethod.IsPublic) || (p.SetMethod != null && p.SetMethod.IsPublic);
}
internal static bool IsStatic(PropertyInfo p)
{
return (p.GetMethod != null && p.GetMethod.IsStatic) || (p.SetMethod != null && p.SetMethod.IsStatic);
}
/// <summary>
/// Private abstract class for all store items
/// </summary>
private abstract class StoreItem
{
private readonly IEnumerable<ValidationAttribute> _validationAttributes;
internal StoreItem(IEnumerable<Attribute> attributes)
{
_validationAttributes = attributes.OfType<ValidationAttribute>();
DisplayAttribute = attributes.OfType<DisplayAttribute>().SingleOrDefault();
}
internal IEnumerable<ValidationAttribute> ValidationAttributes
{
get { return _validationAttributes; }
}
internal DisplayAttribute DisplayAttribute { get; set; }
}
/// <summary>
/// Private class to store data associated with a type
/// </summary>
private class TypeStoreItem : StoreItem
{
private readonly object _syncRoot = new object();
private readonly Type _type;
private Dictionary<string, PropertyStoreItem> _propertyStoreItems;
internal TypeStoreItem(Type type, IEnumerable<Attribute> attributes)
: base(attributes)
{
_type = type;
}
internal PropertyStoreItem GetPropertyStoreItem(string propertyName)
{
PropertyStoreItem item = null;
if (!TryGetPropertyStoreItem(propertyName, out item))
{
throw new ArgumentException(
string.Format(CultureInfo.CurrentCulture,
SR.AttributeStore_Unknown_Property, _type.Name, propertyName),
nameof(propertyName));
}
return item;
}
internal bool TryGetPropertyStoreItem(string propertyName, out PropertyStoreItem item)
{
if (string.IsNullOrEmpty(propertyName))
{
throw new ArgumentNullException(nameof(propertyName));
}
if (_propertyStoreItems == null)
{
lock (_syncRoot)
{
if (_propertyStoreItems == null)
{
_propertyStoreItems = CreatePropertyStoreItems();
}
}
}
return _propertyStoreItems.TryGetValue(propertyName, out item);
}
private Dictionary<string, PropertyStoreItem> CreatePropertyStoreItems()
{
var propertyStoreItems = new Dictionary<string, PropertyStoreItem>();
// exclude index properties to match old TypeDescriptor functionality
var properties = _type.GetRuntimeProperties()
.Where(prop => IsPublic(prop) && !prop.GetIndexParameters().Any());
foreach (PropertyInfo property in properties)
{
// use CustomAttributeExtensions.GetCustomAttributes() to get inherited attributes as well as direct ones
var item = new PropertyStoreItem(property.PropertyType,
CustomAttributeExtensions.GetCustomAttributes(property, true));
propertyStoreItems[property.Name] = item;
}
return propertyStoreItems;
}
}
/// <summary>
/// Private class to store data associated with a property
/// </summary>
private class PropertyStoreItem : StoreItem
{
private readonly Type _propertyType;
internal PropertyStoreItem(Type propertyType, IEnumerable<Attribute> attributes)
: base(attributes)
{
_propertyType = propertyType;
}
internal Type PropertyType
{
get { return _propertyType; }
}
}
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MessageTransferModule")]
public class MessageTransferModule : ISharedRegionModule, IMessageTransferModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
protected List<Scene> m_Scenes = new List<Scene>();
protected Dictionary<UUID, UUID> m_UserRegionMap = new Dictionary<UUID, UUID>();
public event UndeliveredMessage OnUndeliveredMessage;
private IPresenceService m_PresenceService;
protected IPresenceService PresenceService
{
get
{
if (m_PresenceService == null)
m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
return m_PresenceService;
}
}
public virtual void Initialise(IConfigSource config)
{
IConfig cnf = config.Configs["Messaging"];
if (cnf != null && cnf.GetString(
"MessageTransferModule", "MessageTransferModule") !=
"MessageTransferModule")
{
m_log.Debug("[MESSAGE TRANSFER]: Disabled by configuration");
return;
}
m_Enabled = true;
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_log.Debug("[MESSAGE TRANSFER]: Message transfer module active");
scene.RegisterModuleInterface<IMessageTransferModule>(this);
m_Scenes.Add(scene);
}
}
public virtual void PostInitialise()
{
if (!m_Enabled)
return;
MainServer.Instance.AddXmlRPCHandler(
"grid_instant_message", processXMLRPCGridInstantMessage);
}
public virtual void RegionLoaded(Scene scene)
{
}
public virtual void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_Scenes.Remove(scene);
}
}
public virtual void Close()
{
}
public virtual string Name
{
get { return "MessageTransferModule"; }
}
public virtual Type ReplaceableInterface
{
get { return null; }
}
public virtual void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
{
UUID toAgentID = new UUID(im.toAgentID);
// Try root avatar only first
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[INSTANT MESSAGE]: Looking for root agent {0} in {1}",
// toAgentID.ToString(), scene.RegionInfo.RegionName);
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null && !sp.IsChildAgent)
{
// Local message
// m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to root agent {0} {1}", sp.Name, toAgentID);
sp.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
// try child avatar second
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[INSTANT MESSAGE]: Looking for child of {0} in {1}", toAgentID, scene.RegionInfo.RegionName);
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null)
{
// Local message
// m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to child agent {0} {1}", sp.Name, toAgentID);
sp.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
// m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to {0} via XMLRPC", im.toAgentID);
SendGridInstantMessageViaXMLRPC(im, result);
}
public void HandleUndeliverableMessage(GridInstantMessage im, MessageResultNotification result)
{
UndeliveredMessage handlerUndeliveredMessage = OnUndeliveredMessage;
// If this event has handlers, then an IM from an agent will be
// considered delivered. This will suppress the error message.
//
if (handlerUndeliveredMessage != null)
{
handlerUndeliveredMessage(im);
if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
result(true);
else
result(false);
return;
}
//m_log.DebugFormat("[INSTANT MESSAGE]: Undeliverable");
result(false);
}
/// <summary>
/// Process a XMLRPC Grid Instant Message
/// </summary>
/// <param name="request">XMLRPC parameters
/// </param>
/// <returns>Nothing much</returns>
protected virtual XmlRpcResponse processXMLRPCGridInstantMessage(XmlRpcRequest request, IPEndPoint remoteClient)
{
bool successful = false;
// TODO: For now, as IMs seem to be a bit unreliable on OSGrid, catch all exception that
// happen here and aren't caught and log them.
try
{
// various rational defaults
UUID fromAgentID = UUID.Zero;
UUID toAgentID = UUID.Zero;
UUID imSessionID = UUID.Zero;
uint timestamp = 0;
string fromAgentName = "";
string message = "";
byte dialog = (byte)0;
bool fromGroup = false;
byte offline = (byte)0;
uint ParentEstateID=0;
Vector3 Position = Vector3.Zero;
UUID RegionID = UUID.Zero ;
byte[] binaryBucket = new byte[0];
float pos_x = 0;
float pos_y = 0;
float pos_z = 0;
//m_log.Info("Processing IM");
Hashtable requestData = (Hashtable)request.Params[0];
// Check if it's got all the data
if (requestData.ContainsKey("from_agent_id")
&& requestData.ContainsKey("to_agent_id") && requestData.ContainsKey("im_session_id")
&& requestData.ContainsKey("timestamp") && requestData.ContainsKey("from_agent_name")
&& requestData.ContainsKey("message") && requestData.ContainsKey("dialog")
&& requestData.ContainsKey("from_group")
&& requestData.ContainsKey("offline") && requestData.ContainsKey("parent_estate_id")
&& requestData.ContainsKey("position_x") && requestData.ContainsKey("position_y")
&& requestData.ContainsKey("position_z") && requestData.ContainsKey("region_id")
&& requestData.ContainsKey("binary_bucket"))
{
// Do the easy way of validating the UUIDs
UUID.TryParse((string)requestData["from_agent_id"], out fromAgentID);
UUID.TryParse((string)requestData["to_agent_id"], out toAgentID);
UUID.TryParse((string)requestData["im_session_id"], out imSessionID);
UUID.TryParse((string)requestData["region_id"], out RegionID);
try
{
timestamp = (uint)Convert.ToInt32((string)requestData["timestamp"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
fromAgentName = (string)requestData["from_agent_name"];
message = (string)requestData["message"];
if (message == null)
message = string.Empty;
// Bytes don't transfer well over XMLRPC, so, we Base64 Encode them.
string requestData1 = (string)requestData["dialog"];
if (string.IsNullOrEmpty(requestData1))
{
dialog = 0;
}
else
{
byte[] dialogdata = Convert.FromBase64String(requestData1);
dialog = dialogdata[0];
}
if ((string)requestData["from_group"] == "TRUE")
fromGroup = true;
string requestData2 = (string)requestData["offline"];
if (String.IsNullOrEmpty(requestData2))
{
offline = 0;
}
else
{
byte[] offlinedata = Convert.FromBase64String(requestData2);
offline = offlinedata[0];
}
try
{
ParentEstateID = (uint)Convert.ToInt32((string)requestData["parent_estate_id"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_x = (uint)Convert.ToInt32((string)requestData["position_x"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_y = (uint)Convert.ToInt32((string)requestData["position_y"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_z = (uint)Convert.ToInt32((string)requestData["position_z"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
Position = new Vector3(pos_x, pos_y, pos_z);
string requestData3 = (string)requestData["binary_bucket"];
if (string.IsNullOrEmpty(requestData3))
{
binaryBucket = new byte[0];
}
else
{
binaryBucket = Convert.FromBase64String(requestData3);
}
// Create a New GridInstantMessageObject the the data
GridInstantMessage gim = new GridInstantMessage();
gim.fromAgentID = fromAgentID.Guid;
gim.fromAgentName = fromAgentName;
gim.fromGroup = fromGroup;
gim.imSessionID = imSessionID.Guid;
gim.RegionID = RegionID.Guid;
gim.timestamp = timestamp;
gim.toAgentID = toAgentID.Guid;
gim.message = message;
gim.dialog = dialog;
gim.offline = offline;
gim.ParentEstateID = ParentEstateID;
gim.Position = Position;
gim.binaryBucket = binaryBucket;
// Trigger the Instant message in the scene.
foreach (Scene scene in m_Scenes)
{
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null && !sp.IsChildAgent)
{
scene.EventManager.TriggerIncomingInstantMessage(gim);
successful = true;
}
}
if (!successful)
{
// If the message can't be delivered to an agent, it
// is likely to be a group IM. On a group IM, the
// imSessionID = toAgentID = group id. Raise the
// unhandled IM event to give the groups module
// a chance to pick it up. We raise that in a random
// scene, since the groups module is shared.
//
m_Scenes[0].EventManager.TriggerUnhandledInstantMessage(gim);
}
}
}
catch (Exception e)
{
m_log.Error("[INSTANT MESSAGE]: Caught unexpected exception:", e);
successful = false;
}
//Send response back to region calling if it was successful
// calling region uses this to know when to look up a user's location again.
XmlRpcResponse resp = new XmlRpcResponse();
Hashtable respdata = new Hashtable();
if (successful)
respdata["success"] = "TRUE";
else
respdata["success"] = "FALSE";
resp.Value = respdata;
return resp;
}
/// <summary>
/// delegate for sending a grid instant message asynchronously
/// </summary>
public delegate void GridInstantMessageDelegate(GridInstantMessage im, MessageResultNotification result);
protected virtual void GridInstantMessageCompleted(IAsyncResult iar)
{
GridInstantMessageDelegate icon =
(GridInstantMessageDelegate)iar.AsyncState;
icon.EndInvoke(iar);
}
protected virtual void SendGridInstantMessageViaXMLRPC(GridInstantMessage im, MessageResultNotification result)
{
GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsync;
d.BeginInvoke(im, result, GridInstantMessageCompleted, d);
}
/// <summary>
/// Internal SendGridInstantMessage over XMLRPC method.
/// </summary>
/// <remarks>
/// This is called from within a dedicated thread.
/// </remarks>
private void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, MessageResultNotification result)
{
UUID toAgentID = new UUID(im.toAgentID);
UUID regionID;
bool needToLookupAgent;
lock (m_UserRegionMap)
needToLookupAgent = !m_UserRegionMap.TryGetValue(toAgentID, out regionID);
while (true)
{
if (needToLookupAgent)
{
PresenceInfo[] presences = PresenceService.GetAgents(new string[] { toAgentID.ToString() });
UUID foundRegionID = UUID.Zero;
if (presences != null)
{
foreach (PresenceInfo p in presences)
{
if (p.RegionID != UUID.Zero)
{
foundRegionID = p.RegionID;
break;
}
}
}
// If not found or the found region is the same as the last lookup, then message is undeliverable
if (foundRegionID == UUID.Zero || foundRegionID == regionID)
break;
else
regionID = foundRegionID;
}
GridRegion reginfo = m_Scenes[0].GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, regionID);
if (reginfo == null)
{
m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find region {0}", regionID);
break;
}
// Try to send the message to the agent via the retrieved region.
Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im);
msgdata["region_handle"] = 0;
bool imresult = doIMSending(reginfo, msgdata);
// If the message delivery was successful, then cache the entry.
if (imresult)
{
lock (m_UserRegionMap)
{
m_UserRegionMap[toAgentID] = regionID;
}
result(true);
return;
}
// If we reach this point in the first iteration of the while, then we may have unsuccessfully tried
// to use a locally cached region ID. All subsequent attempts need to lookup agent details from
// the presence service.
needToLookupAgent = true;
}
// If we reached this point then the message was not deliverable. Remove the bad cache entry and
// signal the delivery failure.
lock (m_UserRegionMap)
m_UserRegionMap.Remove(toAgentID);
// m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
HandleUndeliverableMessage(im, result);
}
/// <summary>
/// This actually does the XMLRPC Request
/// </summary>
/// <param name="reginfo">RegionInfo we pull the data out of to send the request to</param>
/// <param name="xmlrpcdata">The Instant Message data Hashtable</param>
/// <returns>Bool if the message was successfully delivered at the other side.</returns>
protected virtual bool doIMSending(GridRegion reginfo, Hashtable xmlrpcdata)
{
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
XmlRpcRequest GridReq = new XmlRpcRequest("grid_instant_message", SendParams);
try
{
XmlRpcResponse GridResp = GridReq.Send(reginfo.ServerURI, 3000);
Hashtable responseData = (Hashtable)GridResp.Value;
if (responseData.ContainsKey("success"))
{
if ((string)responseData["success"] == "TRUE")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
catch (WebException e)
{
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: Error sending message to {0} the host didn't respond " + e.ToString(), reginfo.ServerURI.ToString());
}
return false;
}
/// <summary>
/// Get ulong region handle for region by it's Region UUID.
/// We use region handles over grid comms because there's all sorts of free and cool caching.
/// </summary>
/// <param name="regionID">UUID of region to get the region handle for</param>
/// <returns></returns>
// private virtual ulong getLocalRegionHandleFromUUID(UUID regionID)
// {
// ulong returnhandle = 0;
//
// lock (m_Scenes)
// {
// foreach (Scene sn in m_Scenes)
// {
// if (sn.RegionInfo.RegionID == regionID)
// {
// returnhandle = sn.RegionInfo.RegionHandle;
// break;
// }
// }
// }
// return returnhandle;
// }
/// <summary>
/// Takes a GridInstantMessage and converts it into a Hashtable for XMLRPC
/// </summary>
/// <param name="msg">The GridInstantMessage object</param>
/// <returns>Hashtable containing the XMLRPC request</returns>
protected virtual Hashtable ConvertGridInstantMessageToXMLRPC(GridInstantMessage msg)
{
Hashtable gim = new Hashtable();
gim["from_agent_id"] = msg.fromAgentID.ToString();
// Kept for compatibility
gim["from_agent_session"] = UUID.Zero.ToString();
gim["to_agent_id"] = msg.toAgentID.ToString();
gim["im_session_id"] = msg.imSessionID.ToString();
gim["timestamp"] = msg.timestamp.ToString();
gim["from_agent_name"] = msg.fromAgentName;
gim["message"] = msg.message;
byte[] dialogdata = new byte[1];dialogdata[0] = msg.dialog;
gim["dialog"] = Convert.ToBase64String(dialogdata,Base64FormattingOptions.None);
if (msg.fromGroup)
gim["from_group"] = "TRUE";
else
gim["from_group"] = "FALSE";
byte[] offlinedata = new byte[1]; offlinedata[0] = msg.offline;
gim["offline"] = Convert.ToBase64String(offlinedata, Base64FormattingOptions.None);
gim["parent_estate_id"] = msg.ParentEstateID.ToString();
gim["position_x"] = msg.Position.X.ToString();
gim["position_y"] = msg.Position.Y.ToString();
gim["position_z"] = msg.Position.Z.ToString();
gim["region_id"] = new UUID(msg.RegionID).ToString();
gim["binary_bucket"] = Convert.ToBase64String(msg.binaryBucket,Base64FormattingOptions.None);
return gim;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.XWPF.UserModel
{
using System;
using NUnit.Framework;
using NPOI.XWPF;
using NPOI.OpenXmlFormats.Wordprocessing;
using System.Collections.Generic;
/**
* Tests for XWPF Run
*/
[TestFixture]
public class TestXWPFTable
{
[SetUp]
public void SetUp()
{
/*
XWPFDocument doc = new XWPFDocument();
p = doc.CreateParagraph();
this.ctRun = CTR.Factory.NewInstance();
*/
}
[Test]
public void TestConstructor()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
XWPFTable xtab = new XWPFTable(ctTable, doc);
Assert.IsNotNull(xtab);
Assert.AreEqual(1, ctTable.SizeOfTrArray());
Assert.AreEqual(1, ctTable.GetTrArray(0).SizeOfTcArray());
Assert.IsNotNull(ctTable.GetTrArray(0).GetTcArray(0).GetPArray(0));
ctTable = new CT_Tbl();
xtab = new XWPFTable(ctTable, doc, 3, 2);
Assert.IsNotNull(xtab);
Assert.AreEqual(3, ctTable.SizeOfTrArray());
Assert.AreEqual(2, ctTable.GetTrArray(0).SizeOfTcArray());
Assert.IsNotNull(ctTable.GetTrArray(0).GetTcArray(0).GetPArray(0));
}
[Test]
public void TestTblGrid()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
CT_TblGrid cttblgrid = ctTable.AddNewTblGrid();
cttblgrid.AddNewGridCol().w = 123;
cttblgrid.AddNewGridCol().w = 321;
XWPFTable xtab = new XWPFTable(ctTable, doc);
Assert.AreEqual(123, xtab.GetCTTbl().tblGrid.gridCol[0].w);
Assert.AreEqual(321, xtab.GetCTTbl().tblGrid.gridCol[1].w);
}
[Test]
public void TestGetText()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl table = new CT_Tbl();
CT_Row row = table.AddNewTr();
CT_Tc cell = row.AddNewTc();
CT_P paragraph = cell.AddNewP();
CT_R run = paragraph.AddNewR();
CT_Text text = run.AddNewT();
text.Value = ("finally I can Write!");
XWPFTable xtab = new XWPFTable(table, doc);
Assert.AreEqual("finally I can Write!\n", xtab.Text);
}
[Test]
public void TestCreateRow()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl table = new CT_Tbl();
CT_Row r1 = table.AddNewTr();
r1.AddNewTc().AddNewP();
r1.AddNewTc().AddNewP();
CT_Row r2 = table.AddNewTr();
r2.AddNewTc().AddNewP();
r2.AddNewTc().AddNewP();
CT_Row r3 = table.AddNewTr();
r3.AddNewTc().AddNewP();
r3.AddNewTc().AddNewP();
XWPFTable xtab = new XWPFTable(table, doc);
Assert.AreEqual(3, xtab.NumberOfRows);
Assert.IsNotNull(xtab.GetRow(2));
//add a new row
xtab.CreateRow();
Assert.AreEqual(4, xtab.NumberOfRows);
//check number of cols
Assert.AreEqual(2, table.GetTrArray(0).SizeOfTcArray());
//check creation of first row
xtab = new XWPFTable(new CT_Tbl(), doc);
Assert.AreEqual(1, xtab.GetCTTbl().GetTrArray(0).SizeOfTcArray());
}
[Test]
public void TestSetGetWidth()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl table = new CT_Tbl();
table.AddNewTblPr().AddNewTblW().w = "1000";
XWPFTable xtab = new XWPFTable(table, doc);
Assert.AreEqual(1000, xtab.Width);
xtab.Width = 100;
Assert.AreEqual(100, int.Parse(table.tblPr.tblW.w));
}
[Test]
public void TestSetGetHeight()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl table = new CT_Tbl();
XWPFTable xtab = new XWPFTable(table, doc);
XWPFTableRow row = xtab.CreateRow();
row.Height = (20);
Assert.AreEqual(20, row.Height);
}
[Test]
public void TestSetGetMargins()
{
// instantiate the following class so it'll Get picked up by
// the XmlBean process and Added to the jar file. it's required
// for the following XWPFTable methods.
CT_TblCellMar ctm = new CT_TblCellMar();
Assert.IsNotNull(ctm);
// create a table
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
XWPFTable table = new XWPFTable(ctTable, doc);
// Set margins
table.SetCellMargins(50, 50, 250, 450);
// Get margin components
int t = table.CellMarginTop;
Assert.AreEqual(50, t);
int l = table.CellMarginLeft;
Assert.AreEqual(50, l);
int b = table.CellMarginBottom;
Assert.AreEqual(250, b);
int r = table.CellMarginRight;
Assert.AreEqual(450, r);
}
[Test]
public void TestSetGetHBorders()
{
// instantiate the following classes so they'll Get picked up by
// the XmlBean process and Added to the jar file. they are required
// for the following XWPFTable methods.
CT_TblBorders cttb = new CT_TblBorders();
Assert.IsNotNull(cttb);
ST_Border stb = new ST_Border();
Assert.IsNotNull(stb);
// create a table
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
XWPFTable table = new XWPFTable(ctTable, doc);
// Set inside horizontal border
table.SetInsideHBorder(NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType.SINGLE, 4, 0, "FF0000");
// Get inside horizontal border components
int s = table.InsideHBorderSize;
Assert.AreEqual(4, s);
int sp = table.InsideHBorderSpace;
Assert.AreEqual(0, sp);
String clr = table.InsideHBorderColor;
Assert.AreEqual("FF0000", clr);
NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType bt = table.InsideHBorderType;
Assert.AreEqual(NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType.SINGLE, bt);
}
[Test]
public void TestSetGetVBorders()
{
// create a table
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
XWPFTable table = new XWPFTable(ctTable, doc);
// Set inside vertical border
table.SetInsideVBorder(NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType.DOUBLE, 4, 0, "00FF00");
// Get inside vertical border components
NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType bt = table.InsideVBorderType;
Assert.AreEqual(NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType.DOUBLE, bt);
int sz = table.InsideVBorderSize;
Assert.AreEqual(4, sz);
int sp = table.InsideVBorderSpace;
Assert.AreEqual(0, sp);
String clr = table.InsideVBorderColor;
Assert.AreEqual("00FF00", clr);
}
[Test]
public void TestSetGetRowBandSize()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
XWPFTable table = new XWPFTable(ctTable, doc);
table.RowBandSize = 12;
int sz = table.RowBandSize;
Assert.AreEqual(12, sz);
}
[Test]
public void TestSetGetColBandSize()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
XWPFTable table = new XWPFTable(ctTable, doc);
table.ColBandSize = 16;
int sz = table.ColBandSize;
Assert.AreEqual(16, sz);
}
[Test]
public void TestCreateTable()
{
// open an empty document
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
// create a table with 5 rows and 7 coloumns
int noRows = 5;
int noCols = 7;
XWPFTable table = doc.CreateTable(noRows, noCols);
// assert the table is empty
List<XWPFTableRow> rows = table.Rows;
Assert.AreEqual(noRows, rows.Count, "Table has less rows than requested.");
foreach (XWPFTableRow xwpfRow in rows)
{
Assert.IsNotNull(xwpfRow);
for (int i = 0; i < 7; i++)
{
XWPFTableCell xwpfCell = xwpfRow.GetCell(i);
Assert.IsNotNull(xwpfCell);
Assert.AreEqual(1, xwpfCell.Paragraphs.Count, "Empty cells should not have one paragraph.");
xwpfCell = xwpfRow.GetCell(i);
Assert.AreEqual(1, xwpfCell.Paragraphs.Count, "Calling 'getCell' must not modify cells content.");
}
}
doc.Package.Revert();
}
}
}
| |
/*
* 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.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm with a custom universe and benchmark, both using the same security.
/// </summary>
public class CustomUniverseWithBenchmarkRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const int ExpectedLeverage = 2;
private Symbol _spy;
private decimal _previousBenchmarkValue;
private DateTime _previousTime;
private decimal _previousSecurityValue;
private bool _universeSelected;
private bool _onDataWasCalled;
private int _benchmarkPriceDidNotChange;
/// <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()
{
SetStartDate(2013, 10, 4);
SetEndDate(2013, 10, 11);
// Hour resolution
_spy = AddEquity("SPY", Resolution.Hour).Symbol;
// Minute resolution
AddUniverse("my-universe", x =>
{
if(x.Day % 2 == 0)
{
_universeSelected = true;
return new List<string> {"SPY"};
}
_universeSelected = false;
return Enumerable.Empty<string>();
}
);
// internal daily resolution
SetBenchmark("SPY");
Symbol symbol;
if (!SymbolCache.TryGetSymbol("SPY", out symbol)
|| !ReferenceEquals(_spy, symbol))
{
throw new Exception("We expected 'SPY' to be added to the Symbol cache," +
" since the algorithm is also using it");
}
}
/// <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)
{
var security = Securities[_spy];
_onDataWasCalled = true;
var bar = data.Bars.Values.Single();
if (_universeSelected)
{
if (bar.IsFillForward
|| bar.Period != TimeSpan.FromMinutes(1))
{
// bar should always be the Minute resolution one here
throw new Exception("Unexpected Bar error");
}
if (_previousTime.Date == data.Time.Date
&& (data.Time - _previousTime) != TimeSpan.FromMinutes(1))
{
throw new Exception("For the same date expected data updates every 1 minute");
}
}
else
{
if (data.Time.Minute == 0
&& _previousSecurityValue == security.Price)
{
throw new Exception($"Security Price error. Price should change every new hour");
}
if (data.Time.Minute != 0
&& _previousSecurityValue != security.Price)
{
throw new Exception($"Security Price error. Price should not change every minute");
}
}
_previousSecurityValue = security.Price;
// assert benchmark updates only on date change
var currentValue = Benchmark.Evaluate(data.Time);
if (_previousTime.Hour == data.Time.Hour)
{
if (currentValue != _previousBenchmarkValue)
{
throw new Exception($"Benchmark value error - expected: {_previousBenchmarkValue} {_previousTime}, actual: {currentValue} {data.Time}. " +
"Benchmark value should only change when there is a change in hours");
}
}
else
{
if (data.Time.Minute == 0)
{
if (currentValue == _previousBenchmarkValue)
{
_benchmarkPriceDidNotChange++;
// there are two consecutive equal data points so we give it some room
if (_benchmarkPriceDidNotChange > 1)
{
throw new Exception($"Benchmark value error - expected a new value, current {currentValue} {data.Time}" +
"Benchmark value should change when there is a change in hours");
}
}
else
{
_benchmarkPriceDidNotChange = 0;
}
}
}
_previousBenchmarkValue = currentValue;
_previousTime = data.Time;
// assert algorithm security is the correct one - not the internal one
if (security.Leverage != ExpectedLeverage)
{
throw new Exception($"Leverage error - expected: {ExpectedLeverage}, actual: {security.Leverage}");
}
}
public override void OnEndOfAlgorithm()
{
if (!_onDataWasCalled)
{
throw new Exception("OnData was not called");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.564"},
{"Tracking Error", "0.214"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}
| |
namespace Cql.Core.Owin
{
using System;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using Cql.Core.ServiceLocation;
using Cql.Core.Web;
using JetBrains.Annotations;
using Microsoft.Owin;
using Newtonsoft.Json.Linq;
public abstract class CqlApiControllerBase : ApiController
{
private IOwinContext _owinContext;
/// <summary>
/// The currently signed in user.
/// </summary>
[CanBeNull]
public new ClaimsPrincipal User => base.User as ClaimsPrincipal;
/// <summary>
/// Gets the current <see cref="IOwinContext" /> for the current request.
/// </summary>
[NotNull]
protected IOwinContext OwinContext => this.Request == null
? new OwinContext()
: LazyInitializer.EnsureInitialized(ref this._owinContext, () => this.Request.GetOwinContext() ?? new OwinContext());
/// <summary>
/// Generates an <see cref="IOperationResult" /> for the specified <paramref name="ex" />.
/// </summary>
[NotNull]
protected virtual IOperationResult CreateErrorResult([NotNull] Exception ex)
{
var operationResult = OperationResult.Error(ex);
Exception unauthorized = ex as UnauthorizedAccessException;
if (unauthorized != null)
{
operationResult = OperationResult.Unauthorized(ex.Message);
}
return operationResult;
}
/// <summary>
/// Invokes the <paramref name="serviceTask" /> using an instance of <typeparamref name="TService" /> and returns the
/// operation result.
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="serviceTask">The specific task to be executed by the service.</param>
/// <param name="service"></param>
/// <returns></returns>
[NotNull]
protected virtual async Task<IOperationResult> ExcuteServiceTask<TService, TResult>([NotNull] Func<TService, Task<TResult>> serviceTask, [NotNull] TService service)
where TResult : IOperationResult
{
if (serviceTask == null)
{
throw new ArgumentNullException(nameof(serviceTask));
}
if (service == null)
{
throw new ArgumentNullException(nameof(service));
}
Contract.EndContractBlock();
var operationResult = await serviceTask(service);
if (operationResult == null)
{
throw new InvalidOperationException("The service task operation did not return a result.");
}
return operationResult;
}
/// <summary>
/// Logging hook called when a service task throws an exception.
/// </summary>
/// <param name="ex">The exception</param>
/// <param name="result">The operation result, which is usually <c>null</c></param>
protected abstract void LogException(Exception ex, [CanBeNull] IOperationResult result = null);
/// <summary>
/// Called after the service task has been completed and the response has been determined, but before the response has
/// actually executed.
/// </summary>
/// <param name="httpResult">The HttpResponse created as a result of the operation.</param>
/// <param name="result">The result data created by the operation.</param>
protected virtual Task OnServiceTaskExecuted(IHttpActionResult httpResult, IOperationResult result)
{
return Task.FromResult(true);
}
/// <summary>
/// Produces an <see cref="IHttpActionResult" /> based on the <see cref="OperationResultType" /> of the
/// <see cref="IOperationResult" />.
/// </summary>
[NotNull]
protected virtual IHttpActionResult OperationResponse([NotNull] IOperationResult result)
{
switch (result.Result)
{
case OperationResultType.Ok:
var fileContent = result.Data as FileContent;
if (fileContent != null)
{
if (fileContent.NotFound)
{
return this.NotFound();
}
return new FileContentResult(fileContent);
}
return this.Ok(result.Data ?? new MessageResult("ok"));
case OperationResultType.NotFound:
if (!string.IsNullOrEmpty(result.Message))
{
return this.Content(HttpStatusCode.NotFound, result.Message);
}
return this.NotFound();
case OperationResultType.Unauthorized:
if (!string.IsNullOrEmpty(result.Message))
{
return this.Content(HttpStatusCode.Unauthorized, result.Message);
}
return this.Unauthorized();
case OperationResultType.Invalid:
if (this.Request.IsAjaxRequest())
{
var jsonResult = new JObject();
if (!string.IsNullOrWhiteSpace(result.Message))
{
jsonResult["message"] = result.Message;
}
if (result.ValidationResults != null)
{
jsonResult["errors"] = new JArray(
result.ValidationResults.Select(x => new JObject { ["fields"] = new JArray(x.MemberNames), ["message"] = x.ErrorMessage }));
}
return this.Content(HttpStatusCode.BadRequest, jsonResult);
}
else
{
if (!string.IsNullOrEmpty(result.Message))
{
return this.Content(HttpStatusCode.BadRequest, result.Message);
}
return this.BadRequest();
}
case OperationResultType.Error:
return this.Content(HttpStatusCode.BadRequest, result.Message);
default:
throw new ArgumentOutOfRangeException(nameof(result.Result), result.Result, "Result type not supported.");
}
}
/// <summary>
/// Resolves the instance of <typeparamref name="TService" />.
/// </summary>
[NotNull]
protected virtual TService ResolveService<TService>()
{
var svc = ServiceResolver.Resolve<TService>();
if (svc == null)
{
throw new InvalidOperationException($"An instance of {nameof(TService)} could not be resoved.");
}
return svc;
}
/// <summary>
/// Executes an operation task that does not return a value.
/// </summary>
/// <typeparam name="TService">The type of service being invoked.</typeparam>
/// <paramref name="serviceTask">The specific service task to be executed: svc => svc.DeleteCustomer(5)</paramref>
/// <returns>An Operation result indicating whether or not the operation succeeded, typically OperationResult.Ok()</returns>
protected virtual Task<IHttpActionResult> ServiceTask<TService>(Func<TService, Task<OperationResult>> serviceTask)
{
return this.ServiceTaskImpl(serviceTask);
}
/// <summary>
/// Executes an operation task that returns a value.
/// </summary>
/// <typeparam name="TService">The type of service being invoked.</typeparam>
/// <typeparam name="TResult">The type of result generated by the service.</typeparam>
/// <paramref name="serviceTask">The specific service task to be executed: svc => svc.GetCustomer(5)</paramref>
/// <returns>
/// An Operation result indicating whether or not the operation succeeded along with the data from the response,
/// typically something like OperationResult.Ok(customer)
/// </returns>
protected virtual Task<IHttpActionResult> ServiceTask<TService, TResult>(Func<TService, Task<OperationResult<TResult>>> serviceTask)
{
return this.ServiceTaskImpl(serviceTask);
}
private async Task<IHttpActionResult> ServiceTaskImpl<TService, T>(Func<TService, Task<T>> serviceTask)
where T : IOperationResult
{
IOperationResult result = null;
try
{
var service = this.ResolveService<TService>();
result = await this.ExcuteServiceTask(serviceTask, service);
var httpResult = this.OperationResponse(result);
await this.OnServiceTaskExecuted(httpResult, result);
return httpResult;
}
catch (Exception ex)
{
try
{
this.LogException(ex, result);
}
catch
{
// ignored
}
var errorResult = this.CreateErrorResult(ex);
return this.OperationResponse(errorResult);
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Threading;
using CoreAnimation;
using CoreGraphics;
using Foundation;
using Metal;
using OpenTK;
using UIKit;
namespace MetalImageProcessing
{
public class Renderer
{
const float interfaceOrientationLandscapeAngle = 35.0f;
const float interfaceOrientationPortraitAngle = 50.0f;
const float prespectiveNear = 0.1f;
const float prespectiveFar = 100.0f;
const int maxInflightBuffers = 3;
nuint sampleCount;
IMTLDevice device;
MTLPixelFormat depthPixelFormat;
MTLPixelFormat stencilPixelFormat;
Quad mpQuad;
// Interface Orientation
UIInterfaceOrientation mnOrientation;
Semaphore inflightSemaphore;
// Renderer globals
IMTLCommandQueue commandQueue;
IMTLLibrary shaderLibrary;
IMTLDepthStencilState depthState;
// Compute ivars
IMTLComputePipelineState kernel;
MTLSize workgroupSize;
MTLSize localCount;
// textured Quad
Texture mpInTexture;
IMTLTexture outTexture;
IMTLRenderPipelineState pipelineState;
#pragma warning disable 649
// Dimensions
CGSize size;
#pragma warning restore 649
// Viewing matrix is derived from an eye point, a reference point
// indicating the center of the scene, and an up vector.
Matrix4 lookAt;
// Translate the object in (x,y,z) space.
Matrix4 translate;
// Quad transform buffers
Matrix4 transform;
IMTLBuffer transformBuffer;
public Renderer ()
{
// initialize properties
sampleCount = 1;
depthPixelFormat = MTLPixelFormat.Depth32Float;
stencilPixelFormat = MTLPixelFormat.Invalid;
// find a usable Device
device = MTLDevice.SystemDefault;
// create a new command queue
commandQueue = device.CreateCommandQueue ();
NSError error;
shaderLibrary = device.CreateLibrary ("default.metallib", out error);
// if the shader libary isnt loading, nothing good will happen
if (shaderLibrary == null)
throw new Exception ("ERROR: Couldnt create a default shader library");
inflightSemaphore = new Semaphore (maxInflightBuffers, maxInflightBuffers);
}
public void Compute (IMTLCommandBuffer commandBuffer)
{
IMTLComputeCommandEncoder computeEncoder = commandBuffer.ComputeCommandEncoder;
if (computeEncoder == null)
return;
computeEncoder.SetComputePipelineState (kernel);
computeEncoder.SetTexture (mpInTexture.MetalTexture, 0);
computeEncoder.SetTexture (outTexture, 1);
computeEncoder.DispatchThreadgroups (localCount, workgroupSize);
computeEncoder.EndEncoding ();
}
public void Encode (IMTLRenderCommandEncoder renderEncoder)
{
renderEncoder.PushDebugGroup ("encode quad");
renderEncoder.SetFrontFacingWinding (MTLWinding.CounterClockwise);
renderEncoder.SetDepthStencilState (depthState);
renderEncoder.SetRenderPipelineState (pipelineState);
renderEncoder.SetVertexBuffer (transformBuffer, 0, 2);
renderEncoder.SetFragmentTexture (outTexture, 0);
// Encode quad vertex and texture coordinate buffers
mpQuad.Encode (renderEncoder);
// tell the render context we want to draw our primitives
renderEncoder.DrawPrimitives (MTLPrimitiveType.Triangle, 0, 6, 1);
renderEncoder.EndEncoding ();
renderEncoder.PopDebugGroup ();
}
public void Reshape (ImageView view)
{
// To correctly compute the aspect ration determine the device
// interface orientation.
UIInterfaceOrientation orientation = UIApplication.SharedApplication.StatusBarOrientation;
// Update the quad and linear _transformation matrices, if and
// only if, the device orientation is changed.
if (mnOrientation == orientation)
return;
float angleInDegrees = GetActualAngle (orientation, view.Layer.Bounds);
CreateMatrix (angleInDegrees);
UpdateBuffer ();
}
public void Render (ImageView view)
{
inflightSemaphore.WaitOne ();
IMTLCommandBuffer commandBuffer = commandQueue.CommandBuffer ();
// compute image processing on the (same) drawable texture
Compute (commandBuffer);
ICAMetalDrawable drawable = view.GetNextDrawable ();
// create a render command encoder so we can render into something
MTLRenderPassDescriptor renderPassDescriptor = view.GetRenderPassDescriptor (drawable);
if (renderPassDescriptor == null) {
inflightSemaphore.Release ();
return;
}
// Get a render encoder
IMTLRenderCommandEncoder renderEncoder = commandBuffer.CreateRenderCommandEncoder (renderPassDescriptor);
// render textured quad
Encode (renderEncoder);
commandBuffer.AddCompletedHandler ((IMTLCommandBuffer buffer) => {
inflightSemaphore.Release ();
drawable.Dispose ();
});
commandBuffer.PresentDrawable (drawable);
commandBuffer.Commit ();
}
public void Configure (ImageView renderView)
{
renderView.DepthPixelFormat = depthPixelFormat;
renderView.StencilPixelFormat = stencilPixelFormat;
renderView.SampleCount = sampleCount;
// we need to set the framebuffer only property of the layer to NO so we
// can perform compute on the drawable's texture
var metalLayer = (CAMetalLayer)renderView.Layer;
metalLayer.FramebufferOnly = false;
if(!PreparePipelineState ())
throw new ApplicationException ("ERROR: Failed creating a depth stencil state descriptor!");
if(!PrepareTexturedQuad ("Default", "jpg"))
throw new ApplicationException ("ERROR: Failed creating a textured quad!");
if(!PrepareCompute ())
throw new ApplicationException ("ERROR: Failed creating a compute stage!");
if(!PrepareDepthStencilState ())
throw new ApplicationException ("ERROR: Failed creating a depth stencil state!");
if(!PrepareTransformBuffer ())
throw new ApplicationException ("ERROR: Failed creating a transform buffer!");
// Default orientation is unknown
mnOrientation = UIInterfaceOrientation.Unknown;
// Create linear transformation matrices
PrepareTransforms ();
}
bool PreparePipelineState ()
{
// get the fragment function from the library
IMTLFunction fragmentProgram = shaderLibrary.CreateFunction ("texturedQuadFragment");
if(fragmentProgram == null)
Console.WriteLine ("ERROR: Couldn't load fragment function from default library");
// get the vertex function from the library
IMTLFunction vertexProgram = shaderLibrary.CreateFunction ("texturedQuadVertex");
if(vertexProgram == null)
Console.WriteLine ("ERROR: Couldn't load vertex function from default library");
// create a pipeline state for the quad
var quadPipelineStateDescriptor = new MTLRenderPipelineDescriptor {
DepthAttachmentPixelFormat = depthPixelFormat,
StencilAttachmentPixelFormat = MTLPixelFormat.Invalid,
SampleCount = sampleCount,
VertexFunction = vertexProgram,
FragmentFunction = fragmentProgram
};
quadPipelineStateDescriptor.ColorAttachments[0].PixelFormat = MTLPixelFormat.BGRA8Unorm;
NSError error;
pipelineState = device.CreateRenderPipelineState (quadPipelineStateDescriptor, out error);
if(pipelineState == null) {
Console.WriteLine ("ERROR: Failed acquiring pipeline state descriptor: %@", error.Description);
return false;
}
return true;
}
bool PrepareTexturedQuad (string texStr, string extStr)
{
mpInTexture = new Texture (texStr, extStr);
bool isAcquired = mpInTexture.Finalize (device);
mpInTexture.MetalTexture.Label = texStr;
if(!isAcquired) {
Console.WriteLine ("ERROR: Failed creating an input 2d texture!");
return false;
}
size.Width = mpInTexture.Width;
size.Height = mpInTexture.Height;
mpQuad = new Quad (device) {
Size = size
};
return true;
}
bool PrepareCompute ()
{
NSError error;
// Create a compute kernel function
IMTLFunction function = shaderLibrary.CreateFunction ("grayscale");
if(function == null) {
Console.WriteLine ("ERROR: Failed creating a new function!");
return false;
}
// Create a compute kernel
kernel = device.CreateComputePipelineState (function, out error);
if(kernel == null) {
Console.WriteLine ("ERROR: Failed creating a compute kernel: %@", error.Description);
return false;
}
MTLTextureDescriptor texDesc = MTLTextureDescriptor.CreateTexture2DDescriptor (MTLPixelFormat.RGBA8Unorm, (nuint)size.Width, (nuint)size.Height, false);
if(texDesc == null) {
Console.WriteLine ("ERROR: Failed creating a texture 2d descriptor with RGBA unnormalized pixel format!");
return false;
}
outTexture = device.CreateTexture (texDesc);
if(outTexture == null) {
Console.WriteLine ("ERROR: Failed creating an output 2d texture!");
return false;
}
// Set the compute kernel's workgroup size and count
workgroupSize = new MTLSize (1, 1, 1);
localCount = new MTLSize ((nint)size.Width, (nint)size.Height, 1);
return true;
}
bool PrepareTransformBuffer ()
{
// allocate regions of memory for the constant buffer
transformBuffer = device.CreateBuffer ((nuint)Marshal.SizeOf<Matrix4> (), MTLResourceOptions.CpuCacheModeDefault);
if(transformBuffer == null)
return false;
transformBuffer.Label = "TransformBuffer";
return true;
}
bool PrepareDepthStencilState ()
{
var depthStateDesc = new MTLDepthStencilDescriptor {
DepthCompareFunction = MTLCompareFunction.Always,
DepthWriteEnabled = true
};
depthState = device.CreateDepthStencilState (depthStateDesc);
if (depthState == null)
return false;
return true;
}
void PrepareTransforms ()
{
// Create a viewing matrix derived from an eye point, a reference point
// indicating the center of the scene, and an up vector.
var eye = Vector3.Zero;
var center = new Vector3 (0f, 0f, 1f);
var up = new Vector3 (0f, 1f, 0f);
lookAt = MathUtils.LookAt (eye, center, up);
// Translate the object in (x,y,z) space.
translate = MathUtils.Translate (0.0f, -0.25f, 2.0f);
}
float GetActualAngle (UIInterfaceOrientation orientation, CGRect bounds)
{
// Update the device orientation
mnOrientation = orientation;
// Get the bounds for the current rendering layer
mpQuad.Bounds = bounds;
// Based on the device orientation, set the angle in degrees
// between a plane which passes through the camera position
// and the top of your screen and another plane which passes
// through the camera position and the bottom of your screen.
float dangle = 0.0f;
switch(mnOrientation)
{
case UIInterfaceOrientation.LandscapeLeft:
case UIInterfaceOrientation.LandscapeRight:
dangle = interfaceOrientationLandscapeAngle;
break;
case UIInterfaceOrientation.Portrait:
case UIInterfaceOrientation.PortraitUpsideDown:
default:
dangle = interfaceOrientationPortraitAngle;
break;
}
return dangle;
}
void CreateMatrix (float angle)
{
// Describes a tranformation matrix that produces a perspective projection
float near = prespectiveNear;
float far = prespectiveFar;
float rangle = MathUtils.Radians (angle);
float length = near * (float)Math.Tan (rangle);
float right = length / (float)mpQuad.Aspect;
float left = -right;
float top = length;
float bottom = -top;
Matrix4 perspective = MathUtils.FrustrumOc (left, right, bottom, top, near, far);
// Create a viewing matrix derived from an eye point, a reference point
// indicating the center of the scene, and an up vector.
transform = (lookAt * translate).SwapColumnsAndRows ();
// Create a linear _transformation matrix
transform = (perspective * transform).SwapColumnsAndRows ();
}
void UpdateBuffer ()
{
// Update the buffer associated with the linear _transformation matrix
int rawsize = Marshal.SizeOf <Matrix4> ();
var rawdata = new byte[rawsize];
GCHandle pinnedTransform = GCHandle.Alloc (transform, GCHandleType.Pinned);
IntPtr ptr = pinnedTransform.AddrOfPinnedObject ();
Marshal.Copy (ptr, rawdata, 0, rawsize);
pinnedTransform.Free ();
Marshal.Copy (rawdata, 0, transformBuffer.Contents, rawsize);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
/// <summary>
/// A set of initialization methods for instances of <see cref="ImmutableList{T}"/>.
/// </summary>
public static class ImmutableList
{
/// <summary>
/// Returns an empty collection.
/// </summary>
/// <typeparam name="T">The type of items stored by the collection.</typeparam>
/// <returns>The immutable collection.</returns>
[Pure]
public static ImmutableList<T> Create<T>() => ImmutableList<T>.Empty;
/// <summary>
/// Creates a new immutable collection prefilled with the specified item.
/// </summary>
/// <typeparam name="T">The type of items stored by the collection.</typeparam>
/// <param name="item">The item to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
public static ImmutableList<T> Create<T>(T item) => ImmutableList<T>.Empty.Add(item);
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="T">The type of items stored by the collection.</typeparam>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
public static ImmutableList<T> CreateRange<T>(IEnumerable<T> items) => ImmutableList<T>.Empty.AddRange(items);
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="T">The type of items stored by the collection.</typeparam>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
public static ImmutableList<T> Create<T>(params T[] items) => ImmutableList<T>.Empty.AddRange(items);
/// <summary>
/// Creates a new immutable list builder.
/// </summary>
/// <typeparam name="T">The type of items stored by the collection.</typeparam>
/// <returns>The immutable collection builder.</returns>
[Pure]
public static ImmutableList<T>.Builder CreateBuilder<T>() => Create<T>().ToBuilder();
/// <summary>
/// Enumerates a sequence exactly once and produces an immutable list of its contents.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <param name="source">The sequence to enumerate.</param>
/// <returns>An immutable list.</returns>
[Pure]
public static ImmutableList<TSource> ToImmutableList<TSource>(this IEnumerable<TSource> source)
{
var existingList = source as ImmutableList<TSource>;
if (existingList != null)
{
return existingList;
}
return ImmutableList<TSource>.Empty.AddRange(source);
}
/// <summary>
/// Replaces the first equal element in the list with the specified element.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="oldValue">The element to replace.</param>
/// <param name="newValue">The element to replace the old element with.</param>
/// <returns>The new list -- even if the value being replaced is equal to the new value for that position.</returns>
/// <exception cref="ArgumentException">Thrown when the old value does not exist in the list.</exception>
[Pure]
public static IImmutableList<T> Replace<T>(this IImmutableList<T> list, T oldValue, T newValue)
{
Requires.NotNull(list, nameof(list));
return list.Replace(oldValue, newValue, EqualityComparer<T>.Default);
}
/// <summary>
/// Removes the specified value from this list.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="value">The value to remove.</param>
/// <returns>A new list with the element removed, or this list if the element is not in this list.</returns>
[Pure]
public static IImmutableList<T> Remove<T>(this IImmutableList<T> list, T value)
{
Requires.NotNull(list, nameof(list));
return list.Remove(value, EqualityComparer<T>.Default);
}
/// <summary>
/// Removes the specified values from this list.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="items">The items to remove if matches are found in this list.</param>
/// <returns>
/// A new list with the elements removed.
/// </returns>
[Pure]
public static IImmutableList<T> RemoveRange<T>(this IImmutableList<T> list, IEnumerable<T> items)
{
Requires.NotNull(list, nameof(list));
return list.RemoveRange(items, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches for the specified object and returns the zero-based index of the
/// first occurrence within the <see cref="IImmutableList{T}"/>.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="item">
/// The object to locate in the <see cref="IImmutableList{T}"/>. The value
/// can be null for reference types.
/// </param>
/// <returns>
/// The zero-based index of the first occurrence of item within the range of
/// elements in the <see cref="IImmutableList{T}"/> that extends from index
/// to the last element, if found; otherwise, -1.
/// </returns>
[Pure]
public static int IndexOf<T>(this IImmutableList<T> list, T item)
{
Requires.NotNull(list, nameof(list));
return list.IndexOf(item, 0, list.Count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches for the specified object and returns the zero-based index of the
/// first occurrence within the <see cref="IImmutableList{T}"/>.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="item">
/// The object to locate in the <see cref="IImmutableList{T}"/>. The value
/// can be null for reference types.
/// </param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>
/// The zero-based index of the first occurrence of item within the range of
/// elements in the <see cref="IImmutableList{T}"/> that extends from index
/// to the last element, if found; otherwise, -1.
/// </returns>
[Pure]
public static int IndexOf<T>(this IImmutableList<T> list, T item, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull(list, nameof(list));
return list.IndexOf(item, 0, list.Count, equalityComparer);
}
/// <summary>
/// Searches for the specified object and returns the zero-based index of the
/// first occurrence within the range of elements in the <see cref="IImmutableList{T}"/>
/// that extends from the specified index to the last element.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="item">
/// The object to locate in the <see cref="IImmutableList{T}"/>. The value
/// can be null for reference types.
/// </param>
/// <param name="startIndex">
/// The zero-based starting index of the search. 0 (zero) is valid in an empty
/// list.
/// </param>
/// <returns>
/// The zero-based index of the first occurrence of item within the range of
/// elements in the <see cref="IImmutableList{T}"/> that extends from index
/// to the last element, if found; otherwise, -1.
/// </returns>
[Pure]
public static int IndexOf<T>(this IImmutableList<T> list, T item, int startIndex)
{
Requires.NotNull(list, nameof(list));
return list.IndexOf(item, startIndex, list.Count - startIndex, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches for the specified object and returns the zero-based index of the
/// first occurrence within the range of elements in the <see cref="IImmutableList{T}"/>
/// that extends from the specified index to the last element.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="item">
/// The object to locate in the <see cref="IImmutableList{T}"/>. The value
/// can be null for reference types.
/// </param>
/// <param name="startIndex">
/// The zero-based starting index of the search. 0 (zero) is valid in an empty
/// list.
/// </param>
/// <param name="count">
/// The number of elements in the section to search.
/// </param>
/// <returns>
/// The zero-based index of the first occurrence of item within the range of
/// elements in the <see cref="IImmutableList{T}"/> that extends from index
/// to the last element, if found; otherwise, -1.
/// </returns>
[Pure]
public static int IndexOf<T>(this IImmutableList<T> list, T item, int startIndex, int count)
{
Requires.NotNull(list, nameof(list));
return list.IndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches for the specified object and returns the zero-based index of the
/// last occurrence within the entire <see cref="IImmutableList{T}"/>.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="item">
/// The object to locate in the <see cref="IImmutableList{T}"/>. The value
/// can be null for reference types.
/// </param>
/// <returns>
/// The zero-based index of the last occurrence of item within the entire the
/// <see cref="IImmutableList{T}"/>, if found; otherwise, -1.
/// </returns>
[Pure]
public static int LastIndexOf<T>(this IImmutableList<T> list, T item)
{
Requires.NotNull(list, nameof(list));
if (list.Count == 0)
{
// Avoid argument out of range exceptions.
return -1;
}
return list.LastIndexOf(item, list.Count - 1, list.Count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches for the specified object and returns the zero-based index of the
/// last occurrence within the entire <see cref="IImmutableList{T}"/>.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="item">
/// The object to locate in the <see cref="IImmutableList{T}"/>. The value
/// can be null for reference types.
/// </param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>
/// The zero-based index of the last occurrence of item within the entire the
/// <see cref="IImmutableList{T}"/>, if found; otherwise, -1.
/// </returns>
[Pure]
public static int LastIndexOf<T>(this IImmutableList<T> list, T item, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull(list, nameof(list));
if (list.Count == 0)
{
// Avoid argument out of range exceptions.
return -1;
}
return list.LastIndexOf(item, list.Count - 1, list.Count, equalityComparer);
}
/// <summary>
/// Searches for the specified object and returns the zero-based index of the
/// last occurrence within the range of elements in the <see cref="IImmutableList{T}"/>
/// that extends from the first element to the specified index.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="item">
/// The object to locate in the <see cref="IImmutableList{T}"/>. The value
/// can be null for reference types.
/// </param>
/// <param name="startIndex">
/// The zero-based starting index of the backward search.
/// </param>
/// <returns>
/// The zero-based index of the last occurrence of item within the range of elements
/// in the <see cref="IImmutableList{T}"/> that extends from the first element
/// to index, if found; otherwise, -1.
/// </returns>
[Pure]
public static int LastIndexOf<T>(this IImmutableList<T> list, T item, int startIndex)
{
Requires.NotNull(list, nameof(list));
if (list.Count == 0 && startIndex == 0)
{
return -1;
}
return list.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches for the specified object and returns the zero-based index of the
/// last occurrence within the range of elements in the <see cref="IImmutableList{T}"/>
/// that extends from the first element to the specified index.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="item">
/// The object to locate in the <see cref="IImmutableList{T}"/>. The value
/// can be null for reference types.
/// </param>
/// <param name="startIndex">
/// The zero-based starting index of the backward search.
/// </param>
/// <param name="count">
/// The number of elements in the section to search.
/// </param>
/// <returns>
/// The zero-based index of the last occurrence of item within the range of elements
/// in the <see cref="IImmutableList{T}"/> that extends from the first element
/// to index, if found; otherwise, -1.
/// </returns>
[Pure]
public static int LastIndexOf<T>(this IImmutableList<T> list, T item, int startIndex, int count)
{
Requires.NotNull(list, nameof(list));
return list.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_FULL_CONSOLE
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using Microsoft.Scripting.Hosting.Providers;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
namespace Microsoft.Scripting.Hosting.Shell {
/// <summary>
/// Command line hosting service.
/// </summary>
public class CommandLine {
private LanguageContext _language;
private IConsole _console;
private ConsoleOptions _options;
private ScriptScope _scope;
private ScriptEngine _engine;
private ICommandDispatcher _commandDispatcher;
private int? _terminatingExitCode;
private int _exitCode = 1;
protected IConsole Console { get { return _console; } }
protected ConsoleOptions Options { get { return _options; } }
protected ScriptEngine Engine { get { return _engine; } }
public ScriptScope ScriptScope { get { return _scope; } protected set { _scope = value; } }
public int ExitCode { get { return _exitCode; } protected set { _exitCode = value; } }
/// <summary>
/// Scope is not remotable, and this only works in the same AppDomain.
/// </summary>
protected Scope Scope {
get {
if (_scope == null) {
return null;
}
return HostingHelpers.GetScope(_scope);
}
set {
_scope = HostingHelpers.CreateScriptScope(_engine, value);
}
}
protected LanguageContext Language {
get {
// LanguageContext is not remotable, and this only works in the same AppDomain.
if (_language == null) {
_language = HostingHelpers.GetLanguageContext(_engine);
}
return _language;
}
}
protected virtual string Prompt { get { return ">>> "; } }
public virtual string PromptContinuation { get { return "... "; } }
protected virtual string Logo { get { return null; } }
protected virtual void Initialize() {
if (_commandDispatcher == null) {
_commandDispatcher = CreateCommandDispatcher();
}
}
protected virtual Scope CreateScope() {
return new Scope();
}
protected virtual ICommandDispatcher CreateCommandDispatcher() {
return new SimpleCommandDispatcher();
}
public virtual void Terminate(int exitCode) {
// The default implementation just sets a flag. Derived types can support better termination
_terminatingExitCode = exitCode;
}
/// <summary>
/// Executes the comand line - depending upon the options provided we will
/// either run a single file, a single command, or enter the interactive loop.
/// </summary>
public void Run(ScriptEngine engine, IConsole console, ConsoleOptions options) {
ContractUtils.RequiresNotNull(engine, nameof(engine));
ContractUtils.RequiresNotNull(console, nameof(console));
ContractUtils.RequiresNotNull(options, nameof(options));
_engine = engine;
_options = options;
_console = console;
Initialize();
try {
_exitCode = Run();
#if FEATURE_EXCEPTION_STATE
} catch (System.Threading.ThreadAbortException tae) {
if (tae.ExceptionState is KeyboardInterruptException) {
Thread.ResetAbort();
_exitCode = -1;
} else {
throw;
}
#endif
} finally {
Shutdown();
_engine = null;
_options = null;
_console = null;
}
}
/// <summary>
/// Runs the command line. Languages can override this to provide custom behavior other than:
/// 1. Running a single command
/// 2. Running a file
/// 3. Entering the interactive console loop.
/// </summary>
/// <returns></returns>
protected virtual int Run() {
int result;
if (_options.Command != null) {
result = RunCommand(_options.Command);
} else if (_options.FileName != null) {
result = RunFile(_options.FileName);
} else {
return RunInteractive();
}
if (_options.Introspection) {
return RunInteractiveLoop();
}
return result;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected virtual void Shutdown() {
try {
_engine.Runtime.Shutdown();
} catch (Exception e) {
UnhandledException(e);
}
}
protected virtual int RunFile(string fileName) {
return RunFile(_engine.CreateScriptSourceFromFile(fileName));
}
protected virtual int RunCommand(string command) {
return RunFile(_engine.CreateScriptSourceFromString(command, SourceCodeKind.Statements));
}
/// <summary>
/// Runs the specified filename
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected virtual int RunFile(ScriptSource source) {
int result = 1;
if (Options.HandleExceptions) {
try {
result = source.ExecuteProgram();
} catch (Exception e) {
UnhandledException(e);
}
} else {
result = source.ExecuteProgram();
}
return result;
}
protected void PrintLogo() {
if (Logo != null) {
_console.Write(Logo, Style.Out);
}
}
#region Interactivity
/// <summary>
/// Starts the interactive loop. Performs any initialization necessary before
/// starting the loop and then calls RunInteractiveLoop to start the loop.
///
/// Returns the exit code when the interactive loop is completed.
/// </summary>
protected virtual int RunInteractive() {
PrintLogo();
return RunInteractiveLoop();
}
/// <summary>
/// Runs the interactive loop. Repeatedly parse and run interactive actions
/// until an exit code is received. If any exceptions are unhandled displays
/// them to the console
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected virtual int RunInteractiveLoop() {
if (_scope == null) {
_scope = _engine.CreateScope();
}
#if FEATURE_REMOTING
string remoteRuntimeChannel = _options.RemoteRuntimeChannel;
if (remoteRuntimeChannel != null) {
// Publish the ScriptScope so that the host can use it
Remote.RemoteRuntimeServer.StartServer(remoteRuntimeChannel, _scope);
return 0;
}
#endif
int? res = null;
do {
if (Options.HandleExceptions) {
try {
res = TryInteractiveAction();
#if !FEATURE_PROCESS
} catch (ExitProcessException e) {
res = e.ExitCode;
#endif
} catch (Exception e) {
if (CommandLine.IsFatalException(e)) {
// Some exceptions are too dangerous to try to catch
throw;
}
// There should be no unhandled exceptions in the interactive session
// We catch all (most) exceptions here, and just display it,
// and keep on going
UnhandledException(e);
}
} else {
res = TryInteractiveAction();
}
} while (res == null);
return res.Value;
}
internal static bool IsFatalException(Exception e) {
if (e is ThreadAbortException tae) {
#if !FEATURE_EXCEPTION_STATE
return true;
#else
if ((tae.ExceptionState as KeyboardInterruptException) == null) {
return true;
}
#endif
}
return false;
}
protected virtual void UnhandledException(Exception e) {
ExceptionOperations exceptionOperations = _engine.GetService<ExceptionOperations>();
_console.WriteLine(exceptionOperations.FormatException(e), Style.Error);
}
/// <summary>
/// Attempts to run a single interaction and handle any language-specific
/// exceptions. Base classes can override this and call the base implementation
/// surrounded with their own exception handling.
///
/// Returns null if successful and execution should continue, or an exit code.
/// </summary>
protected virtual int? TryInteractiveAction() {
int? result = null;
try {
result = RunOneInteraction();
#if !FEATURE_EXCEPTION_STATE
} catch (ThreadAbortException) {
#else
} catch (ThreadAbortException tae) {
if (tae.ExceptionState is KeyboardInterruptException pki) {
UnhandledException(tae);
Thread.ResetAbort();
} else {
throw;
}
#endif
}
return result;
}
/// <summary>
/// Parses a single interactive command or a set of statements and executes it.
///
/// Returns null if successful and execution should continue, or the appropiate exit code.
///
/// We check if the code read is an interactive command or statements is by checking for NewLine
/// If the code contains NewLine, it's a set of statements (most probably from SendToConsole)
/// If the code does not contain a NewLine, it's an interactive command typed by the user at the prompt
/// </summary>
private int? RunOneInteraction() {
string s = ReadStatement(out bool continueInteraction);
if (continueInteraction == false) {
return _terminatingExitCode ?? 0;
}
if (String.IsNullOrEmpty(s)) {
// Is it an empty line?
_console.Write(String.Empty, Style.Out);
return null;
}
ExecuteCommand(s);
return null;
}
protected virtual void ExecuteCommand(string command) {
ExecuteCommand(_engine.CreateScriptSourceFromString(command, SourceCodeKind.InteractiveCode));
}
protected object ExecuteCommand(ScriptSource source) {
ErrorListener errorListener = new ErrorSinkProxyListener(ErrorSink);
CompiledCode compiledCode = source.Compile(_engine.GetCompilerOptions(_scope), errorListener);
return _commandDispatcher.Execute(compiledCode, _scope);
}
protected virtual ErrorSink ErrorSink {
get { return ErrorSink.Default; }
}
/// <summary>
/// Private helper function to see if we should treat the current input as a blank link.
///
/// We do this if we only have auto-indent text.
/// </summary>
private static bool TreatAsBlankLine(string line, int autoIndentSize) {
if (line.Length == 0) return true;
if (autoIndentSize != 0 && line.Trim().Length == 0 && line.Length == autoIndentSize) {
return true;
}
return false;
}
/// <summary>
/// Read a statement, which can potentially be a multiple-line statement suite (like a class declaration).
/// </summary>
/// <param name="continueInteraction">Should the console session continue, or did the user indicate
/// that it should be terminated?</param>
/// <returns>Expression to evaluate. null for empty input</returns>
protected string ReadStatement(out bool continueInteraction) {
StringBuilder b = new StringBuilder();
int autoIndentSize = 0;
_console.Write(Prompt, Style.Prompt);
while (true) {
string line = ReadLine(autoIndentSize);
continueInteraction = true;
if (line == null || (_terminatingExitCode != null)) {
continueInteraction = false;
return null;
}
bool allowIncompleteStatement = TreatAsBlankLine(line, autoIndentSize);
b.Append(line);
// Note that this does not use Environment.NewLine because some languages (eg. Python) only
// recognize \n as a line terminator.
b.Append("\n");
string code = b.ToString();
var props = GetCommandProperties(code);
if (SourceCodePropertiesUtils.IsCompleteOrInvalid(props, allowIncompleteStatement)) {
return props != ScriptCodeParseResult.Empty ? code : null;
}
if (_options.AutoIndent && _options.AutoIndentSize != 0) {
autoIndentSize = GetNextAutoIndentSize(code);
}
// Keep on reading input
_console.Write(PromptContinuation, Style.Prompt);
}
}
protected virtual ScriptCodeParseResult GetCommandProperties(string code) {
ScriptSource command = _engine.CreateScriptSourceFromString(code, SourceCodeKind.InteractiveCode);
return command.GetCodeProperties(_engine.GetCompilerOptions(_scope));
}
/// <summary>
/// Gets the next level for auto-indentation
/// </summary>
protected virtual int GetNextAutoIndentSize(string text) {
return 0;
}
protected virtual string ReadLine(int autoIndentSize) {
return _console.ReadLine(autoIndentSize);
}
internal protected virtual TextWriter GetOutputWriter(bool isErrorOutput) {
return isErrorOutput ? System.Console.Error : System.Console.Out;
}
//private static DynamicSite<object, IList<string>> _memberCompletionSite =
// new DynamicSite<object, IList<string>>(OldDoOperationAction.Make(Operators.GetMemberNames));
public IList<string> GetMemberNames(string code) {
object value = _engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression).Execute(_scope);
return _engine.Operations.GetMemberNames(value);
// TODO: why doesn't this work ???
//return _memberCompletionSite.Invoke(new CodeContext(_scope, _engine), value);
}
public virtual IList<string> GetGlobals(string name) {
List<string> res = new List<string>();
foreach (string scopeName in _scope.GetVariableNames()) {
if (scopeName.StartsWith(name, StringComparison.Ordinal)) {
res.Add(scopeName);
}
}
return res;
}
#endregion
class SimpleCommandDispatcher : ICommandDispatcher {
public object Execute(CompiledCode compiledCode, ScriptScope scope) {
return compiledCode.Execute(scope);
}
}
}
}
#endif
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class StartPositionRequestDecoder
{
public const ushort BLOCK_LENGTH = 24;
public const ushort TEMPLATE_ID = 52;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private StartPositionRequestDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public StartPositionRequestDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public StartPositionRequestDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdId()
{
return 1;
}
public static int ControlSessionIdSinceVersion()
{
return 0;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public long ControlSessionId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int RecordingIdId()
{
return 3;
}
public static int RecordingIdSinceVersion()
{
return 0;
}
public static int RecordingIdEncodingOffset()
{
return 16;
}
public static int RecordingIdEncodingLength()
{
return 8;
}
public static string RecordingIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long RecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long RecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long RecordingIdMaxValue()
{
return 9223372036854775807L;
}
public long RecordingId()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[StartPositionRequest](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ControlSessionId=");
builder.Append(ControlSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='recordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("RecordingId=");
builder.Append(RecordingId());
Limit(originalLimit);
return builder;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using CommandLine;
using Google.Apis.Auth.OAuth2;
using Google.Protobuf;
using Grpc.Auth;
using Grpc.Core;
using Grpc.Core.Utils;
using Grpc.Testing;
using NUnit.Framework;
using CommandLine.Text;
using System.IO;
namespace Grpc.IntegrationTesting
{
public class InteropClient
{
private class ClientOptions
{
[Option("server_host", DefaultValue = "127.0.0.1")]
public string ServerHost { get; set; }
[Option("server_host_override", DefaultValue = TestCredentials.DefaultHostOverride)]
public string ServerHostOverride { get; set; }
[Option("server_port", Required = true)]
public int ServerPort { get; set; }
[Option("test_case", DefaultValue = "large_unary")]
public string TestCase { get; set; }
[Option("use_tls")]
public bool UseTls { get; set; }
[Option("use_test_ca")]
public bool UseTestCa { get; set; }
[Option("default_service_account", Required = false)]
public string DefaultServiceAccount { get; set; }
[Option("oauth_scope", Required = false)]
public string OAuthScope { get; set; }
[Option("service_account_key_file", Required = false)]
public string ServiceAccountKeyFile { get; set; }
[HelpOption]
public string GetUsage()
{
var help = new HelpText
{
Heading = "gRPC C# interop testing client",
AddDashesToOption = true
};
help.AddPreOptionsLine("Usage:");
help.AddOptions(this);
return help;
}
}
ClientOptions options;
private InteropClient(ClientOptions options)
{
this.options = options;
}
public static void Run(string[] args)
{
var options = new ClientOptions();
if (!Parser.Default.ParseArguments(args, options))
{
Environment.Exit(1);
}
var interopClient = new InteropClient(options);
interopClient.Run().Wait();
}
private async Task Run()
{
var credentials = options.UseTls ? TestCredentials.CreateTestClientCredentials(options.UseTestCa) : Credentials.Insecure;
List<ChannelOption> channelOptions = null;
if (!string.IsNullOrEmpty(options.ServerHostOverride))
{
channelOptions = new List<ChannelOption>
{
new ChannelOption(ChannelOptions.SslTargetNameOverride, options.ServerHostOverride)
};
}
var channel = new Channel(options.ServerHost, options.ServerPort, credentials, channelOptions);
TestService.TestServiceClient client = new TestService.TestServiceClient(channel);
await RunTestCaseAsync(client, options);
await channel.ShutdownAsync();
}
private async Task RunTestCaseAsync(TestService.TestServiceClient client, ClientOptions options)
{
switch (options.TestCase)
{
case "empty_unary":
RunEmptyUnary(client);
break;
case "large_unary":
RunLargeUnary(client);
break;
case "client_streaming":
await RunClientStreamingAsync(client);
break;
case "server_streaming":
await RunServerStreamingAsync(client);
break;
case "ping_pong":
await RunPingPongAsync(client);
break;
case "empty_stream":
await RunEmptyStreamAsync(client);
break;
case "compute_engine_creds":
await RunComputeEngineCredsAsync(client, options.DefaultServiceAccount, options.OAuthScope);
break;
case "jwt_token_creds":
await RunJwtTokenCredsAsync(client, options.DefaultServiceAccount);
break;
case "oauth2_auth_token":
await RunOAuth2AuthTokenAsync(client, options.DefaultServiceAccount, options.OAuthScope);
break;
case "per_rpc_creds":
await RunPerRpcCredsAsync(client, options.DefaultServiceAccount, options.OAuthScope);
break;
case "cancel_after_begin":
await RunCancelAfterBeginAsync(client);
break;
case "cancel_after_first_response":
await RunCancelAfterFirstResponseAsync(client);
break;
case "timeout_on_sleeping_server":
await RunTimeoutOnSleepingServerAsync(client);
break;
case "benchmark_empty_unary":
RunBenchmarkEmptyUnary(client);
break;
default:
throw new ArgumentException("Unknown test case " + options.TestCase);
}
}
public static void RunEmptyUnary(TestService.ITestServiceClient client)
{
Console.WriteLine("running empty_unary");
var response = client.EmptyCall(new Empty());
Assert.IsNotNull(response);
Console.WriteLine("Passed!");
}
public static void RunLargeUnary(TestService.ITestServiceClient client)
{
Console.WriteLine("running large_unary");
var request = new SimpleRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseSize = 314159,
Payload = CreateZerosPayload(271828)
};
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Console.WriteLine("Passed!");
}
public static async Task RunClientStreamingAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running client_streaming");
var bodySizes = new List<int> { 27182, 8, 1828, 45904 }.ConvertAll((size) => new StreamingInputCallRequest { Payload = CreateZerosPayload(size) });
using (var call = client.StreamingInputCall())
{
await call.RequestStream.WriteAllAsync(bodySizes);
var response = await call.ResponseAsync;
Assert.AreEqual(74922, response.AggregatedPayloadSize);
}
Console.WriteLine("Passed!");
}
public static async Task RunServerStreamingAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running server_streaming");
var bodySizes = new List<int> { 31415, 9, 2653, 58979 };
var request = new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { bodySizes.ConvertAll((size) => new ResponseParameters { Size = size }) }
};
using (var call = client.StreamingOutputCall(request))
{
var responseList = await call.ResponseStream.ToListAsync();
foreach (var res in responseList)
{
Assert.AreEqual(PayloadType.COMPRESSABLE, res.Payload.Type);
}
CollectionAssert.AreEqual(bodySizes, responseList.ConvertAll((item) => item.Payload.Body.Length));
}
Console.WriteLine("Passed!");
}
public static async Task RunPingPongAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running ping_pong");
using (var call = client.FullDuplexCall())
{
await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { new ResponseParameters { Size = 31415 } },
Payload = CreateZerosPayload(27182)
});
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { new ResponseParameters { Size = 9 } },
Payload = CreateZerosPayload(8)
});
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(9, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { new ResponseParameters { Size = 2653 } },
Payload = CreateZerosPayload(1828)
});
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(2653, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { new ResponseParameters { Size = 58979 } },
Payload = CreateZerosPayload(45904)
});
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(58979, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.CompleteAsync();
Assert.IsFalse(await call.ResponseStream.MoveNext());
}
Console.WriteLine("Passed!");
}
public static async Task RunEmptyStreamAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running empty_stream");
using (var call = client.FullDuplexCall())
{
await call.RequestStream.CompleteAsync();
var responseList = await call.ResponseStream.ToListAsync();
Assert.AreEqual(0, responseList.Count);
}
Console.WriteLine("Passed!");
}
public static async Task RunComputeEngineCredsAsync(TestService.TestServiceClient client, string defaultServiceAccount, string oauthScope)
{
Console.WriteLine("running compute_engine_creds");
var credential = await GoogleCredential.GetApplicationDefaultAsync();
Assert.IsFalse(credential.IsCreateScopedRequired);
client.HeaderInterceptor = AuthInterceptors.FromCredential(credential);
var request = new SimpleRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseSize = 314159,
Payload = CreateZerosPayload(271828),
FillUsername = true,
FillOauthScope = true
};
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Assert.False(string.IsNullOrEmpty(response.OauthScope));
Assert.True(oauthScope.Contains(response.OauthScope));
Assert.AreEqual(defaultServiceAccount, response.Username);
Console.WriteLine("Passed!");
}
public static async Task RunJwtTokenCredsAsync(TestService.TestServiceClient client, string defaultServiceAccount)
{
Console.WriteLine("running jwt_token_creds");
var credential = await GoogleCredential.GetApplicationDefaultAsync();
Assert.IsTrue(credential.IsCreateScopedRequired);
client.HeaderInterceptor = AuthInterceptors.FromCredential(credential);
var request = new SimpleRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseSize = 314159,
Payload = CreateZerosPayload(271828),
FillUsername = true,
};
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Assert.AreEqual(defaultServiceAccount, response.Username);
Console.WriteLine("Passed!");
}
public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client, string defaultServiceAccount, string oauthScope)
{
Console.WriteLine("running oauth2_auth_token");
ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope });
string oauth2Token = await credential.GetAccessTokenForRequestAsync();
client.HeaderInterceptor = AuthInterceptors.FromAccessToken(oauth2Token);
var request = new SimpleRequest
{
FillUsername = true,
FillOauthScope = true
};
var response = client.UnaryCall(request);
Assert.False(string.IsNullOrEmpty(response.OauthScope));
Assert.True(oauthScope.Contains(response.OauthScope));
Assert.AreEqual(defaultServiceAccount, response.Username);
Console.WriteLine("Passed!");
}
public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client, string defaultServiceAccount, string oauthScope)
{
Console.WriteLine("running per_rpc_creds");
ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope });
string accessToken = await credential.GetAccessTokenForRequestAsync();
var headerInterceptor = AuthInterceptors.FromAccessToken(accessToken);
var request = new SimpleRequest
{
FillUsername = true,
};
var headers = new Metadata();
headerInterceptor(null, "", headers);
var response = client.UnaryCall(request, headers: headers);
Assert.AreEqual(defaultServiceAccount, response.Username);
Console.WriteLine("Passed!");
}
public static async Task RunCancelAfterBeginAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running cancel_after_begin");
var cts = new CancellationTokenSource();
using (var call = client.StreamingInputCall(cancellationToken: cts.Token))
{
// TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it.
await Task.Delay(1000);
cts.Cancel();
var ex = Assert.Throws<RpcException>(async () => await call.ResponseAsync);
Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode);
}
Console.WriteLine("Passed!");
}
public static async Task RunCancelAfterFirstResponseAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running cancel_after_first_response");
var cts = new CancellationTokenSource();
using (var call = client.FullDuplexCall(cancellationToken: cts.Token))
{
await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
{
ResponseType = PayloadType.COMPRESSABLE,
ResponseParameters = { new ResponseParameters { Size = 31415 } },
Payload = CreateZerosPayload(27182)
});
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length);
cts.Cancel();
var ex = Assert.Throws<RpcException>(async () => await call.ResponseStream.MoveNext());
Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode);
}
Console.WriteLine("Passed!");
}
public static async Task RunTimeoutOnSleepingServerAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running timeout_on_sleeping_server");
var deadline = DateTime.UtcNow.AddMilliseconds(1);
using (var call = client.FullDuplexCall(deadline: deadline))
{
try
{
await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { Payload = CreateZerosPayload(27182) });
}
catch (InvalidOperationException)
{
// Deadline was reached before write has started. Eat the exception and continue.
}
var ex = Assert.Throws<RpcException>(async () => await call.ResponseStream.MoveNext());
Assert.AreEqual(StatusCode.DeadlineExceeded, ex.Status.StatusCode);
}
Console.WriteLine("Passed!");
}
// This is not an official interop test, but it's useful.
public static void RunBenchmarkEmptyUnary(TestService.ITestServiceClient client)
{
BenchmarkUtil.RunBenchmark(10000, 10000,
() => { client.EmptyCall(new Empty()); });
}
private static Payload CreateZerosPayload(int size)
{
return new Payload { Body = ByteString.CopyFrom(new byte[size]) };
}
}
}
| |
// Copyright 2020 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 GgpGrpc.Cloud;
using GgpGrpc.Models;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Threading;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using YetiCommon;
using YetiCommon.Cloud;
using YetiCommon.SSH;
using YetiVSI.Metrics;
using YetiVSI.Shared.Metrics;
using YetiVSI.Util;
namespace YetiVSI.CoreAttach
{
// A window showing a list of crash dumps that the user can attach to.
public partial class CoreAttachWindow : DialogWindow
{
readonly JoinableTaskContext _taskContext;
readonly CancelableTask.Factory _cancelableTaskFactory;
readonly ProjectInstanceSelection.Factory _instanceSelectionWindowFactory;
readonly ICoreListRequest _coreListRequest;
readonly ICloudRunner _cloudRunner;
readonly GameletClient.Factory _gameletClientFactory;
readonly IRemoteFile _remoteFile;
readonly ISshManager _sshManager;
readonly IDialogUtil _dialogUtil;
readonly ActionRecorder _actionRecorder;
readonly DebugSessionMetrics _debugSessionMetrics;
readonly string _developerAccount;
Gamelet _instance;
public CoreAttachWindow(IServiceProvider serviceProvider)
{
try
{
var serviceManager = new ServiceManager();
_taskContext = serviceManager.GetJoinableTaskContext();
_dialogUtil = new DialogUtil();
IExtensionOptions options =
((YetiVSIService)serviceManager.RequireGlobalService(typeof(YetiVSIService)))
.Options;
var managedProcessFactory = new ManagedProcess.Factory();
var progressDialogFactory = new ProgressDialog.Factory();
_cancelableTaskFactory =
new CancelableTask.Factory(_taskContext, progressDialogFactory);
_coreListRequest = new CoreListRequest.Factory().Create();
var jsonUtil = new JsonUtil();
var credentialConfigFactory = new CredentialConfig.Factory(jsonUtil);
var accountOptionLoader = new VsiAccountOptionLoader(options);
var credentialManager =
new CredentialManager(credentialConfigFactory, accountOptionLoader);
_developerAccount = credentialManager.LoadAccount();
IRemoteCommand remoteCommand = new RemoteCommand(managedProcessFactory);
_remoteFile = new RemoteFile(managedProcessFactory);
var cloudConnection = new CloudConnection();
var sdkConfigFactory = new SdkConfig.Factory(jsonUtil);
// NOTE: the lifetime of this CloudRunner is limited to the current CoreAttachWindow.
_cloudRunner = new CloudRunner(sdkConfigFactory, credentialManager, cloudConnection,
new GgpSDKUtil());
_gameletClientFactory = new GameletClient.Factory();
var sshKeyLoader = new SshKeyLoader(managedProcessFactory);
var sshKnownHostsWriter = new SshKnownHostsWriter();
_sshManager = new SshManager(_gameletClientFactory, _cloudRunner, sshKeyLoader,
sshKnownHostsWriter, remoteCommand);
_debugSessionMetrics = new DebugSessionMetrics(
serviceProvider.GetService(typeof(SMetrics)) as IMetrics);
_debugSessionMetrics.UseNewDebugSessionId();
_actionRecorder = new ActionRecorder(_debugSessionMetrics);
InitializeComponent();
_instanceSelectionWindowFactory = new ProjectInstanceSelection.Factory();
SelectInstanceOnInit();
}
catch (Exception exception)
{
Trace.WriteLine($"CoreAttachWindow ctor failed: {exception.Demystify()}");
throw;
}
}
void SelectInstanceOnInit()
{
List<Gamelet> instances = ListInstances();
if (instances == null)
{
return;
}
var ownedInstances = FilterOwnedInstances(instances);
SelectInstanceLabel.Content = $"Select from {instances.Count} Project Instances " +
$"({ownedInstances.Count} reserved):";
if (ownedInstances.Count == 1)
{
SetCurrentInstance(ownedInstances[0]);
}
}
void SelectInstance()
{
List<Gamelet> instances = ListInstances();
if (instances == null)
{
return;
}
SortInstancesByReserver(instances);
var selected = _instanceSelectionWindowFactory.Create(instances).Run();
// The operation was canceled.
if (selected == null)
{
return;
}
SetCurrentInstance(selected);
}
void SetCurrentInstance(Gamelet instance)
{
_instance = instance;
if (!EnableSsh())
{
_instance = null;
}
GameletMessageTextBox.Text = "";
RefreshInstanceLabel();
RefreshCoreList();
}
void RefreshCoreList()
{
if (_instance == null)
{
CoreList.ItemsSource = new List<CoreListEntry>();
return;
}
Cursor = System.Windows.Input.Cursors.Wait;
try
{
var queryTaskTitle = "Querying instance crash dumps...";
var queryTask = _cancelableTaskFactory.Create(
queryTaskTitle,
async () => await _coreListRequest.GetCoreListAsync(new SshTarget(_instance)));
// Ignore cancelation, and accept the empty result.
queryTask.RunAndRecord(_actionRecorder, ActionType.CrashDumpList);
CoreList.ItemsSource = queryTask.Result;
}
catch (ProcessException e)
{
Trace.WriteLine($"Unable to query instance crash dumps: {e.Demystify()}");
GameletMessageTextBox.Text = ErrorStrings.ErrorQueryingCoreFiles(e.Message);
CoreList.ItemsSource = new List<CoreListEntry>();
}
finally
{
Cursor = null;
}
}
List<Gamelet> ListInstances()
{
try
{
var action = _actionRecorder.CreateToolAction(ActionType.GameletsList);
var gameletClient = _gameletClientFactory.Create(_cloudRunner.Intercept(action));
var queryTask = _cancelableTaskFactory.Create(
"Querying instances...",
async () => await gameletClient.ListGameletsAsync(false));
if (!queryTask.RunAndRecord(action))
{
return null;
}
return queryTask.Result;
}
catch (CloudException e)
{
Trace.Write("An exception was thrown while querying instances." +
Environment.NewLine + e);
GameletMessageTextBox.Text = ErrorStrings.FailedToRetrieveGamelets(e.Message);
return null;
}
}
List<Gamelet> FilterOwnedInstances(List<Gamelet> instances) =>
instances.Where(i => i.ReserverEmail == _developerAccount).ToList();
void SortInstancesByReserver(List<Gamelet> instances)
{
instances.Sort((g1, g2) =>
{
if (g1.ReserverEmail != _developerAccount && g2.ReserverEmail != _developerAccount)
{
return string.CompareOrdinal(g1.ReserverEmail, g2.ReserverEmail);
}
if (g1.ReserverEmail == _developerAccount && g2.ReserverEmail == _developerAccount)
{
return string.CompareOrdinal(g1.DisplayName, g2.DisplayName);
}
return g1.ReserverEmail == _developerAccount ? -1 : 1;
});
}
bool EnableSsh()
{
try
{
var action = _actionRecorder.CreateToolAction(ActionType.GameletEnableSsh);
var enableSshTask = _cancelableTaskFactory.Create(
TaskMessages.EnablingSSH,
async _ => { await _sshManager.EnableSshAsync(_instance, action); });
if (!enableSshTask.RunAndRecord(action))
{
return false;
}
}
catch (Exception e) when (e is CloudException || e is SshKeyException)
{
Trace.Write("An exception was thrown while enabling ssh." + Environment.NewLine +
e);
GameletMessageTextBox.Text = ErrorStrings.FailedToEnableSsh(e.Message);
return false;
}
return true;
}
void RefreshInstanceLabel()
{
InstanceLabel.Content = "Instance: " + (string.IsNullOrEmpty(_instance?.DisplayName)
? _instance?.Id
: _instance.DisplayName);
}
void CoreListSelectionChanged(object sender, SelectionChangedEventArgs e)
{
AttachButton.IsEnabled = CoreList.SelectedItem != null;
}
void RefreshClick(object sender, RoutedEventArgs e)
{
RefreshCoreList();
}
void CancelClick(object sender, RoutedEventArgs e)
{
Close();
}
void AttachClick(object sender, RoutedEventArgs e)
{
_taskContext.ThrowIfNotOnMainThread();
// Figure out core file path
CoreListEntry? coreListEntry = null;
if (TabControl.SelectedContent == GameletGroupBox)
{
coreListEntry = (CoreListEntry?) CoreList.SelectedItem;
if (coreListEntry == null)
{
_dialogUtil.ShowError(ErrorStrings.NoCoreFileSelected);
return;
}
}
string coreFilePath = null;
bool deleteAfter = false;
if (TabControl.SelectedContent == LocalGroupBox)
{
coreFilePath = LocalCorePathBox.Text;
}
else if (TabControl.SelectedContent == GameletGroupBox)
{
var tempPath = Path.GetTempPath();
try
{
_cancelableTaskFactory
.Create(TaskMessages.DownloadingCoreFile,
async task => await _remoteFile.GetAsync(new SshTarget(_instance),
"/usr/local/cloudcast/core/" +
coreListEntry?.Name,
tempPath, task))
.RunAndRecord(_actionRecorder, ActionType.CrashDumpDownload);
}
catch (ProcessException ex)
{
Trace.WriteLine($"Failed to download core file: {ex.Demystify()}");
_dialogUtil.ShowError(ErrorStrings.FailedToDownloadCore(ex.Message), ex);
return;
}
coreFilePath = Path.Combine(tempPath, coreListEntry?.Name);
deleteAfter = true;
}
if (string.IsNullOrEmpty(coreFilePath))
{
ShowMessage(ErrorStrings.FailedToRetrieveCoreFilePath);
return;
}
// Check if we have a debugger (should always be the case).
var vsDebugger =
(IVsDebugger4) ServiceProvider.GlobalProvider.GetService(typeof(IVsDebugger));
if (vsDebugger == null)
{
ShowMessage(ErrorStrings.FailedToStartDebugger);
return;
}
try
{
_actionRecorder.RecordToolAction(ActionType.CrashDumpAttach, delegate
{
_taskContext.ThrowIfNotOnMainThread();
VsDebugTargetInfo4[] debugTargets = new VsDebugTargetInfo4[1];
debugTargets[0].dlo = (uint) DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;
// LaunchDebugTargets4() throws an exception if |bstrExe| and |bstrCurDir|
// are empty. Use core path and temp directory as placeholders.
debugTargets[0].bstrExe = coreFilePath;
debugTargets[0].bstrCurDir = Path.GetTempPath();
var parameters = new DebugEngine.DebugEngine.Params
{
CoreFilePath = coreFilePath,
DebugSessionId = _debugSessionMetrics.DebugSessionId,
DeleteCoreFile = deleteAfter
};
debugTargets[0].bstrOptions = JsonConvert.SerializeObject(parameters);
debugTargets[0].guidLaunchDebugEngine = YetiConstants.DebugEngineGuid;
var processInfo = new VsDebugTargetProcessInfo[debugTargets.Length];
vsDebugger.LaunchDebugTargets4(1, debugTargets, processInfo);
});
}
catch (COMException ex)
{
Trace.WriteLine($"Failed to start debugger: {ex.Demystify()}");
// Both DebugEngine and Visual Studio already show error dialogs if DebugEngine
// has to abort while it's attaching, no need to show another dialog in that case.
if (ex.ErrorCode != VSConstants.E_ABORT)
{
_dialogUtil.ShowError(ErrorStrings.FailedToStartDebugger, ex);
}
}
finally
{
Close();
}
}
void BrowseClick(object sender, RoutedEventArgs e)
{
var openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Core files (*.core, *.dmp)|*.core; *.dmp|All files (*.*)|*.*";
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
LocalCorePathBox.Text = openFileDialog.FileName;
}
}
void TabSelected(object sender, SelectionChangedEventArgs e)
{
// |e| has the newly selected tab while |tabControl.SelectedContent| has the
// previously selected content.
if (e.AddedItems.Count == 0)
{
return;
}
GameletMessageTextBox.Text = "";
LocalMessageTextBox.Text = "";
if (e.AddedItems[0] == LocalTab)
{
AttachButton.IsEnabled = File.Exists(LocalCorePathBox.Text);
}
}
void localCorePathBox_TextChanged(object sender, TextChangedEventArgs e)
{
AttachButton.IsEnabled = File.Exists(LocalCorePathBox.Text);
if (!string.IsNullOrEmpty(LocalCorePathBox.Text) && !File.Exists(LocalCorePathBox.Text))
{
LocalMessageTextBox.Text = ErrorStrings.CoreFileDoesNotExist;
}
}
void ShowMessage(string message)
{
if (TabControl.SelectedContent == LocalGroupBox)
{
LocalMessageTextBox.Text = message;
}
else
{
GameletMessageTextBox.Text = message;
}
}
void InstanceSelectClick(object sender, RoutedEventArgs e)
{
SelectInstance();
}
}
}
| |
// 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 Microsoft.VisualBasic
{
public enum CallType
{
Get = 2,
Let = 4,
Method = 1,
Set = 8,
}
[Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute]
public sealed partial class Constants
{
internal Constants() { }
public const string vbBack = "\b";
public const string vbCr = "\r";
public const string vbCrLf = "\r\n";
public const string vbFormFeed = "\f";
public const string vbLf = "\n";
[System.Obsolete("For a carriage return and line feed, use vbCrLf. For the current platform's newline, use System.Environment.NewLine.")]
public const string vbNewLine = "\r\n";
public const string vbNullChar = "\0";
public const string vbNullString = null;
public const string vbTab = "\t";
public const string vbVerticalTab = "\v";
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple = false, Inherited = false)]
public sealed partial class HideModuleNameAttribute : System.Attribute
{
public HideModuleNameAttribute() { }
}
[Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute]
public sealed partial class Strings
{
internal Strings() { }
public static int AscW(char String) { throw null; }
public static int AscW(string String) { throw null; }
public static char ChrW(int CharCode) { throw null; }
}
}
namespace Microsoft.VisualBasic.CompilerServices
{
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class Conversions
{
internal Conversions() { }
public static object ChangeType(object Expression, System.Type TargetType) { throw null; }
public static bool ToBoolean(object Value) { throw null; }
public static bool ToBoolean(string Value) { throw null; }
public static byte ToByte(object Value) { throw null; }
public static byte ToByte(string Value) { throw null; }
public static char ToChar(object Value) { throw null; }
public static char ToChar(string Value) { throw null; }
public static char[] ToCharArrayRankOne(object Value) { throw null; }
public static char[] ToCharArrayRankOne(string Value) { throw null; }
public static System.DateTime ToDate(object Value) { throw null; }
public static System.DateTime ToDate(string Value) { throw null; }
public static decimal ToDecimal(bool Value) { throw null; }
public static decimal ToDecimal(object Value) { throw null; }
public static decimal ToDecimal(string Value) { throw null; }
public static double ToDouble(object Value) { throw null; }
public static double ToDouble(string Value) { throw null; }
public static T ToGenericParameter<T>(object Value) { throw null; }
public static int ToInteger(object Value) { throw null; }
public static int ToInteger(string Value) { throw null; }
public static long ToLong(object Value) { throw null; }
public static long ToLong(string Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(object Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string Value) { throw null; }
public static short ToShort(object Value) { throw null; }
public static short ToShort(string Value) { throw null; }
public static float ToSingle(object Value) { throw null; }
public static float ToSingle(string Value) { throw null; }
public static string ToString(bool Value) { throw null; }
public static string ToString(byte Value) { throw null; }
public static string ToString(char Value) { throw null; }
public static string ToString(System.DateTime Value) { throw null; }
public static string ToString(decimal Value) { throw null; }
public static string ToString(double Value) { throw null; }
public static string ToString(short Value) { throw null; }
public static string ToString(int Value) { throw null; }
public static string ToString(long Value) { throw null; }
public static string ToString(object Value) { throw null; }
public static string ToString(float Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static string ToString(uint Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static string ToString(ulong Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static uint ToUInteger(object Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static uint ToUInteger(string Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static ulong ToULong(object Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static ulong ToULong(string Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static ushort ToUShort(object Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static ushort ToUShort(string Value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple = false, Inherited = false)]
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class DesignerGeneratedAttribute : System.Attribute
{
public DesignerGeneratedAttribute() { }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class IncompleteInitialization : System.Exception
{
public IncompleteInitialization() { }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class NewLateBinding
{
internal NewLateBinding() { }
public static object LateCall(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool[] CopyBack, bool IgnoreReturn) { throw null; }
public static object LateGet(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool[] CopyBack) { throw null; }
public static object LateIndexGet(object Instance, object[] Arguments, string[] ArgumentNames) { throw null; }
public static void LateIndexSet(object Instance, object[] Arguments, string[] ArgumentNames) { }
public static void LateIndexSetComplex(object Instance, object[] Arguments, string[] ArgumentNames, bool OptimisticSet, bool RValueBase) { }
public static void LateSet(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments) { }
public static void LateSet(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool OptimisticSet, bool RValueBase, Microsoft.VisualBasic.CallType CallType) { }
public static void LateSetComplex(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool OptimisticSet, bool RValueBase) { }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class ObjectFlowControl
{
internal ObjectFlowControl() { }
public static void CheckForSyncLockOnValueType(object Expression) { }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class ForLoopControl
{
internal ForLoopControl() { }
public static bool ForLoopInitObj(object Counter, object Start, object Limit, object StepValue, ref object LoopForResult, ref object CounterResult) { throw null; }
public static bool ForNextCheckDec(decimal count, decimal limit, decimal StepValue) { throw null; }
public static bool ForNextCheckObj(object Counter, object LoopObj, ref object CounterResult) { throw null; }
public static bool ForNextCheckR4(float count, float limit, float StepValue) { throw null; }
public static bool ForNextCheckR8(double count, double limit, double StepValue) { throw null; }
}
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class Operators
{
internal Operators() { }
public static object AddObject(object Left, object Right) { throw null; }
public static object AndObject(object Left, object Right) { throw null; }
public static object CompareObjectEqual(object Left, object Right, bool TextCompare) { throw null; }
public static object CompareObjectGreater(object Left, object Right, bool TextCompare) { throw null; }
public static object CompareObjectGreaterEqual(object Left, object Right, bool TextCompare) { throw null; }
public static object CompareObjectLess(object Left, object Right, bool TextCompare) { throw null; }
public static object CompareObjectLessEqual(object Left, object Right, bool TextCompare) { throw null; }
public static object CompareObjectNotEqual(object Left, object Right, bool TextCompare) { throw null; }
public static int CompareString(string Left, string Right, bool TextCompare) { throw null; }
public static object ConcatenateObject(object Left, object Right) { throw null; }
public static bool ConditionalCompareObjectEqual(object Left, object Right, bool TextCompare) { throw null; }
public static bool ConditionalCompareObjectGreater(object Left, object Right, bool TextCompare) { throw null; }
public static bool ConditionalCompareObjectGreaterEqual(object Left, object Right, bool TextCompare) { throw null; }
public static bool ConditionalCompareObjectLess(object Left, object Right, bool TextCompare) { throw null; }
public static bool ConditionalCompareObjectLessEqual(object Left, object Right, bool TextCompare) { throw null; }
public static bool ConditionalCompareObjectNotEqual(object Left, object Right, bool TextCompare) { throw null; }
public static object DivideObject(object Left, object Right) { throw null; }
public static object ExponentObject(object Left, object Right) { throw null; }
public static object IntDivideObject(object Left, object Right) { throw null; }
public static object LeftShiftObject(object Operand, object Amount) { throw null; }
public static object ModObject(object Left, object Right) { throw null; }
public static object MultiplyObject(object Left, object Right) { throw null; }
public static object NegateObject(object Operand) { throw null; }
public static object NotObject(object Operand) { throw null; }
public static object OrObject(object Left, object Right) { throw null; }
public static object PlusObject(object Operand) { throw null; }
public static object RightShiftObject(object Operand, object Amount) { throw null; }
public static object SubtractObject(object Left, object Right) { throw null; }
public static object XorObject(object Left, object Right) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2048), Inherited = false, AllowMultiple = false)]
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class OptionCompareAttribute : System.Attribute
{
public OptionCompareAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited = false, AllowMultiple = false)]
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class OptionTextAttribute : System.Attribute
{
public OptionTextAttribute() { }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class ProjectData
{
internal ProjectData() { }
[System.Security.SecuritySafeCriticalAttribute]
public static void ClearProjectError() { }
[System.Security.SecuritySafeCriticalAttribute]
public static void SetProjectError(System.Exception ex) { }
[System.Security.SecuritySafeCriticalAttribute]
public static void SetProjectError(System.Exception ex, int lErl) { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited = false, AllowMultiple = false)]
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class StandardModuleAttribute : System.Attribute
{
public StandardModuleAttribute() { }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class StaticLocalInitFlag
{
public short State;
public StaticLocalInitFlag() { }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class Utils
{
internal Utils() { }
public static System.Array CopyArray(System.Array arySrc, System.Array aryDest) { throw null; }
}
}
| |
using System;
using System.ComponentModel;
using System.IO;
using IdSharp.Common.Utils;
using IdSharp.Tagging.ID3v2.Extensions;
using IdSharp.Tagging.ID3v2.Frames.Items;
using IdSharp.Tagging.ID3v2.Frames.Lists;
namespace IdSharp.Tagging.ID3v2.Frames
{
internal sealed class Commercial : Frame, ICommercial
{
private EncodingType _textEncoding;
private readonly PriceInformationBindingList _priceList;
private DateTime _validUntil;
private string _contactUrl;
private string _nameOfSeller;
private ReceivedAs _receivedAs;
private string _description;
private string _sellerLogoMimeType;
private byte[] _sellerLogo;
public Commercial()
{
_priceList = new PriceInformationBindingList();
}
public EncodingType TextEncoding
{
get { return _textEncoding; }
set
{
_textEncoding = value;
RaisePropertyChanged("TextEncoding");
}
}
public BindingList<IPriceInformation> PriceList
{
get { return _priceList; }
}
public DateTime ValidUntil
{
get { return _validUntil.Date; }
set
{
_validUntil = value.Date;
RaisePropertyChanged("ValidUntil");
}
}
public string ContactUrl
{
get { return _contactUrl; }
set
{
_contactUrl = value;
RaisePropertyChanged("ContactUrl");
}
}
public ReceivedAs ReceivedAs
{
get { return _receivedAs; }
set
{
_receivedAs = value;
RaisePropertyChanged("ReceivedAs");
}
}
public string NameOfSeller
{
get { return _nameOfSeller; }
set
{
_nameOfSeller = value;
RaisePropertyChanged("NameOfSeller");
}
}
public string Description
{
get { return _description; }
set
{
_description = value;
RaisePropertyChanged("Description");
}
}
public string SellerLogoMimeType
{
get { return _sellerLogoMimeType; }
set
{
_sellerLogoMimeType = value;
RaisePropertyChanged("SellerLogoMimeType");
}
}
public byte[] SellerLogo
{
get { return ByteUtils.Clone(_sellerLogo); }
set
{
_sellerLogo = ByteUtils.Clone(value);
RaisePropertyChanged("SellerLogo");
}
}
public override string GetFrameID(ID3v2TagVersion tagVersion)
{
switch (tagVersion)
{
case ID3v2TagVersion.ID3v24:
case ID3v2TagVersion.ID3v23:
return "COMR";
case ID3v2TagVersion.ID3v22:
return null;
default:
throw new ArgumentException("Unknown tag version");
}
}
public override void Read(TagReadingInfo tagReadingInfo, Stream stream)
{
Reset();
_frameHeader.Read(tagReadingInfo, ref stream);
int bytesLeft = _frameHeader.FrameSizeExcludingAdditions;
if (bytesLeft > 1)
{
TextEncoding = (EncodingType)stream.Read1(ref bytesLeft);
string priceString = ID3v2Utils.ReadString(EncodingType.ISO88591, stream, ref bytesLeft);
if (!string.IsNullOrEmpty(priceString))
{
foreach (string priceItem in priceString.Split('/'))
{
if (priceItem.Length > 3)
{
decimal price;
string pricePart = priceItem.Substring(3, priceItem.Length - 3);
if (decimal.TryParse(pricePart, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out price))
{
IPriceInformation priceInfo = new PriceInformation();
priceInfo.CurrencyCode = priceItem.Substring(0, 3);
priceInfo.Price = price;
_priceList.Add(priceInfo);
}
}
}
}
if (bytesLeft > 0)
{
string validUntil = ID3v2Utils.ReadString(EncodingType.ISO88591, stream, 8);
bytesLeft -= 8;
if (validUntil.Length == 8)
{
validUntil = string.Format("{0}-{1}-{2}", validUntil.Substring(0, 4),
validUntil.Substring(4, 2), validUntil.Substring(6, 2));
DateTime.TryParse(validUntil, out _validUntil);
}
if (bytesLeft > 0)
{
ContactUrl = ID3v2Utils.ReadString(EncodingType.ISO88591, stream, ref bytesLeft);
if (bytesLeft > 0)
{
ReceivedAs = (ReceivedAs)stream.Read1(ref bytesLeft);
NameOfSeller = ID3v2Utils.ReadString(TextEncoding, stream, ref bytesLeft);
Description = ID3v2Utils.ReadString(TextEncoding, stream, ref bytesLeft);
SellerLogoMimeType = ID3v2Utils.ReadString(EncodingType.ISO88591, stream, ref bytesLeft);
if (bytesLeft > 0)
{
SellerLogo = stream.Read(bytesLeft);
bytesLeft = 0;
}
}
}
}
}
if (bytesLeft != 0)
{
stream.Seek(bytesLeft, SeekOrigin.Current);
}
}
public override byte[] GetBytes(ID3v2TagVersion tagVersion)
{
if (_priceList.Count == 0)
return new byte[0];
using (MemoryStream frameData = new MemoryStream())
{
byte[] nameOfSellerData;
byte[] descriptionData;
do
{
nameOfSellerData = ID3v2Utils.GetStringBytes(tagVersion, _textEncoding, _nameOfSeller, true);
descriptionData = ID3v2Utils.GetStringBytes(tagVersion, _textEncoding, _description, true);
} while (
this.RequiresFix(tagVersion, _nameOfSeller, nameOfSellerData) ||
this.RequiresFix(tagVersion, _description, descriptionData)
);
frameData.WriteByte((byte)_textEncoding);
string priceString = string.Empty;
foreach (IPriceInformation priceInfo in _priceList)
{
if (priceInfo.CurrencyCode != null && priceInfo.CurrencyCode.Length == 3)
{
if (priceString != string.Empty)
priceString += "/";
priceString += string.Format("{0}{1:0.00}", priceInfo.CurrencyCode, priceInfo.Price);
}
}
// No valid price items
if (priceString == string.Empty)
return new byte[0];
frameData.Write(ByteUtils.ISO88591GetBytes(priceString));
frameData.WriteByte(0); // terminator
frameData.Write(ByteUtils.ISO88591GetBytes(_validUntil.ToString("yyyyMMdd")));
frameData.Write(ByteUtils.ISO88591GetBytes(_contactUrl));
frameData.WriteByte(0); // terminator
frameData.WriteByte((byte)_receivedAs);
frameData.Write(nameOfSellerData);
frameData.Write(descriptionData);
// This section is optional
if (_sellerLogo != null && _sellerLogo.Length != 0)
{
frameData.Write(ByteUtils.ISO88591GetBytes(_sellerLogoMimeType));
frameData.WriteByte(0); // terminator
frameData.Write(_sellerLogo);
}
return _frameHeader.GetBytes(frameData, tagVersion, GetFrameID(tagVersion));
}
}
private void Reset()
{
TextEncoding = EncodingType.ISO88591;
PriceList.Clear();
ValidUntil = DateTime.MinValue;
ContactUrl = null;
ReceivedAs = ReceivedAs.Other;
NameOfSeller = null;
Description = null;
SellerLogoMimeType = null;
SellerLogo = null;
}
}
}
| |
namespace KnowledgeBase.ViewModels
{
using System.Reflection;
using System.Windows.Input;
using CefSharp.Wpf;
using KnowledgeBase.ViewModels.Commands;
/// <summary>
/// Define an application specific interface for viewmodels that contain a
/// <seealso cref="IWpfWebBrowser"/> interface.
/// </summary>
public interface IWebBrowser
{
IWpfWebBrowser WebBrowser { get; }
}
/// <summary>
/// ApplicationViewModel manages the appplications state and its main objects.
/// </summary>
public class AppViewModel : Base.ViewModelBase, IWebBrowser
{
#region fields
// This string holds a URL to the web.zip file in the local file system
public string LocalZipUrl = "{0}/00_SampleData/web.zip";
public string LocalZipUrl1 = "{0}/00_SampleData/CP_Articles.zip";
public string LocalZipUrl2 = "{0}/00_SampleData/cef_binary_3.2171.1979_docs.zip";
// These 2 Demo URLs are based on the local zip file path
// but point to individual html pages inside the package
public const string TestResourceUrl = "local://{0}::/index.html";
public const string TestCefResourceUrl = "local://{0}::/projects/(default)/CefBrowser.html";
private ICommand mTestUrlCommand = null;
private ICommand mTestUrl1Command = null;
private ICommand mTestUrl2Command = null;
private ICommand mShowDevToolsCommand = null;
private string mBrowserAddress;
private IWpfWebBrowser mWebBrowser;
private string mAssemblyTitle;
private string mAssemblyPath;
private string mSampleDataPath;
private FindTextViewModel mFind;
#endregion fields
#region constructors
/// <summary>
/// Class Constructor
/// </summary>
public AppViewModel()
{
// Set title of assembly in viewmodel and reset first browser address
this.mAssemblyTitle = Assembly.GetEntryAssembly().GetName().Name;
this.mAssemblyPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
this.mSampleDataPath = System.IO.Directory.GetParent(this.mAssemblyPath).FullName;
for (int i = 0; i < 4; i++)
this.mSampleDataPath = System.IO.Directory.GetParent(this.mSampleDataPath).FullName;
this.mSampleDataPath = this.mSampleDataPath.Replace(" ", "%20");
this.mSampleDataPath = this.mSampleDataPath.Replace("\\", "/");
this.LocalZipUrl = string.Format(LocalZipUrl, this.mSampleDataPath);
this.LocalZipUrl1 = string.Format(LocalZipUrl1, this.mSampleDataPath);
this.LocalZipUrl2 = string.Format(LocalZipUrl2, this.mSampleDataPath);
this.BrowserAddress = string.Format(TestCefResourceUrl, this.LocalZipUrl2);
}
#endregion constructors
#region properties
/// <summary>
/// Get/set current address of web browser URI.
/// </summary>
public string BrowserAddress
{
get
{
return this.mBrowserAddress;
}
set
{
if (this.mBrowserAddress != value)
{
this.mBrowserAddress = value;
this.RaisePropertyChanged(() => this.BrowserAddress);
this.RaisePropertyChanged(() => this.BrowserTitle);
}
}
}
/// <summary>
/// Gets/sets the web browser object bound from the ChromiumWebBrowser control.
/// </summary>
public IWpfWebBrowser WebBrowser
{
get
{
return this.mWebBrowser;
}
set
{
if (mWebBrowser != value)
{
this.mWebBrowser = value;
this.RaisePropertyChanged(() => this.WebBrowser);
}
}
}
/// <summary>
/// Gets a property that exposes all viewmodel related functions
/// for finding and highlighting text.
/// </summary>
public FindTextViewModel Find
{
get
{
if (this.mFind == null)
this.mFind = new FindTextViewModel(this);
return this.mFind;
}
}
/// <summary>
/// Get "title" - "Uri" string of current address of web browser URI
/// for display in UI - to let the user know what his looking at.
/// </summary>
public string BrowserTitle
{
get
{
return string.Format("{0} - {1}", this.mAssemblyTitle, this.mBrowserAddress);
}
}
/// <summary>
/// Get test Command to browse to a test URL ...
/// </summary>
public ICommand TestUrlCommand
{
get
{
if (this.mTestUrlCommand == null)
{
this.mTestUrlCommand = new RelayCommand(() =>
{
// Setting this address sets the current address of the browser
// control via bound BrowserAddress property
this.BrowserAddress = string.Format(AppViewModel.TestResourceUrl, this.LocalZipUrl);
});
}
return this.mTestUrlCommand;
}
}
/// <summary>
/// Get test Command to browse to a test URL 1 ...
/// </summary>
public ICommand TestUrl1Command
{
get
{
if (this.mTestUrl1Command == null)
{
this.mTestUrl1Command = new RelayCommand(() =>
{
// Setting this address sets the current address of the browser
// control via bound BrowserAddress property
this.BrowserAddress = string.Format(AppViewModel.TestResourceUrl, this.LocalZipUrl1);
});
}
return this.mTestUrl1Command;
}
}
/// <summary>
/// Get test Command to browse to a test URL 2 ...
/// </summary>
public ICommand TestUrl2Command
{
get
{
if (this.mTestUrl2Command == null)
{
this.mTestUrl2Command = new RelayCommand(() =>
{
// Setting this address sets the current address of the browser
// control via bound BrowserAddress property
this.BrowserAddress = string.Format(AppViewModel.TestCefResourceUrl, this.LocalZipUrl2);
});
}
return this.mTestUrl2Command;
}
}
/// <summary>
/// Get ShowDevToolsCommand Command to display chromiums web browser.
/// </summary>
public ICommand ShowDevToolsCommand
{
get
{
if (this.mShowDevToolsCommand == null)
{
this.mShowDevToolsCommand = new RelayCommand<object>((p) =>
{
var chromBrowser = p as ChromiumWebBrowser;
if (chromBrowser != null)
chromBrowser.ShowDevTools();
});
}
return this.mShowDevToolsCommand;
}
}
#endregion properties
#region methods
#endregion methods
}
}
| |
namespace Azure.ResourceManager.KeyVault
{
public partial class KeyVaultManagementClient
{
protected KeyVaultManagementClient() { }
public KeyVaultManagementClient(string subscriptionId, Azure.Core.TokenCredential tokenCredential, Azure.ResourceManager.KeyVault.KeyVaultManagementClientOptions options = null) { }
public KeyVaultManagementClient(string subscriptionId, System.Uri endpoint, Azure.Core.TokenCredential tokenCredential, Azure.ResourceManager.KeyVault.KeyVaultManagementClientOptions options = null) { }
public virtual Azure.ResourceManager.KeyVault.Operations Operations { get { throw null; } }
public virtual Azure.ResourceManager.KeyVault.PrivateEndpointConnectionsOperations PrivateEndpointConnections { get { throw null; } }
public virtual Azure.ResourceManager.KeyVault.PrivateLinkResourcesOperations PrivateLinkResources { get { throw null; } }
public virtual Azure.ResourceManager.KeyVault.VaultsOperations Vaults { get { throw null; } }
}
public partial class KeyVaultManagementClientOptions : Azure.Core.ClientOptions
{
public KeyVaultManagementClientOptions() { }
}
public partial class Operations
{
protected Operations() { }
public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.Models.Operation> List(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.Models.Operation> ListAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class PrivateEndpointConnectionsDeleteOperation : Azure.Operation<Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnection>
{
internal PrivateEndpointConnectionsDeleteOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnection Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnection>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnection>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class PrivateEndpointConnectionsOperations
{
protected PrivateEndpointConnectionsOperations() { }
public virtual Azure.Response<Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnection> Get(string resourceGroupName, string vaultName, string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnection>> GetAsync(string resourceGroupName, string vaultName, string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnection> Put(string resourceGroupName, string vaultName, string privateEndpointConnectionName, Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnection properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnection>> PutAsync(string resourceGroupName, string vaultName, string privateEndpointConnectionName, Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnection properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.KeyVault.PrivateEndpointConnectionsDeleteOperation StartDelete(string resourceGroupName, string vaultName, string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.KeyVault.PrivateEndpointConnectionsDeleteOperation> StartDeleteAsync(string resourceGroupName, string vaultName, string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class PrivateLinkResourcesOperations
{
protected PrivateLinkResourcesOperations() { }
public virtual Azure.Response<Azure.ResourceManager.KeyVault.Models.PrivateLinkResourceListResult> ListByVault(string resourceGroupName, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Models.PrivateLinkResourceListResult>> ListByVaultAsync(string resourceGroupName, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class VaultsCreateOrUpdateOperation : Azure.Operation<Azure.ResourceManager.KeyVault.Models.Vault>
{
internal VaultsCreateOrUpdateOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.ResourceManager.KeyVault.Models.Vault Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.KeyVault.Models.Vault>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.KeyVault.Models.Vault>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class VaultsOperations
{
protected VaultsOperations() { }
public virtual Azure.Response<Azure.ResourceManager.KeyVault.Models.CheckNameAvailabilityResult> CheckNameAvailability(Azure.ResourceManager.KeyVault.Models.VaultCheckNameAvailabilityParameters vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Models.CheckNameAvailabilityResult>> CheckNameAvailabilityAsync(Azure.ResourceManager.KeyVault.Models.VaultCheckNameAvailabilityParameters vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response Delete(string resourceGroupName, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteAsync(string resourceGroupName, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.KeyVault.Models.Vault> Get(string resourceGroupName, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Models.Vault>> GetAsync(string resourceGroupName, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.KeyVault.Models.DeletedVault> GetDeleted(string vaultName, string location, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Models.DeletedVault>> GetDeletedAsync(string vaultName, string location, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.Models.Resource> List(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.Models.Resource> ListAsync(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.Models.Vault> ListByResourceGroup(string resourceGroupName, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.Models.Vault> ListByResourceGroupAsync(string resourceGroupName, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.Models.Vault> ListBySubscription(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.Models.Vault> ListBySubscriptionAsync(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.Models.DeletedVault> ListDeleted(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.Models.DeletedVault> ListDeletedAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.KeyVault.VaultsCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string vaultName, Azure.ResourceManager.KeyVault.Models.VaultCreateOrUpdateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.KeyVault.VaultsCreateOrUpdateOperation> StartCreateOrUpdateAsync(string resourceGroupName, string vaultName, Azure.ResourceManager.KeyVault.Models.VaultCreateOrUpdateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.KeyVault.VaultsPurgeDeletedOperation StartPurgeDeleted(string vaultName, string location, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.KeyVault.VaultsPurgeDeletedOperation> StartPurgeDeletedAsync(string vaultName, string location, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.KeyVault.Models.Vault> Update(string resourceGroupName, string vaultName, Azure.ResourceManager.KeyVault.Models.VaultPatchParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.KeyVault.Models.VaultAccessPolicyParameters> UpdateAccessPolicy(string resourceGroupName, string vaultName, Azure.ResourceManager.KeyVault.Models.AccessPolicyUpdateKind operationKind, Azure.ResourceManager.KeyVault.Models.VaultAccessPolicyParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Models.VaultAccessPolicyParameters>> UpdateAccessPolicyAsync(string resourceGroupName, string vaultName, Azure.ResourceManager.KeyVault.Models.AccessPolicyUpdateKind operationKind, Azure.ResourceManager.KeyVault.Models.VaultAccessPolicyParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Models.Vault>> UpdateAsync(string resourceGroupName, string vaultName, Azure.ResourceManager.KeyVault.Models.VaultPatchParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class VaultsPurgeDeletedOperation : Azure.Operation<Azure.Response>
{
internal VaultsPurgeDeletedOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.Response Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
}
namespace Azure.ResourceManager.KeyVault.Models
{
public partial class AccessPolicyEntry
{
public AccessPolicyEntry(System.Guid tenantId, string objectId, Azure.ResourceManager.KeyVault.Models.Permissions permissions) { }
public System.Guid? ApplicationId { get { throw null; } set { } }
public string ObjectId { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.Permissions Permissions { get { throw null; } set { } }
public System.Guid TenantId { get { throw null; } set { } }
}
public enum AccessPolicyUpdateKind
{
Add = 0,
Replace = 1,
Remove = 2,
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct CertificatePermissions : System.IEquatable<Azure.ResourceManager.KeyVault.Models.CertificatePermissions>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public CertificatePermissions(string value) { throw null; }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Backup { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Create { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Delete { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Deleteissuers { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Get { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Getissuers { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Import { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions List { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Listissuers { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Managecontacts { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Manageissuers { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Purge { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Recover { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Restore { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Setissuers { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Update { get { throw null; } }
public bool Equals(Azure.ResourceManager.KeyVault.Models.CertificatePermissions other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.KeyVault.Models.CertificatePermissions left, Azure.ResourceManager.KeyVault.Models.CertificatePermissions right) { throw null; }
public static implicit operator Azure.ResourceManager.KeyVault.Models.CertificatePermissions (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.KeyVault.Models.CertificatePermissions left, Azure.ResourceManager.KeyVault.Models.CertificatePermissions right) { throw null; }
public override string ToString() { throw null; }
}
public partial class CheckNameAvailabilityResult
{
internal CheckNameAvailabilityResult() { }
public string Message { get { throw null; } }
public bool? NameAvailable { get { throw null; } }
public Azure.ResourceManager.KeyVault.Models.Reason? Reason { get { throw null; } }
}
public enum CreateMode
{
Recover = 0,
Default = 1,
}
public partial class DeletedVault
{
internal DeletedVault() { }
public string Id { get { throw null; } }
public string Name { get { throw null; } }
public Azure.ResourceManager.KeyVault.Models.DeletedVaultProperties Properties { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class DeletedVaultListResult
{
internal DeletedVaultListResult() { }
public string NextLink { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.KeyVault.Models.DeletedVault> Value { get { throw null; } }
}
public partial class DeletedVaultProperties
{
internal DeletedVaultProperties() { }
public System.DateTimeOffset? DeletionDate { get { throw null; } }
public string Location { get { throw null; } }
public System.DateTimeOffset? ScheduledPurgeDate { get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, string> Tags { get { throw null; } }
public string VaultId { get { throw null; } }
}
public partial class IPRule
{
public IPRule(string value) { }
public string Value { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct KeyPermissions : System.IEquatable<Azure.ResourceManager.KeyVault.Models.KeyPermissions>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public KeyPermissions(string value) { throw null; }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Backup { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Create { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Decrypt { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Delete { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Encrypt { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Get { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Import { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions List { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Purge { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Recover { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Restore { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Sign { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions UnwrapKey { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Update { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Verify { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.KeyPermissions WrapKey { get { throw null; } }
public bool Equals(Azure.ResourceManager.KeyVault.Models.KeyPermissions other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.KeyVault.Models.KeyPermissions left, Azure.ResourceManager.KeyVault.Models.KeyPermissions right) { throw null; }
public static implicit operator Azure.ResourceManager.KeyVault.Models.KeyPermissions (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.KeyVault.Models.KeyPermissions left, Azure.ResourceManager.KeyVault.Models.KeyPermissions right) { throw null; }
public override string ToString() { throw null; }
}
public partial class LogSpecification
{
internal LogSpecification() { }
public string BlobDuration { get { throw null; } }
public string DisplayName { get { throw null; } }
public string Name { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct NetworkRuleAction : System.IEquatable<Azure.ResourceManager.KeyVault.Models.NetworkRuleAction>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public NetworkRuleAction(string value) { throw null; }
public static Azure.ResourceManager.KeyVault.Models.NetworkRuleAction Allow { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.NetworkRuleAction Deny { get { throw null; } }
public bool Equals(Azure.ResourceManager.KeyVault.Models.NetworkRuleAction other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.KeyVault.Models.NetworkRuleAction left, Azure.ResourceManager.KeyVault.Models.NetworkRuleAction right) { throw null; }
public static implicit operator Azure.ResourceManager.KeyVault.Models.NetworkRuleAction (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.KeyVault.Models.NetworkRuleAction left, Azure.ResourceManager.KeyVault.Models.NetworkRuleAction right) { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct NetworkRuleBypassOptions : System.IEquatable<Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public NetworkRuleBypassOptions(string value) { throw null; }
public static Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions AzureServices { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions None { get { throw null; } }
public bool Equals(Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions left, Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions right) { throw null; }
public static implicit operator Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions left, Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions right) { throw null; }
public override string ToString() { throw null; }
}
public partial class NetworkRuleSet
{
public NetworkRuleSet() { }
public Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions? Bypass { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.NetworkRuleAction? DefaultAction { get { throw null; } set { } }
public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.IPRule> IpRules { get { throw null; } set { } }
public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.VirtualNetworkRule> VirtualNetworkRules { get { throw null; } set { } }
}
public partial class Operation
{
internal Operation() { }
public Azure.ResourceManager.KeyVault.Models.OperationDisplay Display { get { throw null; } }
public string Name { get { throw null; } }
public string Origin { get { throw null; } }
public Azure.ResourceManager.KeyVault.Models.ServiceSpecification ServiceSpecification { get { throw null; } }
}
public partial class OperationDisplay
{
internal OperationDisplay() { }
public string Description { get { throw null; } }
public string Operation { get { throw null; } }
public string Provider { get { throw null; } }
public string Resource { get { throw null; } }
}
public partial class OperationListResult
{
internal OperationListResult() { }
public string NextLink { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.KeyVault.Models.Operation> Value { get { throw null; } }
}
public partial class Permissions
{
public Permissions() { }
public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.CertificatePermissions> Certificates { get { throw null; } set { } }
public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.KeyPermissions> Keys { get { throw null; } set { } }
public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.SecretPermissions> Secrets { get { throw null; } set { } }
public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.StoragePermissions> Storage { get { throw null; } set { } }
}
public partial class PrivateEndpoint
{
public PrivateEndpoint() { }
public string Id { get { throw null; } }
}
public partial class PrivateEndpointConnection : Azure.ResourceManager.KeyVault.Models.Resource
{
public PrivateEndpointConnection() { }
public Azure.ResourceManager.KeyVault.Models.PrivateEndpoint PrivateEndpoint { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.PrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState? ProvisioningState { get { throw null; } }
}
public partial class PrivateEndpointConnectionItem
{
public PrivateEndpointConnectionItem() { }
public Azure.ResourceManager.KeyVault.Models.PrivateEndpoint PrivateEndpoint { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.PrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState? ProvisioningState { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct PrivateEndpointConnectionProvisioningState : System.IEquatable<Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public PrivateEndpointConnectionProvisioningState(string value) { throw null; }
public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState Creating { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState Deleting { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState Disconnected { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState Failed { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState Succeeded { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState Updating { get { throw null; } }
public bool Equals(Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState left, Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState right) { throw null; }
public static implicit operator Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState left, Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState right) { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct PrivateEndpointServiceConnectionStatus : System.IEquatable<Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public PrivateEndpointServiceConnectionStatus(string value) { throw null; }
public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus Approved { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus Disconnected { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus Pending { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus Rejected { get { throw null; } }
public bool Equals(Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus left, Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus right) { throw null; }
public static implicit operator Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus left, Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus right) { throw null; }
public override string ToString() { throw null; }
}
public partial class PrivateLinkResource : Azure.ResourceManager.KeyVault.Models.Resource
{
public PrivateLinkResource() { }
public string GroupId { get { throw null; } }
public System.Collections.Generic.IList<string> RequiredMembers { get { throw null; } }
public System.Collections.Generic.IList<string> RequiredZoneNames { get { throw null; } set { } }
}
public partial class PrivateLinkResourceListResult
{
internal PrivateLinkResourceListResult() { }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.KeyVault.Models.PrivateLinkResource> Value { get { throw null; } }
}
public partial class PrivateLinkServiceConnectionState
{
public PrivateLinkServiceConnectionState() { }
public string ActionRequired { get { throw null; } set { } }
public string Description { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus? Status { get { throw null; } set { } }
}
public enum Reason
{
AccountNameInvalid = 0,
AlreadyExists = 1,
}
public partial class Resource
{
public Resource() { }
public string Id { get { throw null; } }
public string Location { get { throw null; } }
public string Name { get { throw null; } }
public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class ResourceListResult
{
internal ResourceListResult() { }
public string NextLink { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.KeyVault.Models.Resource> Value { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct SecretPermissions : System.IEquatable<Azure.ResourceManager.KeyVault.Models.SecretPermissions>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public SecretPermissions(string value) { throw null; }
public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Backup { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Delete { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Get { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.SecretPermissions List { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Purge { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Recover { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Restore { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Set { get { throw null; } }
public bool Equals(Azure.ResourceManager.KeyVault.Models.SecretPermissions other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.KeyVault.Models.SecretPermissions left, Azure.ResourceManager.KeyVault.Models.SecretPermissions right) { throw null; }
public static implicit operator Azure.ResourceManager.KeyVault.Models.SecretPermissions (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.KeyVault.Models.SecretPermissions left, Azure.ResourceManager.KeyVault.Models.SecretPermissions right) { throw null; }
public override string ToString() { throw null; }
}
public partial class ServiceSpecification
{
internal ServiceSpecification() { }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.KeyVault.Models.LogSpecification> LogSpecifications { get { throw null; } }
}
public partial class Sku
{
public Sku(Azure.ResourceManager.KeyVault.Models.SkuName name) { }
public string Family { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.SkuName Name { get { throw null; } set { } }
}
public enum SkuName
{
Standard = 0,
Premium = 1,
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct StoragePermissions : System.IEquatable<Azure.ResourceManager.KeyVault.Models.StoragePermissions>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public StoragePermissions(string value) { throw null; }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Backup { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Delete { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Deletesas { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Get { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Getsas { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions List { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Listsas { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Purge { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Recover { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Regeneratekey { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Restore { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Set { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Setsas { get { throw null; } }
public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Update { get { throw null; } }
public bool Equals(Azure.ResourceManager.KeyVault.Models.StoragePermissions other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.KeyVault.Models.StoragePermissions left, Azure.ResourceManager.KeyVault.Models.StoragePermissions right) { throw null; }
public static implicit operator Azure.ResourceManager.KeyVault.Models.StoragePermissions (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.KeyVault.Models.StoragePermissions left, Azure.ResourceManager.KeyVault.Models.StoragePermissions right) { throw null; }
public override string ToString() { throw null; }
}
public partial class Vault
{
internal Vault() { }
public string Id { get { throw null; } }
public string Location { get { throw null; } }
public string Name { get { throw null; } }
public Azure.ResourceManager.KeyVault.Models.VaultProperties Properties { get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, string> Tags { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class VaultAccessPolicyParameters
{
public VaultAccessPolicyParameters(Azure.ResourceManager.KeyVault.Models.VaultAccessPolicyProperties properties) { }
public string Id { get { throw null; } }
public string Location { get { throw null; } }
public string Name { get { throw null; } }
public Azure.ResourceManager.KeyVault.Models.VaultAccessPolicyProperties Properties { get { throw null; } set { } }
public string Type { get { throw null; } }
}
public partial class VaultAccessPolicyProperties
{
public VaultAccessPolicyProperties(System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.Models.AccessPolicyEntry> accessPolicies) { }
public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.AccessPolicyEntry> AccessPolicies { get { throw null; } }
}
public partial class VaultCheckNameAvailabilityParameters
{
public VaultCheckNameAvailabilityParameters(string name) { }
public string Name { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class VaultCreateOrUpdateParameters
{
public VaultCreateOrUpdateParameters(string location, Azure.ResourceManager.KeyVault.Models.VaultProperties properties) { }
public string Location { get { throw null; } }
public Azure.ResourceManager.KeyVault.Models.VaultProperties Properties { get { throw null; } }
public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } set { } }
}
public partial class VaultListResult
{
internal VaultListResult() { }
public string NextLink { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.KeyVault.Models.Vault> Value { get { throw null; } }
}
public partial class VaultPatchParameters
{
public VaultPatchParameters() { }
public Azure.ResourceManager.KeyVault.Models.VaultPatchProperties Properties { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } set { } }
}
public partial class VaultPatchProperties
{
public VaultPatchProperties() { }
public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.AccessPolicyEntry> AccessPolicies { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.CreateMode? CreateMode { get { throw null; } set { } }
public bool? EnabledForDeployment { get { throw null; } set { } }
public bool? EnabledForDiskEncryption { get { throw null; } set { } }
public bool? EnabledForTemplateDeployment { get { throw null; } set { } }
public bool? EnablePurgeProtection { get { throw null; } set { } }
public bool? EnableSoftDelete { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.NetworkRuleSet NetworkAcls { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.Sku Sku { get { throw null; } set { } }
public System.Guid? TenantId { get { throw null; } set { } }
}
public partial class VaultProperties
{
public VaultProperties(System.Guid tenantId, Azure.ResourceManager.KeyVault.Models.Sku sku) { }
public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.AccessPolicyEntry> AccessPolicies { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.CreateMode? CreateMode { get { throw null; } set { } }
public bool? EnabledForDeployment { get { throw null; } set { } }
public bool? EnabledForDiskEncryption { get { throw null; } set { } }
public bool? EnabledForTemplateDeployment { get { throw null; } set { } }
public bool? EnablePurgeProtection { get { throw null; } set { } }
public bool? EnableSoftDelete { get { throw null; } set { } }
public Azure.ResourceManager.KeyVault.Models.NetworkRuleSet NetworkAcls { get { throw null; } set { } }
public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionItem> PrivateEndpointConnections { get { throw null; } }
public Azure.ResourceManager.KeyVault.Models.Sku Sku { get { throw null; } set { } }
public System.Guid TenantId { get { throw null; } set { } }
public string VaultUri { get { throw null; } set { } }
}
public partial class VirtualNetworkRule
{
public VirtualNetworkRule(string id) { }
public string Id { get { throw null; } set { } }
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
#if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
using Microsoft.Xna.Framework.Graphics;
#endif
using FlatRedBall.ManagedSpriteGroups;
using FlatRedBall.Graphics;
namespace FlatRedBall.Gui
{
#region Skin classes
#region WindowSkin
public class WindowSkin
{
public Texture2D Texture;
public float SpriteBorderWidth = .2f;
public float TextureBorderWidth = .5f;
public float Alpha = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
public SpriteFrame.BorderSides BorderSides = SpriteFrame.BorderSides.All;
public Texture2D MoveBarTexture;
public float MoveBarSpriteBorderWidth = .1f;
public float MoveBarTextureBorderWidth = .5f;
public SpriteFrame.BorderSides MoveBarBorderSides = SpriteFrame.BorderSides.TopLeftRight;
public ButtonSkin CloseButtonSkin;
public void SetValuesFrom(SpriteFrame spriteFrame)
{
Texture = spriteFrame.Texture;
SpriteBorderWidth = spriteFrame.SpriteBorderWidth;
TextureBorderWidth = spriteFrame.TextureBorderWidth;
Alpha = spriteFrame.Alpha;
BorderSides = spriteFrame.Borders;
}
}
#endregion
#region ButtonSkin
public class ButtonSkin : WindowSkin
{
public BitmapFont Font = TextManager.DefaultFont;
public float TextSpacing = 1;
public float TextScale = 1;
}
#endregion
#region TextBoxSkin
public class TextBoxSkin : WindowSkin
{
public BitmapFont Font = TextManager.DefaultFont;
public float TextSpacing = 1;
public float TextScale = 1;
public float TextRed;
public float TextGreen;
public float TextBlue;
public void SetValuesFrom(SpriteFrame baseFrame, Text text)
{
base.SetValuesFrom(baseFrame);
TextSpacing = text.Spacing;
TextScale = text.Scale;
TextRed = text.Red;
TextGreen = text.Green;
TextBlue = text.Blue;
Font = text.Font;
}
}
#endregion
#region HighlightBarSkin
public class HighlightBarSkin : WindowSkin
{
public float HighlightBarHorizontalBuffer = 1;
public float ScaleY = 1;
public float HorizontalOffset = 0;
}
#endregion
#region SeparatorSkin
public class SeparatorSkin : WindowSkin
{
public float ScaleY = .35f;
public float HorizontalOffset = 0;
public int ExtraSeparators = 1;
}
#endregion
#region ListBoxSkin
public class ListBoxSkin : WindowSkin
{
public BitmapFont Font = TextManager.DefaultFont;
public float TextSpacing = 1;
public float TextScale = 1;
public float DistanceBetweenLines = 2.4f;
public float FirstItemDistanceFromTop = 2.4f;
public float Red = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
public float Green = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
public float Blue = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
public float DisabledRed = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue/2.0f;
public float DisabledGreen = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue / 2.0f;
public float DisabledBlue = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue / 2.0f;
public float HorizontalTextOffset = 0;
public HighlightBarSkin HighlightBarSkin = new HighlightBarSkin();
public SeparatorSkin SeparatorSkin = new SeparatorSkin();
}
#endregion
#region ScrollBarSkin
public class ScrollBarSkin : WindowSkin
{
public ButtonSkin UpButtonSkin = new ButtonSkin();
public ButtonSkin UpButtonDownSkin = new ButtonSkin();
public ButtonSkin DownButtonSkin = new ButtonSkin();
public ButtonSkin DownButtonDownSkin = new ButtonSkin();
public WindowSkin PositionBarSkin = new WindowSkin();
}
#endregion
#endregion
public class GuiSkin
{
#region Fields
internal WindowSkin mWindowSkin = new WindowSkin();
internal ButtonSkin mButtonSkin = new ButtonSkin();
internal ButtonSkin mButtonDownSkin = new ButtonSkin();
internal TextBoxSkin mTextBoxSkin = new TextBoxSkin();
internal ListBoxSkin mListBoxSkin = new ListBoxSkin();
internal ScrollBarSkin mScrollBarSkin = new ScrollBarSkin();
#endregion
#region Properties
public ButtonSkin ButtonSkin
{
get { return mButtonSkin; }
}
public ButtonSkin ButtonDownSkin
{
get { return mButtonDownSkin; }
}
public ListBoxSkin ListBoxSkin
{
get { return mListBoxSkin; }
}
public ScrollBarSkin ScrollBarSkin
{
get { return mScrollBarSkin; }
}
public TextBoxSkin TextBoxSkin
{
get { return mTextBoxSkin; }
}
public WindowSkin WindowSkin
{
get { return mWindowSkin; }
}
#endregion
#region Methods
// This needs a parameterless constructor so it can be instantiated
// by the content pipeline.
public GuiSkin() { }
public void SetAllTextures(Texture2D textureToSet)
{
mWindowSkin.Texture = textureToSet;
mWindowSkin.MoveBarTexture = textureToSet;
if (mWindowSkin.CloseButtonSkin != null)
{
mWindowSkin.Texture = textureToSet;
}
mButtonSkin.Texture = textureToSet;
mButtonDownSkin.Texture = textureToSet;
mListBoxSkin.Texture = textureToSet;
mListBoxSkin.HighlightBarSkin.Texture = textureToSet;
mListBoxSkin.SeparatorSkin.Texture = textureToSet;
mTextBoxSkin.Texture = textureToSet;
mScrollBarSkin.Texture = textureToSet;
mScrollBarSkin.UpButtonSkin.Texture = textureToSet;
mScrollBarSkin.UpButtonDownSkin.Texture = textureToSet;
mScrollBarSkin.DownButtonSkin.Texture = textureToSet;
mScrollBarSkin.DownButtonDownSkin.Texture = textureToSet;
mScrollBarSkin.PositionBarSkin.Texture = textureToSet;
}
#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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
namespace System.Collections.Immutable
{
public partial struct ImmutableArray<T> : IReadOnlyList<T>, IList<T>, IEquatable<ImmutableArray<T>>, IList, IImmutableArray, IStructuralComparable, IStructuralEquatable, IImmutableList<T>
{
/// <summary>
/// Gets or sets the element at the specified index in the read-only list.
/// </summary>
/// <param name="index">The zero-based index of the element to get.</param>
/// <returns>The element at the specified index in the read-only list.</returns>
/// <exception cref="NotSupportedException">Always thrown from the setter.</exception>
/// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception>
T IList<T>.this[int index]
{
get
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self[index];
}
set { throw new NotSupportedException(); }
}
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value>
/// <c>true</c> if this instance is read only; otherwise, <c>false</c>.
/// </value>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection<T>.IsReadOnly
{
get { return true; }
}
/// <summary>
/// Gets the number of array in the collection.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
int ICollection<T>.Count
{
get
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.Length;
}
}
/// <summary>
/// Gets the number of array in the collection.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
int IReadOnlyCollection<T>.Count
{
get
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.Length;
}
}
/// <summary>
/// Gets the element at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns>
/// The element.
/// </returns>
/// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception>
T IReadOnlyList<T>.this[int index]
{
get
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self[index];
}
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item)
{
var self = this;
return self.IndexOf(item, 0, self.Length, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, IEqualityComparer<T> equalityComparer)
{
var self = this;
return self.IndexOf(item, startIndex, self.Length - startIndex, equalityComparer);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex)
{
var self = this;
return self.IndexOf(item, startIndex, self.Length - startIndex, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count)
{
return this.IndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">
/// The equality comparer to use in the search.
/// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used.
/// </param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < self.Length, nameof(startIndex));
Requires.Range(count >= 0 && startIndex + count <= self.Length, nameof(count));
equalityComparer = equalityComparer ?? EqualityComparer<T>.Default;
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.IndexOf(self.array, item, startIndex, count);
}
else
{
for (int i = startIndex; i < startIndex + count; i++)
{
if (equalityComparer.Equals(self.array[i], item))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item)
{
var self = this;
if (self.Length == 0)
{
return -1;
}
return self.LastIndexOf(item, self.Length - 1, self.Length, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex)
{
var self = this;
if (self.Length == 0 && startIndex == 0)
{
return -1;
}
return self.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count)
{
return this.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
if (startIndex == 0 && count == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < self.Length, nameof(startIndex));
Requires.Range(count >= 0 && startIndex - count + 1 >= 0, nameof(count));
equalityComparer = equalityComparer ?? EqualityComparer<T>.Default;
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.LastIndexOf(self.array, item, startIndex, count);
}
else
{
for (int i = startIndex; i >= startIndex - count + 1; i--)
{
if (equalityComparer.Equals(item, self.array[i]))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Determines whether the specified item exists in the array.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns><c>true</c> if an equal value was found in the array; <c>false</c> otherwise.</returns>
[Pure]
public bool Contains(T item)
{
return this.IndexOf(item) >= 0;
}
/// <summary>
/// Returns a new array with the specified value inserted at the specified position.
/// </summary>
/// <param name="index">The 0-based index into the array at which the new item should be added.</param>
/// <param name="item">The item to insert at the start of the array.</param>
/// <returns>A new array.</returns>
[Pure]
public ImmutableArray<T> Insert(int index, T item)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
Requires.Range(index >= 0 && index <= self.Length, nameof(index));
if (self.Length == 0)
{
return ImmutableArray.Create(item);
}
T[] tmp = new T[self.Length + 1];
tmp[index] = item;
if (index != 0)
{
Array.Copy(self.array, 0, tmp, 0, index);
}
if (index != self.Length)
{
Array.Copy(self.array, index, tmp, index + 1, self.Length - index);
}
return new ImmutableArray<T>(tmp);
}
/// <summary>
/// Inserts the specified values at the specified index.
/// </summary>
/// <param name="index">The index at which to insert the value.</param>
/// <param name="items">The elements to insert.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
public ImmutableArray<T> InsertRange(int index, IEnumerable<T> items)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
Requires.Range(index >= 0 && index <= self.Length, nameof(index));
Requires.NotNull(items, nameof(items));
if (self.Length == 0)
{
return ImmutableArray.CreateRange(items);
}
int count = ImmutableExtensions.GetCount(ref items);
if (count == 0)
{
return self;
}
T[] tmp = new T[self.Length + count];
if (index != 0)
{
Array.Copy(self.array, 0, tmp, 0, index);
}
if (index != self.Length)
{
Array.Copy(self.array, index, tmp, index + count, self.Length - index);
}
// We want to copy over the items we need to insert.
// Check first to see if items is a well-known collection we can call CopyTo
// on to the array, which is an order of magnitude faster than foreach.
// Otherwise, go to the fallback route where we manually enumerate the sequence
// and place the items in the array one-by-one.
if (!items.TryCopyTo(tmp, index))
{
int sequenceIndex = index;
foreach (var item in items)
{
tmp[sequenceIndex++] = item;
}
}
return new ImmutableArray<T>(tmp);
}
/// <summary>
/// Inserts the specified values at the specified index.
/// </summary>
/// <param name="index">The index at which to insert the value.</param>
/// <param name="items">The elements to insert.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
public ImmutableArray<T> InsertRange(int index, ImmutableArray<T> items)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
items.ThrowNullRefIfNotInitialized();
Requires.Range(index >= 0 && index <= self.Length, nameof(index));
if (self.IsEmpty)
{
return items;
}
else if (items.IsEmpty)
{
return self;
}
T[] tmp = new T[self.Length + items.Length];
if (index != 0)
{
Array.Copy(self.array, 0, tmp, 0, index);
}
if (index != self.Length)
{
Array.Copy(self.array, index, tmp, index + items.Length, self.Length - index);
}
Array.Copy(items.array, 0, tmp, index, items.Length);
return new ImmutableArray<T>(tmp);
}
/// <summary>
/// Returns a new array with the specified value inserted at the end.
/// </summary>
/// <param name="item">The item to insert at the end of the array.</param>
/// <returns>A new array.</returns>
[Pure]
public ImmutableArray<T> Add(T item)
{
var self = this;
if (self.Length == 0)
{
return ImmutableArray.Create(item);
}
return self.Insert(self.Length, item);
}
/// <summary>
/// Adds the specified values to this list.
/// </summary>
/// <param name="items">The values to add.</param>
/// <returns>A new list with the elements added.</returns>
[Pure]
public ImmutableArray<T> AddRange(IEnumerable<T> items)
{
var self = this;
return self.InsertRange(self.Length, items);
}
/// <summary>
/// Adds the specified values to this list.
/// </summary>
/// <param name="items">The values to add.</param>
/// <returns>A new list with the elements added.</returns>
[Pure]
public ImmutableArray<T> AddRange(ImmutableArray<T> items)
{
var self = this;
return self.InsertRange(self.Length, items);
}
/// <summary>
/// Returns an array with the item at the specified position replaced.
/// </summary>
/// <param name="index">The index of the item to replace.</param>
/// <param name="item">The new item.</param>
/// <returns>The new array.</returns>
[Pure]
public ImmutableArray<T> SetItem(int index, T item)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
Requires.Range(index >= 0 && index < self.Length, nameof(index));
T[] tmp = new T[self.Length];
Array.Copy(self.array, 0, tmp, 0, self.Length);
tmp[index] = item;
return new ImmutableArray<T>(tmp);
}
/// <summary>
/// Replaces the first equal element in the list with the specified element.
/// </summary>
/// <param name="oldValue">The element to replace.</param>
/// <param name="newValue">The element to replace the old element with.</param>
/// <returns>The new list -- even if the value being replaced is equal to the new value for that position.</returns>
/// <exception cref="ArgumentException">Thrown when the old value does not exist in the list.</exception>
[Pure]
public ImmutableArray<T> Replace(T oldValue, T newValue)
{
return this.Replace(oldValue, newValue, EqualityComparer<T>.Default);
}
/// <summary>
/// Replaces the first equal element in the list with the specified element.
/// </summary>
/// <param name="oldValue">The element to replace.</param>
/// <param name="newValue">The element to replace the old element with.</param>
/// <param name="equalityComparer">
/// The equality comparer to use in the search.
/// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used.
/// </param>
/// <returns>The new list -- even if the value being replaced is equal to the new value for that position.</returns>
/// <exception cref="ArgumentException">Thrown when the old value does not exist in the list.</exception>
[Pure]
public ImmutableArray<T> Replace(T oldValue, T newValue, IEqualityComparer<T> equalityComparer)
{
var self = this;
int index = self.IndexOf(oldValue, 0, self.Length, equalityComparer);
if (index < 0)
{
throw new ArgumentException(SR.CannotFindOldValue, nameof(oldValue));
}
return self.SetItem(index, newValue);
}
/// <summary>
/// Returns an array with the first occurrence of the specified element removed from the array.
/// If no match is found, the current array is returned.
/// </summary>
/// <param name="item">The item to remove.</param>
/// <returns>The new array.</returns>
[Pure]
public ImmutableArray<T> Remove(T item)
{
return this.Remove(item, EqualityComparer<T>.Default);
}
/// <summary>
/// Returns an array with the first occurrence of the specified element removed from the array.
/// If no match is found, the current array is returned.
/// </summary>
/// <param name="item">The item to remove.</param>
/// <param name="equalityComparer">
/// The equality comparer to use in the search.
/// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used.
/// </param>
/// <returns>The new array.</returns>
[Pure]
public ImmutableArray<T> Remove(T item, IEqualityComparer<T> equalityComparer)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
int index = self.IndexOf(item, 0, self.Length, equalityComparer);
return index < 0
? self
: self.RemoveAt(index);
}
/// <summary>
/// Returns an array with the element at the specified position removed.
/// </summary>
/// <param name="index">The 0-based index into the array for the element to omit from the returned array.</param>
/// <returns>The new array.</returns>
[Pure]
public ImmutableArray<T> RemoveAt(int index)
{
return this.RemoveRange(index, 1);
}
/// <summary>
/// Returns an array with the elements at the specified position removed.
/// </summary>
/// <param name="index">The 0-based index into the array for the element to omit from the returned array.</param>
/// <param name="length">The number of elements to remove.</param>
/// <returns>The new array.</returns>
[Pure]
public ImmutableArray<T> RemoveRange(int index, int length)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
Requires.Range(index >= 0 && index <= self.Length, nameof(index));
Requires.Range(length >= 0 && index + length <= self.Length, nameof(length));
if (length == 0)
{
return self;
}
T[] tmp = new T[self.Length - length];
Array.Copy(self.array, 0, tmp, 0, index);
Array.Copy(self.array, index + length, tmp, index, self.Length - index - length);
return new ImmutableArray<T>(tmp);
}
/// <summary>
/// Removes the specified values from this list.
/// </summary>
/// <param name="items">The items to remove if matches are found in this list.</param>
/// <returns>
/// A new list with the elements removed.
/// </returns>
[Pure]
public ImmutableArray<T> RemoveRange(IEnumerable<T> items)
{
return this.RemoveRange(items, EqualityComparer<T>.Default);
}
/// <summary>
/// Removes the specified values from this list.
/// </summary>
/// <param name="items">The items to remove if matches are found in this list.</param>
/// <param name="equalityComparer">
/// The equality comparer to use in the search.
/// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used.
/// </param>
/// <returns>
/// A new list with the elements removed.
/// </returns>
[Pure]
public ImmutableArray<T> RemoveRange(IEnumerable<T> items, IEqualityComparer<T> equalityComparer)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
Requires.NotNull(items, nameof(items));
var indicesToRemove = new SortedSet<int>();
foreach (var item in items)
{
int index = self.IndexOf(item, 0, self.Length, equalityComparer);
while (index >= 0 && !indicesToRemove.Add(index) && index + 1 < self.Length)
{
// This is a duplicate of one we've found. Try hard to find another instance in the list to remove.
index = self.IndexOf(item, index + 1, equalityComparer);
}
}
return self.RemoveAtRange(indicesToRemove);
}
/// <summary>
/// Removes the specified values from this list.
/// </summary>
/// <param name="items">The items to remove if matches are found in this list.</param>
/// <returns>
/// A new list with the elements removed.
/// </returns>
[Pure]
public ImmutableArray<T> RemoveRange(ImmutableArray<T> items)
{
return this.RemoveRange(items, EqualityComparer<T>.Default);
}
/// <summary>
/// Removes the specified values from this list.
/// </summary>
/// <param name="items">The items to remove if matches are found in this list.</param>
/// <param name="equalityComparer">
/// The equality comparer to use in the search.
/// </param>
/// <returns>
/// A new list with the elements removed.
/// </returns>
[Pure]
public ImmutableArray<T> RemoveRange(ImmutableArray<T> items, IEqualityComparer<T> equalityComparer)
{
var self = this;
Requires.NotNull(items.array, nameof(items));
if (items.IsEmpty)
{
self.ThrowNullRefIfNotInitialized();
return self;
}
else if (items.Length == 1)
{
return self.Remove(items[0], equalityComparer);
}
else
{
return self.RemoveRange(items.array, equalityComparer);
}
}
/// <summary>
/// Removes all the elements that match the conditions defined by the specified
/// predicate.
/// </summary>
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions of the elements
/// to remove.
/// </param>
/// <returns>
/// The new list.
/// </returns>
[Pure]
public ImmutableArray<T> RemoveAll(Predicate<T> match)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
Requires.NotNull(match, nameof(match));
if (self.IsEmpty)
{
return self;
}
List<int> removeIndices = null;
for (int i = 0; i < self.array.Length; i++)
{
if (match(self.array[i]))
{
if (removeIndices == null)
{
removeIndices = new List<int>();
}
removeIndices.Add(i);
}
}
return removeIndices != null ?
self.RemoveAtRange(removeIndices) :
self;
}
/// <summary>
/// Returns an empty array.
/// </summary>
[Pure]
public ImmutableArray<T> Clear()
{
return Empty;
}
/// <summary>
/// Returns a sorted instance of this array.
/// </summary>
[Pure]
public ImmutableArray<T> Sort()
{
var self = this;
return self.Sort(0, self.Length, Comparer<T>.Default);
}
/// <summary>
/// Sorts the elements in the entire <see cref="ImmutableArray{T}"/> using
/// the specified <see cref="Comparison{T}"/>.
/// </summary>
/// <param name="comparison">
/// The <see cref="Comparison{T}"/> to use when comparing elements.
/// </param>
/// <returns>The sorted list.</returns>
/// <exception cref="ArgumentNullException"><paramref name="comparison"/> is null.</exception>
[Pure]
public ImmutableArray<T> Sort(Comparison<T> comparison)
{
Requires.NotNull(comparison, nameof(comparison));
var self = this;
return self.Sort(Comparer<T>.Create(comparison));
}
/// <summary>
/// Returns a sorted instance of this array.
/// </summary>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
[Pure]
public ImmutableArray<T> Sort(IComparer<T> comparer)
{
var self = this;
return self.Sort(0, self.Length, comparer);
}
/// <summary>
/// Returns a sorted instance of this array.
/// </summary>
/// <param name="index">The index of the first element to consider in the sort.</param>
/// <param name="count">The number of elements to include in the sort.</param>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
[Pure]
public ImmutableArray<T> Sort(int index, int count, IComparer<T> comparer)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
Requires.Range(index >= 0, nameof(index));
Requires.Range(count >= 0 && index + count <= self.Length, nameof(count));
// 0 and 1 element arrays don't need to be sorted.
if (count > 1)
{
if (comparer == null)
{
comparer = Comparer<T>.Default;
}
// Avoid copying the entire array when the array is already sorted.
bool outOfOrder = false;
for (int i = index + 1; i < index + count; i++)
{
if (comparer.Compare(self.array[i - 1], self.array[i]) > 0)
{
outOfOrder = true;
break;
}
}
if (outOfOrder)
{
var tmp = new T[self.Length];
Array.Copy(self.array, 0, tmp, 0, self.Length);
Array.Sort(tmp, index, count, comparer);
return new ImmutableArray<T>(tmp);
}
}
return self;
}
/// <summary>
/// Filters the elements of this array to those assignable to the specified type.
/// </summary>
/// <typeparam name="TResult">The type to filter the elements of the sequence on.</typeparam>
/// <returns>
/// An <see cref="IEnumerable{T}"/> that contains elements from
/// the input sequence of type <typeparamref name="TResult"/>.
/// </returns>
[Pure]
public IEnumerable<TResult> OfType<TResult>()
{
var self = this;
if (self.array == null || self.array.Length == 0)
{
return Enumerable.Empty<TResult>();
}
return self.array.OfType<TResult>();
}
#region Explicit interface methods
[Pure]
void IList<T>.Insert(int index, T item)
{
throw new NotSupportedException();
}
[Pure]
void IList<T>.RemoveAt(int index)
{
throw new NotSupportedException();
}
[Pure]
void ICollection<T>.Add(T item)
{
throw new NotSupportedException();
}
[Pure]
void ICollection<T>.Clear()
{
throw new NotSupportedException();
}
[Pure]
bool ICollection<T>.Remove(T item)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="IImmutableList{T}"/>
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableList<T> IImmutableList<T>.Clear()
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.Clear();
}
/// <summary>
/// See <see cref="IImmutableList{T}"/>
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableList<T> IImmutableList<T>.Add(T value)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.Add(value);
}
/// <summary>
/// See <see cref="IImmutableList{T}"/>
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableList<T> IImmutableList<T>.AddRange(IEnumerable<T> items)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.AddRange(items);
}
/// <summary>
/// See <see cref="IImmutableList{T}"/>
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableList<T> IImmutableList<T>.Insert(int index, T element)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.Insert(index, element);
}
/// <summary>
/// See <see cref="IImmutableList{T}"/>
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableList<T> IImmutableList<T>.InsertRange(int index, IEnumerable<T> items)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.InsertRange(index, items);
}
/// <summary>
/// See <see cref="IImmutableList{T}"/>
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableList<T> IImmutableList<T>.Remove(T value, IEqualityComparer<T> equalityComparer)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.Remove(value, equalityComparer);
}
/// <summary>
/// See <see cref="IImmutableList{T}"/>
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableList<T> IImmutableList<T>.RemoveAll(Predicate<T> match)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.RemoveAll(match);
}
/// <summary>
/// See <see cref="IImmutableList{T}"/>
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableList<T> IImmutableList<T>.RemoveRange(IEnumerable<T> items, IEqualityComparer<T> equalityComparer)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.RemoveRange(items, equalityComparer);
}
/// <summary>
/// See <see cref="IImmutableList{T}"/>
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableList<T> IImmutableList<T>.RemoveRange(int index, int count)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.RemoveRange(index, count);
}
/// <summary>
/// See <see cref="IImmutableList{T}"/>
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableList<T> IImmutableList<T>.RemoveAt(int index)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.RemoveAt(index);
}
/// <summary>
/// See <see cref="IImmutableList{T}"/>
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableList<T> IImmutableList<T>.SetItem(int index, T value)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.SetItem(index, value);
}
/// <summary>
/// See <see cref="IImmutableList{T}"/>
/// </summary>
IImmutableList<T> IImmutableList<T>.Replace(T oldValue, T newValue, IEqualityComparer<T> equalityComparer)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.Replace(oldValue, newValue, equalityComparer);
}
/// <summary>
/// Adds an item to the <see cref="IList"/>.
/// </summary>
/// <param name="value">The object to add to the <see cref="IList"/>.</param>
/// <returns>
/// The position into which the new element was inserted, or -1 to indicate that the item was not inserted into the collection,
/// </returns>
/// <exception cref="System.NotSupportedException"></exception>
[ExcludeFromCodeCoverage]
int IList.Add(object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Removes all items from the <see cref="ICollection{T}"/>.
/// </summary>
/// <exception cref="System.NotSupportedException"></exception>
[ExcludeFromCodeCoverage]
void IList.Clear()
{
throw new NotSupportedException();
}
/// <summary>
/// Determines whether the <see cref="IList"/> contains a specific value.
/// </summary>
/// <param name="value">The object to locate in the <see cref="IList"/>.</param>
/// <returns>
/// true if the <see cref="object"/> is found in the <see cref="IList"/>; otherwise, false.
/// </returns>
[ExcludeFromCodeCoverage]
bool IList.Contains(object value)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.Contains((T)value);
}
/// <summary>
/// Determines the index of a specific item in the <see cref="IList"/>.
/// </summary>
/// <param name="value">The object to locate in the <see cref="IList"/>.</param>
/// <returns>
/// The index of <paramref name="value"/> if found in the list; otherwise, -1.
/// </returns>
[ExcludeFromCodeCoverage]
int IList.IndexOf(object value)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.IndexOf((T)value);
}
/// <summary>
/// Inserts an item to the <see cref="IList"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="value"/> should be inserted.</param>
/// <param name="value">The object to insert into the <see cref="IList"/>.</param>
/// <exception cref="System.NotSupportedException"></exception>
[ExcludeFromCodeCoverage]
void IList.Insert(int index, object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets a value indicating whether this instance is fixed size.
/// </summary>
/// <value>
/// <c>true</c> if this instance is fixed size; otherwise, <c>false</c>.
/// </value>
[ExcludeFromCodeCoverage]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool IList.IsFixedSize
{
get { return true; }
}
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value>
/// <c>true</c> if this instance is read only; otherwise, <c>false</c>.
/// </value>
[ExcludeFromCodeCoverage]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool IList.IsReadOnly
{
get { return true; }
}
/// <summary>
/// Gets the size of the array.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception>
[ExcludeFromCodeCoverage]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
int ICollection.Count
{
get
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self.Length;
}
}
/// <summary>
/// See the <see cref="ICollection"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get
{
// This is immutable, so it is always thread-safe.
return true;
}
}
/// <summary>
/// Gets the sync root.
/// </summary>
[ExcludeFromCodeCoverage]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="IList"/>.
/// </summary>
/// <param name="value">The object to remove from the <see cref="IList"/>.</param>
/// <exception cref="System.NotSupportedException"></exception>
[ExcludeFromCodeCoverage]
void IList.Remove(object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Removes the <see cref="IList{T}"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
/// <exception cref="System.NotSupportedException"></exception>
[ExcludeFromCodeCoverage]
void IList.RemoveAt(int index)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets or sets the <see cref="System.Object"/> at the specified index.
/// </summary>
/// <value>
/// The <see cref="System.Object"/>.
/// </value>
/// <param name="index">The index.</param>
/// <returns></returns>
/// <exception cref="NotSupportedException">Always thrown from the setter.</exception>
/// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception>
[ExcludeFromCodeCoverage]
object IList.this[int index]
{
get
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
return self[index];
}
set { throw new NotSupportedException(); }
}
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
[ExcludeFromCodeCoverage]
void ICollection.CopyTo(Array array, int index)
{
var self = this;
self.ThrowInvalidOperationIfNotInitialized();
Array.Copy(self.array, 0, array, index, self.Length);
}
/// <summary>
/// Determines whether an object is structurally equal to the current instance.
/// </summary>
/// <param name="other">The object to compare with the current instance.</param>
/// <param name="comparer">An object that determines whether the current instance and other are equal.</param>
/// <returns>true if the two objects are equal; otherwise, false.</returns>
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
var self = this;
Array otherArray = other as Array;
if (otherArray == null)
{
var theirs = other as IImmutableArray;
if (theirs != null)
{
otherArray = theirs.Array;
if (self.array == null && otherArray == null)
{
return true;
}
else if (self.array == null)
{
return false;
}
}
}
IStructuralEquatable ours = self.array;
return ours.Equals(otherArray, comparer);
}
/// <summary>
/// Returns a hash code for the current instance.
/// </summary>
/// <param name="comparer">An object that computes the hash code of the current object.</param>
/// <returns>The hash code for the current instance.</returns>
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
var self = this;
IStructuralEquatable ours = self.array;
return ours != null ? ours.GetHashCode(comparer) : self.GetHashCode();
}
/// <summary>
/// Determines whether the current collection object precedes, occurs in the
/// same position as, or follows another object in the sort order.
/// </summary>
/// <param name="other">The object to compare with the current instance.</param>
/// <param name="comparer">
/// An object that compares members of the current collection object with the
/// corresponding members of other.
/// </param>
/// <returns>
/// An integer that indicates the relationship of the current collection object
/// to other.
/// </returns>
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
var self = this;
Array otherArray = other as Array;
if (otherArray == null)
{
var theirs = other as IImmutableArray;
if (theirs != null)
{
otherArray = theirs.Array;
if (self.array == null && otherArray == null)
{
return 0;
}
else if (self.array == null ^ otherArray == null)
{
throw new ArgumentException(SR.ArrayInitializedStateNotEqual, nameof(other));
}
}
}
if (otherArray != null)
{
IStructuralComparable ours = self.array;
return ours.CompareTo(otherArray, comparer);
}
throw new ArgumentException(SR.ArrayLengthsNotEqual, nameof(other));
}
#endregion
/// <summary>
/// Returns an array with items at the specified indices removed.
/// </summary>
/// <param name="indicesToRemove">A **sorted set** of indices to elements that should be omitted from the returned array.</param>
/// <returns>The new array.</returns>
private ImmutableArray<T> RemoveAtRange(ICollection<int> indicesToRemove)
{
var self = this;
self.ThrowNullRefIfNotInitialized();
Requires.NotNull(indicesToRemove, nameof(indicesToRemove));
if (indicesToRemove.Count == 0)
{
// Be sure to return a !IsDefault instance.
return self;
}
var newArray = new T[self.Length - indicesToRemove.Count];
int copied = 0;
int removed = 0;
int lastIndexRemoved = -1;
foreach (var indexToRemove in indicesToRemove)
{
int copyLength = lastIndexRemoved == -1 ? indexToRemove : (indexToRemove - lastIndexRemoved - 1);
Debug.Assert(indexToRemove > lastIndexRemoved); // We require that the input be a sorted set.
Array.Copy(self.array, copied + removed, newArray, copied, copyLength);
removed++;
copied += copyLength;
lastIndexRemoved = indexToRemove;
}
Array.Copy(self.array, copied + removed, newArray, copied, self.Length - (copied + removed));
return new ImmutableArray<T>(newArray);
}
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEditor;
//using System;
using System.Collections.Generic;
using System.Linq;
namespace Sabresaurus.SabreCSG
{
[CanEditMultipleObjects]
[CustomEditor(typeof(PrimitiveBrush))]
public class PrimitiveBrushInspector : Editor
{
string rescaleString = "1";
string resizeString = "1";
Mesh sourceMesh = null;
SerializedProperty prismSideCountProp;
SerializedProperty cylinderSideCountProp;
SerializedProperty sphereSideCountProp;
PrimitiveBrushType? overridenBrushType = null;
void OnEnable ()
{
// Setup the SerializedProperties.
prismSideCountProp = serializedObject.FindProperty ("prismSideCount");
cylinderSideCountProp = serializedObject.FindProperty ("cylinderSideCount");
sphereSideCountProp = serializedObject.FindProperty ("sphereSideCount");
}
PrimitiveBrush BrushTarget
{
get
{
return (PrimitiveBrush)target;
}
}
PrimitiveBrush[] BrushTargets
{
get
{
return System.Array.ConvertAll(targets, item => (PrimitiveBrush)item);
}
}
public void DrawBrushTypeField()
{
GUILayout.BeginHorizontal();
PrimitiveBrushType[] selectedTypes = BrushTargets.Select(item => item.BrushType).ToArray();
if(overridenBrushType.HasValue)
{
selectedTypes = new PrimitiveBrushType[] { overridenBrushType.Value };
}
PrimitiveBrushType? newType = SabreGUILayout.EnumPopupMixed("Brush Type", selectedTypes);
if(newType.HasValue)
{
overridenBrushType = newType;
if(newType.Value == PrimitiveBrushType.Prism)
{
GUILayout.Label("Sides", SabreGUILayout.GetForeStyle(), GUILayout.Width(30));
EditorGUILayout.PropertyField(prismSideCountProp, new GUIContent(""));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
}
else if(newType.Value == PrimitiveBrushType.Cylinder)
{
GUILayout.Label("Sides", SabreGUILayout.GetForeStyle(), GUILayout.Width(30));
EditorGUILayout.PropertyField(cylinderSideCountProp, new GUIContent(""));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
}
else if(newType.Value == PrimitiveBrushType.Sphere)
{
GUILayout.Label("Sides", SabreGUILayout.GetForeStyle(), GUILayout.Width(30));
EditorGUILayout.PropertyField(sphereSideCountProp, new GUIContent(""));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
}
}
if (GUILayout.Button("Reset Polygons"))
{
Undo.RecordObjects(targets, "Reset Polygons");
foreach (var thisBrush in targets)
{
if(overridenBrushType.HasValue)
{
((PrimitiveBrush)thisBrush).BrushType = overridenBrushType.Value;
}
((PrimitiveBrush)thisBrush).ResetPolygons();
((PrimitiveBrush)thisBrush).Invalidate(true);
}
overridenBrushType = null;
}
GUILayout.EndHorizontal();
if (GUILayout.Button("Shell"))
{
List<GameObject> newSelection = new List<GameObject>();
foreach (var thisBrush in targets)
{
GameObject newObject = ((PrimitiveBrush)thisBrush).Duplicate();
Polygon[] polygons = newObject.GetComponent<PrimitiveBrush>().GetPolygons();
VertexUtility.DisplacePolygons(polygons, -CurrentSettings.PositionSnapDistance);
Bounds newBounds = newObject.GetComponent<PrimitiveBrush>().GetBounds();
// Verify the new geometry
if(GeometryHelper.IsBrushConvex(polygons)
&& newBounds.GetSmallestExtent() > 0)
{
Undo.RegisterCreatedObjectUndo(newObject, "Shell");
newSelection.Add(newObject);
}
else
{
// Produced a concave brush, delete it and pretend nothing happened
GameObject.DestroyImmediate(newObject);
Debug.LogWarning("Could not shell " + thisBrush.name + " as shelled geometry would not be valid. Try lowering Pos Snapping and attempt Shell again.");
}
}
if(newSelection.Count > 0)
{
Selection.objects = newSelection.ToArray();
}
}
}
public override void OnInspectorGUI()
{
// DrawDefaultInspector();
DrawBrushTypeField();
// BrushOrder brushOrder = BrushTarget.GetBrushOrder();
// string positionString = string.Join(",", brushOrder.Position.Select(item => item.ToString()).ToArray());
// GUILayout.Label(positionString, EditorStyles.boldLabel);
// List<BrushCache> intersections = BrushTarget.BrushCache.IntersectingVisualBrushCaches;
//
// for (int i = 0; i < intersections.Count; i++)
// {
// GUILayout.Label(intersections[i].Mode.ToString(), EditorStyles.boldLabel);
// }
GUILayout.BeginHorizontal();
GUI.SetNextControlName("rescaleTextbox");
rescaleString = EditorGUILayout.TextField(rescaleString);
bool keyboardEnter = Event.current.isKey
&& Event.current.keyCode == KeyCode.Return
&& Event.current.type == EventType.KeyUp
&& GUI.GetNameOfFocusedControl() == "rescaleTextbox";
if(GUILayout.Button("Rescale") || keyboardEnter)
{
// Try to parse a Vector3 scale from the input string
Vector3 rescaleVector3;
if(StringHelper.TryParseScale(rescaleString, out rescaleVector3))
{
// None of the scale components can be zero
if(rescaleVector3.x != 0 && rescaleVector3.y != 0 && rescaleVector3.z != 0)
{
// Rescale all the brushes
Undo.RecordObjects(targets, "Rescale Polygons");
foreach (var thisBrush in targets)
{
BrushUtility.Rescale((PrimitiveBrush)thisBrush, rescaleVector3);
}
}
}
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUI.SetNextControlName("resizeTextbox");
resizeString = EditorGUILayout.TextField(resizeString);
keyboardEnter = Event.current.isKey
&& Event.current.keyCode == KeyCode.Return
&& Event.current.type == EventType.KeyUp
&& GUI.GetNameOfFocusedControl() == "resizeTextbox";
if(GUILayout.Button("Resize") || keyboardEnter)
{
// Try to parse a Vector3 scale from the input string
Vector3 resizeVector3;
if(StringHelper.TryParseScale(resizeString, out resizeVector3))
{
// None of the size components can be zero
if(resizeVector3.x != 0 && resizeVector3.y != 0 && resizeVector3.z != 0)
{
// Rescale all the brushes so that the local bounds is the same size as the resize vector
Undo.RecordObjects(targets, "Resize Polygons");
PrimitiveBrush[] brushes = BrushTargets;
foreach (PrimitiveBrush brush in brushes)
{
BrushUtility.Resize(brush, resizeVector3);
}
}
}
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
sourceMesh = EditorGUILayout.ObjectField(sourceMesh, typeof(Mesh), false) as Mesh;
if (GUILayout.Button("Import"))
{
if(sourceMesh != null)
{
Undo.RecordObjects(targets, "Import Polygons From Mesh");
Polygon[] polygons = BrushFactory.GeneratePolygonsFromMesh(sourceMesh).ToArray();
bool convex = GeometryHelper.IsBrushConvex(polygons);
if(!convex)
{
Debug.LogError("Concavities detected in imported mesh. This may result in issues during CSG, please change the source geometry so that it is convex");
}
foreach (var thisBrush in targets)
{
((PrimitiveBrush)thisBrush).SetPolygons(polygons, true);
}
}
}
GUILayout.EndHorizontal();
List<PrimitiveBrush> orderedTargets = BrushTargets.ToList();
orderedTargets.Sort((x,y) => x.transform.GetSiblingIndex().CompareTo(y.transform.GetSiblingIndex()));
if (GUILayout.Button("Set As First"))
{
for (int i = 0; i < orderedTargets.Count; i++)
{
// REVERSED
PrimitiveBrush thisBrush = orderedTargets[orderedTargets.Count-1-i];
Undo.SetTransformParent(thisBrush.transform, thisBrush.transform.parent, "Change Order");
thisBrush.transform.SetAsFirstSibling();
}
// Force all the brushes to recalculate their intersections and get ready for rebuilding
for (int i = 0; i < orderedTargets.Count; i++)
{
orderedTargets[i].RecalculateIntersections();
orderedTargets[i].BrushCache.SetUnbuilt();
}
}
if (GUILayout.Button("Send Earlier"))
{
for (int i = 0; i < orderedTargets.Count; i++)
{
PrimitiveBrush thisBrush = orderedTargets[i];
int siblingIndex = thisBrush.transform.GetSiblingIndex();
if(siblingIndex > 0)
{
Undo.SetTransformParent(thisBrush.transform, thisBrush.transform.parent, "Change Order");
siblingIndex--;
thisBrush.transform.SetSiblingIndex(siblingIndex);
}
}
// Force all the brushes to recalculate their intersections and get ready for rebuilding
for (int i = 0; i < orderedTargets.Count; i++)
{
orderedTargets[i].RecalculateIntersections();
orderedTargets[i].BrushCache.SetUnbuilt();
}
}
if (GUILayout.Button("Send Later"))
{
for (int i = 0; i < orderedTargets.Count; i++)
{
// REVERSED
PrimitiveBrush thisBrush = orderedTargets[orderedTargets.Count-1-i];
int siblingIndex = thisBrush.transform.GetSiblingIndex();
Undo.SetTransformParent(thisBrush.transform, thisBrush.transform.parent, "Change Order");
siblingIndex++;
thisBrush.transform.SetSiblingIndex(siblingIndex);
}
// Force all the brushes to recalculate their intersections and get ready for rebuilding
for (int i = 0; i < orderedTargets.Count; i++)
{
orderedTargets[i].RecalculateIntersections();
orderedTargets[i].BrushCache.SetUnbuilt();
}
}
if (GUILayout.Button("Set As Last"))
{
for (int i = 0; i < orderedTargets.Count; i++)
{
PrimitiveBrush thisBrush = orderedTargets[i];
Undo.SetTransformParent(thisBrush.transform, thisBrush.transform.parent, "Change Order");
thisBrush.transform.SetAsLastSibling();
}
// Force all the brushes to recalculate their intersections and get ready for rebuilding
for (int i = 0; i < orderedTargets.Count; i++)
{
orderedTargets[i].RecalculateIntersections();
orderedTargets[i].BrushCache.SetUnbuilt();
}
}
serializedObject.ApplyModifiedProperties ();
// GUILayout.Label("UVs", EditorStyles.boldLabel);
//
// if (GUILayout.Button("Flip XY"))
// {
// UVUtility.FlipUVsXY(thisBrush.Polygons);
// }
//
// GUILayout.BeginHorizontal();
// if (GUILayout.Button("Flip X"))
// {
// UVUtility.FlipUVsX(thisBrush.Polygons);
// }
// if (GUILayout.Button("Flip Y"))
// {
// UVUtility.FlipUVsY(thisBrush.Polygons);
// }
// GUILayout.EndHorizontal();
//
// GUILayout.BeginHorizontal();
// if (GUILayout.Button("UVs x 2"))
// {
// UVUtility.ScaleUVs(thisBrush.Polygons, 2f);
// }
// if (GUILayout.Button("UVs / 2"))
// {
// UVUtility.ScaleUVs(thisBrush.Polygons, .5f);
// }
// GUILayout.EndHorizontal();
// Ensure Edit Mode is on
// csgModel.EditMode = true;
}
}
}
| |
//#define DEBUG
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ICSimulator
{
public struct Coord
{
public int x;
public int y;
public int ID; // identifier of the node.
public Coord(int x, int y)
{
this.x = x;
this.y = y;
ID = getIDfromXY(x, y);
}
public Coord(int ID)
{
this.ID = ID;
getXYfromID(ID, out x, out y);
}
public override bool Equals(object obj)
{
return (obj is Coord) && ((Coord)obj).x == x && ((Coord)obj).y == y;
}
public override int GetHashCode()
{
return ID.GetHashCode(); // x.GetHashCode() ^ y.GetHashCode();
}
public override string ToString()
{
return "(" + x + "," + y + ")";
}
public static int getIDfromXY(int x, int y)
{
return x * Config.network_nrY + y;
}
public static void getXYfromID(int id, out int x, out int y)
{
x = id / Config.network_nrY;
y = id % Config.network_nrY;
}
}
public struct RC_Coord
{
public int x;
public int y; // x, y: coord of the ring
public int z; // z : coord within a ring
public int ID; // identifier of the node.
public RC_Coord(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
ID = getIDfromXYZ(x, y, z);
}
public RC_Coord(int ID)
{
this.ID = ID;
getXYZfromID(ID, out x, out y, out z);
}
public override bool Equals(object obj)
{
return (obj is RC_Coord) && ((RC_Coord)obj).x == x && ((RC_Coord)obj).y == y && ((RC_Coord)obj).z == z;
}
public override int GetHashCode()
{
return ID.GetHashCode(); // x.GetHashCode() ^ y.GetHashCode();
}
public override string ToString()
{
return "(" + x + "," + y + "," + z + ")";
}
public static int getIDfromXYZ(int x, int y, int z)
{
return z + x * Config.network_nrY * 2 + 4 * y;
}
public static void getXYZfromID(int id, out int x, out int y, out int z)
{
z = id % 4;
x = id / (Config.network_nrY * 2);
y = id % (Config.network_nrY * 2) / 4;
}
}
public class Packet
{
public delegate void Sender(Packet p);
private static ulong nrPackets = 0;
public Coord src { get { return _src; } }
private Coord _src;
public Coord dest { get { return _dest; } }
private Coord _dest;
public ulong ID { get { return _ID; } }
private ulong _ID;
public Request request { get { return _request; } }
private Request _request;
public int requesterID;
public ulong seq;
public int pktParity; // 0:clockwise 1:counter clockwise -1:dont care
public bool flow_open; // grab slot; queue, bounce for retx if none avail
public bool flow_close; // release slot
public int retx_count;
// N.B.:
// block number may be different than that in the request: as with
// CachePacket above, a request is associated with a packet because
// that packet is due to the request, but the packet may not be[4]
// delivering data for that request (e.g., it may be a writeback)
public ulong block { get { return _block; } }
private ulong _block;
public ulong creationTime;
public ulong injectionTime;
public Flit[] flits;
public int nrOfFlits; // { get { return flits.Length; } }
public int nrOfArrivedFlits = 0;
//TODO: move these into router-policy aware structures
#region TO_BE_ISOLATED
public int MIN_AD_dir;
public ulong staticPriority; //summary> Static portion of prioritization. </summary>
public ulong batchID;
#endregion
// SCARAB
public int scarab_retransmit_count;
public Packet scarab_retransmit;
public bool scarab_is_nack, scarab_is_teardown;
public Packet(Request request, ulong block, int nrOfFlits, Coord source, Coord dest)
{
_request = request;
if (_request != null)
_request.beenToNetwork = true;
_block = block; // may not come from request (see above)
_src = source;
_dest = dest;
if (request != null)
request.setCarrier(this);
requesterID = -1;
initialize(Simulator.CurrentRound, nrOfFlits);
}
/**
* Always call this initialization method before using a packet. All flits are also appropriately initialized
*/
public void initialize(ulong creationTime, int nrOfFlits)
{
_ID = Packet.nrPackets;
Packet.nrPackets++;
batchID = (Simulator.CurrentRound / Config.STC_batchPeriod) % Config.STC_batchCount;
this.nrOfFlits = nrOfFlits;
flits = new Flit[nrOfFlits];
for (int i = 0; i < nrOfFlits; i++)
flits[i] = new Flit(this, i);
flits[0].isHeadFlit = true;
for (int i = 1; i < nrOfFlits; i++)
flits[i].isHeadFlit = false;
this.creationTime = creationTime;
injectionTime = ulong.MaxValue;
nrOfArrivedFlits = 0;
for (int i = 0; i < nrOfFlits; i++)
{
flits[i].hasFlitArrived = false;
flits[i].nrOfDeflections = 0;
}
/* This is needed for wormhole routing in bidirectional ring.
* Body flits have to take the same ring as the head.
*/
pktParity = -1;
for (int i = 0; i < nrOfFlits; i++)
{
flits[i].isTailFlit = false;
flits[i].isHeadFlit = false;
}
flits[0].isHeadFlit = true;
flits[nrOfFlits - 1].isTailFlit = true;
flow_open = false;
flow_close = false;
retx_count = 0;
scarab_retransmit_count = 0;
scarab_retransmit = null;
scarab_is_nack = false;
scarab_is_teardown = false;
}
public void setRequest(Request req)
{
_request = req;
req.setCarrier(this);
}
public static int numQueues
{
get
{
if (Config.split_queues)
return 3; // control, data response, WB (off critical path)
else
return 1;
}
}
public virtual int getQueue()
{
return 0; // should be overridden
}
public virtual int getClass()
{
return 0; // should be overridden
}
}
public class Flit
{
public Packet packet;
public int flitNr;
public bool hasFlitArrived;
public bool isHeadFlit;
public bool isTailFlit;
public ulong nrOfDeflections;
public int virtualChannel; // to which virtual channel the packet should go in the next router.
public bool sortnet_winner;
public int currentX;
public int currentY;
public bool Deflected;
public bool routingOrder; //if (false): x direction prioritized over y
public ulong injectionTime; // absolute injection timestamp
public ulong headT; // reaches-head-of-queue timestamp
public int nackWire; // nack wire nr. for last hop
public int inDir;
public int prefDir;
public int parity; // 0:clockwise 1:counter clockwise -1:dont care
public enum State { Normal, Placeholder, Rescuer, Carrier }
public State state;
public Coord rescuerCoord;
//for stats: how many useless cycles the flit is comsuming
public ulong timeIntoTheBuffer;
public ulong timeSpentInBuffer = 0;
public ulong timeWaitToInject = 0;
public ulong timeInTheSourceRing = 0;
public ulong timeInTheTransitionRing = 0;
public ulong timeInTheDestRing = 0;
public ulong timeInGR = 0;
public ulong enterBuffer = 0;
public ulong ejectTrial = 0;
public ulong firstEjectTrial = 0;
public BufRingMultiNetwork_Coord bufrings_coord;
public Coord dest
{
get
{
switch (state)
{
case State.Normal: return packet.dest;
case State.Carrier: return packet.dest;
case State.Rescuer: return rescuerCoord;
case State.Placeholder: return new Coord(0);
}
throw new Exception("Unknown flit state");
}
}
public ulong distance;
//private bool[] deflections;
//private int deflectionsIndex;
public Flit(Packet packet, int flitNr)
{
this.packet = packet;
this.flitNr = flitNr;
hasFlitArrived = false;
this.Deflected = false;
//deflections = new bool[100];
//deflectionsIndex = 0;
if (packet != null)
distance = Simulator.distance(packet.src, packet.dest);
this.routingOrder = false;
if (packet == null) return;
int srcX = packet.src.ID / Config.network_nrY / 2;
int destX = packet.dest.ID / Config.network_nrY / 2;
if (Config.AllBiDirLink || Config.HR_NoBias || Config.topology != Topology.Mesh)
parity = -1;
if (Config.topology == Topology.MeshOfRings && Config.RC_mesh == true)
{
if (srcX == destX)
parity = -1;
else if (destX > srcX)
parity = 0;
else // destX < srcX
parity = 1;
}
if (Config.SingleDirRing)
parity = 0;
/*if ((srcCluster == 0 || srcCluster == 3) &&
(destCluster == 1 || destCluster == 2))
Simulator.stats.flitToUpper.Add();
else if ((srcCluster == 1 || srcCluster == 2) &&
(destCluster == 0 || destCluster == 3))
Simulator.stats.flitToLower.Add();*/
}
/*
public void deflectTest()
{
if (deflectionsIndex == 100)
return;
//Console.WriteLine("{0} {1}", Deflected, deflectionsIndex);
deflections[deflectionsIndex] = this.Deflected;
//Console.WriteLine("{0} {1}", deflections[deflectionsIndex], deflectionsIndex);
deflectionsIndex++;
}
public void dumpDeflections()
{
for (int i = 0; i < deflectionsIndex; i++)
Console.Write(deflections[i] ? "D" : "-");
Console.WriteLine();
}*/
public delegate void Visitor(Flit f);
public override string ToString()
{
if (packet != null)
return String.Format("Flit {0} of packet {1} (state {2})", flitNr, packet, state);
else
return String.Format("Flit {0} of packet <NONE> (state {1})", flitNr, state);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
namespace Amib.Threading
{
public interface ISTPPerformanceCountersReader
{
long InUseThreads { get; }
long ActiveThreads { get; }
long WorkItemsQueued { get; }
long WorkItemsProcessed { get; }
}
}
namespace Amib.Threading.Internal
{
internal interface ISTPInstancePerformanceCounters : IDisposable
{
void Close();
void SampleThreads(long activeThreads, long inUseThreads);
void SampleWorkItems(long workItemsQueued, long workItemsProcessed);
void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime);
void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime);
}
#if !(_WINDOWS_CE) && !(_SILVERLIGHT)
internal enum STPPerformanceCounterType
{
// Fields
ActiveThreads = 0,
InUseThreads = 1,
OverheadThreads = 2,
OverheadThreadsPercent = 3,
OverheadThreadsPercentBase = 4,
WorkItems = 5,
WorkItemsInQueue = 6,
WorkItemsProcessed = 7,
WorkItemsQueuedPerSecond = 8,
WorkItemsProcessedPerSecond = 9,
AvgWorkItemWaitTime = 10,
AvgWorkItemWaitTimeBase = 11,
AvgWorkItemProcessTime = 12,
AvgWorkItemProcessTimeBase = 13,
WorkItemsGroups = 14,
LastCounter = 14,
}
/// <summary>
/// Summary description for STPPerformanceCounter.
/// </summary>
internal class STPPerformanceCounter
{
// Fields
private readonly PerformanceCounterType _pcType;
protected string _counterHelp;
protected string _counterName;
// Methods
public STPPerformanceCounter(
string counterName,
string counterHelp,
PerformanceCounterType pcType)
{
_counterName = counterName;
_counterHelp = counterHelp;
_pcType = pcType;
}
public void AddCounterToCollection(CounterCreationDataCollection counterData)
{
CounterCreationData counterCreationData = new CounterCreationData(
_counterName,
_counterHelp,
_pcType);
counterData.Add(counterCreationData);
}
// Properties
public string Name
{
get
{
return _counterName;
}
}
}
internal class STPPerformanceCounters
{
// Fields
internal STPPerformanceCounter[] _stpPerformanceCounters;
private static readonly STPPerformanceCounters _instance;
internal const string _stpCategoryHelp = "SmartThreadPool performance counters";
internal const string _stpCategoryName = "SmartThreadPool";
// Methods
static STPPerformanceCounters()
{
_instance = new STPPerformanceCounters();
}
private STPPerformanceCounters()
{
STPPerformanceCounter[] stpPerformanceCounters = new STPPerformanceCounter[]
{
new STPPerformanceCounter("Active threads", "The current number of available in the thread pool.", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("In use threads", "The current number of threads that execute a work item.", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("Overhead threads", "The current number of threads that are active, but are not in use.", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("% overhead threads", "The current number of threads that are active, but are not in use in percents.", PerformanceCounterType.RawFraction),
new STPPerformanceCounter("% overhead threads base", "The current number of threads that are active, but are not in use in percents.", PerformanceCounterType.RawBase),
new STPPerformanceCounter("Work Items", "The number of work items in the Smart Thread Pool. Both queued and processed.", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("Work Items in queue", "The current number of work items in the queue", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("Work Items processed", "The number of work items already processed", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("Work Items queued/sec", "The number of work items queued per second", PerformanceCounterType.RateOfCountsPerSecond32),
new STPPerformanceCounter("Work Items processed/sec", "The number of work items processed per second", PerformanceCounterType.RateOfCountsPerSecond32),
new STPPerformanceCounter("Avg. Work Item wait time/sec", "The average time a work item supends in the queue waiting for its turn to execute.", PerformanceCounterType.AverageCount64),
new STPPerformanceCounter("Avg. Work Item wait time base", "The average time a work item supends in the queue waiting for its turn to execute.", PerformanceCounterType.AverageBase),
new STPPerformanceCounter("Avg. Work Item process time/sec", "The average time it takes to process a work item.", PerformanceCounterType.AverageCount64),
new STPPerformanceCounter("Avg. Work Item process time base", "The average time it takes to process a work item.", PerformanceCounterType.AverageBase),
new STPPerformanceCounter("Work Items Groups", "The current number of work item groups associated with the Smart Thread Pool.", PerformanceCounterType.NumberOfItems32),
};
_stpPerformanceCounters = stpPerformanceCounters;
SetupCategory();
}
private void SetupCategory()
{
if (!PerformanceCounterCategory.Exists(_stpCategoryName))
{
CounterCreationDataCollection counters = new CounterCreationDataCollection();
for (int i = 0; i < _stpPerformanceCounters.Length; i++)
{
_stpPerformanceCounters[i].AddCounterToCollection(counters);
}
PerformanceCounterCategory.Create(
_stpCategoryName,
_stpCategoryHelp,
PerformanceCounterCategoryType.MultiInstance,
counters);
}
}
// Properties
public static STPPerformanceCounters Instance
{
get
{
return _instance;
}
}
}
internal class STPInstancePerformanceCounter : IDisposable
{
// Fields
private bool _isDisposed;
private PerformanceCounter _pcs;
// Methods
protected STPInstancePerformanceCounter()
{
_isDisposed = false;
}
public STPInstancePerformanceCounter(
string instance,
STPPerformanceCounterType spcType) : this()
{
STPPerformanceCounters counters = STPPerformanceCounters.Instance;
_pcs = new PerformanceCounter(
STPPerformanceCounters._stpCategoryName,
counters._stpPerformanceCounters[(int) spcType].Name,
instance,
false);
_pcs.RawValue = _pcs.RawValue;
}
public void Close()
{
if (_pcs != null)
{
_pcs.RemoveInstance();
_pcs.Close();
_pcs = null;
}
}
public void Dispose()
{
Dispose(true);
}
public virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
Close();
}
}
_isDisposed = true;
}
public virtual void Increment()
{
_pcs.Increment();
}
public virtual void IncrementBy(long val)
{
_pcs.IncrementBy(val);
}
public virtual void Set(long val)
{
_pcs.RawValue = val;
}
}
internal class STPInstanceNullPerformanceCounter : STPInstancePerformanceCounter
{
// Methods
public override void Increment() {}
public override void IncrementBy(long value) {}
public override void Set(long val) {}
}
internal class STPInstancePerformanceCounters : ISTPInstancePerformanceCounters
{
private bool _isDisposed;
// Fields
private STPInstancePerformanceCounter[] _pcs;
private static readonly STPInstancePerformanceCounter _stpInstanceNullPerformanceCounter;
// Methods
static STPInstancePerformanceCounters()
{
_stpInstanceNullPerformanceCounter = new STPInstanceNullPerformanceCounter();
}
public STPInstancePerformanceCounters(string instance)
{
_isDisposed = false;
_pcs = new STPInstancePerformanceCounter[(int)STPPerformanceCounterType.LastCounter];
// Call the STPPerformanceCounters.Instance so the static constructor will
// intialize the STPPerformanceCounters singleton.
STPPerformanceCounters.Instance.GetHashCode();
for (int i = 0; i < _pcs.Length; i++)
{
if (instance != null)
{
_pcs[i] = new STPInstancePerformanceCounter(
instance,
(STPPerformanceCounterType) i);
}
else
{
_pcs[i] = _stpInstanceNullPerformanceCounter;
}
}
}
public void Close()
{
if (null != _pcs)
{
for (int i = 0; i < _pcs.Length; i++)
{
if (null != _pcs[i])
{
_pcs[i].Dispose();
}
}
_pcs = null;
}
}
public void Dispose()
{
Dispose(true);
}
public virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
Close();
}
}
_isDisposed = true;
}
private STPInstancePerformanceCounter GetCounter(STPPerformanceCounterType spcType)
{
return _pcs[(int) spcType];
}
public void SampleThreads(long activeThreads, long inUseThreads)
{
GetCounter(STPPerformanceCounterType.ActiveThreads).Set(activeThreads);
GetCounter(STPPerformanceCounterType.InUseThreads).Set(inUseThreads);
GetCounter(STPPerformanceCounterType.OverheadThreads).Set(activeThreads-inUseThreads);
GetCounter(STPPerformanceCounterType.OverheadThreadsPercentBase).Set(activeThreads-inUseThreads);
GetCounter(STPPerformanceCounterType.OverheadThreadsPercent).Set(inUseThreads);
}
public void SampleWorkItems(long workItemsQueued, long workItemsProcessed)
{
GetCounter(STPPerformanceCounterType.WorkItems).Set(workItemsQueued+workItemsProcessed);
GetCounter(STPPerformanceCounterType.WorkItemsInQueue).Set(workItemsQueued);
GetCounter(STPPerformanceCounterType.WorkItemsProcessed).Set(workItemsProcessed);
GetCounter(STPPerformanceCounterType.WorkItemsQueuedPerSecond).Set(workItemsQueued);
GetCounter(STPPerformanceCounterType.WorkItemsProcessedPerSecond).Set(workItemsProcessed);
}
public void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime)
{
GetCounter(STPPerformanceCounterType.AvgWorkItemWaitTime).IncrementBy((long)workItemWaitTime.TotalMilliseconds);
GetCounter(STPPerformanceCounterType.AvgWorkItemWaitTimeBase).Increment();
}
public void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime)
{
GetCounter(STPPerformanceCounterType.AvgWorkItemProcessTime).IncrementBy((long)workItemProcessTime.TotalMilliseconds);
GetCounter(STPPerformanceCounterType.AvgWorkItemProcessTimeBase).Increment();
}
}
#endif
internal class NullSTPInstancePerformanceCounters : ISTPInstancePerformanceCounters, ISTPPerformanceCountersReader
{
private static readonly NullSTPInstancePerformanceCounters _instance = new NullSTPInstancePerformanceCounters();
public static NullSTPInstancePerformanceCounters Instance
{
get { return _instance; }
}
public void Close() {}
public void Dispose() {}
public void SampleThreads(long activeThreads, long inUseThreads) {}
public void SampleWorkItems(long workItemsQueued, long workItemsProcessed) {}
public void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime) {}
public void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime) {}
public long InUseThreads
{
get { return 0; }
}
public long ActiveThreads
{
get { return 0; }
}
public long WorkItemsQueued
{
get { return 0; }
}
public long WorkItemsProcessed
{
get { return 0; }
}
}
internal class LocalSTPInstancePerformanceCounters : ISTPInstancePerformanceCounters, ISTPPerformanceCountersReader
{
public void Close() { }
public void Dispose() { }
private long _activeThreads;
private long _inUseThreads;
private long _workItemsQueued;
private long _workItemsProcessed;
public long InUseThreads
{
get { return _inUseThreads; }
}
public long ActiveThreads
{
get { return _activeThreads; }
}
public long WorkItemsQueued
{
get { return _workItemsQueued; }
}
public long WorkItemsProcessed
{
get { return _workItemsProcessed; }
}
public void SampleThreads(long activeThreads, long inUseThreads)
{
_activeThreads = activeThreads;
_inUseThreads = inUseThreads;
}
public void SampleWorkItems(long workItemsQueued, long workItemsProcessed)
{
_workItemsQueued = workItemsQueued;
_workItemsProcessed = workItemsProcessed;
}
public void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime)
{
// Not supported
}
public void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime)
{
// Not supported
}
}
}
| |
using System;
using log4net;
using log4net.Core;
namespace NMaier.SimpleDlna.Utilities
{
public class Logging : ILog
{
private ILog instance;
private ILog logger
{
get
{
if (instance == null) {
instance = LogManager.GetLogger(GetType());
}
return instance;
}
}
public bool IsDebugEnabled
{
get
{
return logger.IsDebugEnabled;
}
}
public bool IsErrorEnabled
{
get
{
return logger.IsErrorEnabled;
}
}
public bool IsFatalEnabled
{
get
{
return logger.IsFatalEnabled;
}
}
public bool IsInfoEnabled
{
get
{
return logger.IsInfoEnabled;
}
}
public bool IsNoticeEnabled
{
get
{
return Logger.IsEnabledFor(Level.Notice);
}
}
public bool IsWarnEnabled
{
get
{
return logger.IsWarnEnabled;
}
}
public ILogger Logger
{
get
{
return logger.Logger;
}
}
public void Debug(object message)
{
logger.Debug(message);
}
public void Debug(object message, Exception exception)
{
logger.Debug(message, exception);
}
public void DebugFormat(string format, params object[] args)
{
logger.DebugFormat(format, args);
}
public void DebugFormat(string format, object arg0)
{
logger.DebugFormat(format, arg0);
}
public void DebugFormat(string format, object arg0, object arg1)
{
logger.DebugFormat(format, arg0, arg1);
}
public void DebugFormat(IFormatProvider provider, string format, params object[] args)
{
logger.DebugFormat(provider, format, args);
}
public void DebugFormat(string format, object arg0, object arg1, object arg2)
{
logger.DebugFormat(format, arg0, arg1, arg2);
}
public void Error(object message)
{
logger.Error(message);
}
public void Error(object message, Exception exception)
{
logger.Error(message, exception);
}
public void ErrorFormat(string format, params object[] args)
{
logger.ErrorFormat(format, args);
}
public void ErrorFormat(string format, object arg0)
{
logger.ErrorFormat(format, arg0);
}
public void ErrorFormat(string format, object arg0, object arg1)
{
logger.ErrorFormat(format, arg0, arg1);
}
public void ErrorFormat(IFormatProvider provider, string format, params object[] args)
{
logger.ErrorFormat(provider, format, args);
}
public void ErrorFormat(string format, object arg0, object arg1, object arg2)
{
logger.ErrorFormat(format, arg0, arg1, arg2);
}
public void Fatal(object message)
{
logger.Fatal(message);
}
public void Fatal(object message, Exception exception)
{
logger.Fatal(message, exception);
}
public void FatalFormat(string format, params object[] args)
{
logger.FatalFormat(format, args);
}
public void FatalFormat(string format, object arg0)
{
logger.FatalFormat(format, arg0);
}
public void FatalFormat(string format, object arg0, object arg1)
{
logger.FatalFormat(format, arg0, arg1);
}
public void FatalFormat(IFormatProvider provider, string format, params object[] args)
{
logger.FatalFormat(provider, format, args);
}
public void FatalFormat(string format, object arg0, object arg1, object arg2)
{
logger.FatalFormat(format, arg0, arg1, arg2);
}
public void Info(object message)
{
logger.Info(message);
}
public void Info(object message, Exception exception)
{
logger.Info(message, exception);
}
public void InfoFormat(string format, params object[] args)
{
logger.InfoFormat(format, args);
}
public void InfoFormat(string format, object arg0)
{
logger.InfoFormat(format, arg0);
}
public void InfoFormat(string format, object arg0, object arg1)
{
logger.InfoFormat(format, arg0, arg1);
}
public void InfoFormat(IFormatProvider provider, string format, params object[] args)
{
logger.InfoFormat(provider, format, args);
}
public void InfoFormat(string format, object arg0, object arg1, object arg2)
{
logger.InfoFormat(format, arg0, arg1, arg2);
}
public void Notice(object message)
{
Logger.Log(GetType(), Level.Notice, message, null);
}
public void Notice(object message, Exception exception)
{
Logger.Log(GetType(), Level.Notice, message, exception);
}
public void NoticeFormat(string format, params object[] args)
{
Logger.Log(GetType(), Level.Notice, string.Format(format, args), null);
}
public void NoticeFormat(string format, object arg0)
{
Logger.Log(GetType(), Level.Notice, string.Format(format, arg0), null);
}
public void NoticeFormat(string format, object arg0, object arg1)
{
Logger.Log(GetType(), Level.Notice, string.Format(format, arg0, arg1), null);
}
public void NoticeFormat(IFormatProvider provider, string format, params object[] args)
{
Logger.Log(GetType(), Level.Notice, string.Format(provider, format, args), null);
}
public void NoticeFormat(string format, object arg0, object arg1, object arg2)
{
Logger.Log(GetType(), Level.Notice, string.Format(format, arg0, arg1, arg2), null);
}
public void Warn(object message)
{
logger.Warn(message);
}
public void Warn(object message, Exception exception)
{
logger.Warn(message, exception);
}
public void WarnFormat(string format, params object[] args)
{
logger.WarnFormat(format, args);
}
public void WarnFormat(string format, object arg0)
{
logger.WarnFormat(format, arg0);
}
public void WarnFormat(string format, object arg0, object arg1)
{
logger.WarnFormat(format, arg0, arg1);
}
public void WarnFormat(IFormatProvider provider, string format, params object[] args)
{
logger.WarnFormat(provider, format, args);
}
public void WarnFormat(string format, object arg0, object arg1, object arg2)
{
logger.WarnFormat(format, arg0, arg1, arg2);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApp.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);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// GroupByQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using IEnumerator = System.Collections.IEnumerator;
namespace System.Linq.Parallel
{
/// <summary>
/// The operator type for GroupBy statements. This operator groups the input based on
/// a key-selection routine, yielding one-to-many values of key-to-elements. The
/// implementation is very much like the hash join operator, in which we first build
/// a big hashtable of the input; then we just iterate over each unique key in the
/// hashtable, yielding it plus all of the elements with the same key.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TGroupKey"></typeparam>
/// <typeparam name="TElement"></typeparam>
internal sealed class GroupByQueryOperator<TSource, TGroupKey, TElement> :
UnaryQueryOperator<TSource, IGrouping<TGroupKey, TElement>>
{
private readonly Func<TSource, TGroupKey> _keySelector; // Key selection function.
private readonly Func<TSource, TElement> _elementSelector; // Optional element selection function.
private readonly IEqualityComparer<TGroupKey> _keyComparer; // An optional key comparison object.
//---------------------------------------------------------------------------------------
// Initializes a new group by operator.
//
// Arguments:
// child - the child operator or data source from which to pull data
// keySelector - a delegate representing the key selector function
// elementSelector - a delegate representing the element selector function
// keyComparer - an optional key comparison routine
//
// Assumptions:
// keySelector must be non null.
// elementSelector must be non null.
//
internal GroupByQueryOperator(IEnumerable<TSource> child,
Func<TSource, TGroupKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TGroupKey> keyComparer)
: base(child)
{
Debug.Assert(child != null, "child data source cannot be null");
Debug.Assert(keySelector != null, "need a selector function");
Debug.Assert(elementSelector != null ||
typeof(TSource) == typeof(TElement), "need an element function if TSource!=TElement");
_keySelector = keySelector;
_elementSelector = elementSelector;
_keyComparer = keyComparer;
SetOrdinalIndexState(OrdinalIndexState.Shuffled);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
bool preferStriping, QuerySettings settings)
{
// Hash-repartition the source stream
if (Child.OutputOrdered)
{
WrapPartitionedStreamHelperOrdered<TKey>(
ExchangeUtilities.HashRepartitionOrdered<TSource, TGroupKey, TKey>(
inputStream, _keySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
recipient,
settings.CancellationState.MergedCancellationToken
);
}
else
{
WrapPartitionedStreamHelper<TKey, int>(
ExchangeUtilities.HashRepartition<TSource, TGroupKey, TKey>(
inputStream, _keySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
recipient,
settings.CancellationState.MergedCancellationToken
);
}
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelper<TIgnoreKey, TKey>(
PartitionedStream<Pair, TKey> hashStream,
IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
CancellationToken cancellationToken)
{
int partitionCount = hashStream.PartitionCount;
PartitionedStream<IGrouping<TGroupKey, TElement>, TKey> outputStream =
new PartitionedStream<IGrouping<TGroupKey, TElement>, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled);
// If there is no element selector, we return a special identity enumerator. Otherwise,
// we return one that will apply the element selection function during enumeration.
for (int i = 0; i < partitionCount; i++)
{
if (_elementSelector == null)
{
Debug.Assert(typeof(TSource) == typeof(TElement));
var enumerator = new GroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TKey>(
hashStream[i], _keyComparer, cancellationToken);
outputStream[i] = (QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TKey>)(object)enumerator;
}
else
{
outputStream[i] = new GroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TKey>(
hashStream[i], _keyComparer, _elementSelector, cancellationToken);
}
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelperOrdered<TKey>(
PartitionedStream<Pair, TKey> hashStream,
IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
CancellationToken cancellationToken)
{
int partitionCount = hashStream.PartitionCount;
PartitionedStream<IGrouping<TGroupKey, TElement>, TKey> outputStream =
new PartitionedStream<IGrouping<TGroupKey, TElement>, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled);
// If there is no element selector, we return a special identity enumerator. Otherwise,
// we return one that will apply the element selection function during enumeration.
IComparer<TKey> orderComparer = hashStream.KeyComparer;
for (int i = 0; i < partitionCount; i++)
{
if (_elementSelector == null)
{
Debug.Assert(typeof(TSource) == typeof(TElement));
var enumerator = new OrderedGroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TKey>(
hashStream[i], _keySelector, _keyComparer, orderComparer, cancellationToken);
outputStream[i] = (QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TKey>)(object)enumerator;
}
else
{
outputStream[i] = new OrderedGroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TKey>(
hashStream[i], _keySelector, _elementSelector, _keyComparer, orderComparer,
cancellationToken);
}
}
recipient.Receive(outputStream);
}
//-----------------------------------------------------------------------------------
// Override of the query operator base class's Open method.
//
internal override QueryResults<IGrouping<TGroupKey, TElement>> Open(QuerySettings settings, bool preferStriping)
{
// We just open our child operator. Do not propagate the preferStriping value, but instead explicitly
// set it to false. Regardless of whether the parent prefers striping or range partitioning, the output
// will be hash-partitioned.
QueryResults<TSource> childResults = Child.Open(settings, false);
return new UnaryQueryOperatorResults(childResults, this, settings, false);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<IGrouping<TGroupKey, TElement>> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TSource> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token);
if (_elementSelector == null)
{
Debug.Assert(typeof(TElement) == typeof(TSource));
return (IEnumerable<IGrouping<TGroupKey, TElement>>)(object)(wrappedChild.GroupBy(_keySelector, _keyComparer));
}
else
{
return wrappedChild.GroupBy(_keySelector, _elementSelector, _keyComparer);
}
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for grouping elements and yielding the key-value sets.
//
// Assumptions:
// Just like the Join operator, this won't work properly at all if the analysis engine
// didn't choose to hash partition. We will simply not yield correct groupings.
//
internal abstract class GroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TOrderKey>
{
protected readonly QueryOperatorEnumerator<Pair, TOrderKey> _source; // The data source to enumerate.
protected readonly IEqualityComparer<TGroupKey> _keyComparer; // A key comparer.
protected readonly CancellationToken _cancellationToken;
private Mutables _mutables; // All of the mutable state.
class Mutables
{
internal HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> _hashLookup; // The lookup with key-value mappings.
internal int _hashLookupIndex; // The current index within the lookup.
}
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
protected GroupByQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair, TOrderKey> source,
IEqualityComparer<TGroupKey> keyComparer, CancellationToken cancellationToken)
{
Debug.Assert(source != null);
_source = source;
_keyComparer = keyComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// MoveNext will invoke the entire query sub-tree, accumulating results into a hash-
// table, upon the first call. Then for the first call and all subsequent calls, we will
// just enumerate the key-set from the hash-table, retrieving groupings of key-elements.
//
internal override bool MoveNext(ref IGrouping<TGroupKey, TElement> currentElement, ref TOrderKey currentKey)
{
Debug.Assert(_source != null);
// Lazy-init the mutable state. This also means we haven't yet built our lookup of
// groupings, so we can go ahead and do that too.
Mutables mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
// Build the hash lookup and start enumerating the lookup at the beginning.
mutables._hashLookup = BuildHashLookup();
Debug.Assert(mutables._hashLookup != null);
mutables._hashLookupIndex = -1;
}
// Now, with a hash lookup in hand, we just enumerate the keys. So long
// as the key-value lookup has elements, we have elements.
if (++mutables._hashLookupIndex < mutables._hashLookup.Count)
{
currentElement = new GroupByGrouping<TGroupKey, TElement>(
mutables._hashLookup[mutables._hashLookupIndex]);
return true;
}
return false;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected abstract HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> BuildHashLookup();
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
}
//---------------------------------------------------------------------------------------
// A specialization of the group by enumerator for yielding elements with the identity
// function.
//
internal sealed class GroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TOrderKey> :
GroupByQueryOperatorEnumerator<TSource, TGroupKey, TSource, TOrderKey>
{
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal GroupByIdentityQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair, TOrderKey> source,
IEqualityComparer<TGroupKey> keyComparer, CancellationToken cancellationToken)
: base(source, keyComparer, cancellationToken)
{
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>> hashlookup =
new HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>>(new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair sourceElement = new Pair(default(TSource), default(TGroupKey));
TOrderKey sourceKeyUnused = default(TOrderKey);
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>((TGroupKey)sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
ListChunk<TSource> currentValue = null;
if (!hashlookup.TryGetValue(key, ref currentValue))
{
const int INITIAL_CHUNK_SIZE = 2;
currentValue = new ListChunk<TSource>(INITIAL_CHUNK_SIZE);
hashlookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue.Add((TSource)sourceElement.First);
}
return hashlookup;
}
}
//---------------------------------------------------------------------------------------
// A specialization of the group by enumerator for yielding elements with any arbitrary
// element selection function.
//
internal sealed class GroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
GroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey>
{
private readonly Func<TSource, TElement> _elementSelector; // Function to select elements.
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal GroupByElementSelectorQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair, TOrderKey> source,
IEqualityComparer<TGroupKey> keyComparer, Func<TSource, TElement> elementSelector, CancellationToken cancellationToken) :
base(source, keyComparer, cancellationToken)
{
Debug.Assert(elementSelector != null);
_elementSelector = elementSelector;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> hashlookup =
new HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>>(new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair sourceElement = new Pair(default(TSource), default(TGroupKey));
TOrderKey sourceKeyUnused = default(TOrderKey);
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>((TGroupKey)sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
ListChunk<TElement> currentValue = null;
if (!hashlookup.TryGetValue(key, ref currentValue))
{
const int INITIAL_CHUNK_SIZE = 2;
currentValue = new ListChunk<TElement>(INITIAL_CHUNK_SIZE);
hashlookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue.Add(_elementSelector((TSource)sourceElement.First));
}
return hashlookup;
}
}
//---------------------------------------------------------------------------------------
// Ordered version of the GroupBy operator.
//
internal abstract class OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TOrderKey>
{
protected readonly QueryOperatorEnumerator<Pair, TOrderKey> _source; // The data source to enumerate.
private readonly Func<TSource, TGroupKey> _keySelector; // The key selection routine.
protected readonly IEqualityComparer<TGroupKey> _keyComparer; // The key comparison routine.
protected readonly IComparer<TOrderKey> _orderComparer; // The comparison routine for order keys.
protected readonly CancellationToken _cancellationToken;
private Mutables _mutables; // All the mutable state.
class Mutables
{
internal HashLookup<Wrapper<TGroupKey>, GroupKeyData> _hashLookup; // The lookup with key-value mappings.
internal int _hashLookupIndex; // The current index within the lookup.
}
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
protected OrderedGroupByQueryOperatorEnumerator(QueryOperatorEnumerator<Pair, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, IEqualityComparer<TGroupKey> keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
Debug.Assert(keySelector != null);
_source = source;
_keySelector = keySelector;
_keyComparer = keyComparer;
_orderComparer = orderComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// MoveNext will invoke the entire query sub-tree, accumulating results into a hash-
// table, upon the first call. Then for the first call and all subsequent calls, we will
// just enumerate the key-set from the hash-table, retrieving groupings of key-elements.
//
internal override bool MoveNext(ref IGrouping<TGroupKey, TElement> currentElement, ref TOrderKey currentKey)
{
Debug.Assert(_source != null);
Debug.Assert(_keySelector != null);
// Lazy-init the mutable state. This also means we haven't yet built our lookup of
// groupings, so we can go ahead and do that too.
Mutables mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
// Build the hash lookup and start enumerating the lookup at the beginning.
mutables._hashLookup = BuildHashLookup();
Debug.Assert(mutables._hashLookup != null);
mutables._hashLookupIndex = -1;
}
// Now, with a hash lookup in hand, we just enumerate the keys. So long
// as the key-value lookup has elements, we have elements.
if (++mutables._hashLookupIndex < mutables._hashLookup.Count)
{
GroupKeyData value = mutables._hashLookup[mutables._hashLookupIndex].Value;
currentElement = value._grouping;
currentKey = value._orderKey;
return true;
}
return false;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected abstract HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup();
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
//-----------------------------------------------------------------------------------
// A data structure that holds information about elements with a particular key.
//
// This information includes two parts:
// - An order key for the grouping.
// - The grouping itself. The grouping consists of elements and the grouping key.
//
protected class GroupKeyData
{
internal TOrderKey _orderKey;
internal OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement> _grouping;
internal GroupKeyData(TOrderKey orderKey, TGroupKey hashKey, IComparer<TOrderKey> orderComparer)
{
_orderKey = orderKey;
_grouping = new OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement>(hashKey, orderComparer);
}
}
}
//---------------------------------------------------------------------------------------
// A specialization of the ordered GroupBy enumerator for yielding elements with the identity
// function.
//
internal sealed class OrderedGroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TOrderKey> :
OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TSource, TOrderKey>
{
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal OrderedGroupByIdentityQueryOperatorEnumerator(QueryOperatorEnumerator<Pair, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, IEqualityComparer<TGroupKey> keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken)
: base(source, keySelector, keyComparer, orderComparer, cancellationToken)
{
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, GroupKeyData> hashLookup = new HashLookup<Wrapper<TGroupKey>, GroupKeyData>(
new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair sourceElement = new Pair(default(TSource), default(TGroupKey));
TOrderKey sourceOrderKey = default(TOrderKey);
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceOrderKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>((TGroupKey)sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
GroupKeyData currentValue = null;
if (hashLookup.TryGetValue(key, ref currentValue))
{
if (_orderComparer.Compare(sourceOrderKey, currentValue._orderKey) < 0)
{
currentValue._orderKey = sourceOrderKey;
}
}
else
{
currentValue = new GroupKeyData(sourceOrderKey, key.Value, _orderComparer);
hashLookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
currentValue._grouping.Add((TSource)sourceElement.First, sourceOrderKey);
}
// Sort the elements within each group
for (int j = 0; j < hashLookup.Count; j++)
{
hashLookup[j].Value._grouping.DoneAdding();
}
return hashLookup;
}
}
//---------------------------------------------------------------------------------------
// A specialization of the ordered GroupBy enumerator for yielding elements with any arbitrary
// element selection function.
//
internal sealed class OrderedGroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey>
{
private readonly Func<TSource, TElement> _elementSelector; // Function to select elements.
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal OrderedGroupByElementSelectorQueryOperatorEnumerator(QueryOperatorEnumerator<Pair, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TGroupKey> keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken) :
base(source, keySelector, keyComparer, orderComparer, cancellationToken)
{
Debug.Assert(elementSelector != null);
_elementSelector = elementSelector;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, GroupKeyData> hashLookup = new HashLookup<Wrapper<TGroupKey>, GroupKeyData>(
new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair sourceElement = new Pair(default(TSource), default(TGroupKey));
TOrderKey sourceOrderKey = default(TOrderKey);
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceOrderKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>((TGroupKey)sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
GroupKeyData currentValue = null;
if (hashLookup.TryGetValue(key, ref currentValue))
{
if (_orderComparer.Compare(sourceOrderKey, currentValue._orderKey) < 0)
{
currentValue._orderKey = sourceOrderKey;
}
}
else
{
currentValue = new GroupKeyData(sourceOrderKey, key.Value, _orderComparer);
hashLookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue._grouping.Add(_elementSelector((TSource)sourceElement.First), sourceOrderKey);
}
// Sort the elements within each group
for (int j = 0; j < hashLookup.Count; j++)
{
hashLookup[j].Value._grouping.DoneAdding();
}
return hashLookup;
}
}
//---------------------------------------------------------------------------------------
// This little type implements the IGrouping<K,T> interface, and exposes a single
// key-to-many-values mapping.
//
internal class GroupByGrouping<TGroupKey, TElement> : IGrouping<TGroupKey, TElement>
{
private KeyValuePair<Wrapper<TGroupKey>, ListChunk<TElement>> _keyValues; // A key value pair.
//---------------------------------------------------------------------------------------
// Constructs a new grouping out of the key value pair.
//
internal GroupByGrouping(KeyValuePair<Wrapper<TGroupKey>, ListChunk<TElement>> keyValues)
{
Debug.Assert(keyValues.Value != null);
_keyValues = keyValues;
}
//---------------------------------------------------------------------------------------
// The key this mapping represents.
//
TGroupKey IGrouping<TGroupKey, TElement>.Key
{
get
{
return _keyValues.Key.Value;
}
}
//---------------------------------------------------------------------------------------
// Access to value enumerators.
//
IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator()
{
Debug.Assert(_keyValues.Value != null);
return _keyValues.Value.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<TElement>)this).GetEnumerator();
}
}
/// <summary>
/// An ordered version of the grouping data structure. Represents an ordered group of elements that
/// have the same grouping key.
/// </summary>
internal class OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement> : IGrouping<TGroupKey, TElement>
{
private TGroupKey _groupKey; // The group key for this grouping
private GrowingArray<TElement> _values; // Values in this group
private GrowingArray<TOrderKey> _orderKeys; // Order keys that correspond to the values
private IComparer<TOrderKey> _orderComparer; // Comparer for order keys
private KeyAndValuesComparer _wrappedComparer; // Comparer that wraps the _orderComparer used for sorting key/value pairs
/// <summary>
/// Constructs a new grouping
/// </summary>
internal OrderedGroupByGrouping(
TGroupKey groupKey,
IComparer<TOrderKey> orderComparer)
{
_groupKey = groupKey;
_values = new GrowingArray<TElement>();
_orderKeys = new GrowingArray<TOrderKey>();
_orderComparer = orderComparer;
_wrappedComparer = new KeyAndValuesComparer(_orderComparer);
}
/// <summary>
/// The key this grouping represents.
/// </summary>
TGroupKey IGrouping<TGroupKey, TElement>.Key
{
get
{
return _groupKey;
}
}
IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator()
{
Debug.Assert(_values != null);
int valueCount = _values.Count;
TElement[] valueArray = _values.InternalArray;
Debug.Assert(valueArray.Length >= valueCount); // valueArray.Length may be larger than valueCount
for (int i = 0; i < valueCount; i++)
{
yield return valueArray[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<TElement>)this).GetEnumerator();
}
/// <summary>
/// Add an element
/// </summary>
internal void Add(TElement value, TOrderKey orderKey)
{
Debug.Assert(_values != null);
Debug.Assert(_orderKeys != null);
_values.Add(value);
_orderKeys.Add(orderKey);
}
/// <summary>
/// No more elements will be added, so we can sort the group now.
/// </summary>
internal void DoneAdding()
{
Debug.Assert(_values != null);
Debug.Assert(_orderKeys != null);
// Create a map of key-value pair.
// We can't use a dictionary since the keys are not necessarily unique
List<KeyValuePair<TOrderKey, TElement>> sortedValues = new List<KeyValuePair<TOrderKey, TElement>>();
for (int i = 0; i < _orderKeys.InternalArray.Length; i++)
{
sortedValues.Add(new KeyValuePair<TOrderKey, TElement>(_orderKeys.InternalArray[i], _values.InternalArray[i]));
}
// Sort the values by using the _orderComparer wrapped in a Tuple comparer
sortedValues.Sort(0, _values.Count, _wrappedComparer);
// Un-pack the values from the list back into the 2 separate arrays
for (int i = 0; i < _values.InternalArray.Length; i++)
{
_orderKeys.InternalArray[i] = sortedValues[i].Key;
_values.InternalArray[i] = sortedValues[i].Value;
}
#if DEBUG
_orderKeys = null; // Any future calls to Add() or DoneAdding() will fail
#endif
}
private class KeyAndValuesComparer : IComparer<KeyValuePair<TOrderKey, TElement>>
{
private IComparer<TOrderKey> myComparer;
public KeyAndValuesComparer(IComparer<TOrderKey> comparer)
{
myComparer = comparer;
}
public int Compare(KeyValuePair<TOrderKey, TElement> x, KeyValuePair<TOrderKey, TElement> y)
{
return myComparer.Compare(x.Key, y.Key);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace IDoTodos.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
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);
}
}
}
}
| |
using AllReady.Areas.Admin.Features.Tasks;
using AllReady.Areas.Admin.ViewModels.Validators.VolunteerTask;
using AllReady.Areas.Admin.ViewModels.VolunteerTask;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AllReady.Areas.Admin.Features.Events;
using AllReady.Areas.Admin.Features.Users;
using AllReady.Areas.Admin.ViewModels.Event;
using AllReady.Constants;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using DeleteQuery = AllReady.Areas.Admin.Features.Tasks.DeleteQuery;
using DeleteViewModel = AllReady.Areas.Admin.ViewModels.VolunteerTask.DeleteViewModel;
namespace AllReady.Areas.Admin.Controllers
{
[Area(AreaNames.Admin)]
[Authorize]
public class VolunteerTaskController : Controller
{
private readonly IMediator _mediator;
private readonly IValidateVolunteerTaskEditViewModelValidator _volunteerTaskEditViewModelValidator;
public VolunteerTaskController(IMediator mediator, IValidateVolunteerTaskEditViewModelValidator volunteerTaskEditViewModelValidator)
{
_mediator = mediator;
_volunteerTaskEditViewModelValidator = volunteerTaskEditViewModelValidator;
}
[HttpGet]
[Route("Admin/VolunteerTask/Details/{id}")]
public async Task<IActionResult> Details(int id)
{
var viewModel = await _mediator.SendAsync(new DetailsQuery { VolunteerTaskId = id });
if (viewModel == null)
{
return NotFound();
}
var authorizableTask = await _mediator.SendAsync(new AuthorizableTaskQuery(id));
if (!await authorizableTask.UserCanView())
{
return new ForbidResult();
}
return View(viewModel);
}
[HttpGet]
[Route("Admin/VolunteerTask/Create/{eventId}")]
public async Task<IActionResult> Create(int eventId)
{
var viewModel = await _mediator.SendAsync(new CreateVolunteerTaskQuery { EventId = eventId });
var authorizableEvent = await _mediator.SendAsync(new Features.Events.AuthorizableEventQuery(eventId));
if (!await authorizableEvent.UserCanManageChildObjects())
{
return new ForbidResult();
}
viewModel.CancelUrl = Url.Action(new UrlActionContext { Action = nameof(EventController.Details), Controller = "Event", Values = new { id = viewModel.EventId, area = AreaNames.Admin } });
ViewBag.Title = "Create Task";
return View("Edit", viewModel);
}
[HttpGet]
[Route("Admin/VolunteerTask/Edit/{id}")]
public async Task<IActionResult> Edit(int id)
{
var viewModel = await _mediator.SendAsync(new EditVolunteerTaskQuery { VolunteerTaskId = id });
var authorizableTask = await _mediator.SendAsync(new AuthorizableTaskQuery(id));
if (!await authorizableTask.UserCanView())
{
return new ForbidResult();
}
viewModel.CancelUrl = Url.Action(new UrlActionContext { Action = nameof(Details), Controller = "VolunteerTask", Values = new { eventId = viewModel.EventId, id = viewModel.Id, area = AreaNames.Admin } });
ViewBag.Title = "Edit Task";
return View("Edit", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(EditViewModel viewModel)
{
var errors = await _volunteerTaskEditViewModelValidator.Validate(viewModel);
errors.ToList().ForEach(e => ModelState.AddModelError(e.Key, e.Value));
if (ModelState.IsValid)
{
if (viewModel.Id == 0)
{
var authorizableEvent = await _mediator.SendAsync(new Features.Events.AuthorizableEventQuery(viewModel.EventId));
if (!await authorizableEvent.UserCanManageChildObjects())
{
return new ForbidResult();
}
}
else
{
var authorizableTask = await _mediator.SendAsync(new AuthorizableTaskQuery(viewModel.Id));
if (!await authorizableTask.UserCanEdit())
{
return new ForbidResult();
}
}
var volunteerTaskId = await _mediator.SendAsync(new EditVolunteerTaskCommand { VolunteerTask = viewModel });
return viewModel.Id == 0 ?
RedirectToAction(nameof(EventController.Details), "Event", new { id = viewModel.EventId }) :
RedirectToAction(nameof(Details), "VolunteerTask", new { id = volunteerTaskId });
}
if (viewModel.Id == 0)
{
viewModel.CancelUrl = Url.Action(new UrlActionContext { Action = nameof(EventController.Details), Controller = "Event", Values = new { id = viewModel.EventId, area = AreaNames.Admin } });
}
else
{
viewModel.CancelUrl = Url.Action(new UrlActionContext { Action = nameof(Details), Controller = "VolunteerTask", Values = new { eventId = viewModel.EventId, id = viewModel.Id, area = AreaNames.Admin } });
}
return View(viewModel);
}
public async Task<IActionResult> Delete(int id)
{
var viewModel = await _mediator.SendAsync(new DeleteQuery { VolunteerTaskId = id });
var authorizableTask = await _mediator.SendAsync(new AuthorizableTaskQuery(id));
if (!await authorizableTask.UserCanEdit())
{
return new ForbidResult();
}
viewModel.Title = $"Delete task {viewModel.Name}";
viewModel.UserIsOrgAdmin = true;
return View(viewModel);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(DeleteViewModel viewModel)
{
if (!viewModel.UserIsOrgAdmin)
{
return new ForbidResult();
}
await _mediator.SendAsync(new DeleteVolunteerTaskCommand { VolunteerTaskId = viewModel.Id });
return RedirectToAction(nameof(EventController.Details), "Event", new { id = viewModel.EventId });
}
[HttpPost, ActionName("RemoveVolunteer")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveVolunteer(RemoveVolunteerViewModel viewModel)
{
await _mediator.SendAsync(new RemoveVolunteerFromTaskCommand
{
TaskId = viewModel.TaskId,
UserId = viewModel.UserId,
NotifyUser = viewModel.Notify
});
return RedirectToAction(nameof(Details), new { id = viewModel.TaskId});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Assign(int id, List<string> userIds)
{
var volunteerTasksOrganizationId = await _mediator.SendAsync(new OrganizationIdByVolunteerTaskIdQuery { VolunteerTaskId = id });
var authorizableTask = await _mediator.SendAsync(new AuthorizableTaskQuery(id));
if (!await authorizableTask.UserCanEdit())
{
return new ForbidResult();
}
await _mediator.SendAsync(new AssignVolunteerTaskCommand { VolunteerTaskId = id, UserIds = userIds });
return RedirectToRoute(new { controller = "VolunteerTask", area = AreaNames.Admin, action = nameof(Details), id });
}
[Route("Admin/Event/{eventId}/Task/{taskId}/candidates")]
public async Task<IActionResult> VolunteerCandidates(int eventId, int taskId)
{
var viewModel = await _mediator.SendAsync(new DetailsQuery() { VolunteerTaskId = taskId });
var authorizableTask = await _mediator.SendAsync(new AuthorizableTaskQuery(taskId));
if (!await authorizableTask.UserCanEdit())
return new ForbidResult();
var eventInfo = await _mediator.SendAsync(new EventDetailQuery() { EventId = eventId });
var query = new ListPossibleVolunteersForTaskQuery
{
OrganizationId = eventInfo.OrganizationId,
TaskId = taskId
};
var users = await _mediator.SendAsync(query);
var model = new VolunteerCandidatesViewModel
{
MaxSelectableCount = viewModel.NumberOfVolunteersRequired - viewModel.AssignedVolunteers.Count,
Volunteers = users
.Select(x => new SelectListItem { Value = x.UserId, Text = $"{x.Name} ({x.TaskCount} assigned tasks)" })
.ToList(),
};
return Json(model);
}
[HttpPost]
[Route("Admin/Task/Assign/Volunteer")]
public async Task<IActionResult> AssignChosenVolunteers(AssignVolunteersViewModel viewModel)
{
var authorizableTask = await _mediator.SendAsync(new AuthorizableTaskQuery(viewModel.TaskId));
if (!await authorizableTask.UserCanEdit())
return new ForbidResult();
foreach (var userId in viewModel.UserId)
{
var cmd = new AssignVolunteerToTaskCommand
{
UserId = userId,
VolunteerTaskId = viewModel.TaskId,
NotifyUser = viewModel.NotifyUsers
};
await _mediator.SendAsync(cmd);
}
var task = await _mediator.SendAsync(new DetailsQuery() { VolunteerTaskId = viewModel.TaskId });
return RedirectToAction("Details", "Event", new { id = task.EventId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> MessageAllVolunteers(MessageTaskVolunteersViewModel viewModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var volunteerTasksOrganizationId = await _mediator.SendAsync(new OrganizationIdByVolunteerTaskIdQuery { VolunteerTaskId = viewModel.VolunteerTaskId });
var authorizableTask = await _mediator.SendAsync(new AuthorizableTaskQuery(viewModel.VolunteerTaskId));
if (!await authorizableTask.UserCanEdit())
{
return new ForbidResult();
}
await _mediator.SendAsync(new MessageTaskVolunteersCommand { Model = viewModel });
return Ok();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Validation;
using BCL = System.Collections.Generic;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable unordered dictionary implementation.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableDictionaryDebuggerProxy<,>))]
public sealed partial class ImmutableDictionary<TKey, TValue> : IImmutableDictionary<TKey, TValue>, IImmutableDictionaryInternal<TKey, TValue>, IHashKeyCollection<TKey>, IDictionary<TKey, TValue>, IDictionary
{
/// <summary>
/// An empty immutable dictionary with default equality comparers.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly ImmutableDictionary<TKey, TValue> Empty = new ImmutableDictionary<TKey, TValue>();
/// <summary>
/// The singleton delegate that freezes the contents of hash buckets when the root of the data structure is frozen.
/// </summary>
private static readonly Action<KeyValuePair<int, HashBucket>> s_FreezeBucketAction = (kv) => kv.Value.Freeze();
/// <summary>
/// The number of elements in the collection.
/// </summary>
private readonly int _count;
/// <summary>
/// The root node of the tree that stores this map.
/// </summary>
private readonly SortedInt32KeyNode<HashBucket> _root;
/// <summary>
/// The comparer used when comparing hash buckets.
/// </summary>
private readonly Comparers _comparers;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableDictionary<TKey, TValue>"/> class.
/// </summary>
/// <param name="root">The root.</param>
/// <param name="comparers">The comparers.</param>
/// <param name="count">The number of elements in the map.</param>
private ImmutableDictionary(SortedInt32KeyNode<HashBucket> root, Comparers comparers, int count)
: this(Requires.NotNullPassthrough(comparers, "comparers"))
{
Requires.NotNull(root, "root");
root.Freeze(s_FreezeBucketAction);
_root = root;
_count = count;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableDictionary<TKey, TValue>"/> class.
/// </summary>
/// <param name="comparers">The comparers.</param>
private ImmutableDictionary(Comparers comparers = null)
{
_comparers = comparers ?? Comparers.Get(EqualityComparer<TKey>.Default, EqualityComparer<TValue>.Default);
_root = SortedInt32KeyNode<HashBucket>.EmptyNode;
}
/// <summary>
/// How to respond when a key collision is discovered.
/// </summary>
internal enum KeyCollisionBehavior
{
/// <summary>
/// Sets the value for the given key, even if that overwrites an existing value.
/// </summary>
SetValue,
/// <summary>
/// Skips the mutating operation if a key conflict is detected.
/// </summary>
Skip,
/// <summary>
/// Throw an exception if the key already exists with a different key.
/// </summary>
ThrowIfValueDifferent,
/// <summary>
/// Throw an exception if the key already exists regardless of its value.
/// </summary>
ThrowAlways,
}
/// <summary>
/// The result of a mutation operation.
/// </summary>
internal enum OperationResult
{
/// <summary>
/// The change was applied and did not require a change to the number of elements in the collection.
/// </summary>
AppliedWithoutSizeChange,
/// <summary>
/// The change required element(s) to be added or removed from the collection.
/// </summary>
SizeChanged,
/// <summary>
/// No change was required (the operation ended in a no-op).
/// </summary>
NoChangeRequired,
}
#region Public Properties
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
public ImmutableDictionary<TKey, TValue> Clear()
{
return this.IsEmpty ? this : EmptyWithComparers(_comparers);
}
/// <summary>
/// Gets the number of elements in this collection.
/// </summary>
public int Count
{
get { return _count; }
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get { return this.Count == 0; }
}
/// <summary>
/// Gets the key comparer.
/// </summary>
public IEqualityComparer<TKey> KeyComparer
{
get { return _comparers.KeyComparer; }
}
/// <summary>
/// Gets the value comparer used to determine whether values are equal.
/// </summary>
public IEqualityComparer<TValue> ValueComparer
{
get { return _comparers.ValueComparer; }
}
/// <summary>
/// Gets the keys in the map.
/// </summary>
public IEnumerable<TKey> Keys
{
get
{
foreach (var bucket in _root)
{
foreach (var item in bucket.Value)
{
yield return item.Key;
}
}
}
}
/// <summary>
/// Gets the values in the map.
/// </summary>
public IEnumerable<TValue> Values
{
get
{
foreach (var bucket in _root)
{
foreach (var item in bucket.Value)
{
yield return item.Value;
}
}
}
}
#endregion
#region IImmutableDictionary<TKey,TValue> Properties
/// <summary>
/// Gets the empty instance.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear()
{
return this.Clear();
}
#endregion
#region IDictionary<TKey, TValue> Properties
/// <summary>
/// Gets the keys.
/// </summary>
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return new KeysCollectionAccessor<TKey, TValue>(this); }
}
/// <summary>
/// Gets the values.
/// </summary>
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return new ValuesCollectionAccessor<TKey, TValue>(this); }
}
#endregion
/// <summary>
/// Gets a data structure that captures the current state of this map, as an input into a query or mutating function.
/// </summary>
private MutationInput Origin
{
get { return new MutationInput(this); }
}
/// <summary>
/// Gets the <typeparamref name="TValue"/> with the specified key.
/// </summary>
public TValue this[TKey key]
{
get
{
Requires.NotNullAllowStructs(key, "key");
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
throw new KeyNotFoundException();
}
}
/// <summary>
/// Gets or sets the <typeparamref name="TValue"/> with the specified key.
/// </summary>
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get { return this[key]; }
set { throw new NotSupportedException(); }
}
#region ICollection<KeyValuePair<TKey, TValue>> Properties
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return true; }
}
#endregion
#region Public methods
/// <summary>
/// Creates a collection with the same contents as this collection that
/// can be efficiently mutated across multiple operations using standard
/// mutable interfaces.
/// </summary>
/// <remarks>
/// This is an O(1) operation and results in only a single (small) memory allocation.
/// The mutable collection that is returned is *not* thread-safe.
/// </remarks>
[Pure]
public Builder ToBuilder()
{
// We must not cache the instance created here and return it to various callers.
// Those who request a mutable collection must get references to the collection
// that version independently of each other.
return new Builder(this);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableDictionary<TKey, TValue> Add(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, "key");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var result = Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, new MutationInput(this));
return result.Finalize(this);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public ImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
Requires.NotNull(pairs, "pairs");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
return this.AddRange(pairs, false);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableDictionary<TKey, TValue> SetItem(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, "key");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
Contract.Ensures(!Contract.Result<ImmutableDictionary<TKey, TValue>>().IsEmpty);
var result = Add(key, value, KeyCollisionBehavior.SetValue, new MutationInput(this));
return result.Finalize(this);
}
/// <summary>
/// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary.
/// </summary>
/// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param>
/// <returns>An immutable dictionary.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public ImmutableDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, "items");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var result = AddRange(items, this.Origin, KeyCollisionBehavior.SetValue);
return result.Finalize(this);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableDictionary<TKey, TValue> Remove(TKey key)
{
Requires.NotNullAllowStructs(key, "key");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var result = Remove(key, new MutationInput(this));
return result.Finalize(this);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, "keys");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
int count = _count;
var root = _root;
foreach (var key in keys)
{
int hashCode = this.KeyComparer.GetHashCode(key);
HashBucket bucket;
if (root.TryGetValue(hashCode, out bucket))
{
OperationResult result;
var newBucket = bucket.Remove(key, _comparers.KeyOnlyComparer, out result);
root = UpdateRoot(root, hashCode, newBucket, _comparers.HashBucketEqualityComparer);
if (result == OperationResult.SizeChanged)
{
count--;
}
}
}
return this.Wrap(root, count);
}
/// <summary>
/// Determines whether the specified key contains key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
/// </returns>
public bool ContainsKey(TKey key)
{
Requires.NotNullAllowStructs(key, "key");
return ContainsKey(key, new MutationInput(this));
}
/// <summary>
/// Determines whether [contains] [the specified key value pair].
/// </summary>
/// <param name="pair">The key value pair.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified key value pair]; otherwise, <c>false</c>.
/// </returns>
public bool Contains(KeyValuePair<TKey, TValue> pair)
{
return Contains(pair, this.Origin);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
Requires.NotNullAllowStructs(key, "key");
return TryGetValue(key, this.Origin, out value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
Requires.NotNullAllowStructs(equalKey, "equalKey");
return TryGetKey(equalKey, this.Origin, out actualKey);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableDictionary<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
if (keyComparer == null)
{
keyComparer = EqualityComparer<TKey>.Default;
}
if (valueComparer == null)
{
valueComparer = EqualityComparer<TValue>.Default;
}
if (this.KeyComparer == keyComparer)
{
if (this.ValueComparer == valueComparer)
{
return this;
}
else
{
// When the key comparer is the same but the value comparer is different, we don't need a whole new tree
// because the structure of the tree does not depend on the value comparer.
// We just need a new root node to store the new value comparer.
var comparers = _comparers.WithValueComparer(valueComparer);
return new ImmutableDictionary<TKey, TValue>(_root, comparers, _count);
}
}
else
{
var comparers = Comparers.Get(keyComparer, valueComparer);
var set = new ImmutableDictionary<TKey, TValue>(comparers);
set = set.AddRange(this, avoidToHashMap: true);
return set;
}
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableDictionary<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer)
{
return this.WithComparers(keyComparer, _comparers.ValueComparer);
}
/// <summary>
/// Determines whether the ImmutableSortedMap<TKey,TValue>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the ImmutableSortedMap<TKey,TValue>.
/// The value can be null for reference types.
/// </param>
/// <returns>
/// true if the ImmutableSortedMap<TKey,TValue> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
public bool ContainsValue(TValue value)
{
foreach (KeyValuePair<TKey, TValue> item in this)
{
if (this.ValueComparer.Equals(value, item.Value))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator(_root);
}
#endregion
#region IImmutableDictionary<TKey,TValue> Methods
/// <summary>
/// See the IImmutableMap{TKey,TValue} interface
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
return this.Add(key, value);
}
/// <summary>
/// See the IImmutableMap{TKey,TValue} interface
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value)
{
return this.SetItem(key, value);
}
/// <summary>
/// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary.
/// </summary>
/// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param>
/// <returns>An immutable dictionary.</returns>
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return this.SetItems(items);
}
/// <summary>
/// See the IImmutableMap{TKey,TValue} interface
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
return this.AddRange(pairs);
}
/// <summary>
/// See the IImmutableMap{TKey,TValue} interface
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys)
{
return this.RemoveRange(keys);
}
/// <summary>
/// See the IImmutableMap{TKey,TValue} interface
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key)
{
return this.Remove(key);
}
#endregion
#region IDictionary<TKey, TValue> Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.
/// </exception>
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
throw new NotSupportedException();
}
/// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.
/// </exception>
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
throw new NotSupportedException();
}
#endregion
#region ICollection<KeyValuePair<TKey, TValue>> Methods
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
Requires.NotNull(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex");
Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex");
foreach (var item in this)
{
array[arrayIndex++] = item;
}
}
#endregion
#region IDictionary Properties
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary" /> object has a fixed size.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.IDictionary" /> object has a fixed size; otherwise, false.</returns>
bool IDictionary.IsFixedSize
{
get { return true; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only; otherwise, false.
/// </returns>
bool IDictionary.IsReadOnly
{
get { return true; }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </returns>
ICollection IDictionary.Keys
{
get { return new KeysCollectionAccessor<TKey, TValue>(this); }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </returns>
ICollection IDictionary.Values
{
get { return new ValuesCollectionAccessor<TKey, TValue>(this); }
}
#endregion
/// <summary>
/// Gets the root node (for testing purposes).
/// </summary>
internal SortedInt32KeyNode<HashBucket> Root
{
get { return _root; }
}
#region IDictionary Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.IDictionary" /> object.
/// </summary>
/// <param name="key">The <see cref="T:System.Object" /> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="T:System.Object" /> to use as the value of the element to add.</param>
void IDictionary.Add(object key, object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.IDictionary" /> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.IDictionary" /> object.</param>
/// <returns>
/// true if the <see cref="T:System.Collections.IDictionary" /> contains an element with the key; otherwise, false.
/// </returns>
bool IDictionary.Contains(object key)
{
return this.ContainsKey((TKey)key);
}
/// <summary>
/// Returns an <see cref="T:System.Collections.IDictionaryEnumerator" /> object for the <see cref="T:System.Collections.IDictionary" /> object.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IDictionaryEnumerator" /> object for the <see cref="T:System.Collections.IDictionary" /> object.
/// </returns>
/// <exception cref="System.NotImplementedException"></exception>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator());
}
/// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.IDictionary" /> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
void IDictionary.Remove(object key)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
object IDictionary.this[object key]
{
get { return this[(TKey)key]; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Clears this instance.
/// </summary>
/// <exception cref="System.NotSupportedException"></exception>
void IDictionary.Clear()
{
throw new NotSupportedException();
}
#endregion
#region ICollection Methods
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param>
void ICollection.CopyTo(Array array, int arrayIndex)
{
Requires.NotNull(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex");
Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex");
if (_count == 0)
{
return;
}
int[] indices = new int[1]; // SetValue takes a params array; lifting out the implicit allocation from the loop
foreach (var item in this)
{
indices[0] = arrayIndex++;
array.SetValue(new DictionaryEntry(item.Key, item.Value), indices);
}
}
#endregion
#region ICollection Properties
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get { return this; }
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection" /> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="T:System.Collections.ICollection" /> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get
{
// This is immutable, so it is always thread-safe.
return true;
}
}
#endregion
#region IEnumerable<KeyValuePair<TKey, TValue>> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
[ExcludeFromCodeCoverage]
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Gets an empty collection with the specified comparers.
/// </summary>
/// <param name="comparers">The comparers.</param>
/// <returns>The empty dictionary.</returns>
[Pure]
private static ImmutableDictionary<TKey, TValue> EmptyWithComparers(Comparers comparers)
{
Requires.NotNull(comparers, "comparers");
return Empty._comparers == comparers
? Empty
: new ImmutableDictionary<TKey, TValue>(comparers);
}
/// <summary>
/// Attempts to discover an <see cref="ImmutableDictionary<TKey, TValue>"/> instance beneath some enumerable sequence
/// if one exists.
/// </summary>
/// <param name="sequence">The sequence that may have come from an immutable map.</param>
/// <param name="other">Receives the concrete <see cref="ImmutableDictionary<TKey, TValue>"/> typed value if one can be found.</param>
/// <returns><c>true</c> if the cast was successful; <c>false</c> otherwise.</returns>
private static bool TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, out ImmutableDictionary<TKey, TValue> other)
{
other = sequence as ImmutableDictionary<TKey, TValue>;
if (other != null)
{
return true;
}
var builder = sequence as Builder;
if (builder != null)
{
other = builder.ToImmutable();
return true;
}
return false;
}
#region Static query and manipulator methods
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static bool ContainsKey(TKey key, MutationInput origin)
{
int hashCode = origin.KeyComparer.GetHashCode(key);
HashBucket bucket;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
TValue value;
return bucket.TryGetValue(key, origin.KeyOnlyComparer, out value);
}
return false;
}
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static bool Contains(KeyValuePair<TKey, TValue> keyValuePair, MutationInput origin)
{
int hashCode = origin.KeyComparer.GetHashCode(keyValuePair.Key);
HashBucket bucket;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
TValue value;
return bucket.TryGetValue(keyValuePair.Key, origin.KeyOnlyComparer, out value)
&& origin.ValueComparer.Equals(value, keyValuePair.Value);
}
return false;
}
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static bool TryGetValue(TKey key, MutationInput origin, out TValue value)
{
int hashCode = origin.KeyComparer.GetHashCode(key);
HashBucket bucket;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
return bucket.TryGetValue(key, origin.KeyOnlyComparer, out value);
}
value = default(TValue);
return false;
}
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static bool TryGetKey(TKey equalKey, MutationInput origin, out TKey actualKey)
{
int hashCode = origin.KeyComparer.GetHashCode(equalKey);
HashBucket bucket;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
return bucket.TryGetKey(equalKey, origin.KeyOnlyComparer, out actualKey);
}
actualKey = equalKey;
return false;
}
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static MutationResult Add(TKey key, TValue value, KeyCollisionBehavior behavior, MutationInput origin)
{
Requires.NotNullAllowStructs(key, "key");
OperationResult result;
int hashCode = origin.KeyComparer.GetHashCode(key);
HashBucket bucket = origin.Root.GetValueOrDefault(hashCode);
var newBucket = bucket.Add(key, value, origin.KeyOnlyComparer, origin.ValueComparer, behavior, out result);
if (result == OperationResult.NoChangeRequired)
{
return new MutationResult(origin);
}
var newRoot = UpdateRoot(origin.Root, hashCode, newBucket, origin.HashBucketComparer);
return new MutationResult(newRoot, result == OperationResult.SizeChanged ? +1 : 0);
}
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static MutationResult AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items, MutationInput origin, KeyCollisionBehavior collisionBehavior = KeyCollisionBehavior.ThrowIfValueDifferent)
{
Requires.NotNull(items, "items");
int countAdjustment = 0;
var newRoot = origin.Root;
foreach (var pair in items)
{
int hashCode = origin.KeyComparer.GetHashCode(pair.Key);
HashBucket bucket = newRoot.GetValueOrDefault(hashCode);
OperationResult result;
var newBucket = bucket.Add(pair.Key, pair.Value, origin.KeyOnlyComparer, origin.ValueComparer, collisionBehavior, out result);
newRoot = UpdateRoot(newRoot, hashCode, newBucket, origin.HashBucketComparer);
if (result == OperationResult.SizeChanged)
{
countAdjustment++;
}
}
return new MutationResult(newRoot, countAdjustment);
}
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static MutationResult Remove(TKey key, MutationInput origin)
{
int hashCode = origin.KeyComparer.GetHashCode(key);
HashBucket bucket;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
OperationResult result;
var newRoot = UpdateRoot(origin.Root, hashCode, bucket.Remove(key, origin.KeyOnlyComparer, out result), origin.HashBucketComparer);
return new MutationResult(newRoot, result == OperationResult.SizeChanged ? -1 : 0);
}
return new MutationResult(origin);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static SortedInt32KeyNode<HashBucket> UpdateRoot(SortedInt32KeyNode<HashBucket> root, int hashCode, HashBucket newBucket, IEqualityComparer<HashBucket> hashBucketComparer)
{
bool mutated;
if (newBucket.IsEmpty)
{
return root.Remove(hashCode, out mutated);
}
else
{
bool replacedExistingValue;
return root.SetItem(hashCode, newBucket, hashBucketComparer, out replacedExistingValue, out mutated);
}
}
#endregion
/// <summary>
/// Wraps the specified data structure with an immutable collection wrapper.
/// </summary>
/// <param name="root">The root of the data structure.</param>
/// <param name="comparers">The comparers.</param>
/// <param name="count">The number of elements in the data structure.</param>
/// <returns>
/// The immutable collection.
/// </returns>
private static ImmutableDictionary<TKey, TValue> Wrap(SortedInt32KeyNode<HashBucket> root, Comparers comparers, int count)
{
Requires.NotNull(root, "root");
Requires.NotNull(comparers, "comparers");
Requires.Range(count >= 0, "count");
return new ImmutableDictionary<TKey, TValue>(root, comparers, count);
}
/// <summary>
/// Wraps the specified data structure with an immutable collection wrapper.
/// </summary>
/// <param name="root">The root of the data structure.</param>
/// <param name="adjustedCountIfDifferentRoot">The adjusted count if the root has changed.</param>
/// <returns>The immutable collection.</returns>
private ImmutableDictionary<TKey, TValue> Wrap(SortedInt32KeyNode<HashBucket> root, int adjustedCountIfDifferentRoot)
{
if (root == null)
{
return this.Clear();
}
if (_root != root)
{
return root.IsEmpty ? this.Clear() : new ImmutableDictionary<TKey, TValue>(root, _comparers, adjustedCountIfDifferentRoot);
}
return this;
}
/// <summary>
/// Bulk adds entries to the map.
/// </summary>
/// <param name="pairs">The entries to add.</param>
/// <param name="avoidToHashMap"><c>true</c> when being called from ToHashMap to avoid StackOverflow.</param>
[Pure]
private ImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs, bool avoidToHashMap)
{
Requires.NotNull(pairs, "pairs");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
// Some optimizations may apply if we're an empty list.
if (this.IsEmpty && !avoidToHashMap)
{
// If the items being added actually come from an ImmutableHashMap<TKey, TValue>
// then there is no value in reconstructing it.
ImmutableDictionary<TKey, TValue> other;
if (TryCastToImmutableMap(pairs, out other))
{
return other.WithComparers(this.KeyComparer, this.ValueComparer);
}
}
var result = AddRange(pairs, this.Origin);
return result.Finalize(this);
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
namespace Pathfinding.Recast {
using System;
using Pathfinding;
using Pathfinding.Voxels;
internal class RecastMeshGatherer {
readonly int terrainSampleSize;
readonly LayerMask mask;
readonly List<string> tagMask;
readonly float colliderRasterizeDetail;
readonly Bounds bounds;
public RecastMeshGatherer (Bounds bounds, int terrainSampleSize, LayerMask mask, List<string> tagMask, float colliderRasterizeDetail) {
// Clamp to at least 1 since that's the resolution of the heightmap
terrainSampleSize = Math.Max(terrainSampleSize, 1);
this.bounds = bounds;
this.terrainSampleSize = terrainSampleSize;
this.mask = mask;
this.tagMask = tagMask ?? new List<string>();
this.colliderRasterizeDetail = colliderRasterizeDetail;
}
static List<MeshFilter> FilterMeshes (MeshFilter[] meshFilters, List<string> tagMask, LayerMask layerMask) {
var filtered = new List<MeshFilter>(meshFilters.Length / 3);
for (int i = 0; i < meshFilters.Length; i++) {
MeshFilter filter = meshFilters[i];
Renderer rend = filter.GetComponent<Renderer>();
if (rend != null && filter.sharedMesh != null && rend.enabled && (((1 << filter.gameObject.layer) & layerMask) != 0 || tagMask.Contains(filter.tag))) {
if (filter.GetComponent<RecastMeshObj>() == null) {
filtered.Add(filter);
}
}
}
return filtered;
}
public void CollectSceneMeshes (List<RasterizationMesh> meshes) {
if (tagMask.Count > 0 || mask != 0) {
// This is unfortunately the fastest way to find all mesh filters.. and it is not particularly fast.
var meshFilters = GameObject.FindObjectsOfType<MeshFilter>();
var filteredMeshes = FilterMeshes(meshFilters, tagMask, mask);
var cachedVertices = new Dictionary<Mesh, Vector3[]>();
var cachedTris = new Dictionary<Mesh, int[]>();
bool containedStatic = false;
for (int i = 0; i < filteredMeshes.Count; i++) {
MeshFilter filter = filteredMeshes[i];
// Note, guaranteed to have a renderer
Renderer rend = filter.GetComponent<Renderer>();
if (rend.isPartOfStaticBatch) {
// Statically batched meshes cannot be used due to Unity limitations
// log a warning about this
containedStatic = true;
} else {
// Only include it if it intersects with the graph
if (rend.bounds.Intersects(bounds)) {
Mesh mesh = filter.sharedMesh;
RasterizationMesh smesh;
// Check the cache to avoid allocating
// a new array unless necessary
if (cachedVertices.ContainsKey(mesh)) {
smesh = new RasterizationMesh(cachedVertices[mesh], cachedTris[mesh], rend.bounds);
} else {
smesh = new RasterizationMesh(mesh.vertices, mesh.triangles, rend.bounds);
cachedVertices[mesh] = smesh.vertices;
cachedTris[mesh] = smesh.triangles;
}
smesh.matrix = rend.localToWorldMatrix;
smesh.original = filter;
meshes.Add(smesh);
}
}
if (containedStatic)
Debug.LogWarning("Some meshes were statically batched. These meshes can not be used for navmesh calculation" +
" due to technical constraints.\nDuring runtime scripts cannot access the data of meshes which have been statically batched.\n" +
"One way to solve this problem is to use cached startup (Save & Load tab in the inspector) to only calculate the graph when the game is not playing.");
}
#if ASTARDEBUG
int y = 0;
foreach (RasterizationMesh smesh in meshes) {
y++;
Vector3[] vecs = smesh.vertices;
int[] tris = smesh.triangles;
for (int i = 0; i < tris.Length; i += 3) {
Vector3 p1 = smesh.matrix.MultiplyPoint3x4(vecs[tris[i+0]]);
Vector3 p2 = smesh.matrix.MultiplyPoint3x4(vecs[tris[i+1]]);
Vector3 p3 = smesh.matrix.MultiplyPoint3x4(vecs[tris[i+2]]);
Debug.DrawLine(p1, p2, Color.red, 1);
Debug.DrawLine(p2, p3, Color.red, 1);
Debug.DrawLine(p3, p1, Color.red, 1);
}
}
#endif
}
}
/** Find all relevant RecastMeshObj components and create ExtraMeshes for them */
public void CollectRecastMeshObjs (List<RasterizationMesh> buffer) {
var buffer2 = Util.ListPool<RecastMeshObj>.Claim();
// Get all recast mesh objects inside the bounds
RecastMeshObj.GetAllInBounds(buffer2, bounds);
var cachedVertices = new Dictionary<Mesh, Vector3[]>();
var cachedTris = new Dictionary<Mesh, int[]>();
// Create an RasterizationMesh object
// for each RecastMeshObj
for (int i = 0; i < buffer2.Count; i++) {
MeshFilter filter = buffer2[i].GetMeshFilter();
Renderer rend = filter != null ? filter.GetComponent<Renderer>() : null;
if (filter != null && rend != null) {
Mesh mesh = filter.sharedMesh;
RasterizationMesh smesh;
// Don't read the vertices and triangles from the
// mesh if we have seen the same mesh previously
if (cachedVertices.ContainsKey(mesh)) {
smesh = new RasterizationMesh(cachedVertices[mesh], cachedTris[mesh], rend.bounds);
} else {
smesh = new RasterizationMesh(mesh.vertices, mesh.triangles, rend.bounds);
cachedVertices[mesh] = smesh.vertices;
cachedTris[mesh] = smesh.triangles;
}
smesh.matrix = rend.localToWorldMatrix;
smesh.original = filter;
smesh.area = buffer2[i].area;
buffer.Add(smesh);
} else {
Collider coll = buffer2[i].GetCollider();
if (coll == null) {
Debug.LogError("RecastMeshObject ("+buffer2[i].gameObject.name +") didn't have a collider or MeshFilter+Renderer attached", buffer2[i].gameObject);
continue;
}
RasterizationMesh smesh = RasterizeCollider(coll);
// Make sure a valid RasterizationMesh was returned
if (smesh != null) {
smesh.area = buffer2[i].area;
buffer.Add(smesh);
}
}
}
// Clear cache to avoid memory leak
capsuleCache.Clear();
Util.ListPool<RecastMeshObj>.Release(ref buffer2);
}
public void CollectTerrainMeshes (bool rasterizeTrees, float desiredChunkSize, List<RasterizationMesh> result) {
// Find all terrains in the scene
var terrains = Terrain.activeTerrains;
if (terrains.Length > 0) {
// Loop through all terrains in the scene
for (int j = 0; j < terrains.Length; j++) {
if (terrains[j].terrainData == null) continue;
GenerateTerrainChunks(terrains[j], bounds, desiredChunkSize, result);
if (rasterizeTrees) {
// Rasterize all tree colliders on this terrain object
CollectTreeMeshes(terrains[j], result);
}
}
}
}
void GenerateTerrainChunks (Terrain terrain, Bounds bounds, float desiredChunkSize, List<RasterizationMesh> result) {
var terrainData = terrain.terrainData;
if (terrainData == null)
throw new System.ArgumentException("Terrain contains no terrain data");
Vector3 offset = terrain.GetPosition();
Vector3 center = offset + terrainData.size * 0.5F;
// Figure out the bounds of the terrain in world space
var terrainBounds = new Bounds(center, terrainData.size);
// Only include terrains which intersects the graph
if (!terrainBounds.Intersects(bounds))
return;
// Original heightmap size
int heightmapWidth = terrainData.heightmapWidth;
int heightmapDepth = terrainData.heightmapHeight;
// Sample the terrain heightmap
float[, ] heights = terrainData.GetHeights(0, 0, heightmapWidth, heightmapDepth);
Vector3 sampleSize = terrainData.heightmapScale;
sampleSize.y = terrainData.size.y;
// Make chunks at least 12 quads wide
// since too small chunks just decreases performance due
// to the overhead of checking for bounds and similar things
const int MinChunkSize = 12;
// Find the number of samples along each edge that corresponds to a world size of desiredChunkSize
// Then round up to the nearest multiple of terrainSampleSize
var chunkSizeAlongX = Mathf.CeilToInt(Mathf.Max(desiredChunkSize / (sampleSize.x * terrainSampleSize), MinChunkSize)) * terrainSampleSize;
var chunkSizeAlongZ = Mathf.CeilToInt(Mathf.Max(desiredChunkSize / (sampleSize.z * terrainSampleSize), MinChunkSize)) * terrainSampleSize;
for (int z = 0; z < heightmapDepth; z += chunkSizeAlongZ) {
for (int x = 0; x < heightmapWidth; x += chunkSizeAlongX) {
var width = Mathf.Min(chunkSizeAlongX, heightmapWidth - x);
var depth = Mathf.Min(chunkSizeAlongZ, heightmapDepth - z);
var chunkMin = offset + new Vector3(z * sampleSize.x, 0, x * sampleSize.z);
var chunkMax = offset + new Vector3((z + depth) * sampleSize.x, sampleSize.y, (x + width) * sampleSize.z);
var chunkBounds = new Bounds();
chunkBounds.SetMinMax(chunkMin, chunkMax);
// Skip chunks that are not inside the desired bounds
if (chunkBounds.Intersects(bounds)) {
var chunk = GenerateHeightmapChunk(heights, sampleSize, offset, x, z, width, depth, terrainSampleSize);
result.Add(chunk);
}
}
}
}
/** Returns ceil(lhs/rhs), i.e lhs/rhs rounded up */
static int CeilDivision (int lhs, int rhs) {
return (lhs + rhs - 1)/rhs;
}
/** Generates a terrain chunk mesh */
RasterizationMesh GenerateHeightmapChunk (float[, ] heights, Vector3 sampleSize, Vector3 offset, int x0, int z0, int width, int depth, int stride) {
// Downsample to a smaller mesh (full resolution will take a long time to rasterize)
// Round up the width to the nearest multiple of terrainSampleSize and then add 1
// (off by one because there are vertices at the edge of the mesh)
int resultWidth = CeilDivision(width, terrainSampleSize) + 1;
int resultDepth = CeilDivision(depth, terrainSampleSize) + 1;
var heightmapWidth = heights.GetLength(0);
var heightmapDepth = heights.GetLength(1);
// Create a mesh from the heightmap
var numVerts = resultWidth * resultDepth;
var terrainVertices = Util.ArrayPool<Vector3>.Claim(numVerts);
// Create lots of vertices
for (int z = 0; z < resultDepth; z++) {
for (int x = 0; x < resultWidth; x++) {
int sampleX = Math.Min(x0 + x*stride, heightmapWidth-1);
int sampleZ = Math.Min(z0 + z*stride, heightmapDepth-1);
terrainVertices[z*resultWidth + x] = new Vector3(sampleZ * sampleSize.x, heights[sampleX, sampleZ]*sampleSize.y, sampleX * sampleSize.z) + offset;
}
}
// Create the mesh by creating triangles in a grid like pattern
int numTris = (resultWidth-1)*(resultDepth-1)*2*3;
var tris = Util.ArrayPool<int>.Claim(numTris);
int triangleIndex = 0;
for (int z = 0; z < resultDepth-1; z++) {
for (int x = 0; x < resultWidth-1; x++) {
tris[triangleIndex] = z*resultWidth + x;
tris[triangleIndex+1] = z*resultWidth + x+1;
tris[triangleIndex+2] = (z+1)*resultWidth + x+1;
triangleIndex += 3;
tris[triangleIndex] = z*resultWidth + x;
tris[triangleIndex+1] = (z+1)*resultWidth + x+1;
tris[triangleIndex+2] = (z+1)*resultWidth + x;
triangleIndex += 3;
}
}
#if ASTARDEBUG
var color = AstarMath.IntToColor(x0 + 7 * z0, 0.7f);
for (int i = 0; i < numTris; i += 3) {
Debug.DrawLine(terrainVertices[tris[i]], terrainVertices[tris[i+1]], color, 40);
Debug.DrawLine(terrainVertices[tris[i+1]], terrainVertices[tris[i+2]], color, 40);
Debug.DrawLine(terrainVertices[tris[i+2]], terrainVertices[tris[i]], color, 40);
}
#endif
var mesh = new RasterizationMesh(terrainVertices, tris, new Bounds());
mesh.numVertices = numVerts;
mesh.numTriangles = numTris;
mesh.pool = true;
// Could probably calculate these bounds in a faster way
mesh.RecalculateBounds();
return mesh;
}
void CollectTreeMeshes (Terrain terrain, List<RasterizationMesh> result) {
TerrainData data = terrain.terrainData;
for (int i = 0; i < data.treeInstances.Length; i++) {
TreeInstance instance = data.treeInstances[i];
TreePrototype prot = data.treePrototypes[instance.prototypeIndex];
// Make sure that the tree prefab exists
if (prot.prefab == null) {
continue;
}
var collider = prot.prefab.GetComponent<Collider>();
var treePosition = terrain.transform.position + Vector3.Scale(instance.position, data.size);
if (collider == null) {
var instanceBounds = new Bounds(terrain.transform.position + Vector3.Scale(instance.position, data.size), new Vector3(instance.widthScale, instance.heightScale, instance.widthScale));
Matrix4x4 matrix = Matrix4x4.TRS(treePosition, Quaternion.identity, new Vector3(instance.widthScale, instance.heightScale, instance.widthScale)*0.5f);
var mesh = new RasterizationMesh(BoxColliderVerts, BoxColliderTris, instanceBounds, matrix);
result.Add(mesh);
} else {
// The prefab has a collider, use that instead
var scale = new Vector3(instance.widthScale, instance.heightScale, instance.widthScale);
// Generate a mesh from the collider
RasterizationMesh mesh = RasterizeCollider(collider, Matrix4x4.TRS(treePosition, Quaternion.identity, scale));
// Make sure a valid mesh was generated
if (mesh != null) {
// The bounds are incorrectly based on collider.bounds.
// It is incorrect because the collider is on the prefab, not on the tree instance
// so we need to recalculate the bounds based on the actual vertex positions
mesh.RecalculateBounds();
result.Add(mesh);
}
}
}
}
public void CollectColliderMeshes (List<RasterizationMesh> result) {
/** \todo Use Physics.OverlapBox on newer Unity versions */
// Find all colliders that could possibly be inside the bounds
var colls = Physics.OverlapSphere(bounds.center, bounds.size.magnitude, -1, QueryTriggerInteraction.Ignore);
if (tagMask.Count > 0 || mask != 0) {
for (int i = 0; i < colls.Length; i++) {
Collider collider = colls[i];
if ((((mask >> collider.gameObject.layer) & 1) != 0 || tagMask.Contains(collider.tag)) && collider.enabled && !collider.isTrigger && collider.bounds.Intersects(bounds) && collider.GetComponent<RecastMeshObj>() == null) {
RasterizationMesh emesh = RasterizeCollider(collider);
//Make sure a valid RasterizationMesh was returned
if (emesh != null)
result.Add(emesh);
}
}
}
// Clear cache to avoid memory leak
capsuleCache.Clear();
}
/** Box Collider triangle indices can be reused for multiple instances.
* \warning This array should never be changed
*/
private readonly static int[] BoxColliderTris = {
0, 1, 2,
0, 2, 3,
6, 5, 4,
7, 6, 4,
0, 5, 1,
0, 4, 5,
1, 6, 2,
1, 5, 6,
2, 7, 3,
2, 6, 7,
3, 4, 0,
3, 7, 4
};
/** Box Collider vertices can be reused for multiple instances.
* \warning This array should never be changed
*/
private readonly static Vector3[] BoxColliderVerts = {
new Vector3(-1, -1, -1),
new Vector3(1, -1, -1),
new Vector3(1, -1, 1),
new Vector3(-1, -1, 1),
new Vector3(-1, 1, -1),
new Vector3(1, 1, -1),
new Vector3(1, 1, 1),
new Vector3(-1, 1, 1),
};
/** Holds meshes for capsules to avoid generating duplicate capsule meshes for identical capsules */
private List<CapsuleCache> capsuleCache = new List<CapsuleCache>();
class CapsuleCache {
public int rows;
public float height;
public Vector3[] verts;
public int[] tris;
}
/** Rasterizes a collider to a mesh.
* This will pass the col.transform.localToWorldMatrix to the other overload of this function.
*/
RasterizationMesh RasterizeCollider (Collider col) {
return RasterizeCollider(col, col.transform.localToWorldMatrix);
}
/** Rasterizes a collider to a mesh assuming it's vertices should be multiplied with the matrix.
* Note that the bounds of the returned RasterizationMesh is based on collider.bounds. So you might want to
* call myExtraMesh.RecalculateBounds on the returned mesh to recalculate it if the collider.bounds would
* not give the correct value.
*/
RasterizationMesh RasterizeCollider (Collider col, Matrix4x4 localToWorldMatrix) {
RasterizationMesh result = null;
if (col is BoxCollider) {
result = RasterizeBoxCollider(col as BoxCollider, localToWorldMatrix);
} else if (col is SphereCollider || col is CapsuleCollider) {
var scollider = col as SphereCollider;
var ccollider = col as CapsuleCollider;
float radius = (scollider != null ? scollider.radius : ccollider.radius);
float height = scollider != null ? 0 : (ccollider.height*0.5f/radius) - 1;
Quaternion rot = Quaternion.identity;
// Capsule colliders can be aligned along the X, Y or Z axis
if (ccollider != null) rot = Quaternion.Euler(ccollider.direction == 2 ? 90 : 0, 0, ccollider.direction == 0 ? 90 : 0);
Matrix4x4 matrix = Matrix4x4.TRS(scollider != null ? scollider.center : ccollider.center, rot, Vector3.one*radius);
matrix = localToWorldMatrix * matrix;
result = RasterizeCapsuleCollider(radius, height, col.bounds, matrix);
} else if (col is MeshCollider) {
var collider = col as MeshCollider;
if (collider.sharedMesh != null) {
result = new RasterizationMesh(collider.sharedMesh.vertices, collider.sharedMesh.triangles, collider.bounds, localToWorldMatrix);
}
}
#if ASTARDEBUG
for (int i = 0; i < result.triangles.Length; i += 3) {
Debug.DrawLine(result.matrix.MultiplyPoint3x4(result.vertices[result.triangles[i]]), result.matrix.MultiplyPoint3x4(result.vertices[result.triangles[i+1]]), Color.yellow);
Debug.DrawLine(result.matrix.MultiplyPoint3x4(result.vertices[result.triangles[i+2]]), result.matrix.MultiplyPoint3x4(result.vertices[result.triangles[i+1]]), Color.yellow);
Debug.DrawLine(result.matrix.MultiplyPoint3x4(result.vertices[result.triangles[i]]), result.matrix.MultiplyPoint3x4(result.vertices[result.triangles[i+2]]), Color.yellow);
}
#endif
return result;
}
RasterizationMesh RasterizeBoxCollider (BoxCollider collider, Matrix4x4 localToWorldMatrix) {
Matrix4x4 matrix = Matrix4x4.TRS(collider.center, Quaternion.identity, collider.size*0.5f);
matrix = localToWorldMatrix * matrix;
return new RasterizationMesh(BoxColliderVerts, BoxColliderTris, collider.bounds, matrix);
}
RasterizationMesh RasterizeCapsuleCollider (float radius, float height, Bounds bounds, Matrix4x4 localToWorldMatrix) {
// Calculate the number of rows to use
// grows as sqrt(x) to the radius of the sphere/capsule which I have found works quite well
int rows = Mathf.Max(4, Mathf.RoundToInt(colliderRasterizeDetail*Mathf.Sqrt(localToWorldMatrix.MultiplyVector(Vector3.one).magnitude)));
if (rows > 100) {
Debug.LogWarning("Very large detail for some collider meshes. Consider decreasing Collider Rasterize Detail (RecastGraph)");
}
int cols = rows;
Vector3[] verts;
int[] trisArr;
// Check if we have already calculated a similar capsule
CapsuleCache cached = null;
for (int i = 0; i < capsuleCache.Count; i++) {
CapsuleCache c = capsuleCache[i];
if (c.rows == rows && Mathf.Approximately(c.height, height)) {
cached = c;
}
}
if (cached == null) {
// Generate a sphere/capsule mesh
verts = new Vector3[(rows)*cols + 2];
var tris = new List<int>();
verts[verts.Length-1] = Vector3.up;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
verts[c + r*cols] = new Vector3(Mathf.Cos(c*Mathf.PI*2/cols)*Mathf.Sin((r*Mathf.PI/(rows-1))), Mathf.Cos((r*Mathf.PI/(rows-1))) + (r < rows/2 ? height : -height), Mathf.Sin(c*Mathf.PI*2/cols)*Mathf.Sin((r*Mathf.PI/(rows-1))));
}
}
verts[verts.Length-2] = Vector3.down;
for (int i = 0, j = cols-1; i < cols; j = i++) {
tris.Add(verts.Length-1);
tris.Add(0*cols + j);
tris.Add(0*cols + i);
}
for (int r = 1; r < rows; r++) {
for (int i = 0, j = cols-1; i < cols; j = i++) {
tris.Add(r*cols + i);
tris.Add(r*cols + j);
tris.Add((r-1)*cols + i);
tris.Add((r-1)*cols + j);
tris.Add((r-1)*cols + i);
tris.Add(r*cols + j);
}
}
for (int i = 0, j = cols-1; i < cols; j = i++) {
tris.Add(verts.Length-2);
tris.Add((rows-1)*cols + j);
tris.Add((rows-1)*cols + i);
}
// Add calculated mesh to the cache
cached = new CapsuleCache();
cached.rows = rows;
cached.height = height;
cached.verts = verts;
cached.tris = tris.ToArray();
capsuleCache.Add(cached);
}
// Read from cache
verts = cached.verts;
trisArr = cached.tris;
return new RasterizationMesh(verts, trisArr, bounds, localToWorldMatrix);
}
}
}
| |
// Copyright (C) 2007 A.J.Bauer
//
// This software is provided as-is, without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. if you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// -----------------------------------------------------------------------------------
// Copyright (C) 2012 Code Artist
//
// Added several improvement to original code created by A.J.Bauer.
// Visit: http://codearteng.blogspot.com for more information on change history.
//
// -----------------------------------------------------------------------------------
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
namespace System.Windows.Forms
{
/// <summary>
/// <para>AGauge - Copyright (C) 2007 A.J.Bauer</para>
/// <link>http://www.codeproject.com/Articles/17559/A-fast-and-performing-gauge</link>
/// </summary>
[ToolboxBitmap(typeof (AGauge), "AGauge.AGauge.bmp"),
DefaultEvent("ValueInRangeChanged"),
Description("Displays a value on an analog gauge. Raises an event if the value enters one of the definable ranges."
)]
public partial class AGauge : Control
{
#region Private Fields
private Boolean drawGaugeBackground = true;
private Single fontBoundY1;
private Single fontBoundY2;
private Bitmap gaugeBitmap;
private Color m_BaseArcColor = Color.Gray;
private Int32 m_BaseArcRadius = 80;
private Int32 m_BaseArcStart = 135;
private Int32 m_BaseArcSweep = 270;
private Int32 m_BaseArcWidth = 2;
private Point m_Center = new Point(100, 100);
private Single m_MaxValue = 400;
private Single m_MinValue = -100;
private AGaugeNeedleColor m_NeedleColor1 = AGaugeNeedleColor.Gray;
private Color m_NeedleColor2 = Color.DimGray;
private Int32 m_NeedleRadius = 80;
private NeedleType m_NeedleType;
private Int32 m_NeedleWidth = 2;
private Color m_ScaleLinesInterColor = Color.Black;
private Int32 m_ScaleLinesInterInnerRadius = 73;
private Int32 m_ScaleLinesInterOuterRadius = 80;
private Int32 m_ScaleLinesInterWidth = 1;
private Color m_ScaleLinesMajorColor = Color.Black;
private Int32 m_ScaleLinesMajorInnerRadius = 70;
private Int32 m_ScaleLinesMajorOuterRadius = 80;
private Single m_ScaleLinesMajorStepValue = 50.0f;
private Int32 m_ScaleLinesMajorWidth = 2;
private Color m_ScaleLinesMinorColor = Color.Gray;
private Int32 m_ScaleLinesMinorInnerRadius = 75;
private Int32 m_ScaleLinesMinorOuterRadius = 80;
private Int32 m_ScaleLinesMinorTicks = 9;
private Int32 m_ScaleLinesMinorWidth = 1;
private Color m_ScaleNumbersColor = Color.Black;
private String m_ScaleNumbersFormat;
private Int32 m_ScaleNumbersRadius = 95;
private Int32 m_ScaleNumbersRotation;
private Int32 m_ScaleNumbersStartScaleLine;
private Int32 m_ScaleNumbersStepScaleLines = 1;
private Single m_value;
#endregion
#region EventHandler
[Description("This event is raised when gauge value changed.")]
public event EventHandler ValueChanged;
private void OnValueChanged()
{
EventHandler e = ValueChanged;
if (e != null) e(this, null);
}
[Description("This event is raised if the value is entering or leaving defined range.")]
public event EventHandler<ValueInRangeChangedEventArgs> ValueInRangeChanged;
private void OnValueInRangeChanged(AGaugeRange range, Single value)
{
EventHandler<ValueInRangeChangedEventArgs> e = ValueInRangeChanged;
if (e != null) e(this, new ValueInRangeChangedEventArgs(range, value, range.InRange));
}
#endregion
#region Hidden and overridden inherited properties
public new Boolean AllowDrop
{
get { return false; }
set
{
/*Do Nothing */
}
}
public new Boolean AutoSize
{
get { return false; }
set
{
/*Do Nothing */
}
}
public new Boolean ForeColor
{
get { return false; }
set
{
/*Do Nothing */
}
}
public new Boolean ImeMode
{
get { return false; }
set
{
/*Do Nothing */
}
}
public override Color BackColor
{
get { return base.BackColor; }
set
{
base.BackColor = value;
drawGaugeBackground = true;
Refresh();
}
}
public override Font Font
{
get { return base.Font; }
set
{
base.Font = value;
drawGaugeBackground = true;
Refresh();
}
}
public override ImageLayout BackgroundImageLayout
{
get { return base.BackgroundImageLayout; }
set
{
base.BackgroundImageLayout = value;
drawGaugeBackground = true;
Refresh();
}
}
#endregion
public AGauge()
{
InitializeComponent();
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
_GaugeRanges = new AGaugeRangeCollection(this);
_GaugeLabels = new AGaugeLabelCollection(this);
//Default Values
Size = new Size(205, 180);
}
#region Properties
private readonly AGaugeLabelCollection _GaugeLabels;
private readonly AGaugeRangeCollection _GaugeRanges;
#region << Gauge Base >>
[Browsable(true),
Category("AGauge"),
Description("The center of the gauge (in the control's client area).")]
public Point Center
{
get { return m_Center; }
set
{
if (m_Center != value)
{
m_Center = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The color of the base arc.")]
public Color BaseArcColor
{
get { return m_BaseArcColor; }
set
{
if (m_BaseArcColor != value)
{
m_BaseArcColor = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The radius of the base arc.")]
public Int32 BaseArcRadius
{
get { return m_BaseArcRadius; }
set
{
if (m_BaseArcRadius != value)
{
m_BaseArcRadius = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The start angle of the base arc.")]
public Int32 BaseArcStart
{
get { return m_BaseArcStart; }
set
{
if (m_BaseArcStart != value)
{
m_BaseArcStart = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The sweep angle of the base arc.")]
public Int32 BaseArcSweep
{
get { return m_BaseArcSweep; }
set
{
if (m_BaseArcSweep != value)
{
m_BaseArcSweep = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The width of the base arc.")]
public Int32 BaseArcWidth
{
get { return m_BaseArcWidth; }
set
{
if (m_BaseArcWidth != value)
{
m_BaseArcWidth = value;
drawGaugeBackground = true;
Refresh();
}
}
}
#endregion
#region << Gauge Scale >>
[Browsable(true),
Category("AGauge"),
Description("The minimum value to show on the scale.")]
public Single MinValue
{
get { return m_MinValue; }
set
{
if ((m_MinValue != value) && (value < m_MaxValue))
{
m_MinValue = value;
m_value = Math.Min(Math.Max(m_value, m_MinValue), m_MaxValue);
m_ScaleLinesMajorStepValue = Math.Min(m_ScaleLinesMajorStepValue, m_MaxValue - m_MinValue);
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The maximum value to show on the scale.")]
public Single MaxValue
{
get { return m_MaxValue; }
set
{
if ((m_MaxValue != value) && (value > m_MinValue))
{
m_MaxValue = value;
m_value = Math.Min(Math.Max(m_value, m_MinValue), m_MaxValue);
m_ScaleLinesMajorStepValue = Math.Min(m_ScaleLinesMajorStepValue, m_MaxValue - m_MinValue);
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description(
"The color of the inter scale lines which are the middle scale lines for an uneven number of minor scale lines."
)]
public Color ScaleLinesInterColor
{
get { return m_ScaleLinesInterColor; }
set
{
if (m_ScaleLinesInterColor != value)
{
m_ScaleLinesInterColor = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description(
"The inner radius of the inter scale lines which are the middle scale lines for an uneven number of minor scale lines."
)]
public Int32 ScaleLinesInterInnerRadius
{
get { return m_ScaleLinesInterInnerRadius; }
set
{
if (m_ScaleLinesInterInnerRadius != value)
{
m_ScaleLinesInterInnerRadius = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description(
"The outer radius of the inter scale lines which are the middle scale lines for an uneven number of minor scale lines."
)]
public Int32 ScaleLinesInterOuterRadius
{
get { return m_ScaleLinesInterOuterRadius; }
set
{
if (m_ScaleLinesInterOuterRadius != value)
{
m_ScaleLinesInterOuterRadius = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description(
"The width of the inter scale lines which are the middle scale lines for an uneven number of minor scale lines."
)]
public Int32 ScaleLinesInterWidth
{
get { return m_ScaleLinesInterWidth; }
set
{
if (m_ScaleLinesInterWidth != value)
{
m_ScaleLinesInterWidth = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The number of minor scale lines.")]
public Int32 ScaleLinesMinorTicks
{
get { return m_ScaleLinesMinorTicks; }
set
{
if (m_ScaleLinesMinorTicks != value)
{
m_ScaleLinesMinorTicks = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The color of the minor scale lines.")]
public Color ScaleLinesMinorColor
{
get { return m_ScaleLinesMinorColor; }
set
{
if (m_ScaleLinesMinorColor != value)
{
m_ScaleLinesMinorColor = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The inner radius of the minor scale lines.")]
public Int32 ScaleLinesMinorInnerRadius
{
get { return m_ScaleLinesMinorInnerRadius; }
set
{
if (m_ScaleLinesMinorInnerRadius != value)
{
m_ScaleLinesMinorInnerRadius = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The outer radius of the minor scale lines.")]
public Int32 ScaleLinesMinorOuterRadius
{
get { return m_ScaleLinesMinorOuterRadius; }
set
{
if (m_ScaleLinesMinorOuterRadius != value)
{
m_ScaleLinesMinorOuterRadius = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The width of the minor scale lines.")]
public Int32 ScaleLinesMinorWidth
{
get { return m_ScaleLinesMinorWidth; }
set
{
if (m_ScaleLinesMinorWidth != value)
{
m_ScaleLinesMinorWidth = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The step value of the major scale lines.")]
public Single ScaleLinesMajorStepValue
{
get { return m_ScaleLinesMajorStepValue; }
set
{
if ((m_ScaleLinesMajorStepValue != value) && (value > 0))
{
m_ScaleLinesMajorStepValue = Math.Min(value, m_MaxValue - m_MinValue);
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The color of the major scale lines.")]
public Color ScaleLinesMajorColor
{
get { return m_ScaleLinesMajorColor; }
set
{
if (m_ScaleLinesMajorColor != value)
{
m_ScaleLinesMajorColor = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The inner radius of the major scale lines.")]
public Int32 ScaleLinesMajorInnerRadius
{
get { return m_ScaleLinesMajorInnerRadius; }
set
{
if (m_ScaleLinesMajorInnerRadius != value)
{
m_ScaleLinesMajorInnerRadius = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The outer radius of the major scale lines.")]
public Int32 ScaleLinesMajorOuterRadius
{
get { return m_ScaleLinesMajorOuterRadius; }
set
{
if (m_ScaleLinesMajorOuterRadius != value)
{
m_ScaleLinesMajorOuterRadius = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The width of the major scale lines.")]
public Int32 ScaleLinesMajorWidth
{
get { return m_ScaleLinesMajorWidth; }
set
{
if (m_ScaleLinesMajorWidth != value)
{
m_ScaleLinesMajorWidth = value;
drawGaugeBackground = true;
Refresh();
}
}
}
#endregion
#region << Gauge Scale Numbers >>
[Browsable(true),
Category("AGauge"),
Description("The radius of the scale numbers.")]
public Int32 ScaleNumbersRadius
{
get { return m_ScaleNumbersRadius; }
set
{
if (m_ScaleNumbersRadius != value)
{
m_ScaleNumbersRadius = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The color of the scale numbers.")]
public Color ScaleNumbersColor
{
get { return m_ScaleNumbersColor; }
set
{
if (m_ScaleNumbersColor != value)
{
m_ScaleNumbersColor = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The format of the scale numbers.")]
public String ScaleNumbersFormat
{
get { return m_ScaleNumbersFormat; }
set
{
if (m_ScaleNumbersFormat != value)
{
m_ScaleNumbersFormat = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The number of the scale line to start writing numbers next to.")]
public Int32 ScaleNumbersStartScaleLine
{
get { return m_ScaleNumbersStartScaleLine; }
set
{
if (m_ScaleNumbersStartScaleLine != value)
{
m_ScaleNumbersStartScaleLine = Math.Max(value, 1);
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The number of scale line steps for writing numbers.")]
public Int32 ScaleNumbersStepScaleLines
{
get { return m_ScaleNumbersStepScaleLines; }
set
{
if (m_ScaleNumbersStepScaleLines != value)
{
m_ScaleNumbersStepScaleLines = Math.Max(value, 1);
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description(
"The angle relative to the tangent of the base arc at a scale line that is used to rotate numbers. set to 0 for no rotation or e.g. set to 90."
)]
public Int32 ScaleNumbersRotation
{
get { return m_ScaleNumbersRotation; }
set
{
if (m_ScaleNumbersRotation != value)
{
m_ScaleNumbersRotation = value;
drawGaugeBackground = true;
Refresh();
}
}
}
#endregion
#region << Gauge Needle >>
[Browsable(true),
Category("AGauge"),
Description(
"The type of the needle, currently only type 0 and 1 are supported. Type 0 looks nicers but if you experience performance problems you might consider using type 1."
)]
public NeedleType NeedleType
{
get { return m_NeedleType; }
set
{
if (m_NeedleType != value)
{
m_NeedleType = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The radius of the needle.")]
public Int32 NeedleRadius
{
get { return m_NeedleRadius; }
set
{
if (m_NeedleRadius != value)
{
m_NeedleRadius = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The first color of the needle.")]
public AGaugeNeedleColor NeedleColor1
{
get { return m_NeedleColor1; }
set
{
if (m_NeedleColor1 != value)
{
m_NeedleColor1 = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The second color of the needle.")]
public Color NeedleColor2
{
get { return m_NeedleColor2; }
set
{
if (m_NeedleColor2 != value)
{
m_NeedleColor2 = value;
drawGaugeBackground = true;
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("The width of the needle.")]
public Int32 NeedleWidth
{
get { return m_NeedleWidth; }
set
{
if (m_NeedleWidth != value)
{
m_NeedleWidth = value;
drawGaugeBackground = true;
Refresh();
}
}
}
#endregion
[Browsable(true),
Category("AGauge"),
Description("Gauge value.")]
public Single Value
{
get { return m_value; }
set
{
value = Math.Min(Math.Max(value, m_MinValue), m_MaxValue);
if (m_value != value)
{
m_value = value;
OnValueChanged();
if (DesignMode) drawGaugeBackground = true;
foreach (AGaugeRange ptrRange in _GaugeRanges)
{
if ((m_value >= ptrRange.StartValue)
&& (m_value <= ptrRange.EndValue))
{
//Entering Range
if (!ptrRange.InRange)
{
ptrRange.InRange = true;
OnValueInRangeChanged(ptrRange, m_value);
}
}
else
{
//Leaving Range
if (ptrRange.InRange)
{
ptrRange.InRange = false;
OnValueInRangeChanged(ptrRange, m_value);
}
}
}
Refresh();
}
}
}
[Browsable(true),
Category("AGauge"),
Description("Gauge Ranges.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public AGaugeRangeCollection GaugeRanges
{
get { return _GaugeRanges; }
}
[Browsable(true),
Category("AGauge"),
Description("Gauge Labels.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public AGaugeLabelCollection GaugeLabels
{
get { return _GaugeLabels; }
}
#endregion
#region Helper
private void FindFontBounds()
{
//find upper and lower bounds for numeric characters
Int32 c1;
Int32 c2;
Boolean boundfound;
Bitmap b;
Graphics g;
var backBrush = new SolidBrush(Color.White);
var foreBrush = new SolidBrush(Color.Black);
SizeF boundingBox;
b = new Bitmap(5, 5);
g = Graphics.FromImage(b);
boundingBox = g.MeasureString("0123456789", Font, -1, StringFormat.GenericTypographic);
b = new Bitmap((Int32) (boundingBox.Width), (Int32) (boundingBox.Height));
g = Graphics.FromImage(b);
g.FillRectangle(backBrush, 0.0F, 0.0F, boundingBox.Width, boundingBox.Height);
g.DrawString("0123456789", Font, foreBrush, 0.0F, 0.0F, StringFormat.GenericTypographic);
fontBoundY1 = 0;
fontBoundY2 = 0;
c1 = 0;
boundfound = false;
while ((c1 < b.Height) && (!boundfound))
{
c2 = 0;
while ((c2 < b.Width) && (!boundfound))
{
if (b.GetPixel(c2, c1) != backBrush.Color)
{
fontBoundY1 = c1;
boundfound = true;
}
c2++;
}
c1++;
}
c1 = b.Height - 1;
boundfound = false;
while ((0 < c1) && (!boundfound))
{
c2 = 0;
while ((c2 < b.Width) && (!boundfound))
{
if (b.GetPixel(c2, c1) != backBrush.Color)
{
fontBoundY2 = c1;
boundfound = true;
}
c2++;
}
c1--;
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public void RepaintControl()
{
drawGaugeBackground = true;
Refresh();
}
#endregion
#region Base member overrides
protected override void OnPaintBackground(PaintEventArgs pevent)
{
}
protected override void OnPaint(PaintEventArgs e)
{
if ((Width < 10) || (Height < 10))
{
return;
}
if (drawGaugeBackground)
{
drawGaugeBackground = false;
FindFontBounds();
gaugeBitmap = new Bitmap(Width, Height, e.Graphics);
Graphics ggr = Graphics.FromImage(gaugeBitmap);
ggr.FillRectangle(new SolidBrush(BackColor), ClientRectangle);
if (BackgroundImage != null)
{
switch (BackgroundImageLayout)
{
case ImageLayout.Center:
ggr.DrawImageUnscaled(BackgroundImage, Width/2 - BackgroundImage.Width/2,
Height/2 - BackgroundImage.Height/2);
break;
case ImageLayout.None:
ggr.DrawImageUnscaled(BackgroundImage, 0, 0);
break;
case ImageLayout.Stretch:
ggr.DrawImage(BackgroundImage, 0, 0, Width, Height);
break;
case ImageLayout.Tile:
Int32 pixelOffsetX = 0;
Int32 pixelOffsetY = 0;
while (pixelOffsetX < Width)
{
pixelOffsetY = 0;
while (pixelOffsetY < Height)
{
ggr.DrawImageUnscaled(BackgroundImage, pixelOffsetX, pixelOffsetY);
pixelOffsetY += BackgroundImage.Height;
}
pixelOffsetX += BackgroundImage.Width;
}
break;
case ImageLayout.Zoom:
if ((BackgroundImage.Width/Width) < (Single) (BackgroundImage.Height/Height))
{
ggr.DrawImage(BackgroundImage, 0, 0, Height, Height);
}
else
{
ggr.DrawImage(BackgroundImage, 0, 0, Width, Width);
}
break;
}
}
ggr.SmoothingMode = SmoothingMode.HighQuality;
ggr.PixelOffsetMode = PixelOffsetMode.HighQuality;
var gp = new GraphicsPath();
Single rangeStartAngle;
Single rangeSweepAngle;
foreach (AGaugeRange ptrRange in _GaugeRanges)
{
if (ptrRange.EndValue > ptrRange.StartValue)
{
rangeStartAngle = m_BaseArcStart +
(ptrRange.StartValue - m_MinValue)*m_BaseArcSweep/(m_MaxValue - m_MinValue);
rangeSweepAngle = (ptrRange.EndValue - ptrRange.StartValue)*m_BaseArcSweep/
(m_MaxValue - m_MinValue);
gp.Reset();
gp.AddPie(new Rectangle(m_Center.X - ptrRange.OuterRadius, m_Center.Y - ptrRange.OuterRadius,
2*ptrRange.OuterRadius, 2*ptrRange.OuterRadius), rangeStartAngle,
rangeSweepAngle);
gp.Reverse();
gp.AddPie(new Rectangle(m_Center.X - ptrRange.InnerRadius, m_Center.Y - ptrRange.InnerRadius,
2*ptrRange.InnerRadius, 2*ptrRange.InnerRadius), rangeStartAngle,
rangeSweepAngle);
gp.Reverse();
ggr.SetClip(gp);
ggr.FillPie(new SolidBrush(ptrRange.Color),
new Rectangle(m_Center.X - ptrRange.OuterRadius, m_Center.Y - ptrRange.OuterRadius,
2*ptrRange.OuterRadius, 2*ptrRange.OuterRadius), rangeStartAngle,
rangeSweepAngle);
}
}
ggr.SetClip(ClientRectangle);
if (m_BaseArcRadius > 0)
{
ggr.DrawArc(new Pen(m_BaseArcColor, m_BaseArcWidth),
new Rectangle(m_Center.X - m_BaseArcRadius, m_Center.Y - m_BaseArcRadius,
2*m_BaseArcRadius, 2*m_BaseArcRadius), m_BaseArcStart, m_BaseArcSweep);
}
String valueText = "";
SizeF boundingBox;
Single countValue = 0;
Int32 counter1 = 0;
while (countValue <= (m_MaxValue - m_MinValue))
{
valueText = (m_MinValue + countValue).ToString(m_ScaleNumbersFormat);
ggr.ResetTransform();
boundingBox = ggr.MeasureString(valueText, Font, -1, StringFormat.GenericTypographic);
gp.Reset();
gp.AddEllipse(new Rectangle(m_Center.X - m_ScaleLinesMajorOuterRadius,
m_Center.Y - m_ScaleLinesMajorOuterRadius,
2*m_ScaleLinesMajorOuterRadius, 2*m_ScaleLinesMajorOuterRadius));
gp.Reverse();
gp.AddEllipse(new Rectangle(m_Center.X - m_ScaleLinesMajorInnerRadius,
m_Center.Y - m_ScaleLinesMajorInnerRadius,
2*m_ScaleLinesMajorInnerRadius, 2*m_ScaleLinesMajorInnerRadius));
gp.Reverse();
ggr.SetClip(gp);
ggr.DrawLine(new Pen(m_ScaleLinesMajorColor, m_ScaleLinesMajorWidth),
(Center.X),
(Center.Y),
(Single)
(Center.X +
2*m_ScaleLinesMajorOuterRadius*
Math.Cos((m_BaseArcStart + countValue*m_BaseArcSweep/(m_MaxValue - m_MinValue))*
Math.PI/180.0)),
(Single)
(Center.Y +
2*m_ScaleLinesMajorOuterRadius*
Math.Sin((m_BaseArcStart + countValue*m_BaseArcSweep/(m_MaxValue - m_MinValue))*
Math.PI/180.0)));
gp.Reset();
gp.AddEllipse(new Rectangle(m_Center.X - m_ScaleLinesMinorOuterRadius,
m_Center.Y - m_ScaleLinesMinorOuterRadius,
2*m_ScaleLinesMinorOuterRadius, 2*m_ScaleLinesMinorOuterRadius));
gp.Reverse();
gp.AddEllipse(new Rectangle(m_Center.X - m_ScaleLinesMinorInnerRadius,
m_Center.Y - m_ScaleLinesMinorInnerRadius,
2*m_ScaleLinesMinorInnerRadius, 2*m_ScaleLinesMinorInnerRadius));
gp.Reverse();
ggr.SetClip(gp);
if (countValue < (m_MaxValue - m_MinValue))
{
for (Int32 counter2 = 1; counter2 <= m_ScaleLinesMinorTicks; counter2++)
{
if (((m_ScaleLinesMinorTicks%2) == 1) && ((m_ScaleLinesMinorTicks/2) + 1 == counter2))
{
gp.Reset();
gp.AddEllipse(new Rectangle(m_Center.X - m_ScaleLinesInterOuterRadius,
m_Center.Y - m_ScaleLinesInterOuterRadius,
2*m_ScaleLinesInterOuterRadius,
2*m_ScaleLinesInterOuterRadius));
gp.Reverse();
gp.AddEllipse(new Rectangle(m_Center.X - m_ScaleLinesInterInnerRadius,
m_Center.Y - m_ScaleLinesInterInnerRadius,
2*m_ScaleLinesInterInnerRadius,
2*m_ScaleLinesInterInnerRadius));
gp.Reverse();
ggr.SetClip(gp);
ggr.DrawLine(new Pen(m_ScaleLinesInterColor, m_ScaleLinesInterWidth),
(Center.X),
(Center.Y),
(Single)
(Center.X +
2*m_ScaleLinesInterOuterRadius*
Math.Cos((m_BaseArcStart +
countValue*m_BaseArcSweep/(m_MaxValue - m_MinValue) +
counter2*m_BaseArcSweep/
((((m_MaxValue - m_MinValue)/m_ScaleLinesMajorStepValue))*
(m_ScaleLinesMinorTicks + 1)))*Math.PI/180.0)),
(Single)
(Center.Y +
2*m_ScaleLinesInterOuterRadius*
Math.Sin((m_BaseArcStart +
countValue*m_BaseArcSweep/(m_MaxValue - m_MinValue) +
counter2*m_BaseArcSweep/
((((m_MaxValue - m_MinValue)/m_ScaleLinesMajorStepValue))*
(m_ScaleLinesMinorTicks + 1)))*Math.PI/180.0)));
gp.Reset();
gp.AddEllipse(new Rectangle(m_Center.X - m_ScaleLinesMinorOuterRadius,
m_Center.Y - m_ScaleLinesMinorOuterRadius,
2*m_ScaleLinesMinorOuterRadius,
2*m_ScaleLinesMinorOuterRadius));
gp.Reverse();
gp.AddEllipse(new Rectangle(m_Center.X - m_ScaleLinesMinorInnerRadius,
m_Center.Y - m_ScaleLinesMinorInnerRadius,
2*m_ScaleLinesMinorInnerRadius,
2*m_ScaleLinesMinorInnerRadius));
gp.Reverse();
ggr.SetClip(gp);
}
else
{
ggr.DrawLine(new Pen(m_ScaleLinesMinorColor, m_ScaleLinesMinorWidth),
(Center.X),
(Center.Y),
(Single)
(Center.X +
2*m_ScaleLinesMinorOuterRadius*
Math.Cos((m_BaseArcStart +
countValue*m_BaseArcSweep/(m_MaxValue - m_MinValue) +
counter2*m_BaseArcSweep/
((((m_MaxValue - m_MinValue)/m_ScaleLinesMajorStepValue))*
(m_ScaleLinesMinorTicks + 1)))*Math.PI/180.0)),
(Single)
(Center.Y +
2*m_ScaleLinesMinorOuterRadius*
Math.Sin((m_BaseArcStart +
countValue*m_BaseArcSweep/(m_MaxValue - m_MinValue) +
counter2*m_BaseArcSweep/
((((m_MaxValue - m_MinValue)/m_ScaleLinesMajorStepValue))*
(m_ScaleLinesMinorTicks + 1)))*Math.PI/180.0)));
}
}
}
ggr.SetClip(ClientRectangle);
if (m_ScaleNumbersRotation != 0)
{
ggr.TextRenderingHint = TextRenderingHint.AntiAlias;
ggr.RotateTransform(90.0F + m_BaseArcStart + countValue*m_BaseArcSweep/(m_MaxValue - m_MinValue));
}
ggr.TranslateTransform(
(Single)
(Center.X +
m_ScaleNumbersRadius*
Math.Cos((m_BaseArcStart + countValue*m_BaseArcSweep/(m_MaxValue - m_MinValue))*Math.PI/180.0f)),
(Single)
(Center.Y +
m_ScaleNumbersRadius*
Math.Sin((m_BaseArcStart + countValue*m_BaseArcSweep/(m_MaxValue - m_MinValue))*Math.PI/180.0f)),
MatrixOrder.Append);
if (counter1 >= ScaleNumbersStartScaleLine - 1)
{
ggr.DrawString(valueText, Font, new SolidBrush(m_ScaleNumbersColor), -boundingBox.Width/2,
-fontBoundY1 - (fontBoundY2 - fontBoundY1 + 1)/2, StringFormat.GenericTypographic);
}
countValue += m_ScaleLinesMajorStepValue;
counter1++;
}
ggr.ResetTransform();
ggr.SetClip(ClientRectangle);
if (m_ScaleNumbersRotation != 0)
{
ggr.TextRenderingHint = TextRenderingHint.SystemDefault;
}
foreach (AGaugeLabel ptrGaugeLabel in _GaugeLabels)
{
if (!String.IsNullOrEmpty(ptrGaugeLabel.Text))
ggr.DrawString(ptrGaugeLabel.Text, ptrGaugeLabel.Font, new SolidBrush(ptrGaugeLabel.Color),
ptrGaugeLabel.Position.X, ptrGaugeLabel.Position.Y,
StringFormat.GenericTypographic);
}
}
e.Graphics.DrawImageUnscaled(gaugeBitmap, 0, 0);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
Single brushAngle =
(Int32) (m_BaseArcStart + (m_value - m_MinValue)*m_BaseArcSweep/(m_MaxValue - m_MinValue))%360;
Double needleAngle = brushAngle*Math.PI/180;
switch (m_NeedleType)
{
case NeedleType.Advance:
var points = new PointF[3];
Brush brush1 = Brushes.White;
Brush brush2 = Brushes.White;
Brush brush3 = Brushes.White;
Brush brush4 = Brushes.White;
Brush brushBucket = Brushes.White;
var subcol = (Int32) (((brushAngle + 225)%180)*100/180);
var subcol2 = (Int32) (((brushAngle + 135)%180)*100/180);
e.Graphics.FillEllipse(new SolidBrush(m_NeedleColor2), Center.X - m_NeedleWidth*3,
Center.Y - m_NeedleWidth*3, m_NeedleWidth*6, m_NeedleWidth*6);
switch (m_NeedleColor1)
{
case AGaugeNeedleColor.Gray:
brush1 = new SolidBrush(Color.FromArgb(80 + subcol, 80 + subcol, 80 + subcol));
brush2 = new SolidBrush(Color.FromArgb(180 - subcol, 180 - subcol, 180 - subcol));
brush3 = new SolidBrush(Color.FromArgb(80 + subcol2, 80 + subcol2, 80 + subcol2));
brush4 = new SolidBrush(Color.FromArgb(180 - subcol2, 180 - subcol2, 180 - subcol2));
e.Graphics.DrawEllipse(Pens.Gray, Center.X - m_NeedleWidth*3, Center.Y - m_NeedleWidth*3,
m_NeedleWidth*6, m_NeedleWidth*6);
break;
case AGaugeNeedleColor.Red:
brush1 = new SolidBrush(Color.FromArgb(145 + subcol, subcol, subcol));
brush2 = new SolidBrush(Color.FromArgb(245 - subcol, 100 - subcol, 100 - subcol));
brush3 = new SolidBrush(Color.FromArgb(145 + subcol2, subcol2, subcol2));
brush4 = new SolidBrush(Color.FromArgb(245 - subcol2, 100 - subcol2, 100 - subcol2));
e.Graphics.DrawEllipse(Pens.Red, Center.X - m_NeedleWidth*3, Center.Y - m_NeedleWidth*3,
m_NeedleWidth*6, m_NeedleWidth*6);
break;
case AGaugeNeedleColor.Green:
brush1 = new SolidBrush(Color.FromArgb(subcol, 145 + subcol, subcol));
brush2 = new SolidBrush(Color.FromArgb(100 - subcol, 245 - subcol, 100 - subcol));
brush3 = new SolidBrush(Color.FromArgb(subcol2, 145 + subcol2, subcol2));
brush4 = new SolidBrush(Color.FromArgb(100 - subcol2, 245 - subcol2, 100 - subcol2));
e.Graphics.DrawEllipse(Pens.Green, Center.X - m_NeedleWidth*3, Center.Y - m_NeedleWidth*3,
m_NeedleWidth*6, m_NeedleWidth*6);
break;
case AGaugeNeedleColor.Blue:
brush1 = new SolidBrush(Color.FromArgb(subcol, subcol, 145 + subcol));
brush2 = new SolidBrush(Color.FromArgb(100 - subcol, 100 - subcol, 245 - subcol));
brush3 = new SolidBrush(Color.FromArgb(subcol2, subcol2, 145 + subcol2));
brush4 = new SolidBrush(Color.FromArgb(100 - subcol2, 100 - subcol2, 245 - subcol2));
e.Graphics.DrawEllipse(Pens.Blue, Center.X - m_NeedleWidth*3, Center.Y - m_NeedleWidth*3,
m_NeedleWidth*6, m_NeedleWidth*6);
break;
case AGaugeNeedleColor.Magenta:
brush1 = new SolidBrush(Color.FromArgb(subcol, 145 + subcol, 145 + subcol));
brush2 = new SolidBrush(Color.FromArgb(100 - subcol, 245 - subcol, 245 - subcol));
brush3 = new SolidBrush(Color.FromArgb(subcol2, 145 + subcol2, 145 + subcol2));
brush4 = new SolidBrush(Color.FromArgb(100 - subcol2, 245 - subcol2, 245 - subcol2));
e.Graphics.DrawEllipse(Pens.Magenta, Center.X - m_NeedleWidth*3, Center.Y - m_NeedleWidth*3,
m_NeedleWidth*6, m_NeedleWidth*6);
break;
case AGaugeNeedleColor.Violet:
brush1 = new SolidBrush(Color.FromArgb(145 + subcol, subcol, 145 + subcol));
brush2 = new SolidBrush(Color.FromArgb(245 - subcol, 100 - subcol, 245 - subcol));
brush3 = new SolidBrush(Color.FromArgb(145 + subcol2, subcol2, 145 + subcol2));
brush4 = new SolidBrush(Color.FromArgb(245 - subcol2, 100 - subcol2, 245 - subcol2));
e.Graphics.DrawEllipse(Pens.Violet, Center.X - m_NeedleWidth*3, Center.Y - m_NeedleWidth*3,
m_NeedleWidth*6, m_NeedleWidth*6);
break;
case AGaugeNeedleColor.Yellow:
brush1 = new SolidBrush(Color.FromArgb(145 + subcol, 145 + subcol, subcol));
brush2 = new SolidBrush(Color.FromArgb(245 - subcol, 245 - subcol, 100 - subcol));
brush3 = new SolidBrush(Color.FromArgb(145 + subcol2, 145 + subcol2, subcol2));
brush4 = new SolidBrush(Color.FromArgb(245 - subcol2, 245 - subcol2, 100 - subcol2));
e.Graphics.DrawEllipse(Pens.Violet, Center.X - m_NeedleWidth*3, Center.Y - m_NeedleWidth*3,
m_NeedleWidth*6, m_NeedleWidth*6);
break;
}
if (Math.Floor((Single) (((brushAngle + 225)%360)/180.0)) == 0)
{
brushBucket = brush1;
brush1 = brush2;
brush2 = brushBucket;
}
if (Math.Floor((Single) (((brushAngle + 135)%360)/180.0)) == 0)
{
brush4 = brush3;
}
points[0].X = (Single) (Center.X + m_NeedleRadius*Math.Cos(needleAngle));
points[0].Y = (Single) (Center.Y + m_NeedleRadius*Math.Sin(needleAngle));
points[1].X = (Single) (Center.X - m_NeedleRadius/20*Math.Cos(needleAngle));
points[1].Y = (Single) (Center.Y - m_NeedleRadius/20*Math.Sin(needleAngle));
points[2].X =
(Single)
(Center.X - m_NeedleRadius/5*Math.Cos(needleAngle) +
m_NeedleWidth*2*Math.Cos(needleAngle + Math.PI/2));
points[2].Y =
(Single)
(Center.Y - m_NeedleRadius/5*Math.Sin(needleAngle) +
m_NeedleWidth*2*Math.Sin(needleAngle + Math.PI/2));
e.Graphics.FillPolygon(brush1, points);
points[2].X =
(Single)
(Center.X - m_NeedleRadius/5*Math.Cos(needleAngle) +
m_NeedleWidth*2*Math.Cos(needleAngle - Math.PI/2));
points[2].Y =
(Single)
(Center.Y - m_NeedleRadius/5*Math.Sin(needleAngle) +
m_NeedleWidth*2*Math.Sin(needleAngle - Math.PI/2));
e.Graphics.FillPolygon(brush2, points);
points[0].X = (Single) (Center.X - (m_NeedleRadius/20 - 1)*Math.Cos(needleAngle));
points[0].Y = (Single) (Center.Y - (m_NeedleRadius/20 - 1)*Math.Sin(needleAngle));
points[1].X =
(Single)
(Center.X - m_NeedleRadius/5*Math.Cos(needleAngle) +
m_NeedleWidth*2*Math.Cos(needleAngle + Math.PI/2));
points[1].Y =
(Single)
(Center.Y - m_NeedleRadius/5*Math.Sin(needleAngle) +
m_NeedleWidth*2*Math.Sin(needleAngle + Math.PI/2));
points[2].X =
(Single)
(Center.X - m_NeedleRadius/5*Math.Cos(needleAngle) +
m_NeedleWidth*2*Math.Cos(needleAngle - Math.PI/2));
points[2].Y =
(Single)
(Center.Y - m_NeedleRadius/5*Math.Sin(needleAngle) +
m_NeedleWidth*2*Math.Sin(needleAngle - Math.PI/2));
e.Graphics.FillPolygon(brush4, points);
points[0].X = (Single) (Center.X - m_NeedleRadius/20*Math.Cos(needleAngle));
points[0].Y = (Single) (Center.Y - m_NeedleRadius/20*Math.Sin(needleAngle));
points[1].X = (Single) (Center.X + m_NeedleRadius*Math.Cos(needleAngle));
points[1].Y = (Single) (Center.Y + m_NeedleRadius*Math.Sin(needleAngle));
e.Graphics.DrawLine(new Pen(m_NeedleColor2), Center.X, Center.Y, points[0].X, points[0].Y);
e.Graphics.DrawLine(new Pen(m_NeedleColor2), Center.X, Center.Y, points[1].X, points[1].Y);
break;
case NeedleType.Simple:
var startPoint = new Point((Int32) (Center.X - m_NeedleRadius/8*Math.Cos(needleAngle)),
(Int32) (Center.Y - m_NeedleRadius/8*Math.Sin(needleAngle)));
var endPoint = new Point((Int32) (Center.X + m_NeedleRadius*Math.Cos(needleAngle)),
(Int32) (Center.Y + m_NeedleRadius*Math.Sin(needleAngle)));
e.Graphics.FillEllipse(new SolidBrush(m_NeedleColor2), Center.X - m_NeedleWidth*3,
Center.Y - m_NeedleWidth*3, m_NeedleWidth*6, m_NeedleWidth*6);
switch (m_NeedleColor1)
{
case AGaugeNeedleColor.Gray:
e.Graphics.DrawLine(new Pen(Color.DarkGray, m_NeedleWidth), Center.X, Center.Y, endPoint.X,
endPoint.Y);
e.Graphics.DrawLine(new Pen(Color.DarkGray, m_NeedleWidth), Center.X, Center.Y, startPoint.X,
startPoint.Y);
break;
case AGaugeNeedleColor.Red:
e.Graphics.DrawLine(new Pen(Color.Red, m_NeedleWidth), Center.X, Center.Y, endPoint.X,
endPoint.Y);
e.Graphics.DrawLine(new Pen(Color.Red, m_NeedleWidth), Center.X, Center.Y, startPoint.X,
startPoint.Y);
break;
case AGaugeNeedleColor.Green:
e.Graphics.DrawLine(new Pen(Color.Green, m_NeedleWidth), Center.X, Center.Y, endPoint.X,
endPoint.Y);
e.Graphics.DrawLine(new Pen(Color.Green, m_NeedleWidth), Center.X, Center.Y, startPoint.X,
startPoint.Y);
break;
case AGaugeNeedleColor.Blue:
e.Graphics.DrawLine(new Pen(Color.Blue, m_NeedleWidth), Center.X, Center.Y, endPoint.X,
endPoint.Y);
e.Graphics.DrawLine(new Pen(Color.Blue, m_NeedleWidth), Center.X, Center.Y, startPoint.X,
startPoint.Y);
break;
case AGaugeNeedleColor.Magenta:
e.Graphics.DrawLine(new Pen(Color.Magenta, m_NeedleWidth), Center.X, Center.Y, endPoint.X,
endPoint.Y);
e.Graphics.DrawLine(new Pen(Color.Magenta, m_NeedleWidth), Center.X, Center.Y, startPoint.X,
startPoint.Y);
break;
case AGaugeNeedleColor.Violet:
e.Graphics.DrawLine(new Pen(Color.Violet, m_NeedleWidth), Center.X, Center.Y, endPoint.X,
endPoint.Y);
e.Graphics.DrawLine(new Pen(Color.Violet, m_NeedleWidth), Center.X, Center.Y, startPoint.X,
startPoint.Y);
break;
case AGaugeNeedleColor.Yellow:
e.Graphics.DrawLine(new Pen(Color.Yellow, m_NeedleWidth), Center.X, Center.Y, endPoint.X,
endPoint.Y);
e.Graphics.DrawLine(new Pen(Color.Yellow, m_NeedleWidth), Center.X, Center.Y, startPoint.X,
startPoint.Y);
break;
}
break;
}
}
protected override void OnResize(EventArgs e)
{
drawGaugeBackground = true;
Refresh();
}
#endregion
}
#region[ Gauge Range ]
#endregion
#region [ Gauge Label ]
#endregion
#region [ Gauge Enum ]
#endregion
//Namespace Documentation
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using HttpServer.Authentication;
using HttpServer.Exceptions;
using HttpServer.FormDecoders;
using HttpServer.HttpModules;
using HttpServer.Rules;
using HttpServer.Sessions;
namespace HttpServer
{
/// <summary>
/// Delegate used to find a realm/domain.
/// </summary>
/// <param name="domain"></param>
/// <returns></returns>
/// <remarks>
/// Realms are used during HTTP Authentication
/// </remarks>
/// <seealso cref="AuthenticationModule"/>
/// <seealso cref="AuthenticationHandler"/>
public delegate string RealmHandler(string domain);
/// <summary>
/// A complete HTTP server, you need to add a module to it to be able to handle incoming requests.
/// </summary>
/// <example>
/// <code>
/// // this small example will add two web site modules, thus handling
/// // two different sites. In reality you should add Controller modules or something
/// // two the website modules to be able to handle different requests.
/// HttpServer server = new HttpServer();
/// server.Add(new WebSiteModule("www.gauffin.com", "Gauffin Telecom AB"));
/// server.Add(new WebSiteModule("www.vapadi.se", "Remote PBX"));
///
/// // start regular http
/// server.Start(IPAddress.Any, 80);
///
/// // start https
/// server.Start(IPAddress.Any, 443, myCertificate);
/// </code>
/// </example>
/// <seealso cref="HttpModule"/>
/// <seealso cref="FileModule"/>
/// <seealso cref="HttpListener"/>
public class HttpServer
{
private FormDecoderProvider _formDecodersProvider;
private readonly List<HttpModule> _modules = new List<HttpModule>();
private readonly List<IRule> _rules = new List<IRule>();
private readonly List<AuthenticationModule> _authModules = new List<AuthenticationModule>();
private HttpListener _httpListener;
private HttpListener _httpsListener;
private string _serverName = "SeeSharpWebServer";
private string _sessionCookieName = "__tiny_sessid";
private IHttpSessionStore _sessionStore;
private ILogWriter _logWriter = NullLogWriter.Instance;
private int _backLog = 10;
private ExceptionHandler _exceptionHandler;
private readonly IComponentProvider _components;
private RequestQueue _requestQueue;
[ThreadStatic]
private static HttpServer _current;
/// <summary>
/// Server that is handling the current request.
/// </summary>
/// <remarks>
/// Will be set as soon as a request arrives to the <see cref="HttpServer"/> object.
/// </remarks>
public static HttpServer Current
{
get { return _current; }
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class.
/// </summary>
/// <param name="provider">Used to get all components used in the server..</param>
public HttpServer(IComponentProvider provider)
{
_components = provider;
_requestQueue = new RequestQueue(ProcessRequestWrapper);
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class.
/// </summary>
public HttpServer()
{
_components = new ComponentProvider();
_requestQueue = new RequestQueue(ProcessRequestWrapper);
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class.
/// </summary>
/// <param name="decoderProvider">Form decoders are used to convert different types of posted data to the <see cref="HttpInput"/> object types.</param>
/// <seealso cref="IFormDecoder"/>
/// <seealso cref="FormDecoderProviders"/>
public HttpServer(FormDecoderProvider decoderProvider)
{
Check.Require(decoderProvider, "decoderProvider");
_components = new ComponentProvider();
_components.AddInstance<FormDecoderProvider>(decoderProvider);
_requestQueue = new RequestQueue(ProcessRequestWrapper);
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class.
/// </summary>
/// <param name="sessionStore">A session store is used to save and retrieve sessions</param>
/// <seealso cref="IHttpSessionStore"/>
public HttpServer(IHttpSessionStore sessionStore)
{
Check.Require(sessionStore, "sessionStore");
_components = new ComponentProvider();
_components.AddInstance<IHttpSessionStore>(sessionStore);
_requestQueue = new RequestQueue(ProcessRequestWrapper);
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class.
/// </summary>
/// <param name="logWriter">The log writer.</param>
/// <seealso cref="LogWriter"/>
public HttpServer(ILogWriter logWriter)
{
Check.Require(logWriter, "logWriter");
_components = new ComponentProvider();
_components.AddInstance<ILogWriter>(logWriter);
_requestQueue = new RequestQueue(ProcessRequestWrapper);
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class.
/// </summary>
/// <param name="decoderProvider">Form decoders are used to convert different types of posted data to the <see cref="HttpInput"/> object types.</param>
/// <param name="logWriter">The log writer.</param>
/// <seealso cref="IFormDecoder"/>
/// <seealso cref="FormDecoderProviders"/>
/// <seealso cref="LogWriter"/>
public HttpServer(FormDecoderProvider decoderProvider, ILogWriter logWriter)
{
Check.Require(decoderProvider, "decoderProvider");
Check.Require(logWriter, "logWriter");
_components = new ComponentProvider();
_components.AddInstance<FormDecoderProvider>(decoderProvider);
_requestQueue = new RequestQueue(ProcessRequestWrapper);
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class.
/// </summary>
/// <param name="decoderProvider">Form decoders are used to convert different types of posted data to the <see cref="HttpInput"/> object types.</param>
/// <param name="sessionStore">A session store is used to save and retrieve sessions</param>
/// <param name="logWriter">The log writer.</param>
/// <seealso cref="IFormDecoder"/>
/// <seealso cref="FormDecoderProviders"/>
/// <seealso cref="LogWriter"/>
/// <seealso cref="IHttpSessionStore"/>
public HttpServer(FormDecoderProvider decoderProvider, IHttpSessionStore sessionStore, ILogWriter logWriter)
{
Check.Require(decoderProvider, "decoderProvider");
Check.Require(sessionStore, "sessionStore");
_components = new ComponentProvider();
_components.AddInstance<FormDecoderProvider>(sessionStore);
_components.AddInstance<IHttpSessionStore>(sessionStore);
if (logWriter != null)
_components.AddInstance<ILogWriter>(logWriter);
_requestQueue = new RequestQueue(ProcessRequestWrapper);
}
/// <summary>
/// Modules used for authentication. The module that is is added first is used as
/// the default authentication module.
/// </summary>
/// <remarks>Use the corresponding property
/// in the <see cref="WebSiteModule"/> if you are using multiple websites.</remarks>
public IList<AuthenticationModule> AuthenticationModules
{
get { return _authModules; }
}
/// <summary>
/// Form decoder providers are used to decode request body (which normally contains form data).
/// </summary>
public FormDecoderProvider FormDecoderProviders
{
get
{
if (_formDecodersProvider == null)
_formDecodersProvider = _components.Get<FormDecoderProvider>() ?? new FormDecoderProvider();
return _formDecodersProvider;
}
}
/// <summary>
/// Server name sent in HTTP responses.
/// </summary>
/// <remarks>
/// Do NOT include version in name, since it makes it
/// easier for hackers.
/// </remarks>
public string ServerName
{
get { return _serverName; }
set { _serverName = value; }
}
/// <summary>
/// Name of cookie where session id is stored.
/// </summary>
public string SessionCookieName
{
get { return _sessionCookieName; }
set { _sessionCookieName = value; }
}
/// <summary>
/// Specified where logging should go.
/// </summary>
/// <seealso cref="NullLogWriter"/>
/// <seealso cref="ConsoleLogWriter"/>
/// <seealso cref="LogWriter"/>
public ILogWriter LogWriter
{
get { return _logWriter; }
set
{
_logWriter = value ?? NullLogWriter.Instance;
foreach (HttpModule module in _modules)
module.SetLogWriter(_logWriter);
}
}
/// <summary>
/// Number of connections that can wait to be accepted by the server.
/// </summary>
/// <remarks>Default is 10.</remarks>
public int BackLog
{
get { return _backLog; }
set { _backLog = value; }
}
/// <summary>
/// Gets or sets maximum number of allowed simultaneous requests.
/// </summary>
/// <remarks>
/// <para>
/// This property is useful in busy systems. The HTTP server
/// will start queuing new requests if this limit is hit, instead
/// of trying to process all incoming requests directly.
/// </para>
/// <para>
/// The default number if allowed simultaneous requests are 10.
/// </para>
/// </remarks>
public int MaxRequestCount
{
get { return _requestQueue.MaxRequestCount; }
set { _requestQueue.MaxRequestCount = value; }
}
/// <summary>
/// Gets or sets maximum number of requests queuing to be handled.
/// </summary>
/// <remarks>
/// <para>
/// The WebServer will start turning requests away if response code
/// <see cref="HttpStatusCode.ServiceUnavailable"/> to indicate that the server
/// is too busy to be able to handle the request.
/// </para>
/// </remarks>
public int MaxQueueSize
{
get { return _requestQueue.MaxQueueSize; }
set { _requestQueue.MaxQueueSize = value; }
}
/// <summary>
/// Adds the specified rule.
/// </summary>
/// <param name="rule">The rule.</param>
public void Add(IRule rule)
{
_rules.Add(rule);
}
/// <summary>
/// Add a <see cref="HttpModule"/> to the server.
/// </summary>
/// <param name="module">mode to add</param>
public void Add(HttpModule module)
{
_modules.Add(module);
}
/// <summary>
/// Decodes the request body.
/// </summary>
/// <param name="request">The request.</param>
/// <exception cref="InternalServerException">Failed to decode form data.</exception>
protected virtual void DecodeBody(IHttpRequest request)
{
try
{
if (request.Body.Length > 0)
request.DecodeBody(_formDecodersProvider);
}
catch (InvalidOperationException err)
{
throw new InternalServerException("Failed to decode form data.", err);
}
catch (InvalidDataException err)
{
throw new InternalServerException("Form contains invalid format.", err);
}
}
/// <summary>
/// Generate a HTTP error page (that will be added to the response body).
/// response status code is also set.
/// </summary>
/// <param name="response">Response that the page will be generated in.</param>
/// <param name="error"><see cref="HttpStatusCode"/>.</param>
/// <param name="body">response body contents.</param>
protected virtual void ErrorPage(IHttpResponse response, HttpStatusCode error, string body)
{
response.Reason = "Internal server error";
response.Status = error;
response.ContentType = "text/plain";
StreamWriter writer = new StreamWriter(response.Body);
writer.WriteLine(body);
writer.Flush();
}
/// <summary>
/// Generate a HTTP error page (that will be added to the response body).
/// response status code is also set.
/// </summary>
/// <param name="response">Response that the page will be generated in.</param>
/// <param name="err">exception.</param>
protected virtual void ErrorPage(IHttpResponse response, HttpException err)
{
response.Reason = err.GetType().Name;
response.Status = err.HttpStatusCode;
response.ContentType = "text/plain";
StreamWriter writer = new StreamWriter(response.Body);
#if DEBUG
writer.WriteLine(err);
#else
writer.WriteLine(err.Message);
#endif
writer.Flush();
}
/// <summary>
/// Realms are used by the <see cref="AuthenticationModule"/>s.
/// </summary>
/// <param name="request">HTTP request</param>
/// <returns>domain/realm.</returns>
protected virtual string GetRealm(IHttpRequest request)
{
return RealmWanted != null ? RealmWanted(request.Headers["host"] ?? "localhost") : ServerName;
}
/// <summary>
/// Process an incoming request.
/// </summary>
/// <param name="context">connection to client</param>
/// <param name="request">request information</param>
/// <param name="response">response that should be filled</param>
/// <param name="session">session information</param>
protected virtual void HandleRequest(IHttpClientContext context, IHttpRequest request, IHttpResponse response,
IHttpSession session)
{
_logWriter.Write(this, LogPrio.Trace, "Processing request....");
bool handled = false;
try
{
DecodeBody(request);
if (ProcessAuthentication(request, response, session))
{
foreach (HttpModule module in _modules)
{
if (!module.Process(request, response, session))
continue;
handled = true;
if (!module.AllowSecondaryProcessing)
break;
}
}
}
catch (HttpException err)
{
if (err.HttpStatusCode == HttpStatusCode.Unauthorized)
{
AuthenticationModule mod;
lock (_authModules)
mod = _authModules.Count > 0 ? _authModules[0] : null;
if (mod != null)
RequestAuthentication(mod, request, response);
}
else
ErrorPage(response, err);
}
if (!handled && response.Status == HttpStatusCode.OK)
ErrorPage(response, HttpStatusCode.NotFound, "Resource not found: " + request.Uri);
if (!response.HeadersSent)
{
// Dispose session if it was not used.
if (session.Count > 0)
{
_sessionStore.Save(session);
// only set session cookie if it have not been sent in the request.
if (request.Cookies[_sessionCookieName] == null)
response.Cookies.Add(new ResponseCookie(_sessionCookieName, session.Id, DateTime.MinValue));//DateTime.Now.AddMinutes(20).AddDays(1)));
}
else
_sessionStore.AddUnused(session);
}
if (!response.Sent)
response.Send();
_logWriter.Write(this, LogPrio.Trace, "....done.");
}
private void Init()
{
_sessionStore = _components.Get<IHttpSessionStore>();
if (_sessionStore == null)
{
WriteLog(this, LogPrio.Info, "Defaulting to memory session store.");
_sessionStore = new MemorySessionStore();
}
// add default decoders if none have been added.
if (FormDecoderProviders.Count == 0)
{
WriteLog(this, LogPrio.Info, "Loading UrlDecoder, XmlDecoder and MultipartDecoder, since no decoders have been added.");
_formDecodersProvider.Add(new UrlDecoder());
_formDecodersProvider.Add(new MultipartDecoder());
_formDecodersProvider.Add(new XmlDecoder());
}
// Components for building requests.
if (!_components.Contains(typeof(IRequestParserFactory)))
_components.Add<IRequestParserFactory, RequestParserFactory>();
if (!_components.Contains(typeof(IHttpContextFactory)))
_components.AddInstance<IHttpContextFactory>(new HttpContextFactory(LogWriter, 16384,
_components.Get
<IRequestParserFactory>()));
// the special folder does not exist on mono
string tempPath = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
if (string.IsNullOrEmpty(tempPath))
tempPath = "/var/tmp/";
if (!Directory.Exists(tempPath))
{
WriteLog(this, LogPrio.Warning, "Temp path do not exist: " + tempPath);
return;
}
DirectoryInfo info = new DirectoryInfo(tempPath);
foreach (FileInfo file in info.GetFiles("*.tmp"))
file.Delete();
_requestQueue.Start();
}
/// <summary>
/// Can be overloaded to implement stuff when a client have been connected.
/// </summary>
/// <remarks>
/// Default implementation does nothing.
/// </remarks>
/// <param name="client">client that disconnected</param>
/// <param name="error">disconnect reason</param>
protected virtual void OnClientDisconnected(IHttpClientContext client, SocketError error)
{
}
/// <summary>
/// Handle authentication
/// </summary>
/// <param name="request"></param>
/// <param name="response"></param>
/// <param name="session"></param>
/// <returns>true if request can be handled; false if not.</returns>
/// <exception cref="BadRequestException">Invalid authorization header</exception>
protected virtual bool ProcessAuthentication(IHttpRequest request, IHttpResponse response, IHttpSession session)
{
if (_authModules.Count > 0)
{
bool authenticate = false;
object authTag = null;
if (request.Headers["authorization"] != null)
{
authenticate = true;
string authHeader = request.Headers["authorization"];
int pos = authHeader.IndexOf(' ');
if (pos == -1)
throw new BadRequestException("Invalid authorization header");
// first word identifies the type of authentication to use.
string word = authHeader.Substring(0, pos).ToLower();
// find the mod to use.
AuthenticationModule mod = null;
lock (_authModules)
{
foreach (AuthenticationModule aModule in _authModules)
{
if (aModule.Name != word)
continue;
mod = aModule;
break;
}
}
if (mod != null)
{
authTag = mod.Authenticate(authHeader, GetRealm(request), request.Method);
session[AuthenticationModule.AuthenticationTag] = authTag;
}
}
// Check if auth is needed.
if (authTag == null)
{
lock (_authModules)
{
foreach (AuthenticationModule module in _authModules)
{
if (!module.AuthenticationRequired(request))
continue;
RequestAuthentication(module, request, response);
return false;
}
// modules can have inited the authentication
// and then the module.AuthenticationRequired method will not have been used.
if (authenticate && _authModules.Count > 0)
{
RequestAuthentication(_authModules[0], request, response);
return false;
}
}
}
}
return true;
}
/// <summary>
/// Will request authentication.
/// </summary>
/// <remarks>
/// Sends respond to client, nothing else can be done with the response after this.
/// </remarks>
/// <param name="mod"></param>
/// <param name="request"></param>
/// <param name="response"></param>
protected virtual void RequestAuthentication(AuthenticationModule mod, IHttpRequest request, IHttpResponse response)
{
string theResponse = mod.CreateResponse(GetRealm(request));
response.AddHeader("www-authenticate", theResponse);
response.Reason = "Authentication required.";
response.Status = HttpStatusCode.Unauthorized;
}
/// <summary>
/// Received from a <see cref="IHttpClientContext"/> when a request have been parsed successfully.
/// </summary>
/// <param name="source"><see cref="IHttpClientContext"/> that received the request.</param>
/// <param name="args">The request.</param>
private void OnRequest(object source, RequestEventArgs args)
{
_current = this;
IHttpClientContext context = (IHttpClientContext) source;
IHttpRequest request = args.Request;
if (_requestQueue.ShouldQueue)
{
_requestQueue.Enqueue(context, request);
return;
}
ProcessRequestWrapper(context, request);
// no need to lock, if all threads are busy,
// someone is bound to trigger the thread correctly =)
_requestQueue.Trigger();
}
/// <summary>
/// To be able to track request count.
/// </summary>
/// <param name="context"></param>
/// <param name="request"></param>
private void ProcessRequestWrapper(IHttpClientContext context, IHttpRequest request)
{
_requestQueue.CurrentRequestCount += 1;
ProcessRequest(context, request);
_requestQueue.CurrentRequestCount -= 1;
}
private void ProcessRequest(IHttpClientContext context, IHttpRequest request)
{
IHttpResponse response = request.CreateResponse(context);
try
{
foreach (IRule rule in _rules)
{
if (!rule.Process(request, response))
continue;
response.Send();
return;
}
// load cookies if the exist.
RequestCookies cookies = request.Headers["cookie"] != null
? new RequestCookies(request.Headers["cookie"])
: new RequestCookies(string.Empty);
request.SetCookies(cookies);
IHttpSession session;
if (cookies[_sessionCookieName] != null)
{
string sessionCookie = cookies[_sessionCookieName].Value;
// there's a bug somewhere which messes up headers which can render the session cookie useless.
// therefore let's consider the session cookie as not set if that have happened.
if (sessionCookie.Length > 40)
{
_logWriter.Write(this, LogPrio.Error, "Session cookie is invalid: " + sessionCookie);
cookies.Remove(_sessionCookieName);
_sessionStore.Remove(sessionCookie); // free the session cookie (and thus generating a new one).
session = _sessionStore.Create();
}
else
session = _sessionStore.Load(sessionCookie) ??
_sessionStore.Create(sessionCookie);
}
else
session = _sessionStore.Create();
HandleRequest(context, request, response, session);
}
catch (Exception err)
{
if (_exceptionHandler == null)
#if DEBUG
throw;
#else
{
WriteLog(LogPrio.Fatal, err.Message);
return;
}
#endif
_exceptionHandler(this, err);
Exception e = err;
while (e != null)
{
if (e is SocketException)
return;
e = e.InnerException;
}
try
{
#if DEBUG
context.Respond("HTTP/1.0", HttpStatusCode.InternalServerError, "Internal server error", err.ToString(), "text/plain");
#else
context.Respond("HTTP/1.0", HttpStatusCode.InternalServerError, "Internal server error");
#endif
}
catch (Exception err2)
{
LogWriter.Write(this, LogPrio.Fatal, "Failed to respond on message with Internal Server Error: " + err2);
}
}
}
/// <summary>
/// Start the web server using regular HTTP.
/// </summary>
/// <param name="address">IP Address to listen on, use <c>IpAddress.Any </c>to accept connections on all IP addresses/network cards.</param>
/// <param name="port">Port to listen on. 80 can be a good idea =)</param>
/// <exception cref="ArgumentNullException"><c>address</c> is null.</exception>
/// <exception cref="ArgumentException">Port must be a positive number.</exception>
public void Start(IPAddress address, int port)
{
if (address == null)
throw new ArgumentNullException("address");
if (port <= 0)
throw new ArgumentException("Port must be a positive number.");
if (_httpListener != null)
return;
Init();
_httpListener = new HttpListener(address, port, _components.Get<IHttpContextFactory>()) { LogWriter = LogWriter };
_httpListener.RequestReceived += OnRequest;
_httpListener.Start(50);
_httpListener.ExceptionThrown += _exceptionHandler;
}
/// <summary>
/// Accept secure connections.
/// </summary>
/// <param name="address">IP Address to listen on, use <see cref="IPAddress.Any"/> to accept connections on all IP Addresses / network cards.</param>
/// <param name="port">Port to listen on. 80 can be a good idea =)</param>
/// <param name="certificate">Certificate to use</param>
/// <exception cref="ArgumentNullException"><c>address</c> is null.</exception>
/// <exception cref="ArgumentException">Port must be a positive number.</exception>
public void Start(IPAddress address, int port, X509Certificate certificate)
{
if (address == null)
throw new ArgumentNullException("address");
if (port <= 0)
throw new ArgumentException("Port must be a positive number.");
if (_httpsListener != null)
return;
Init();
_httpsListener = new HttpListener(address, port, _components.Get<IHttpContextFactory>(), certificate);
_httpsListener.LogWriter = LogWriter;
_httpsListener.RequestReceived += OnRequest;
_httpsListener.Start(5);
_httpsListener.ExceptionThrown += _exceptionHandler;
}
/// <summary>
/// shut down the server and listeners
/// </summary>
public void Stop()
{
if (_httpListener != null)
{
_httpListener.Stop();
_httpListener = null;
}
if (_httpsListener != null)
{
_httpsListener.Stop();
_httpsListener = null;
}
_requestQueue.Stop();
}
/// <summary>
/// write an entry to the log file
/// </summary>
/// <param name="prio">importance of the message</param>
/// <param name="message">log message</param>
protected virtual void WriteLog(LogPrio prio, string message)
{
LogWriter.Write(this, prio, message);
}
/// <summary>
/// write an entry to the log file
/// </summary>
/// <param name="source">object that wrote the message</param>
/// <param name="prio">importance of the message</param>
/// <param name="message">log message</param>
public void WriteLog(object source, LogPrio prio, string message)
{
LogWriter.Write(source, prio, message);
}
/// <summary>
/// Realms are used during HTTP authentication.
/// Default realm is same as server name.
/// </summary>
public event RealmHandler RealmWanted;
/// <summary>
/// Let's to receive unhandled exceptions from the threads.
/// </summary>
/// <remarks>
/// Exceptions will be thrown during debug mode if this event is not used,
/// exceptions will be printed to console and suppressed during release mode.
/// </remarks>
public event ExceptionHandler ExceptionThrown
{
add
{
_exceptionHandler += value;
if (_httpListener != null)
_httpListener.ExceptionThrown += value;
if (_httpsListener != null)
_httpsListener.ExceptionThrown += value;
}
remove
{
_exceptionHandler -= value;
if (_httpListener != null)
_httpListener.ExceptionThrown -= value;
if (_httpsListener != null)
_httpsListener.ExceptionThrown -= value;
}
}
}
}
| |
// 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.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Thrift.Transports.Client
{
// ReSharper disable once InconsistentNaming
public class TBufferedClientTransport : TClientTransport
{
private readonly int _bufSize;
private readonly MemoryStream _inputBuffer = new MemoryStream(0);
private readonly MemoryStream _outputBuffer = new MemoryStream(0);
private readonly TClientTransport _transport;
private bool _isDisposed;
//TODO: should support only specified input transport?
public TBufferedClientTransport(TClientTransport transport, int bufSize = 1024)
{
if (transport == null)
{
throw new ArgumentNullException(nameof(transport));
}
if (bufSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufSize), "Buffer size must be a positive number.");
}
_transport = transport;
_bufSize = bufSize;
}
public TClientTransport UnderlyingTransport
{
get
{
CheckNotDisposed();
return _transport;
}
}
public override bool IsOpen => !_isDisposed && _transport.IsOpen;
public override async Task OpenAsync(CancellationToken cancellationToken)
{
CheckNotDisposed();
await _transport.OpenAsync(cancellationToken);
}
public override void Close()
{
CheckNotDisposed();
_transport.Close();
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int length,
CancellationToken cancellationToken)
{
//TODO: investigate how it should work correctly
CheckNotDisposed();
ValidateBufferArgs(buffer, offset, length);
if (!IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen);
}
if (_inputBuffer.Capacity < _bufSize)
{
_inputBuffer.Capacity = _bufSize;
}
var got = await _inputBuffer.ReadAsync(buffer, offset, length, cancellationToken);
if (got > 0)
{
return got;
}
_inputBuffer.Seek(0, SeekOrigin.Begin);
_inputBuffer.SetLength(_inputBuffer.Capacity);
ArraySegment<byte> bufSegment;
_inputBuffer.TryGetBuffer(out bufSegment);
// investigate
var filled = await _transport.ReadAsync(bufSegment.Array, 0, (int) _inputBuffer.Length, cancellationToken);
_inputBuffer.SetLength(filled);
if (filled == 0)
{
return 0;
}
return await ReadAsync(buffer, offset, length, cancellationToken);
}
public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
{
CheckNotDisposed();
ValidateBufferArgs(buffer, offset, length);
if (!IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen);
}
// Relative offset from "off" argument
var writtenCount = 0;
if (_outputBuffer.Length > 0)
{
var capa = (int) (_outputBuffer.Capacity - _outputBuffer.Length);
var writeSize = capa <= length ? capa : length;
await _outputBuffer.WriteAsync(buffer, offset, writeSize, cancellationToken);
writtenCount += writeSize;
if (writeSize == capa)
{
//ArraySegment<byte> bufSegment;
//_outputBuffer.TryGetBuffer(out bufSegment);
var data = _outputBuffer.ToArray();
//await _transport.WriteAsync(bufSegment.Array, cancellationToken);
await _transport.WriteAsync(data, cancellationToken);
_outputBuffer.SetLength(0);
}
}
while (length - writtenCount >= _bufSize)
{
await _transport.WriteAsync(buffer, offset + writtenCount, _bufSize, cancellationToken);
writtenCount += _bufSize;
}
var remain = length - writtenCount;
if (remain > 0)
{
if (_outputBuffer.Capacity < _bufSize)
{
_outputBuffer.Capacity = _bufSize;
}
await _outputBuffer.WriteAsync(buffer, offset + writtenCount, remain, cancellationToken);
}
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
CheckNotDisposed();
if (!IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen);
}
if (_outputBuffer.Length > 0)
{
//ArraySegment<byte> bufSegment;
var data = _outputBuffer.ToArray(); // TryGetBuffer(out bufSegment);
await _transport.WriteAsync(data /*bufSegment.Array*/, cancellationToken);
_outputBuffer.SetLength(0);
}
await _transport.FlushAsync(cancellationToken);
}
private void CheckNotDisposed()
{
if (_isDisposed)
{
throw new ObjectDisposedException(nameof(_transport));
}
}
// IDisposable
protected override void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
_inputBuffer.Dispose();
_outputBuffer.Dispose();
}
}
_isDisposed = true;
}
}
}
| |
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using java.lang;
using java.util;
using stab.query;
using stab.reflection;
using cnatural.syntaxtree;
namespace cnatural.compiler {
class CompilerHelper {
static String getDisplayName(AssignOperator operator) {
switch (operator) {
case Add:
return "+=";
case And:
return "&=";
case Divide:
return "/=";
case LeftShift:
return "<<=";
case Modulo:
return "%=";
case Multiply:
return "*=";
case Or:
return "|=";
case RightShift:
return ">>=";
case Subtract:
return "-=";
case UnsignedRightShift:
return ">>>=";
case Xor:
return "^=";
default:
throw new IllegalStateException();
}
}
static String getDisplayName(BinaryOperator operator) {
switch (operator) {
case Add:
return "+";
case And:
return "&";
case As:
return "as";
case Divide:
return "/";
case Equal:
return "==";
case GreaterThan:
return ">";
case GreaterThanOrEqual:
return ">=";
case Instanceof:
return "instanceof";
case LeftShift:
return "<<";
case LessThan:
return "<";
case LessThanOrEqual:
return "<=";
case LogicalAnd:
return "&&";
case LogicalOr:
return "||";
case Modulo:
return "%";
case Multiply:
return "*";
case NotEqual:
return "!=";
case NullCoalescing:
return "??";
case Or:
return "|";
case RightShift:
return ">>";
case Subtract:
return "-";
case UnsignedRightShift:
return ">>>";
case Xor:
return "^";
default:
throw new IllegalStateException();
}
}
static String getDisplayName(UnaryOperator operator) {
switch (operator) {
case Complement:
return "~";
case Minus:
return "-";
case Not:
return "!";
case Plus:
return "+";
case PostDecrement:
case PreDecrement:
return "--";
case PreIncrement:
case PostIncrement:
return "++";
default:
throw new IllegalStateException();
}
}
static bool isZero(ExpressionInfo info) {
if (info.IsConstant) {
Object value = info.Value;
if (value instanceof Double) {
return ((Double)value).doubleValue() == 0d;
} else if (value instanceof Float) {
return ((Float)value).floatValue() == 0f;
} else if (value instanceof Long) {
return ((Long)value).longValue() == 0l;
} else if (value instanceof Integer) {
return ((Integer)value).intValue() == 0;
} else if (value instanceof Character) {
return ((Character)value).charValue() == 0;
} else if (value instanceof Byte) {
return ((Byte)value).byteValue() == 0;
} else if (value instanceof Short) {
return ((Short)value).shortValue() == 0;
}
}
return false;
}
static List<String> getName(CompilerContext context, TypeReferenceNode typeReference) {
switch (typeReference.TypeReferenceKind) {
case SimpleName: {
var simpleName = (SimpleNameTypeReferenceNode)typeReference;
return new ArrayList<String> { context.getIdentifier(simpleName.NameOffset, simpleName.NameLength) };
}
case Qualified: {
var qualified = (QualifiedTypeReferenceNode)typeReference;
var simpleName = qualified.SimpleName;
var result = getName(context, qualified.EnclosingType);
result.add(context.getIdentifier(simpleName.NameOffset, simpleName.NameLength));
return result;
}
default:
throw new RuntimeException("Internal error: unhandled type kind: " + typeReference.TypeReferenceKind);
}
}
static String getFullName(CompilerContext context, TypeReferenceNode typeReference) {
switch (typeReference.TypeReferenceKind) {
case SimpleName: {
var simpleName = (SimpleNameTypeReferenceNode)typeReference;
return context.getIdentifier(simpleName.NameOffset, simpleName.NameLength);
}
case Qualified: {
var qualified = (QualifiedTypeReferenceNode)typeReference;
var simpleName = qualified.SimpleName;
return getFullName(context, qualified.EnclosingType) + '/' +
context.getIdentifier(simpleName.NameOffset, simpleName.NameLength);
}
default:
throw new RuntimeException("Internal error: unhandled type kind: " + typeReference.TypeReferenceKind);
}
}
static TypeInfo resolveTypeReference(CompilerContext context, String packageName, TypeReferenceNode typeReference) {
return resolveTypeReference(context, packageName, typeReference, true, true);
}
static TypeInfo resolveTypeReference(CompilerContext context, String packageName, TypeReferenceNode typeReference,
bool fail, bool reportRawTypeUsage) {
switch (typeReference.TypeReferenceKind) {
case Boolean:
return context.TypeSystem.BooleanType;
case Byte:
return context.TypeSystem.ByteType;
case Char:
return context.TypeSystem.CharType;
case Double:
return context.TypeSystem.DoubleType;
case Float:
return context.TypeSystem.FloatType;
case Int:
return context.TypeSystem.IntType;
case Long:
return context.TypeSystem.LongType;
case Short:
return context.TypeSystem.ShortType;
case String:
return context.TypeSystem.StringType;
case Void:
return context.TypeSystem.VoidType;
case Wildcard:
return context.TypeSystem.UnboundedWildcard;
case LowerBoundedWildcard:
return resolveTypeReference(context, packageName, ((WildcardTypeReferenceNode)typeReference).Bound).LowerBoundedWildcard;
case UpperBoundedWildcard:
return resolveTypeReference(context, packageName, ((WildcardTypeReferenceNode)typeReference).Bound).UpperBoundedWildcard;
case Array:
return resolveTypeReference(context, packageName, ((ArrayTypeReferenceNode)typeReference).ElementType).ArrayType;
case SimpleName: {
var simpleName = (SimpleNameTypeReferenceNode)typeReference;
var name = context.getIdentifier(simpleName.NameOffset, simpleName.NameLength);
var typeInfo = context.MemberResolver.resolveTypeName(packageName, name);
if (typeInfo == null) {
if (fail) {
if (context.MemberResolver.isAmbiguousTypeName(name)) {
throw context.error(CompileErrorId.AmbiguousTypeName, simpleName, name);
} else {
throw context.error(CompileErrorId.UnresolvedTypeName, simpleName, name);
}
} else {
return null;
}
}
return getGenericType(context, packageName, typeInfo.Type, simpleName.TypeArguments, simpleName, fail, reportRawTypeUsage);
}
case Qualified: {
var qualified = (QualifiedTypeReferenceNode)typeReference;
var simpleName = qualified.SimpleName;
var name = context.getIdentifier(simpleName.NameOffset, simpleName.NameLength);
var enclosingType = resolveTypeReference(context, packageName, qualified.EnclosingType, false, false);
if (enclosingType == null) {
var pkg = getFullName(context, qualified.EnclosingType);
if (pkg.indexOf('/') == -1) {
var s = context.MemberResolver.getPackageFromAlias(pkg);
if (s != null) {
pkg = s;
}
}
var fullName = pkg + '/' + name;
if (context.TypeSystem.typeExists(fullName)) {
var t = context.TypeSystem.getType(fullName);
if (!t.IsPublic && !t.PackageName.equals(packageName)) {
if (fail) {
throw context.error(CompileErrorId.UnresolvedTypeName, qualified, fullName.replace('/', '.').replace('$', '.'));
} else {
return null;
}
}
return getGenericType(context, packageName, t, simpleName.TypeArguments, simpleName, fail, reportRawTypeUsage);
} else {
if (fail) {
throw context.error(CompileErrorId.UnresolvedTypeName, qualified, fullName.replace('/', '.').replace('$', '.'));
} else {
return null;
}
}
} else {
var fullName = enclosingType.FullName + '$' + name;
foreach (var t in enclosingType.NestedTypes) {
if (t.FullName.equals(fullName)) {
return getGenericType(context, packageName, t, simpleName.TypeArguments, simpleName, fail, reportRawTypeUsage);
}
}
if (fail) {
throw context.error(CompileErrorId.UnresolvedNestedTypeName, simpleName,
BytecodeHelper.getDisplayName(enclosingType) , name);
} else {
return null;
}
}
}
default:
throw new Exception("Internal error: unhandled type kind: " + typeReference.TypeReferenceKind);
}
}
private static TypeInfo getGenericType(CompilerContext context, String packageName, TypeInfo type,
List<TypeReferenceNode> typeArguments, SyntaxNode node, bool fail, bool reportRawTypeUsage) {
int nTypeArgs = typeArguments.size();
if (!type.IsGenericTypeDefinition) {
if (nTypeArgs > 0) {
if (fail) {
throw context.error(CompileErrorId.TypeArgumentsNonGeneric, node, BytecodeHelper.getDisplayName(type));
} else {
return null;
}
}
return type;
}
int args = type.GenericArguments.count();
if (args > 0 && nTypeArgs == 0) {
var result = type.RawType;
if (reportRawTypeUsage) {
context.addWarning(CompileErrorId.RawTypeUsage, node,
BytecodeHelper.getDisplayName(result), BytecodeHelper.getDisplayName(type));
}
return result;
} else if (nTypeArgs != args) {
if (fail) {
throw context.error(CompileErrorId.WrongTypeArgumentNumber, node, BytecodeHelper.getDisplayName(type), args);
} else {
return null;
}
}
if (nTypeArgs == 0) {
return type;
} else {
var typeArgs = new ArrayList<TypeInfo>();
foreach (var t in typeArguments) {
var ti = resolveTypeReference(context, packageName, t, fail, reportRawTypeUsage);
if (!fail && ti == null) {
return null;
}
if (ti.IsPrimitive) {
throw context.error(CompileErrorId.PrimitiveGenericArgument, node);
}
typeArgs.add(ti);
}
return context.TypeSystem.getGenericType(type, typeArgs);
}
}
static void convertConstant(CompilerContext context, ExpressionNode expression, ExpressionInfo info, TypeInfo targetType) {
switch (targetType.NumericTypeKind) {
case Byte: {
long value;
switch (info.Type.TypeKind) {
case Byte:
break;
case Char:
case Int:
case Long:
case Short:
value = ((Number)info.Value).longValue();
if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE) {
info.Type = context.TypeSystem.ByteType;
info.Value = Byte.valueOf((byte)value);
break;
}
goto default;
default:
context.addError(CompileErrorId.NoImplicitConversion, expression,
BytecodeHelper.getDisplayName(info.Type),
BytecodeHelper.getDisplayName(targetType));
break;
}
break;
}
case Char: {
long value;
switch (info.Type.TypeKind) {
case Char:
break;
case Byte:
case Int:
case Long:
case Short:
value = ((Number)info.getValue()).longValue();
if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE) {
info.Type = context.TypeSystem.CharType;
info.Value = Character.valueOf((char)value);
break;
}
goto default;
default:
context.addError(CompileErrorId.NoImplicitConversion, expression,
BytecodeHelper.getDisplayName(info.Type),
BytecodeHelper.getDisplayName(targetType));
break;
}
break;
}
case Short: {
long value;
switch (info.Type.TypeKind) {
case Short:
break;
case Byte:
case Char:
case Int:
case Long:
value = ((Number)info.Value).longValue();
if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE) {
info.Type = context.TypeSystem.ShortType;
info.Value = Short.valueOf((short)value);
break;
}
goto default;
default:
context.addError(CompileErrorId.NoImplicitConversion, expression,
BytecodeHelper.getDisplayName(info.Type),
BytecodeHelper.getDisplayName(targetType));
break;
}
break;
}
case Int: {
long value;
switch (info.Type.TypeKind) {
case Int:
break;
case Byte:
case Char:
case Short:
case Long:
value = ((Number)info.getValue()).longValue();
if (Integer.MIN_VALUE <= value && value <= Integer.MAX_VALUE) {
info.Type = context.TypeSystem.IntType;
info.Value = Integer.valueOf((int)value);
break;
}
goto default;
default:
context.addError(CompileErrorId.NoImplicitConversion, expression,
BytecodeHelper.getDisplayName(info.Type),
BytecodeHelper.getDisplayName(targetType));
break;
}
break;
}
case Long: {
long value;
switch (info.Type.TypeKind) {
case Long:
break;
case Byte:
case Char:
case Short:
case Int:
value = ((Number)info.getValue()).longValue();
info.Type = context.TypeSystem.LongType;
info.Value = Long.valueOf(value);
break;
default:
context.addError(CompileErrorId.NoImplicitConversion, expression,
BytecodeHelper.getDisplayName(info.Type),
BytecodeHelper.getDisplayName(targetType));
break;
}
break;
}
case Float: {
float value;
switch (info.Type.TypeKind) {
case Float:
break;
case Byte:
case Char:
case Short:
case Int:
case Long:
value = ((Number)info.getValue()).floatValue();
info.Type = context.TypeSystem.FloatType;
info.Value = Float.valueOf(value);
break;
default:
context.addError(CompileErrorId.NoImplicitConversion, expression,
BytecodeHelper.getDisplayName(info.Type),
BytecodeHelper.getDisplayName(targetType));
break;
}
break;
}
case Double: {
double value;
switch (info.Type.TypeKind) {
case Double:
break;
case Byte:
case Char:
case Short:
case Int:
case Long:
case Float:
value = ((Number)info.Value).doubleValue();
info.Type = context.TypeSystem.DoubleType;
info.Value = Double.valueOf(value);
break;
}
break;
}
}
}
public static bool shouldIgnoreCalls(CompilerContext context, MethodInfo method) {
foreach (var ann in BytecodeHelper.getAnnotations(context.AnnotatedTypeSystem, method)) {
if (BytecodeHelper.isConditional(ann)) {
foreach (var elt in ann.getArgument("value").Elements) {
if (context.Symbols.contains(elt.Value)) {
return false;
}
}
return true;
}
}
return false;
}
static void initializeAnonymousType(CompilerContext context, TypeInfo type) {
if (!type.Methods.any(p => p.Name.equals("hashCode"))) {
var typeBuilder = (TypeBuilder)type;
//
// Constructor body
//
var baseConstructor = context.TypeSystem.ObjectType.getMethod("<init>", Query.empty<TypeInfo>());
var constructor = (MethodBuilder)type.Methods.where(p => p.Name.equals("<init>")).first();
var gen = constructor.CodeGenerator;
gen.beginScope();
gen.emit(Opcode.Aload, gen.getLocal("this"));
gen.emit(Opcode.Invokespecial, baseConstructor);
var it = typeBuilder.Fields.iterator();
foreach (var p in constructor.Parameters) {
gen.emit(Opcode.Aload, gen.getLocal("this"));
gen.emit(BytecodeHelper.getLoadOpcode(p.Type), gen.getLocal(p.Name));
gen.emit(Opcode.Putfield, it.next());
}
gen.emit(Opcode.Return);
gen.endScope();
//
// Object.equals redefinition
//
var methodBuilder = typeBuilder.defineMethod("equals");
methodBuilder.setReturnType(context.TypeSystem.BooleanType);
methodBuilder.addParameter(context.TypeSystem.ObjectType).setName("obj");
gen = methodBuilder.CodeGenerator;
gen.beginScope();
gen.emit(Opcode.Aload, gen.getLocal("obj"));
gen.emit(Opcode.Instanceof, typeBuilder);
var label = gen.defineLabel();
gen.emit(Opcode.Ifne, label);
gen.emit(Opcode.Iconst_0);
gen.emit(Opcode.Ireturn);
gen.markLabel(label);
gen.emit(Opcode.Aload, gen.getLocal("obj"));
gen.emit(Opcode.Checkcast, typeBuilder);
gen.emit(Opcode.Astore, gen.declareLocal(typeBuilder, "other"));
var equals = context.TypeSystem.ObjectType.getMethod("equals", Collections.singletonList(context.TypeSystem.ObjectType));
foreach (var f in typeBuilder.Fields) {
gen.emit(Opcode.Aload, gen.getLocal("other"));
gen.emit(Opcode.Getfield, f);
gen.emit(Opcode.Aload, gen.getLocal("this"));
gen.emit(Opcode.Getfield, f);
label = gen.defineLabel();
switch (f.Type.TypeKind) {
case Boolean:
case Byte:
case Char:
case Short:
case Int:
gen.emit(Opcode.If_icmpeq, label);
break;
case Long:
gen.emit(Opcode.Lcmp);
gen.emit(Opcode.Ifeq, label);
break;
case Float:
gen.emit(Opcode.Fcmpg);
gen.emit(Opcode.Ifeq, label);
break;
case Double:
gen.emit(Opcode.Dcmpg);
gen.emit(Opcode.Ifeq, label);
break;
default:
gen.emit(Opcode.Invokevirtual, equals);
gen.emit(Opcode.Ifne, label);
break;
}
gen.emit(Opcode.Iconst_0);
gen.emit(Opcode.Ireturn);
gen.markLabel(label);
}
gen.emit(Opcode.Iconst_1);
gen.emit(Opcode.Ireturn);
gen.endScope();
//
// Object.hashCode redefinition
//
methodBuilder = typeBuilder.defineMethod("hashCode");
methodBuilder.setReturnType(context.TypeSystem.IntType);
gen = methodBuilder.CodeGenerator;
gen.beginScope();
var hashCode = context.TypeSystem.ObjectType.getMethod("hashCode", Query.empty<TypeInfo>());
gen.emit(Opcode.Iconst_0);
gen.emit(Opcode.Istore, gen.declareLocal(context.TypeSystem.IntType, "result"));
var first = true;
foreach (var f in typeBuilder.Fields) {
gen.emit(Opcode.Aload, gen.getLocal("this"));
gen.emit(Opcode.Getfield, f);
switch (f.Type.TypeKind) {
case Boolean:
case Byte:
case Char:
case Short:
case Int:
break;
case Long:
gen.emit(Opcode.L2i);
break;
case Float:
gen.emit(Opcode.F2i);
break;
case Double:
gen.emit(Opcode.D2i);
break;
default:
gen.emit(Opcode.Invokevirtual, hashCode);
break;
}
if (first) {
first = false;
} else {
gen.emit(Opcode.Iload, gen.getLocal("result"));
gen.emit(Opcode.Ixor);
}
gen.emit(Opcode.Istore, gen.getLocal("result"));
}
gen.emit(Opcode.Iload, gen.getLocal("result"));
gen.emit(Opcode.Ireturn);
gen.endScope();
}
}
static TypeInfo createDelegateType(CompilerContext context, TypeInfo delegateType, MethodInfo method) {
var invokeMethod = delegateType.Methods.where(p => p.Name.equals("invoke")).first();
var currentType = (TypeBuilder)context.CurrentType;
var prefix = currentType.FullName + "$Delegate";
int n = currentType.NestedTypes.count(p => p.FullName.startsWith(prefix));
var typeBuilder = currentType.defineNestedType("Delegate" + n);
context.TypeBuilders.add(typeBuilder);
typeBuilder.setSynthetic(true);
typeBuilder.setBaseType(delegateType);
// invoke(...)
var methodBuilder = typeBuilder.defineMethod("invoke");
methodBuilder.setPublic(true);
methodBuilder.setFinal(true);
methodBuilder.setVarargs(invokeMethod.IsVarargs);
methodBuilder.setReturnType(invokeMethod.ReturnType);
foreach (var p in invokeMethod.Parameters) {
var pb = methodBuilder.addParameter(p.Type);
pb.setName(p.Name);
}
foreach (var t in invokeMethod.Exceptions) {
methodBuilder.addException(t);
}
context.MethodGenerationContext.enterLambda(methodBuilder);
var delegateTypeInfo = context.TypeSystem.getType("stab/lang/Delegate");
var gen = methodBuilder.CodeGenerator;
gen.beginScope();
gen.emit(Opcode.Aload, gen.getLocal("this"));
gen.emit(Opcode.Getfield, delegateTypeInfo.getField("delegates"));
var elseLabel = gen.defineLabel();
gen.emit(Opcode.Ifnull, elseLabel);
gen.emit(Opcode.Aload, gen.getLocal("this"));
gen.emit(Opcode.Getfield, delegateTypeInfo.getField("delegates"));
var td = gen.declareLocal(delegateTypeInfo.ArrayType, "td$0");
gen.emit(Opcode.Astore, td);
LocalInfo local = null;
if (method.ReturnType != context.TypeSystem.VoidType) {
local = gen.declareLocal(method.ReturnType, "result$0");
}
var idx = gen.declareLocal(context.TypeSystem.IntType, "i$0");
gen.emit(Opcode.Iconst_0);
gen.emit(Opcode.Istore, idx);
var startLabel = gen.defineLabel();
gen.markLabel(startLabel);
gen.emit(Opcode.Aload, td);
gen.emit(Opcode.Iload, idx);
gen.emit(Opcode.Aaload);
gen.emit(Opcode.Checkcast, delegateType);
foreach (var p in invokeMethod.Parameters) {
gen.emit(BytecodeHelper.getLoadOpcode(p.Type), gen.getLocal(p.Name));
}
gen.emit(Opcode.Invokevirtual, invokeMethod);
if (method.ReturnType != context.TypeSystem.VoidType) {
var m = invokeMethod.OriginalMethodDefinition;
BytecodeGenerator.emitGenericCast(context, invokeMethod.ReturnType, m.ReturnType);
gen.emit(BytecodeHelper.getStoreOpcode(method.ReturnType), local);
}
gen.emit(Opcode.Iinc, idx, 1);
gen.emit(Opcode.Iload, idx);
gen.emit(Opcode.Aload, td);
gen.emit(Opcode.Arraylength);
gen.emit(Opcode.If_icmplt, startLabel);
if (method.ReturnType != context.TypeSystem.VoidType) {
gen.emit(BytecodeHelper.getLoadOpcode(method.ReturnType), local);
}
gen.emit(BytecodeHelper.getReturnOpcode(method.ReturnType));
gen.markLabel(elseLabel);
if (!method.IsStatic) {
gen.emit(Opcode.Aload, gen.getLocal("this"));
gen.emit(Opcode.Invokevirtual, delegateTypeInfo.getMethod("getTarget", Query.empty<TypeInfo>()));
gen.emit(Opcode.Checkcast, method.DeclaringType);
}
foreach (var p in invokeMethod.Parameters) {
gen.emit(BytecodeHelper.getLoadOpcode(p.Type), gen.getLocal(p.Name));
}
emitMethodAccess(context, method, false);
gen.emit(BytecodeHelper.getReturnOpcode(method.ReturnType));
gen.endScope();
context.MethodGenerationContext.leaveLambda();
if (invokeMethod.DeclaringType.GenericArguments.any()) {
BytecodeGenerator.emitBridgeMethod(context, typeBuilder, methodBuilder, invokeMethod);
}
// getMethodCore()
methodBuilder = typeBuilder.defineMethod("getMethodCore");
methodBuilder.setProtected(true);
methodBuilder.setFinal(true);
methodBuilder.setReturnType(context.TypeSystem.getType("java/lang/reflect/Method"));
gen = methodBuilder.CodeGenerator;
gen.beginScope();
var classType = context.TypeSystem.getType("java/lang/Class");
BytecodeHelper.emitTypeof(gen, context.TypeSystem, method.DeclaringType);
gen.emit(Opcode.Ldc, method.Name);
BytecodeHelper.emitIntConstant(gen, invokeMethod.Parameters.count());
BytecodeHelper.emitNewarray(gen, 1, classType);
int i = 0;
foreach (var p in invokeMethod.Parameters) {
gen.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(gen, i++);
BytecodeHelper.emitTypeof(gen, context.TypeSystem, p.Type);
gen.emit(Opcode.Aastore);
}
var argTypes = new ArrayList<TypeInfo>();
argTypes.add(context.TypeSystem.StringType);
argTypes.add(context.TypeSystem.getGenericType(classType, Collections.singletonList(context.TypeSystem.UnboundedWildcard)).ArrayType);
gen.emit(Opcode.Invokevirtual, classType.getMethod("getMethod", argTypes));
gen.emit(Opcode.Areturn);
gen.endScope();
// getMethodSignature()
methodBuilder = typeBuilder.defineMethod("getMethodSignature");
methodBuilder.setProtected(true);
methodBuilder.setFinal(true);
var objectType = context.TypeSystem.ObjectType;
methodBuilder.setReturnType(objectType);
gen = methodBuilder.CodeGenerator;
gen.beginScope();
gen.emit(Opcode.Ldc, method.DeclaringType.FullName + "." + method.Name + method.Descriptor);
gen.emit(Opcode.Areturn);
gen.endScope();
// Constructor T(object)
methodBuilder = typeBuilder.defineMethod("<init>");
methodBuilder.setProtected(true);
methodBuilder.setReturnType(context.TypeSystem.VoidType);
if (!method.IsStatic) {
var parameterBuilder = methodBuilder.addParameter(objectType);
parameterBuilder.setName("target");
}
var baseConstructor = typeBuilder.BaseType.getMethod("<init>", Collections.singletonList(objectType));
gen = methodBuilder.CodeGenerator;
gen.beginScope();
gen.emit(Opcode.Aload, gen.getLocal("this"));
if (method.IsStatic) {
gen.emit(Opcode.Aconst_Null);
} else {
gen.emit(Opcode.Aload, gen.getLocal("target"));
}
gen.emit(Opcode.Invokespecial, baseConstructor);
gen.emit(Opcode.Return);
gen.endScope();
return typeBuilder;
}
private static TypeBuilder getAccessorTypeBuilder(TypeInfo currentType, TypeInfo memberDeclaringType) {
var outerClass = (TypeBuilder)currentType.OriginalTypeDefinition;
memberDeclaringType = memberDeclaringType.OriginalTypeDefinition;
while ((outerClass = (TypeBuilder)outerClass.DeclaringType) != null) {
if (memberDeclaringType.isAssignableFrom(outerClass)) {
break;
}
}
return outerClass;
}
static void emitMethodAccess(CompilerContext context, MethodInfo method, bool isSuperCall) {
var generator = context.MethodGenerationContext.Generator;
if (requireAccessor(context, method.DeclaringType, method.IsPublic, method.IsProtected, method.IsPrivate)) {
var accessor = context.PrivateAccessors[method];
if (accessor == null) {
var outerClass = getAccessorTypeBuilder(context.MethodGenerationContext.CurrentMethod.DeclaringType, method.DeclaringType);
int n = outerClass.Methods.count(p => p.Name.startsWith("access$"));
var methodBuilder = outerClass.defineMethod("access$" + n);
methodBuilder.setReturnType(method.ReturnType);
methodBuilder.setStatic(method.IsStatic);
methodBuilder.setFinal(!method.IsStatic);
methodBuilder.setSynthetic(true);
methodBuilder.setVarargs(method.IsVarargs);
foreach (var p in method.Parameters) {
var pb = methodBuilder.addParameter(p.Type);
pb.setName(p.Name);
}
foreach (var t in method.Exceptions) {
methodBuilder.addException(t);
}
var gen = methodBuilder.CodeGenerator;
gen.beginScope();
if (!method.IsStatic) {
gen.emit(Opcode.Aload, gen.getLocal("this"));
}
foreach (var p in method.Parameters) {
gen.emit(BytecodeHelper.getLoadOpcode(p.Type), gen.getLocal(p.Name));
}
if (method.IsStatic) {
gen.emit(Opcode.Invokestatic, method);
} else {
gen.emit(Opcode.Invokevirtual, method);
}
gen.emit(BytecodeHelper.getReturnOpcode(method.ReturnType));
gen.endScope();
accessor = methodBuilder;
context.PrivateAccessors[method] = accessor;
}
method = accessor;
}
if (method.IsStatic) {
generator.emit(Opcode.Invokestatic, method);
} else if (method.IsConstructor) {
generator.emit(Opcode.Invokespecial, method);
} else if (method.DeclaringType.IsInterface) {
generator.emit(Opcode.Invokeinterface, method);
} else {
if (isSuperCall) {
generator.emit(Opcode.Invokespecial, method);
} else {
generator.emit(Opcode.Invokevirtual, method);
}
}
}
static void emitFieldAccess(CompilerContext context, FieldInfo field) {
var generator = context.MethodGenerationContext.Generator;
if (requireAccessor(context, field.DeclaringType, field.IsPublic, field.IsProtected, field.IsPrivate)) {
var accessor = context.PrivateAccessors[field];
if (accessor == null) {
var outerClass = getAccessorTypeBuilder(context.MethodGenerationContext.CurrentMethod.DeclaringType, field.DeclaringType);
int n = outerClass.Methods.count(p => p.Name.startsWith("access$"));
var methodBuilder = outerClass.defineMethod("access$" + n);
methodBuilder.setReturnType(field.Type);
methodBuilder.setStatic(field.IsStatic);
methodBuilder.setFinal(!field.IsStatic);
methodBuilder.setSynthetic(true);
var gen = methodBuilder.CodeGenerator;
gen.beginScope();
if (field.IsStatic) {
gen.emit(Opcode.Getstatic, field);
} else {
gen.emit(Opcode.Aload, gen.getLocal("this"));
gen.emit(Opcode.Getfield, field);
}
gen.emit(BytecodeHelper.getReturnOpcode(field.Type));
gen.endScope();
accessor = methodBuilder;
context.PrivateAccessors[field] = accessor;
}
if (field.IsStatic) {
generator.emit(Opcode.Invokestatic, accessor);
} else {
generator.emit(Opcode.Invokevirtual, accessor);
}
} else if (field.IsStatic) {
generator.emit(Opcode.Getstatic, field);
} else {
generator.emit(Opcode.Getfield, field);
}
}
static void emitPropertyAccess(CompilerContext context, MethodInfo method) {
var generator = context.MethodGenerationContext.Generator;
if (requireAccessor(context, method.DeclaringType, method.IsPublic, method.IsProtected, method.IsPrivate)) {
var accessor = context.PrivateAccessors[method];
if (accessor == null) {
var outerClass = getAccessorTypeBuilder(context.MethodGenerationContext.CurrentMethod.DeclaringType, method.DeclaringType);
int n = outerClass.Methods.count(p => p.Name.startsWith("access$"));
var type = method.getReturnType();
var methodBuilder = outerClass.defineMethod("access$" + n);
methodBuilder.setReturnType(type);
methodBuilder.setStatic(method.IsStatic);
methodBuilder.setFinal(!method.IsStatic);
methodBuilder.setSynthetic(true);
var gen = methodBuilder.CodeGenerator;
gen.beginScope();
if (method.IsStatic) {
gen.emit(Opcode.Invokestatic, method);
} else {
gen.emit(Opcode.Aload, gen.getLocal("this"));
gen.emit(Opcode.Invokevirtual, method);
}
gen.emit(BytecodeHelper.getReturnOpcode(type));
gen.endScope();
accessor = methodBuilder;
context.PrivateAccessors[method] = accessor;
}
if (method.IsStatic) {
generator.emit(Opcode.Invokestatic, accessor);
} else {
generator.emit(Opcode.Invokevirtual, accessor);
}
} else {
if (method.IsStatic) {
generator.emit(Opcode.Invokestatic, method);
} else if (method.DeclaringType.IsInterface) {
generator.emit(Opcode.Invokeinterface, method);
} else {
generator.emit(Opcode.Invokevirtual, method);
}
}
}
static void emitIndexerAccess(CompilerContext context, MethodInfo method) {
var generator = context.MethodGenerationContext.Generator;
if (requireAccessor(context, method.DeclaringType, method.IsPublic, method.IsProtected, method.IsPrivate)) {
var accessor = context.PrivateAccessors[method];
if (accessor == null) {
var outerClass = getAccessorTypeBuilder(context.MethodGenerationContext.CurrentMethod.DeclaringType, method.DeclaringType);
int n = outerClass.Methods.count(p => p.Name.startsWith("access$"));
var type = method.ReturnType;
var methodBuilder = outerClass.defineMethod("access$" + n);
methodBuilder.setReturnType(type);
methodBuilder.setStatic(method.IsStatic);
methodBuilder.setFinal(!method.IsStatic);
methodBuilder.setSynthetic(true);
foreach (var p in method.Parameters) {
var pb = methodBuilder.addParameter(p.Type);
pb.setName(p.Name);
}
var gen = methodBuilder.CodeGenerator;
gen.beginScope();
if (method.IsStatic) {
foreach (var p in method.Parameters) {
gen.emit(BytecodeHelper.getLoadOpcode(p.Type), gen.getLocal(p.Name));
}
gen.emit(Opcode.Invokestatic, method);
} else {
gen.emit(Opcode.Aload, gen.getLocal("this"));
foreach (var p in method.Parameters) {
gen.emit(BytecodeHelper.getLoadOpcode(p.Type), gen.getLocal(p.Name));
}
gen.emit(Opcode.Invokevirtual, method);
}
gen.emit(BytecodeHelper.getReturnOpcode(type));
gen.endScope();
accessor = methodBuilder;
context.PrivateAccessors[method] = accessor;
}
if (method.IsStatic) {
generator.emit(Opcode.Invokestatic, accessor);
} else {
generator.emit(Opcode.Invokevirtual, accessor);
}
} else {
if (method.IsStatic) {
generator.emit(Opcode.Invokestatic, method);
} else if (method.DeclaringType.IsInterface) {
generator.emit(Opcode.Invokeinterface, method);
} else {
generator.emit(Opcode.Invokevirtual, method);
}
}
}
static void emitFieldModification(CompilerContext context, FieldInfo field) {
var generator = context.MethodGenerationContext.Generator;
if (requireAccessor(context, field.DeclaringType, field.IsPublic, field.IsProtected, field.IsPrivate)) {
var mutator = context.PrivateMutators[field];
if (mutator == null) {
var outerClass = getAccessorTypeBuilder(context.MethodGenerationContext.CurrentMethod.DeclaringType, field.DeclaringType);
int n = outerClass.Methods.count(p => p.Name.startsWith("access$"));
var methodBuilder = outerClass.defineMethod("access$" + n);
methodBuilder.setReturnType(context.TypeSystem.VoidType);
methodBuilder.setStatic(field.IsStatic);
methodBuilder.setFinal(!field.IsStatic);
methodBuilder.setSynthetic(true);
var param = methodBuilder.addParameter(field.Type);
param.setName(field.Name);
var gen = methodBuilder.getCodeGenerator();
gen.beginScope();
if (field.IsStatic) {
gen.emit(BytecodeHelper.getLoadOpcode(field.Type), gen.getLocal(field.Name));
gen.emit(Opcode.Putstatic, field);
} else {
gen.emit(Opcode.Aload, gen.getLocal("this"));
gen.emit(BytecodeHelper.getLoadOpcode(field.Type), gen.getLocal(field.Name));
gen.emit(Opcode.Putfield, field);
}
gen.emit(Opcode.Return);
gen.endScope();
mutator = methodBuilder;
context.PrivateMutators[field] = mutator;
}
if (field.IsStatic) {
generator.emit(Opcode.Invokestatic, mutator);
} else {
generator.emit(Opcode.Invokevirtual, mutator);
}
} else if (field.IsStatic) {
generator.emit(Opcode.Putstatic, field);
} else {
generator.emit(Opcode.Putfield, field);
}
}
static void emitPropertyOrIndexerModification(CompilerContext context, MethodInfo method) {
var generator = context.MethodGenerationContext.Generator;
if (requireAccessor(context, method.DeclaringType, method.IsPublic, method.IsProtected, method.IsPrivate)) {
var mutator = context.PrivateMutators[method];
if (mutator == null) {
var outerClass = (TypeBuilder)context.MethodGenerationContext.CurrentMethod.DeclaringType;
var methodDeclaringType = method.DeclaringType.OriginalTypeDefinition;
while ((outerClass = (TypeBuilder)outerClass.DeclaringType) != null) {
if (methodDeclaringType.isAssignableFrom(outerClass.OriginalTypeDefinition)) {
break;
}
}
int n = outerClass.Methods.count(p => p.Name.startsWith("access$"));
var methodBuilder = outerClass.defineMethod("access$" + n);
methodBuilder.setReturnType(context.TypeSystem.VoidType);
methodBuilder.setStatic(method.IsStatic);
methodBuilder.setFinal(!method.IsStatic);
methodBuilder.setSynthetic(true);
foreach (var p in method.Parameters) {
var param = methodBuilder.addParameter(p.Type);
param.setName(p.Name);
}
var gen = methodBuilder.CodeGenerator;
gen.beginScope();
if (method.IsStatic) {
foreach (var p in method.Parameters) {
gen.emit(BytecodeHelper.getLoadOpcode(p.Type), gen.getLocal(p.Name));
}
gen.emit(Opcode.Invokestatic, method);
} else {
gen.emit(Opcode.Aload, gen.getLocal("this"));
foreach (var p in method.Parameters) {
gen.emit(BytecodeHelper.getLoadOpcode(p.Type), gen.getLocal(p.Name));
}
gen.emit(Opcode.Invokevirtual, method);
}
gen.emit(Opcode.Return);
gen.endScope();
mutator = methodBuilder;
context.PrivateMutators[method] = mutator;
}
if (method.IsStatic) {
generator.emit(Opcode.Invokestatic, mutator);
} else {
generator.emit(Opcode.Invokevirtual, mutator);
}
} else if (method.IsStatic) {
generator.emit(Opcode.Invokestatic, method);
} else if (method.DeclaringType.IsInterface) {
generator.emit(Opcode.Invokeinterface, method);
} else {
generator.emit(Opcode.Invokevirtual, method);
}
}
static bool requireAccessor(CompilerContext context, TypeInfo declaringType,
bool isPublic, bool isProtected, bool isPrivate) {
var currentType = context.MethodGenerationContext.CurrentMethod.DeclaringType;
if (isPublic || declaringType.OriginalTypeDefinition == currentType.OriginalTypeDefinition) {
return false;
}
if (isProtected && declaringType.isAssignableFrom(currentType)) {
return false;
}
if (!isPrivate && declaringType.PackageName.equals(currentType.PackageName)) {
return false;
}
return true;
}
}
}
| |
using System;
using System.Web;
using System.Web.Security;
using System.Web.Configuration;
using System.Globalization;
using System.Collections.Specialized;
using System.Data;
using System.Data.OracleClient;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Configuration.Provider;
using PetShop.DBUtility;
namespace PetShop.Membership {
class OracleMembershipProvider : MembershipProvider {
// Private members
private const int SALT_SIZE_IN_BYTES = 16;
private bool enablePasswordRetrieval;
private bool enablePasswordReset;
private bool requiresQuestionAndAnswer;
private string applicationName;
private int applicationId = 0;
private bool requiresUniqueEmail;
private string connectionStringName;
private string hashAlgorithmType;
private int maxInvalidPasswordAttempts;
private int passwordAttemptWindow;
private int minRequiredPasswordLength;
private int minRequiredNonalphanumericCharacters;
private string passwordStrengthRegularExpression;
private MembershipPasswordFormat passwordFormat;
/// <summary>
/// The name of the application using the custom membership provider.
/// </summary>
public override bool EnablePasswordRetrieval {
get {
return enablePasswordRetrieval;
}
}
/// <summary>
/// Indicates whether the membership provider is configured to allow users to reset their passwords.
/// </summary>
public override bool EnablePasswordReset {
get {
return enablePasswordReset;
}
}
/// <summary>
/// Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval.
/// </summary>
public override bool RequiresQuestionAndAnswer {
get {
return requiresQuestionAndAnswer;
}
}
/// <summary>
/// Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name.
/// </summary>
public override bool RequiresUniqueEmail {
get {
return requiresUniqueEmail;
}
}
/// <summary>
/// Gets a value indicating the format for storing passwords in the membership data store.
/// </summary>
public override MembershipPasswordFormat PasswordFormat {
get {
return passwordFormat;
}
}
/// <summary>
/// Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out.
/// </summary>
public override int MaxInvalidPasswordAttempts {
get {
return maxInvalidPasswordAttempts;
}
}
/// <summary>
/// Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.
/// </summary>
public override int PasswordAttemptWindow {
get {
return passwordAttemptWindow;
}
}
/// <summary>
/// Gets the minimum length required for a password.
/// </summary>
public override int MinRequiredPasswordLength {
get {
return minRequiredPasswordLength;
}
}
/// <summary>
/// Gets the minimum number of special characters that must be present in a valid password.
/// </summary>
public override int MinRequiredNonAlphanumericCharacters {
get {
return minRequiredNonalphanumericCharacters;
}
}
/// <summary>
/// Gets the regular expression used to evaluate a password.
/// </summary>
public override string PasswordStrengthRegularExpression {
get {
return passwordStrengthRegularExpression;
}
}
/// <summary>
/// The name of the application using the custom membership provider.
/// </summary>
public override string ApplicationName {
get {
return applicationName;
}
set {
applicationName = value;
}
}
/// <summary>
/// Initializes the provider.
/// </summary>
/// <param name="name">The friendly name of the provider.</param>
/// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
public override void Initialize(string name, NameValueCollection config) {
// Check config
if(config == null)
throw new ArgumentNullException("config");
// Get name
if(String.IsNullOrEmpty(name))
name = "OracleMembershipProvider";
// Get descripton
if(string.IsNullOrEmpty(config["description"])) {
config.Remove("description");
config.Add("description", "Oracle Membership Provider");
}
// Initialize base class
base.Initialize(name, config);
// Get values from config
enablePasswordRetrieval = GetBooleanValue(config, "enablePasswordRetrieval", false);
enablePasswordReset = GetBooleanValue(config, "enablePasswordReset", true);
requiresQuestionAndAnswer = GetBooleanValue(config, "requiresQuestionAndAnswer", true);
requiresUniqueEmail = GetBooleanValue(config, "requiresUniqueEmail", true);
maxInvalidPasswordAttempts = GetIntValue(config, "maxInvalidPasswordAttempts", 5, false, 0);
passwordAttemptWindow = GetIntValue(config, "passwordAttemptWindow", 10, false, 0);
minRequiredPasswordLength = GetIntValue(config, "minRequiredPasswordLength", 7, false, 128);
minRequiredNonalphanumericCharacters = GetIntValue(config, "minRequiredNonalphanumericCharacters", 1, true, 128);
// Get hash algorhithm
hashAlgorithmType = config["hashAlgorithmType"];
if(String.IsNullOrEmpty(hashAlgorithmType))
hashAlgorithmType = "SHA1";
// Get password validation Regular Expression
passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"];
if(passwordStrengthRegularExpression != null) {
passwordStrengthRegularExpression = passwordStrengthRegularExpression.Trim();
if(passwordStrengthRegularExpression.Length != 0) {
try {
Regex regex = new Regex(passwordStrengthRegularExpression);
}
catch(ArgumentException e) {
throw new ProviderException(e.Message, e);
}
}
}
else
passwordStrengthRegularExpression = string.Empty;
// Get application name
applicationName = config["applicationName"];
if(string.IsNullOrEmpty(applicationName))
applicationName = GetDefaultAppName();
if(applicationName.Length > 255)
throw new ProviderException("Provider application name is too long, max length is 255.");
// Get application ID
applicationId = GetApplicationID(applicationName, true);
if(applicationId == 0)
throw new ProviderException("Provider application ID error.");
// Get password format
string strTemp = config["passwordFormat"];
if(strTemp == null)
strTemp = "Hashed";
switch(strTemp) {
case "Clear":
passwordFormat = MembershipPasswordFormat.Clear;
break;
case "Encrypted":
passwordFormat = MembershipPasswordFormat.Encrypted;
break;
case "Hashed":
passwordFormat = MembershipPasswordFormat.Hashed;
break;
default:
throw new ProviderException("Bad password format");
}
if(passwordFormat == MembershipPasswordFormat.Hashed && enablePasswordRetrieval)
throw new ProviderException("Provider cannot retrieve hashed password");
// Get connection string name
connectionStringName = config["connectionStringName"];
if(connectionStringName == null || connectionStringName.Length < 1)
throw new ProviderException("Connection name not specified");
// Clean up config
config.Remove("connectionStringName");
config.Remove("enablePasswordRetrieval");
config.Remove("enablePasswordReset");
config.Remove("requiresQuestionAndAnswer");
config.Remove("applicationName");
config.Remove("requiresUniqueEmail");
config.Remove("maxInvalidPasswordAttempts");
config.Remove("passwordAttemptWindow");
config.Remove("passwordFormat");
config.Remove("name");
config.Remove("description");
config.Remove("minRequiredPasswordLength");
config.Remove("minRequiredNonalphanumericCharacters");
config.Remove("passwordStrengthRegularExpression");
config.Remove("hashAlgorithmType");
if(config.Count > 0) {
string attribUnrecognized = config.GetKey(0);
if(!String.IsNullOrEmpty(attribUnrecognized))
throw new ProviderException("Provider unrecognized attribute: " + attribUnrecognized);
}
}
/// <summary>
/// Adds a new membership user to the data source.
/// </summary>
/// <param name="username">The user name for the new user.</param>
/// <param name="password">The password for the new user.</param>
/// <param name="email">The e-mail address for the new user.</param>
/// <param name="passwordQuestion">The password question for the new user.</param>
/// <param name="passwordAnswer">The password answer for the new user</param>
/// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
/// <param name="userId">The user ID</param>
/// <param name="status">A System.Web.Security.MembershipCreateStatus enumeration value indicating whether the user was created successfully.</param>
/// <returns></returns>
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object userId, out MembershipCreateStatus status) {
if(!ValidateParameter(ref password, true, true, false, 0)) {
status = MembershipCreateStatus.InvalidPassword;
return null;
}
if(passwordStrengthRegularExpression != null) {
if(!Regex.IsMatch(password, passwordStrengthRegularExpression)) {
status = MembershipCreateStatus.InvalidPassword;
return null;
}
}
if(minRequiredNonalphanumericCharacters > 0) {
if(Regex.Matches(password, @"\W").Count < minRequiredNonalphanumericCharacters) {
status = MembershipCreateStatus.InvalidPassword;
return null;
}
}
if(password.Length < minRequiredPasswordLength) {
status = MembershipCreateStatus.InvalidPassword;
return null;
}
string salt = GenerateSalt();
string pass = EncodePassword(password, (int)passwordFormat, salt);
if(pass.Length > 128) {
status = MembershipCreateStatus.InvalidPassword;
return null;
}
if(!ValidateParameter(ref username, true, true, true, 255)) {
status = MembershipCreateStatus.InvalidUserName;
return null;
}
if(!ValidateParameter(ref email, RequiresUniqueEmail, RequiresUniqueEmail, false, 128)) {
status = MembershipCreateStatus.InvalidEmail;
return null;
}
if(!ValidateParameter(ref passwordQuestion, RequiresQuestionAndAnswer, true, false, 255)) {
status = MembershipCreateStatus.InvalidQuestion;
return null;
}
if(!ValidateParameter(ref passwordAnswer, RequiresQuestionAndAnswer, true, false, 128)) {
status = MembershipCreateStatus.InvalidAnswer;
return null;
}
if(userId != null)
throw new ArgumentException("userId Parameter must be null");
status = MembershipCreateStatus.UserRejected;
//Create connection
OracleConnection connection = new OracleConnection(OracleHelper.ConnectionStringMembership);
connection.Open();
OracleTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
try {
DateTime dt = DateTime.Now;
bool isUserNew = true;
// Step 1: Check if the user exists in the Users table: create if not
int uid = GetUserID(transaction, applicationId, username, true, false, dt, out isUserNew);
if(uid == 0) { // User not created successfully!
status = MembershipCreateStatus.ProviderError;
return null;
}
// Step 2: Check if the user exists in the Membership table: Error if yes.
if(IsUserInMembership(transaction, uid)) {
status = MembershipCreateStatus.DuplicateUserName;
return null;
}
// Step 3: Check if Email is duplicate
if(IsEmailInMembership(transaction, email, applicationId)) {
status = MembershipCreateStatus.DuplicateEmail;
return null;
}
// Step 4: Create user in Membership table
int pFormat = (int)passwordFormat;
if(!InsertUser(transaction, uid, email, pass, pFormat, salt, "", "", isApproved, dt)) {
status = MembershipCreateStatus.ProviderError;
return null;
}
// Step 5: Update activity date if user is not new
if(!isUserNew) {
if(!UpdateLastActivityDate(transaction, uid, dt)) {
status = MembershipCreateStatus.ProviderError;
return null;
}
}
status = MembershipCreateStatus.Success;
return new MembershipUser(this.Name, username, uid, email, passwordQuestion, null, isApproved, false, dt, dt, dt, dt, DateTime.MinValue);
}
catch(Exception) {
if(status == MembershipCreateStatus.Success)
status = MembershipCreateStatus.ProviderError;
throw;
}
finally {
if(status == MembershipCreateStatus.Success)
transaction.Commit();
else
transaction.Rollback();
connection.Close();
connection.Dispose();
}
}
/// <summary>
/// Verifies that the specified user name and password exist in the data source.
/// </summary>
/// <param name="username">The name of the user to validate.</param>
/// <param name="password">The password for the specified user.</param>
/// <returns></returns>
public override bool ValidateUser(string username, string password) {
if(!ValidateParameter(ref username, true, true, false, 255))
return false;
if(!ValidateParameter(ref password, true, true, false, 128))
return false;
//Create connection
OracleConnection connection = new OracleConnection(OracleHelper.ConnectionStringMembership);
connection.Open();
OracleTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
bool success = false;
try {
DateTime dt = DateTime.Now;
bool isUserNew = false;
bool userIsApproved = false;
int uid = GetUserID(transaction, applicationId, username, false, false, dt, out isUserNew);
if(uid <= 0)
success = false;
if(CheckPassword(uid, password, out userIsApproved) && userIsApproved) {
if(!UpdateLastActivityDate(transaction, uid, dt))
success = false;
if(!UpdateLastLoginDate(transaction, uid, dt))
success = false;
success = true;
}
}
finally {
if(success)
transaction.Commit();
else
transaction.Rollback();
connection.Close();
connection.Dispose();
}
return success;
}
/// <summary>
/// Processes a request to update the password for a membership user.
/// </summary>
/// <param name="username">The user to update the password for.</param>
/// <param name="oldPassword">The current password for the specified user.</param>
/// <param name="newPassword">The new password for the specified user.</param>
/// <returns></returns>
public override bool ChangePassword(string username, string oldPassword, string newPassword) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Processes a request to update the password question and answer for a membership user.
/// </summary>
/// <param name="username">The user to change the password question and answer for.</param>
/// <param name="password">The password for the specified user.</param>
/// <param name="newPasswordQuestion">The new password question for the specified user.</param>
/// <param name="newPasswordAnswer">The new password answer for the specified user.</param>
/// <returns></returns>
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Removes a user from the membership data source.
/// </summary>
/// <param name="username">The name of the user to delete.</param>
/// <param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param>
/// <returns>true if the user was successfully deleted; otherwise, false.</returns>
public override bool DeleteUser(string username, bool deleteAllRelatedData) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match.
/// </summary>
/// <param name="emailToMatch">The e-mail address to search for.</param>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>A System.Web.Security.MembershipUserCollection collection that contains a page of pageSizeSystem.Web.Security.MembershipUser objects beginning at the page specified by pageIndex.</returns>
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Gets a collection of membership users where the user name contains the specified user name to match.
/// </summary>
/// <param name="usernameToMatch">The user name to search for.</param>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>A System.Web.Security.MembershipUserCollection collection that contains a page of pageSizeSystem.Web.Security.MembershipUser objects beginning at the page specified by pageIndex.</returns>
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Gets a collection of all the users in the data source in pages of data.
/// </summary>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>A System.Web.Security.MembershipUserCollection collection that contains a page of pageSizeSystem.Web.Security.MembershipUser objects beginning at the page specified by pageIndex.</returns>
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Gets the number of users currently accessing the application.
/// </summary>
/// <returns>The number of users currently accessing the application.</returns>
public override int GetNumberOfUsersOnline() {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Gets the password for the specified user name from the data source.
/// </summary>
/// <param name="username">The user to retrieve the password for.</param>
/// <param name="answer">The password answer for the user.</param>
/// <returns>The password for the specified user name.</returns>
public override string GetPassword(string username, string answer) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user.
/// </summary>
/// <param name="username">The name of the user to get information for.</param>
/// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
/// <returns>A System.Web.Security.MembershipUser object populated with the specified user's information from the data source.</returns>
public override MembershipUser GetUser(string username, bool userIsOnline) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Gets information from the data source for a user based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user.
/// </summary>
/// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param>
/// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
/// <returns>A System.Web.Security.MembershipUser object populated with the specified user's information from the data source.</returns>
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Gets the user name associated with the specified e-mail address.
/// </summary>
/// <param name="email">The e-mail address to search for.</param>
/// <returns>The user name associated with the specified e-mail address. If no match is found, return null.</returns>
public override string GetUserNameByEmail(string email) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Resets a user's password to a new, automatically generated password.
/// </summary>
/// <param name="username">The user to reset the password for.</param>
/// <param name="answer">The password answer for the specified user.</param>
/// <returns>The new password for the specified user.</returns>
public override string ResetPassword(string username, string answer) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Clears a lock so that the membership user can be validated.
/// </summary>
/// <param name="userName">The membership user to clear the lock status for.</param>
/// <returns>true if the membership user was successfully unlocked; otherwise, false.</returns>
public override bool UnlockUser(string userName) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Updates information about a user in the data source.
/// </summary>
/// <param name="user">A System.Web.Security.MembershipUser object that represents the user to update and the updated information for the user.</param>
public override void UpdateUser(MembershipUser user) {
throw new Exception("The method or operation is not implemented.");
}
// Private utility methods
// Oveloaded method to check password
private bool CheckPassword(int userId, string password, out int status) {
string salt;
bool userIsApproved;
int passwordFormat;
string pass = GetPasswordWithFormat(userId, null, false, out passwordFormat, out status, out salt, out userIsApproved);
string pass2 = EncodePassword(password, passwordFormat, salt);
return (pass == pass2);
}
private bool CheckPassword(int userId, string password, out bool userIsApproved) {
string salt;
int passwordFormat, status;
string pass = GetPasswordWithFormat(userId, null, false, out passwordFormat, out status, out salt, out userIsApproved);
string pass2 = EncodePassword(password, passwordFormat, salt);
return (pass == pass2);
}
// Generate salt to secure password encryption
private string GenerateSalt() {
byte[] buffer = new byte[SALT_SIZE_IN_BYTES];
(new RNGCryptoServiceProvider()).GetBytes(buffer);
return Convert.ToBase64String(buffer);
}
// Encode password
private string EncodePassword(string pass, int passwordFormat, string salt) {
if (passwordFormat == 0) // MembershipPasswordFormat.Clear
return pass;
byte[] bIn = Encoding.Unicode.GetBytes(pass);
byte[] bSalt = Convert.FromBase64String(salt);
byte[] bAll = new byte[bSalt.Length + bIn.Length];
byte[] bRet = null;
Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length);
Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length);
if (passwordFormat == 1) { // MembershipPasswordFormat.Hashed
HashAlgorithm s = HashAlgorithm.Create(hashAlgorithmType);
// If the hash algorithm is null (and came from config), throw a config exception
if (s == null)
throw new ProviderException("Could not create a hash algorithm");
bRet = s.ComputeHash(bAll);
}
else
bRet = EncryptPassword(bAll);
return Convert.ToBase64String(bRet);
}
// Discover booean value from config by specifying name
private static bool GetBooleanValue(NameValueCollection config, string valueName, bool defaultValue) {
string sValue = config[valueName];
if(sValue == null)
return defaultValue;
if(sValue == "true")
return true;
if(sValue == "false")
return false;
throw new Exception("The value must be a boolean for property '" + valueName + "'");
}
// Discover int value from config by specifying name
private static int GetIntValue(NameValueCollection config, string valueName, int defaultValue, bool zeroAllowed, int maxValueAllowed) {
string sValue = config[valueName];
if(sValue == null) {
return defaultValue;
}
int iValue;
try {
iValue = Convert.ToInt32(sValue, CultureInfo.InvariantCulture);
}
catch(InvalidCastException e) {
if(zeroAllowed)
throw new Exception("The value must be a positive integer for property '" + valueName + "'", e);
throw new Exception("The value must be a positive integer for property '" + valueName + "'", e);
}
if(zeroAllowed && iValue < 0)
throw new Exception("The value must be a non-negative integer for property '" + valueName + "'");
if(!zeroAllowed && iValue <= 0)
throw new Exception("The value must be a non-negative integer for property '" + valueName + "'");
if(maxValueAllowed > 0 && iValue > maxValueAllowed)
throw new Exception("The value is too big for '" + valueName + "' must be smaller than " + maxValueAllowed.ToString(CultureInfo.InvariantCulture));
return iValue;
}
// Create default application name
private static string GetDefaultAppName() {
string appName = System.Web.HttpRuntime.AppDomainAppVirtualPath;
if(string.IsNullOrEmpty(appName))
return "/";
return appName;
}
// Parameter validator
private static bool ValidateParameter(ref string param, bool checkForNull, bool checkIfEmpty, bool checkForCommas, int maxSize) {
if(param == null) {
if(checkForNull)
return false;
return true;
}
param = param.Trim();
if((checkIfEmpty && param.Length < 1) || (maxSize > 0 && param.Length > maxSize) || (checkForCommas && param.IndexOf(",") != -1))
return false;
return true;
}
// Check for reader for null
private static string GetNullableString(OracleDataReader reader, int col) {
if(reader.IsDBNull(col) == false)
return reader.GetString(col);
return null;
}
// Data Access methods
// Retrieve password
private static string GetPasswordWithFormat(int userId, string passwordAnswer, bool requiresQuestionAndAnswer, out int passwordFormat, out int status, out string passwordSalt, out bool userIsApproved) {
string storedPasswordAnswer;
string pass;
passwordFormat = 0;
status = 1; // status = user not found
passwordSalt = String.Empty;
userIsApproved = false;
if(userId == 0)
return null;
string select = "SELECT PASSWORDFORMAT, PASSWORD, PASSWORDANSWER, PASSWORDSALT, ISAPPROVED FROM MEMBERSHIP m, USERS u WHERE m.USERID = :UserId AND m.USERID = u.UserId";
OracleParameter selectParam = new OracleParameter(":UserId", OracleType.Number, 10);
selectParam.Value = userId;
OracleDataReader reader = OracleHelper.ExecuteReader(OracleHelper.ConnectionStringMembership, CommandType.Text, select, selectParam);
if(!reader.Read()) { // Zero rows read = user-not-found
reader.Close();
return null;
}
passwordFormat = reader.GetInt32(0);
pass = GetNullableString(reader, 1);
storedPasswordAnswer = GetNullableString(reader, 2);
passwordSalt = GetNullableString(reader, 3);
userIsApproved = OracleHelper.OraBool(reader.GetString(4));
if(requiresQuestionAndAnswer && String.Compare(storedPasswordAnswer, passwordAnswer, true, CultureInfo.InvariantCulture) != 0) {
status = 3;
pass = null;
}
else
status = 0;
reader.Close();
return pass;
}
// Update last login date and time
private static bool UpdateLastLoginDate(OracleTransaction transaction, int userId, DateTime dt) {
string update = "UPDATE MEMBERSHIP SET LASTLOGINDATE = :LastLoginDate WHERE USERID = :UserID";
OracleParameter[] updateParms = { new OracleParameter(":UserID", OracleType.Number, 10), new OracleParameter(":LastLoginDate", OracleType.DateTime) };
updateParms[0].Value = userId;
updateParms[1].Value = dt;
if(OracleHelper.ExecuteNonQuery(transaction, CommandType.Text, update, updateParms) != 1)
return false;
else
return true;
}
// Update last activity date and time
private static bool UpdateLastActivityDate(OracleTransaction transaction, int userId, DateTime dt) {
string update = "UPDATE USERS SET LASTACTIVITYDATE = :LastActivityDate WHERE USERID = :UserID";
OracleParameter[] updateParms = { new OracleParameter(":UserID", OracleType.Number, 10), new OracleParameter(":LastActivityDate", OracleType.DateTime) };
updateParms[0].Value = userId;
updateParms[1].Value = dt;
if(OracleHelper.ExecuteNonQuery(transaction, CommandType.Text, update, updateParms) != 1)
return false;
else
return true;
}
// Insert a new user
private static bool InsertUser(OracleTransaction transaction, int userId, string email, string password, int passFormat, string passSalt, string passQuestion, string passAnswer, bool isApproved, DateTime dt) {
string insert = "INSERT INTO MEMBERSHIP (USERID, EMAIL, PASSWORD, PASSWORDFORMAT, PASSWORDSALT, PASSWORDQUESTION, PASSWORDANSWER, ISAPPROVED, CREATEDDATE, LASTLOGINDATE, LASTPASSWORDCHANGEDDATE) VALUES (:UserID, :Email, :Pass, :PasswordFormat, :PasswordSalt, :PasswordQuestion, :PasswordAnswer, :IsApproved, :CDate, :LLDate, :LPCDate)";
OracleParameter[] insertParms = { new OracleParameter(":UserID", OracleType.Number, 10), new OracleParameter(":Email", OracleType.VarChar, 128), new OracleParameter(":Pass", OracleType.VarChar, 128), new OracleParameter(":PasswordFormat", OracleType.Number, 10), new OracleParameter(":PasswordSalt", OracleType.VarChar, 128), new OracleParameter(":PasswordQuestion", OracleType.VarChar, 256), new OracleParameter(":PasswordAnswer", OracleType.VarChar, 128), new OracleParameter(":IsApproved", OracleType.VarChar, 1), new OracleParameter(":CDate", OracleType.DateTime), new OracleParameter(":LLDate", OracleType.DateTime), new OracleParameter(":LPCDate", OracleType.DateTime) };
insertParms[0].Value = userId;
insertParms[1].Value = email;
insertParms[2].Value = password;
insertParms[3].Value = passFormat;
insertParms[4].Value = passSalt;
insertParms[5].Value = passQuestion;
insertParms[6].Value = passAnswer;
insertParms[7].Value = OracleHelper.OraBit(isApproved);
insertParms[8].Value = dt;
insertParms[9].Value = dt;
insertParms[10].Value = dt;
if(OracleHelper.ExecuteNonQuery(transaction, CommandType.Text, insert, insertParms) != 1)
return false;
else
return true;
}
// Check if email exist in membership database
private static bool IsEmailInMembership(OracleTransaction transaction, string email, int applicationID) {
string select = "SELECT u.UserId FROM MEMBERSHIP m, USERS u WHERE u.APPLICATIONID = :AppId AND m.USERID = u.USERID AND m.EMAIL = :Email";
OracleParameter[] selectParms = { new OracleParameter(":AppId", OracleType.Number, 10), new OracleParameter(":Email", OracleType.VarChar, 128) };
selectParms[0].Value = applicationID;
selectParms[1].Value = email;
object result = OracleHelper.ExecuteScalar(transaction, CommandType.Text, select, selectParms);
if(result != null && (Convert.ToInt32(result) != 0))
return true;
else
return false;
}
// Check if user exist in membership database
private static bool IsUserInMembership(OracleTransaction transaction, int UserId) {
string select = "SELECT USERID FROM MEMBERSHIP WHERE USERID = :UserID";
OracleParameter selectParam = new OracleParameter(":UserID", OracleType.Number, 10);
selectParam.Value = UserId;
object result = OracleHelper.ExecuteScalar(transaction, CommandType.Text, select, selectParam);
if(result != null && (Convert.ToInt32(result) != 0))
return true;
else
return false;
}
// Get user ID
private static int GetUserID(OracleTransaction transaction, int applicationID, string userName, bool createIfNeeded, bool newUserIsAnonymous, DateTime lastActivityDate, out bool isUserNew) {
isUserNew = false;
string select = "SELECT UserId FROM USERS WHERE APPLICATIONID = :AppId AND USERNAME = :UserName";
string selectId = "SELECT USERID.NEXTVAL FROM DUAL";
string insert = "INSERT INTO USERS (USERID, APPLICATIONID, USERNAME, ISANONYMOUS, LASTACTIVITYDATE) VALUES (:UserID, :AppID, :UserName, :IsAnonymous, :LastActivityDate)";
//Get UserId
OracleParameter[] selectParms = { new OracleParameter(":AppId", OracleType.Number, 10), new OracleParameter(":UserName", OracleType.VarChar, 256) };
selectParms[0].Value = applicationID;
selectParms[1].Value = userName;
object lookupResult = OracleHelper.ExecuteScalar(transaction, CommandType.Text, select, selectParms);
if(lookupResult != null)
return Convert.ToInt32(lookupResult);
// Create new user
isUserNew = true;
if(createIfNeeded) {
object userId = OracleHelper.ExecuteScalar(transaction, CommandType.Text, selectId, null);
if(userId != null) {
int uid = Convert.ToInt32(userId);
OracleParameter[] insertParms = { new OracleParameter(":UserID", OracleType.Number, 10), new OracleParameter(":AppID", OracleType.Number, 10), new OracleParameter(":UserName", OracleType.VarChar, 256), new OracleParameter(":IsAnonymous", OracleType.VarChar, 1), new OracleParameter(":LastActivityDate", OracleType.DateTime) };
insertParms[0].Value = uid;
insertParms[1].Value = applicationID;
insertParms[2].Value = userName;
insertParms[3].Value = OracleHelper.OraBit(newUserIsAnonymous);
insertParms[4].Value = new DateTime(lastActivityDate.Year, lastActivityDate.Month, lastActivityDate.Day, lastActivityDate.Hour, lastActivityDate.Minute, lastActivityDate.Second);
if(OracleHelper.ExecuteNonQuery(transaction, CommandType.Text, insert, insertParms) != 0)
return uid;
}
}
//Something went wrong
return 0;
}
// Get application ID
private static int GetApplicationID(string applicationName, bool createIfNeeded) {
string select = "SELECT APPLICATIONID FROM APPLICATIONS WHERE APPLICATIONNAME = :AppName";
string selectId = "SELECT APPLICATIONID.NEXTVAL FROM DUAL";
string insert = "INSERT INTO APPLICATIONS (APPLICATIONID, APPLICATIONNAME) VALUES (:AppID, :AppName)";
//Create connection
OracleConnection connection = new OracleConnection(OracleHelper.ConnectionStringMembership);
connection.Open();
try {
OracleParameter selectParam = new OracleParameter(":AppName", OracleType.VarChar, 256);
selectParam.Value = applicationName;
object lookupResult = OracleHelper.ExecuteScalar(connection, CommandType.Text, select, selectParam);
if(lookupResult != null)
return Convert.ToInt32(lookupResult);
if(createIfNeeded) {
object appId = OracleHelper.ExecuteScalar(connection, CommandType.Text, selectId, null);
if((appId != null)) {
int aid = Convert.ToInt32(appId);
OracleParameter[] insertParms = { new OracleParameter(":AppID", OracleType.Number, 10), new OracleParameter(":AppName", OracleType.VarChar, 256) };
insertParms[0].Value = aid;
insertParms[1].Value = applicationName;
if(OracleHelper.ExecuteNonQuery(connection, CommandType.Text, insert, insertParms) == 1)
return aid;
}
}
}
finally {
connection.Close();
connection.Dispose();
}
return 0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading;
using Microsoft.Win32;
namespace System.Diagnostics
{
internal static class SharedUtils
{
internal static Win32Exception CreateSafeWin32Exception()
{
return CreateSafeWin32Exception(0);
}
internal static Win32Exception CreateSafeWin32Exception(int error)
{
Win32Exception newException = null;
if (error == 0)
newException = new Win32Exception();
else
newException = new Win32Exception(error);
return newException;
}
internal static void EnterMutex(string name, ref Mutex mutex)
{
string mutexName = null;
mutexName = "Global\\" + name;
EnterMutexWithoutGlobal(mutexName, ref mutex);
}
internal static void EnterMutexWithoutGlobal(string mutexName, ref Mutex mutex)
{
bool createdNew;
MutexSecurity sec = new MutexSecurity();
SecurityIdentifier everyoneSid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
//sec.AddAccessRule(new MutexAccessRule(everyoneSid, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));
//Mutex tmpMutex = new Mutex(false, mutexName, out createdNew, sec);
Mutex tmpMutex = new Mutex(false, mutexName, out createdNew);
SafeWaitForMutex(tmpMutex, ref mutex);
}
private static bool SafeWaitForMutex(Mutex mutexIn, ref Mutex mutexOut)
{
Debug.Assert(mutexOut == null, "You must pass in a null ref Mutex");
while (true)
{
if (!SafeWaitForMutexOnce(mutexIn, ref mutexOut))
return false;
if (mutexOut != null)
return true;
Thread.Sleep(0);
}
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static bool SafeWaitForMutexOnce(Mutex mutexIn, ref Mutex mutexOut)
{
bool ret;
RuntimeHelpers.PrepareConstrainedRegions();
try
{ }
finally
{
Thread.BeginCriticalRegion();
Thread.BeginThreadAffinity();
int result = Interop.Kernel32.WaitForSingleObject(mutexIn.SafeWaitHandle, 500);
switch (result)
{
case NativeMethods.WAIT_OBJECT_0:
case NativeMethods.WAIT_ABANDONED:
mutexOut = mutexIn;
ret = true;
break;
case NativeMethods.WAIT_TIMEOUT:
ret = true;
break;
default:
ret = false;
break;
}
if (mutexOut == null)
{
Thread.EndThreadAffinity();
Thread.EndCriticalRegion();
}
}
return ret;
}
internal static string GetLatestBuildDllDirectory(string machineName)
{
string dllDir = "";
RegistryKey baseKey = null;
RegistryKey complusReg = null;
try
{
if (machineName.Equals("."))
{
return GetLocalBuildDirectory();
}
else
{
baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName);
}
if (baseKey == null)
throw new InvalidOperationException(SR.Format(SR.RegKeyMissingShort, "HKEY_LOCAL_MACHINE", machineName));
complusReg = baseKey.OpenSubKey("SOFTWARE\\Microsoft\\.NETFramework");
if (complusReg != null)
{
string installRoot = (string)complusReg.GetValue("InstallRoot");
if (installRoot != null && installRoot != String.Empty)
{
string versionPrefix = "v" + Environment.Version.Major + "." + Environment.Version.Minor;
RegistryKey policyKey = complusReg.OpenSubKey("policy");
string version = null;
if (policyKey != null)
{
try
{
RegistryKey bestKey = policyKey.OpenSubKey(versionPrefix);
if (bestKey != null)
{
try
{
version = versionPrefix + "." + GetLargestBuildNumberFromKey(bestKey);
}
finally
{
bestKey.Close();
}
}
else
{
string[] majorVersions = policyKey.GetSubKeyNames();
int[] largestVersion = new int[] { -1, -1, -1 };
for (int i = 0; i < majorVersions.Length; i++)
{
string majorVersion = majorVersions[i];
if (majorVersion.Length > 1 && majorVersion[0] == 'v' && majorVersion.Contains("."))
{
int[] currentVersion = new int[] { -1, -1, -1 };
string[] splitVersion = majorVersion.Substring(1).Split('.');
if (splitVersion.Length != 2)
{
continue;
}
if (!Int32.TryParse(splitVersion[0], out currentVersion[0]) || !Int32.TryParse(splitVersion[1], out currentVersion[1]))
{
continue;
}
RegistryKey k = policyKey.OpenSubKey(majorVersion);
if (k == null)
{
continue;
}
try
{
currentVersion[2] = GetLargestBuildNumberFromKey(k);
if (currentVersion[0] > largestVersion[0]
|| ((currentVersion[0] == largestVersion[0]) && (currentVersion[1] > largestVersion[1])))
{
largestVersion = currentVersion;
}
}
finally
{
k.Close();
}
}
}
version = "v" + largestVersion[0] + "." + largestVersion[1] + "." + largestVersion[2];
}
}
finally
{
policyKey.Close();
}
if (version != null && version != String.Empty)
{
StringBuilder installBuilder = new StringBuilder();
installBuilder.Append(installRoot);
if (!installRoot.EndsWith("\\", StringComparison.Ordinal))
installBuilder.Append("\\");
installBuilder.Append(version);
dllDir = installBuilder.ToString();
}
}
}
}
}
catch
{
}
finally
{
complusReg?.Close();
baseKey?.Close();
}
return dllDir;
}
private static int GetLargestBuildNumberFromKey(RegistryKey rootKey)
{
int largestBuild = -1;
string[] minorVersions = rootKey.GetValueNames();
for (int i = 0; i < minorVersions.Length; i++)
{
int o;
if (Int32.TryParse(minorVersions[i], out o))
{
largestBuild = (largestBuild > o) ? largestBuild : o;
}
}
return largestBuild;
}
private static string GetLocalBuildDirectory()
{
return RuntimeEnvironment.GetRuntimeDirectory();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorLogger;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
{
using Editor.Shared.Utilities;
using DiagnosticId = String;
using LanguageKind = String;
[Export(typeof(ICodeFixService)), Shared]
internal partial class CodeFixService : ForegroundThreadAffinitizedObject, ICodeFixService
{
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> _workspaceFixersMap;
private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>> _projectFixersMap;
// Shared by project fixers and workspace fixers.
private ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>> _fixerToFixableIdsMap = ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>>.Empty;
private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> _fixerPriorityMap;
private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider> _analyzerReferenceToFixersMap;
private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback _createProjectCodeFixProvider;
private readonly ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> _suppressionProvidersMap;
private readonly IEnumerable<Lazy<IErrorLoggerService>> _errorLoggers;
private ImmutableDictionary<object, FixAllProviderInfo> _fixAllProviderMap;
[ImportingConstructor]
public CodeFixService(
IDiagnosticAnalyzerService service,
[ImportMany]IEnumerable<Lazy<IErrorLoggerService>> loggers,
[ImportMany]IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> fixers,
[ImportMany]IEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>> suppressionProviders)
: base(assertIsForeground: false)
{
_errorLoggers = loggers;
_diagnosticService = service;
var fixersPerLanguageMap = fixers.ToPerLanguageMapWithMultipleLanguages();
var suppressionProvidersPerLanguageMap = suppressionProviders.ToPerLanguageMapWithMultipleLanguages();
_workspaceFixersMap = GetFixerPerLanguageMap(fixersPerLanguageMap, null);
_suppressionProvidersMap = GetSuppressionProvidersPerLanguageMap(suppressionProvidersPerLanguageMap);
// REVIEW: currently, fixer's priority is statically defined by the fixer itself. might considering making it more dynamic or configurable.
_fixerPriorityMap = GetFixerPriorityPerLanguageMap(fixersPerLanguageMap);
// Per-project fixers
_projectFixersMap = new ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<string, List<CodeFixProvider>>>();
_analyzerReferenceToFixersMap = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>();
_createProjectCodeFixProvider = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback(r => new ProjectCodeFixProvider(r));
_fixAllProviderMap = ImmutableDictionary<object, FixAllProviderInfo>.Empty;
}
public async Task<FirstDiagnosticResult> GetFirstDiagnosticWithFixAsync(Document document, TextSpan range, bool considerSuppressionFixes, CancellationToken cancellationToken)
{
if (document == null || !document.IsOpen())
{
return default(FirstDiagnosticResult);
}
using (var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject())
{
var fullResult = await _diagnosticService.TryAppendDiagnosticsForSpanAsync(document, range, diagnostics.Object, cancellationToken: cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics.Object)
{
cancellationToken.ThrowIfCancellationRequested();
if (!range.IntersectsWith(diagnostic.TextSpan))
{
continue;
}
// REVIEW: 2 possible designs.
// 1. find the first fix and then return right away. if the lightbulb is actually expanded, find all fixes for the line synchronously. or
// 2. kick off a task that finds all fixes for the given range here but return once we find the first one.
// at the same time, let the task to run to finish. if the lightbulb is expanded, we just simply use the task to get all fixes.
//
// first approach is simpler, so I will implement that first. if the first approach turns out to be not good enough, then
// I will try the second approach which will be more complex but quicker
var hasFix = await ContainsAnyFix(document, diagnostic, considerSuppressionFixes, cancellationToken).ConfigureAwait(false);
if (hasFix)
{
return new FirstDiagnosticResult(!fullResult, hasFix, diagnostic);
}
}
return new FirstDiagnosticResult(!fullResult, false, default(DiagnosticData));
}
}
public async Task<IEnumerable<CodeFixCollection>> GetFixesAsync(Document document, TextSpan range, bool includeSuppressionFixes, CancellationToken cancellationToken)
{
// REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back
// current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information
// (if it is up-to-date) or synchronously do the work at the spot.
//
// this design's weakness is that each side don't have enough information to narrow down works to do. it will most likely always do more works than needed.
// sometimes way more than it is needed. (compilation)
Dictionary<TextSpan, List<DiagnosticData>> aggregatedDiagnostics = null;
foreach (var diagnostic in await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, cancellationToken: cancellationToken).ConfigureAwait(false))
{
if (diagnostic.IsSuppressed)
{
continue;
}
cancellationToken.ThrowIfCancellationRequested();
aggregatedDiagnostics = aggregatedDiagnostics ?? new Dictionary<TextSpan, List<DiagnosticData>>();
aggregatedDiagnostics.GetOrAdd(diagnostic.TextSpan, _ => new List<DiagnosticData>()).Add(diagnostic);
}
var result = new List<CodeFixCollection>();
if (aggregatedDiagnostics == null)
{
return result;
}
foreach (var spanAndDiagnostic in aggregatedDiagnostics)
{
result = await AppendFixesAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false);
}
if (result.Any())
{
// sort the result to the order defined by the fixers
var priorityMap = _fixerPriorityMap[document.Project.Language].Value;
result.Sort((d1, d2) => priorityMap.ContainsKey((CodeFixProvider)d1.Provider) ? (priorityMap.ContainsKey((CodeFixProvider)d2.Provider) ? priorityMap[(CodeFixProvider)d1.Provider] - priorityMap[(CodeFixProvider)d2.Provider] : -1) : 1);
}
// TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
if (document.Project.Solution.Workspace.Kind != WorkspaceKind.Interactive && includeSuppressionFixes)
{
foreach (var spanAndDiagnostic in aggregatedDiagnostics)
{
result = await AppendSuppressionsAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false);
}
}
return result;
}
private async Task<List<CodeFixCollection>> AppendFixesAsync(
Document document,
TextSpan span,
IEnumerable<DiagnosticData> diagnostics,
List<CodeFixCollection> result,
CancellationToken cancellationToken)
{
Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap;
bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap);
var projectFixersMap = GetProjectFixers(document.Project);
var hasAnyProjectFixer = projectFixersMap.Any();
if (!hasAnySharedFixer && !hasAnyProjectFixer)
{
return result;
}
ImmutableArray<CodeFixProvider> workspaceFixers;
List<CodeFixProvider> projectFixers;
var allFixers = new List<CodeFixProvider>();
// TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
bool isInteractive = document.Project.Solution.Workspace.Kind == WorkspaceKind.Interactive;
foreach (var diagnosticId in diagnostics.Select(d => d.Id).Distinct())
{
cancellationToken.ThrowIfCancellationRequested();
if (hasAnySharedFixer && fixerMap.Value.TryGetValue(diagnosticId, out workspaceFixers))
{
if (isInteractive)
{
allFixers.AddRange(workspaceFixers.Where(IsInteractiveCodeFixProvider));
}
else
{
allFixers.AddRange(workspaceFixers);
}
}
if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out projectFixers))
{
Debug.Assert(!isInteractive);
allFixers.AddRange(projectFixers);
}
}
var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
foreach (var fixer in allFixers.Distinct())
{
cancellationToken.ThrowIfCancellationRequested();
Func<Diagnostic, bool> hasFix = (d) => this.GetFixableDiagnosticIds(fixer, extensionManager).Contains(d.Id);
Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes =
async (dxs) =>
{
var fixes = new List<CodeFix>();
var context = new CodeFixContext(document, span, dxs,
// TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs?
(action, applicableDiagnostics) =>
{
// Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
lock (fixes)
{
fixes.Add(new CodeFix(document.Project, action, applicableDiagnostics));
}
},
verifyArguments: false,
cancellationToken: cancellationToken);
var task = fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask;
await task.ConfigureAwait(false);
return fixes;
};
await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, fixer,
hasFix, getFixes, cancellationToken).ConfigureAwait(false);
}
return result;
}
private async Task<List<CodeFixCollection>> AppendSuppressionsAsync(
Document document, TextSpan span, IEnumerable<DiagnosticData> diagnostics, List<CodeFixCollection> result, CancellationToken cancellationToken)
{
Lazy<ISuppressionFixProvider> lazySuppressionProvider;
if (!_suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) || lazySuppressionProvider.Value == null)
{
return result;
}
Func<Diagnostic, bool> hasFix = (d) => lazySuppressionProvider.Value.CanBeSuppressedOrUnsuppressed(d);
Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes = (dxs) => lazySuppressionProvider.Value.GetSuppressionsAsync(document, span, dxs, cancellationToken);
await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, lazySuppressionProvider.Value, hasFix, getFixes, cancellationToken).ConfigureAwait(false);
return result;
}
private async Task<List<CodeFixCollection>> AppendFixesOrSuppressionsAsync(
Document document,
TextSpan span,
IEnumerable<DiagnosticData> diagnosticsWithSameSpan,
List<CodeFixCollection> result,
object fixer,
Func<Diagnostic, bool> hasFix,
Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes,
CancellationToken cancellationToken)
{
var diagnostics = (await diagnosticsWithSameSpan.OrderByDescending(d => d.Severity).ToDiagnosticsAsync(document.Project, cancellationToken).ConfigureAwait(false)).Where(d => hasFix(d)).ToImmutableArray();
if (diagnostics.Length <= 0)
{
// this can happen for suppression case where all diagnostics can't be suppressed
return result;
}
var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
var fixes = await extensionManager.PerformFunctionAsync(fixer, () => getFixes(diagnostics), defaultValue: SpecializedCollections.EmptyEnumerable<CodeFix>()).ConfigureAwait(false);
if (fixes != null && fixes.Any())
{
// If the fix provider supports fix all occurrences, then get the corresponding FixAllProviderInfo and fix all context.
var fixAllProviderInfo = extensionManager.PerformFunction(fixer, () => ImmutableInterlocked.GetOrAdd(ref _fixAllProviderMap, fixer, FixAllProviderInfo.Create), defaultValue: null);
FixAllState fixAllState = null;
IEnumerable<FixAllScope> supportedScopes = null;
if (fixAllProviderInfo != null)
{
var codeFixProvider = (fixer as CodeFixProvider) ?? new WrapperCodeFixProvider((ISuppressionFixProvider)fixer, diagnostics.Select(d => d.Id));
fixAllState = FixAllState.Create(
fixAllProviderInfo.FixAllProvider,
document, fixAllProviderInfo, codeFixProvider, diagnostics,
this.GetDocumentDiagnosticsAsync, this.GetProjectDiagnosticsAsync);
supportedScopes = fixAllProviderInfo.SupportedScopes;
}
result = result ?? new List<CodeFixCollection>();
var codeFix = new CodeFixCollection(
fixer, span, fixes, fixAllState,
supportedScopes, diagnostics.First());
result.Add(codeFix);
}
return result;
}
public CodeFixProvider GetSuppressionFixer(string language, IEnumerable<string> diagnosticIds)
{
Lazy<ISuppressionFixProvider> lazySuppressionProvider;
if (!_suppressionProvidersMap.TryGetValue(language, out lazySuppressionProvider) || lazySuppressionProvider.Value == null)
{
return null;
}
return new WrapperCodeFixProvider(lazySuppressionProvider.Value, diagnosticIds);
}
private async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(document);
var solution = document.Project.Solution;
var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(solution, null, document.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId != null));
return await diagnostics.ToDiagnosticsAsync(document.Project, cancellationToken).ConfigureAwait(false);
}
private async Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(project);
if (includeAllDocumentDiagnostics)
{
// Get all diagnostics for the entire project, including document diagnostics.
var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
return await diagnostics.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
}
else
{
// Get all no-location diagnostics for the project, doesn't include document diagnostics.
var diagnostics = await _diagnosticService.GetProjectDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId == null));
return await diagnostics.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
}
}
private async Task<bool> ContainsAnyFix(Document document, DiagnosticData diagnostic, bool considerSuppressionFixes, CancellationToken cancellationToken)
{
ImmutableArray<CodeFixProvider> workspaceFixers = ImmutableArray<CodeFixProvider>.Empty;
List<CodeFixProvider> projectFixers = null;
Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap;
bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap) && fixerMap.Value.TryGetValue(diagnostic.Id, out workspaceFixers);
var hasAnyProjectFixer = GetProjectFixers(document.Project).TryGetValue(diagnostic.Id, out projectFixers);
// TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
if (hasAnySharedFixer && document.Project.Solution.Workspace.Kind == WorkspaceKind.Interactive)
{
workspaceFixers = workspaceFixers.WhereAsArray(IsInteractiveCodeFixProvider);
hasAnySharedFixer = workspaceFixers.Any();
}
Lazy<ISuppressionFixProvider> lazySuppressionProvider = null;
var hasSuppressionFixer =
considerSuppressionFixes &&
_suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) &&
lazySuppressionProvider.Value != null;
if (!hasAnySharedFixer && !hasAnyProjectFixer && !hasSuppressionFixer)
{
return false;
}
var allFixers = ImmutableArray<CodeFixProvider>.Empty;
if (hasAnySharedFixer)
{
allFixers = workspaceFixers;
}
if (hasAnyProjectFixer)
{
allFixers = allFixers.AddRange(projectFixers);
}
var dx = await diagnostic.ToDiagnosticAsync(document.Project, cancellationToken).ConfigureAwait(false);
if (hasSuppressionFixer && lazySuppressionProvider.Value.CanBeSuppressedOrUnsuppressed(dx))
{
return true;
}
var fixes = new List<CodeFix>();
var context = new CodeFixContext(document, dx,
// TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs?
(action, applicableDiagnostics) =>
{
// Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
lock (fixes)
{
fixes.Add(new CodeFix(document.Project, action, applicableDiagnostics));
}
},
verifyArguments: false,
cancellationToken: cancellationToken);
var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
// we do have fixer. now let's see whether it actually can fix it
foreach (var fixer in allFixers)
{
await extensionManager.PerformActionAsync(fixer, () => fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask).ConfigureAwait(false);
foreach (var fix in fixes)
{
if (!fix.Action.PerformFinalApplicabilityCheck)
{
return true;
}
// Have to see if this fix is still applicable. Jump to the foreground thread
// to make that check.
var applicable = await Task.Factory.StartNew(() =>
{
this.AssertIsForeground();
return fix.Action.IsApplicable(document.Project.Solution.Workspace);
},
cancellationToken, TaskCreationOptions.None, this.ForegroundTaskScheduler).ConfigureAwait(false);
this.AssertIsBackground();
if (applicable)
{
return true;
}
}
}
return false;
}
private bool IsInteractiveCodeFixProvider(CodeFixProvider provider)
{
// TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
if (provider is FullyQualify.AbstractFullyQualifyCodeFixProvider)
{
return true;
}
var providerType = provider?.GetType();
while (providerType != null)
{
if (providerType.IsConstructedGenericType &&
providerType.GetGenericTypeDefinition() == typeof(AddImport.AbstractAddImportCodeFixProvider<>))
{
return true;
}
providerType = providerType.GetTypeInfo().BaseType;
}
return false;
}
private static readonly Func<DiagnosticId, List<CodeFixProvider>> s_createList = _ => new List<CodeFixProvider>();
private ImmutableArray<DiagnosticId> GetFixableDiagnosticIds(CodeFixProvider fixer, IExtensionManager extensionManager)
{
// If we are passed a null extension manager it means we do not have access to a document so there is nothing to
// show the user. In this case we will log any exceptions that occur, but the user will not see them.
if (extensionManager != null)
{
return extensionManager.PerformFunction(
fixer,
() => ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f)),
defaultValue: ImmutableArray<DiagnosticId>.Empty);
}
try
{
return ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f));
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception e)
{
foreach (var logger in _errorLoggers)
{
logger.Value.LogException(fixer, e);
}
return ImmutableArray<DiagnosticId>.Empty;
}
}
private static ImmutableArray<string> GetAndTestFixableDiagnosticIds(CodeFixProvider codeFixProvider)
{
var ids = codeFixProvider.FixableDiagnosticIds;
if (ids.IsDefault)
{
throw new InvalidOperationException(
string.Format(
WorkspacesResources._0_returned_an_uninitialized_ImmutableArray,
codeFixProvider.GetType().Name + "." + nameof(CodeFixProvider.FixableDiagnosticIds)));
}
return ids;
}
private ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> GetFixerPerLanguageMap(
Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage,
IExtensionManager extensionManager)
{
var fixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>>();
foreach (var languageKindAndFixers in fixersPerLanguage)
{
var lazyMap = new Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>(() =>
{
var mutableMap = new Dictionary<DiagnosticId, List<CodeFixProvider>>();
foreach (var fixer in languageKindAndFixers.Value)
{
foreach (var id in this.GetFixableDiagnosticIds(fixer.Value, extensionManager))
{
if (string.IsNullOrWhiteSpace(id))
{
continue;
}
var list = mutableMap.GetOrAdd(id, s_createList);
list.Add(fixer.Value);
}
}
var immutableMap = ImmutableDictionary.CreateBuilder<DiagnosticId, ImmutableArray<CodeFixProvider>>();
foreach (var diagnosticIdAndFixers in mutableMap)
{
immutableMap.Add(diagnosticIdAndFixers.Key, diagnosticIdAndFixers.Value.AsImmutableOrEmpty());
}
return immutableMap.ToImmutable();
}, isThreadSafe: true);
fixerMap = fixerMap.Add(languageKindAndFixers.Key, lazyMap);
}
return fixerMap;
}
private static ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> GetSuppressionProvidersPerLanguageMap(
Dictionary<LanguageKind, List<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>> suppressionProvidersPerLanguage)
{
var suppressionFixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ISuppressionFixProvider>>();
foreach (var languageKindAndFixers in suppressionProvidersPerLanguage)
{
var suppressionFixerLazyMap = new Lazy<ISuppressionFixProvider>(() => languageKindAndFixers.Value.SingleOrDefault().Value);
suppressionFixerMap = suppressionFixerMap.Add(languageKindAndFixers.Key, suppressionFixerLazyMap);
}
return suppressionFixerMap;
}
private static ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> GetFixerPriorityPerLanguageMap(
Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage)
{
var languageMap = ImmutableDictionary.CreateBuilder<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>>();
foreach (var languageAndFixers in fixersPerLanguage)
{
var lazyMap = new Lazy<ImmutableDictionary<CodeFixProvider, int>>(() =>
{
var priorityMap = ImmutableDictionary.CreateBuilder<CodeFixProvider, int>();
var fixers = ExtensionOrderer.Order(languageAndFixers.Value);
for (var i = 0; i < fixers.Count; i++)
{
priorityMap.Add(fixers[i].Value, i);
}
return priorityMap.ToImmutable();
}, isThreadSafe: true);
languageMap.Add(languageAndFixers.Key, lazyMap);
}
return languageMap.ToImmutable();
}
private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> GetProjectFixers(Project project)
{
// TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
return project.Solution.Workspace.Kind == WorkspaceKind.Interactive
? ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty
: _projectFixersMap.GetValue(project.AnalyzerReferences, pId => ComputeProjectFixers(project));
}
private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> ComputeProjectFixers(Project project)
{
var extensionManager = project.Solution.Workspace.Services.GetService<IExtensionManager>();
ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Builder builder = null;
foreach (var reference in project.AnalyzerReferences)
{
var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue(reference, _createProjectCodeFixProvider);
foreach (var fixer in projectCodeFixerProvider.GetFixers(project.Language))
{
var fixableIds = this.GetFixableDiagnosticIds(fixer, extensionManager);
foreach (var id in fixableIds)
{
if (string.IsNullOrWhiteSpace(id))
{
continue;
}
builder = builder ?? ImmutableDictionary.CreateBuilder<DiagnosticId, List<CodeFixProvider>>();
var list = builder.GetOrAdd(id, s_createList);
list.Add(fixer);
}
}
}
if (builder == null)
{
return ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty;
}
return builder.ToImmutable();
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. 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.IO;
using System.Linq;
using System.Text;
using Microsoft.DotNet.ProjectModel.Graph;
using Microsoft.DotNet.ProjectModel.Resolution;
using Microsoft.Extensions.Internal;
using NuGet.Frameworks;
namespace Microsoft.DotNet.ProjectModel
{
public class ProjectContextBuilder
{
private Project Project { get; set; }
private LockFile LockFile { get; set; }
private GlobalSettings GlobalSettings { get; set; }
private NuGetFramework TargetFramework { get; set; }
private IEnumerable<string> RuntimeIdentifiers { get; set; } = Enumerable.Empty<string>();
private string RootDirectory { get; set; }
private string ProjectDirectory { get; set; }
private string PackagesDirectory { get; set; }
private string ReferenceAssembliesPath { get; set; }
private bool IsDesignTime { get; set; }
private Func<string, Project> ProjectResolver { get; set; }
private Func<string, LockFile> LockFileResolver { get; set; }
private ProjectReaderSettings Settings { get; set; } = ProjectReaderSettings.ReadFromEnvironment();
public ProjectContextBuilder()
{
ProjectResolver = ResolveProject;
LockFileResolver = ResolveLockFile;
}
public ProjectContextBuilder WithLockFile(LockFile lockFile)
{
LockFile = lockFile;
return this;
}
public ProjectContextBuilder WithProject(Project project)
{
Project = project;
return this;
}
public ProjectContextBuilder WithProjectDirectory(string projectDirectory)
{
ProjectDirectory = projectDirectory;
return this;
}
public ProjectContextBuilder WithTargetFramework(NuGetFramework targetFramework)
{
TargetFramework = targetFramework;
return this;
}
public ProjectContextBuilder WithTargetFramework(string targetFramework)
{
TargetFramework = NuGetFramework.Parse(targetFramework);
return this;
}
public ProjectContextBuilder WithRuntimeIdentifiers(IEnumerable<string> runtimeIdentifiers)
{
RuntimeIdentifiers = runtimeIdentifiers;
return this;
}
public ProjectContextBuilder WithReferenceAssembliesPath(string referenceAssembliesPath)
{
ReferenceAssembliesPath = referenceAssembliesPath;
return this;
}
public ProjectContextBuilder WithPackagesDirectory(string packagesDirectory)
{
PackagesDirectory = packagesDirectory;
return this;
}
public ProjectContextBuilder WithRootDirectory(string rootDirectory)
{
RootDirectory = rootDirectory;
return this;
}
public ProjectContextBuilder WithProjectResolver(Func<string, Project> projectResolver)
{
ProjectResolver = projectResolver;
return this;
}
public ProjectContextBuilder WithLockFileResolver(Func<string, LockFile> lockFileResolver)
{
LockFileResolver = lockFileResolver;
return this;
}
public ProjectContextBuilder WithReaderSettings(ProjectReaderSettings settings)
{
Settings = settings;
return this;
}
public ProjectContextBuilder AsDesignTime()
{
IsDesignTime = true;
return this;
}
public IEnumerable<ProjectContext> BuildAllTargets()
{
ProjectDirectory = Project?.ProjectDirectory ?? ProjectDirectory;
EnsureProjectLoaded();
LockFile = LockFile ?? LockFileResolver(ProjectDirectory);
if (LockFile != null)
{
foreach (var target in LockFile.Targets)
{
yield return new ProjectContextBuilder()
.WithProject(Project)
.WithLockFile(LockFile)
.WithTargetFramework(target.TargetFramework)
.WithRuntimeIdentifiers(new[] { target.RuntimeIdentifier })
.Build();
}
}
}
public ProjectContext Build()
{
var diagnostics = new List<DiagnosticMessage>();
ProjectDirectory = Project?.ProjectDirectory ?? ProjectDirectory;
if (GlobalSettings == null && ProjectDirectory != null)
{
RootDirectory = ProjectRootResolver.ResolveRootDirectory(ProjectDirectory);
GlobalSettings globalSettings;
if (GlobalSettings.TryGetGlobalSettings(RootDirectory, out globalSettings))
{
GlobalSettings = globalSettings;
}
}
RootDirectory = GlobalSettings?.DirectoryPath ?? RootDirectory;
PackagesDirectory = PackagesDirectory ?? PackageDependencyProvider.ResolvePackagesPath(RootDirectory, GlobalSettings);
ReferenceAssembliesPath = ReferenceAssembliesPath ?? FrameworkReferenceResolver.GetDefaultReferenceAssembliesPath();
var frameworkReferenceResolver = new FrameworkReferenceResolver(ReferenceAssembliesPath);
LockFileLookup lockFileLookup = null;
EnsureProjectLoaded();
ReadLockFile(diagnostics);
var validLockFile = true;
string lockFileValidationMessage = null;
if (LockFile != null)
{
if (Project != null)
{
validLockFile = LockFile.IsValidForProject(Project, out lockFileValidationMessage);
}
lockFileLookup = new LockFileLookup(LockFile);
}
var libraries = new Dictionary<LibraryKey, LibraryDescription>();
var projectResolver = new ProjectDependencyProvider(ProjectResolver);
ProjectDescription mainProject = null;
if (Project != null)
{
mainProject = projectResolver.GetDescription(TargetFramework, Project, targetLibrary: null);
// Add the main project
libraries.Add(new LibraryKey(mainProject.Identity.Name), mainProject);
}
LockFileTarget target = null;
if (lockFileLookup != null)
{
target = SelectTarget(LockFile);
if (target != null)
{
var nugetPackageResolver = new PackageDependencyProvider(PackagesDirectory, frameworkReferenceResolver);
var msbuildProjectResolver = new MSBuildDependencyProvider(Project, ProjectResolver);
ScanLibraries(target, lockFileLookup, libraries, msbuildProjectResolver, nugetPackageResolver, projectResolver);
}
}
var referenceAssemblyDependencyResolver = new ReferenceAssemblyDependencyResolver(frameworkReferenceResolver);
bool requiresFrameworkAssemblies;
// Resolve the dependencies
ResolveDependencies(libraries, referenceAssemblyDependencyResolver, out requiresFrameworkAssemblies);
// REVIEW: Should this be in NuGet (possibly stored in the lock file?)
if (LockFile == null)
{
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.NU1009,
$"The expected lock file doesn't exist. Please run \"dotnet restore\" to generate a new lock file.",
Path.Combine(Project.ProjectDirectory, LockFile.FileName),
DiagnosticMessageSeverity.Error));
}
if (!validLockFile)
{
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.NU1006,
$"{lockFileValidationMessage}. Please run \"dotnet restore\" to generate a new lock file.",
Path.Combine(Project.ProjectDirectory, LockFile.FileName),
DiagnosticMessageSeverity.Warning));
}
if (requiresFrameworkAssemblies)
{
var frameworkInfo = Project.GetTargetFramework(TargetFramework);
if (string.IsNullOrEmpty(ReferenceAssembliesPath))
{
// If there was an attempt to use reference assemblies but they were not installed
// report an error
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.DOTNET1012,
$"The reference assemblies directory was not specified. You can set the location using the DOTNET_REFERENCE_ASSEMBLIES_PATH environment variable.",
filePath: Project.ProjectFilePath,
severity: DiagnosticMessageSeverity.Error,
startLine: frameworkInfo.Line,
startColumn: frameworkInfo.Column
));
}
else if (!frameworkReferenceResolver.IsInstalled(TargetFramework))
{
// If there was an attempt to use reference assemblies but they were not installed
// report an error
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.DOTNET1011,
$"Framework not installed: {TargetFramework.DotNetFrameworkName} in {ReferenceAssembliesPath}",
filePath: Project.ProjectFilePath,
severity: DiagnosticMessageSeverity.Error,
startLine: frameworkInfo.Line,
startColumn: frameworkInfo.Column
));
}
}
// Create a library manager
var libraryManager = new LibraryManager(libraries.Values.ToList(), diagnostics, Project?.ProjectFilePath);
return new ProjectContext(
GlobalSettings,
mainProject,
TargetFramework,
target?.RuntimeIdentifier,
PackagesDirectory,
libraryManager,
LockFile);
}
private void ReadLockFile(ICollection<DiagnosticMessage> diagnostics)
{
try
{
LockFile = LockFile ?? LockFileResolver(ProjectDirectory);
}
catch (FileFormatException e)
{
var lockFilePath = "";
if (LockFile != null)
{
lockFilePath = LockFile.LockFilePath;
}
else if (Project != null)
{
lockFilePath = Path.Combine(Project.ProjectDirectory, LockFile.FileName);
}
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.DOTNET1014,
ComposeMessageFromInnerExceptions(e),
lockFilePath,
DiagnosticMessageSeverity.Error));
}
}
private static string ComposeMessageFromInnerExceptions(Exception exception)
{
var sb = new StringBuilder();
var messages = new HashSet<string>();
while (exception != null)
{
messages.Add(exception.Message);
exception = exception.InnerException;
}
foreach (var message in messages)
{
sb.AppendLine(message);
}
return sb.ToString();
}
private void ResolveDependencies(Dictionary<LibraryKey, LibraryDescription> libraries,
ReferenceAssemblyDependencyResolver referenceAssemblyDependencyResolver,
out bool requiresFrameworkAssemblies)
{
// Remark: the LibraryType in the key of the given dictionary are all "Unspecified" at the beginning.
requiresFrameworkAssemblies = false;
foreach (var pair in libraries.ToList())
{
var library = pair.Value;
// The System.* packages provide placeholders on any non netstandard platform
// To make them work seamlessly on those platforms, we fill the gap with a reference
// assembly (if available)
var package = library as PackageDescription;
if (package != null && package.Resolved && !package.CompileTimeAssemblies.Any())
{
var replacement = referenceAssemblyDependencyResolver.GetDescription(new LibraryRange(library.Identity.Name, LibraryType.ReferenceAssembly), TargetFramework);
if (replacement?.Resolved == true)
{
requiresFrameworkAssemblies = true;
// Remove the original package reference
libraries.Remove(pair.Key);
// Insert a reference assembly key if there isn't one
var key = new LibraryKey(replacement.Identity.Name, LibraryType.ReferenceAssembly);
if (!libraries.ContainsKey(key))
{
libraries[key] = replacement;
}
}
}
}
foreach (var pair in libraries.ToList())
{
var library = pair.Value;
library.Framework = library.Framework ?? TargetFramework;
foreach (var dependency in library.Dependencies)
{
var keyType = dependency.Target == LibraryType.ReferenceAssembly ?
LibraryType.ReferenceAssembly :
LibraryType.Unspecified;
var key = new LibraryKey(dependency.Name, keyType);
LibraryDescription dependencyDescription;
if (!libraries.TryGetValue(key, out dependencyDescription))
{
if (keyType == LibraryType.ReferenceAssembly)
{
// a dependency is specified to be reference assembly but fail to match
// then add a unresolved dependency
dependencyDescription = referenceAssemblyDependencyResolver.GetDescription(dependency, TargetFramework) ??
UnresolvedDependencyProvider.GetDescription(dependency, TargetFramework);
libraries[key] = dependencyDescription;
}
else if (!libraries.TryGetValue(new LibraryKey(dependency.Name, LibraryType.ReferenceAssembly), out dependencyDescription))
{
// a dependency which type is unspecified fails to match, then try to find a
// reference assembly type dependency
dependencyDescription = UnresolvedDependencyProvider.GetDescription(dependency, TargetFramework);
libraries[key] = dependencyDescription;
}
}
dependencyDescription.RequestedRanges.Add(dependency);
dependencyDescription.Parents.Add(library);
}
}
}
private void ScanLibraries(LockFileTarget target,
LockFileLookup lockFileLookup,
Dictionary<LibraryKey, LibraryDescription> libraries,
MSBuildDependencyProvider msbuildResolver,
PackageDependencyProvider packageResolver,
ProjectDependencyProvider projectResolver)
{
foreach (var library in target.Libraries)
{
LibraryDescription description = null;
var type = LibraryType.Unspecified;
if (string.Equals(library.Type, "project"))
{
var projectLibrary = lockFileLookup.GetProject(library.Name);
if (projectLibrary != null)
{
if (MSBuildDependencyProvider.IsMSBuildProjectLibrary(projectLibrary))
{
description = msbuildResolver.GetDescription(TargetFramework, projectLibrary, library, IsDesignTime);
type = LibraryType.MSBuildProject;
}
else
{
var path = Path.GetFullPath(Path.Combine(ProjectDirectory, projectLibrary.Path));
description = projectResolver.GetDescription(library.Name, path, library, ProjectResolver);
type = LibraryType.Project;
}
}
}
else
{
var packageEntry = lockFileLookup.GetPackage(library.Name, library.Version);
if (packageEntry != null)
{
description = packageResolver.GetDescription(TargetFramework, packageEntry, library);
}
type = LibraryType.Package;
}
description = description ?? UnresolvedDependencyProvider.GetDescription(new LibraryRange(library.Name, type), target.TargetFramework);
libraries.Add(new LibraryKey(library.Name), description);
}
}
private void EnsureProjectLoaded()
{
if (Project == null && ProjectDirectory != null)
{
Project = ProjectResolver(ProjectDirectory);
}
}
private LockFileTarget SelectTarget(LockFile lockFile)
{
foreach (var runtimeIdentifier in RuntimeIdentifiers)
{
foreach (var scanTarget in lockFile.Targets)
{
if (Equals(scanTarget.TargetFramework, TargetFramework) && string.Equals(scanTarget.RuntimeIdentifier, runtimeIdentifier, StringComparison.Ordinal))
{
return scanTarget;
}
}
}
foreach (var scanTarget in lockFile.Targets)
{
if (Equals(scanTarget.TargetFramework, TargetFramework) && string.IsNullOrEmpty(scanTarget.RuntimeIdentifier))
{
return scanTarget;
}
}
return null;
}
private Project ResolveProject(string projectDirectory)
{
// TODO: Handle diagnostics
Project project;
if (ProjectReader.TryGetProject(projectDirectory, out project, diagnostics: null, settings: Settings))
{
return project;
}
else
{
return null;
}
}
private static LockFile ResolveLockFile(string projectDir)
{
var projectLockJsonPath = Path.Combine(projectDir, LockFile.FileName);
return File.Exists(projectLockJsonPath) ?
LockFileReader.Read(Path.Combine(projectDir, LockFile.FileName), designTime: false) :
null;
}
private struct LibraryKey
{
public LibraryKey(string name) : this(name, LibraryType.Unspecified)
{
}
public LibraryKey(string name, LibraryType libraryType)
{
Name = name;
LibraryType = libraryType;
}
public string Name { get; }
public LibraryType LibraryType { get; }
public override bool Equals(object obj)
{
var otherKey = (LibraryKey)obj;
return string.Equals(otherKey.Name, Name, StringComparison.Ordinal) &&
otherKey.LibraryType.Equals(LibraryType);
}
public override int GetHashCode()
{
var combiner = new HashCodeCombiner();
combiner.Add(Name);
combiner.Add(LibraryType);
return combiner.CombinedHash;
}
public override string ToString()
{
return Name + " " + LibraryType;
}
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: $
* $Date: $
*
* 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
#region Using
using System;
using System.Data;
using System.Reflection;
using System.Xml.Serialization;
using IBatisNet.Common.Exceptions;
using IBatisNet.Common.Utilities.TypesResolver;
#endregion
namespace IBatisNet.Common
{
/// <summary>
/// Information about a data provider.
/// </summary>
[Serializable]
[XmlRoot("provider", Namespace="http://ibatis.apache.org/providers")]
public class Provider
{
#region Fields
[NonSerialized]
private string _assemblyName = string.Empty;
[NonSerialized]
private string _connectionClass = string.Empty;
[NonSerialized]
private string _commandClass = string.Empty;
[NonSerialized]
private string _dataParameter = string.Empty;
[NonSerialized]
private Type _dataParameterType = null;
[NonSerialized]
private string _parameterDbTypeClass = string.Empty;
[NonSerialized]
private Type _parameterDbType = null;
[NonSerialized]
private string _parameterDbTypeProperty = string.Empty;
[NonSerialized]
private string _dataAdapterClass = string.Empty;
[NonSerialized]
private string _commandBuilderClass = string.Empty;
[NonSerialized]
private string _name = string.Empty;
[NonSerialized]
private string _description = string.Empty;
[NonSerialized]
private bool _isDefault = false;
[NonSerialized]
private bool _isEnabled = true;
[NonSerialized]
private IDbConnection _templateConnection = null;
[NonSerialized]
private IDbCommand _templateCommand= null;
[NonSerialized]
private IDbDataAdapter _templateDataAdapter= null;
[NonSerialized]
private Type _commandBuilderType = null;
[NonSerialized]
private string _parameterPrefix = string.Empty;
[NonSerialized]
private bool _useParameterPrefixInSql = true;
[NonSerialized]
private bool _useParameterPrefixInParameter = true;
[NonSerialized]
private bool _usePositionalParameters = false;
[NonSerialized]
private bool _templateConnectionIsICloneable = false;
[NonSerialized]
private bool _templateCommandIsICloneable = false;
[NonSerialized]
private bool _templateDataAdapterIsICloneable = false;
[NonSerialized]
private bool _setDbParameterSize = true;
[NonSerialized]
private bool _setDbParameterPrecision = true;
[NonSerialized]
private bool _setDbParameterScale = true;
[NonSerialized]
private bool _useDeriveParameters = true;
// private static readonly ILog _connectionLogger = LogManager.GetLogger("System.Data.IDbConnection");
#endregion
#region Properties
/// <summary>
/// The name of the assembly which conatins the definition of the provider.
/// </summary>
/// <example>Examples : "System.Data", "Microsoft.Data.Odbc"</example>
[XmlAttribute("assemblyName")]
public string AssemblyName
{
get { return _assemblyName; }
set
{
if ((value == null) || (value.Length < 1))
throw new ArgumentNullException("AssemblyName");
_assemblyName = value;
}
}
/// <summary>
/// Tell us if it is the default data source.
/// Default false.
/// </summary>
[XmlAttribute("default")]
public bool IsDefault
{
get { return _isDefault; }
set {_isDefault = value;}
}
/// <summary>
/// Tell us if this provider is enabled.
/// Default true.
/// </summary>
[XmlAttribute("enabled")]
public bool IsEnabled
{
get { return _isEnabled; }
set {_isEnabled = value;}
}
/// <summary>
/// The connection class name to use.
/// </summary>
/// <example>
/// "System.Data.OleDb.OleDbConnection",
/// "System.Data.SqlClient.SqlConnection",
/// "Microsoft.Data.Odbc.OdbcConnection"
/// </example>
[XmlAttribute("connectionClass")]
public string ConnectionClass
{
get { return _connectionClass; }
set
{
if ((value == null) || (value.Length < 1))
throw new ArgumentNullException("The connectionClass attribute is mandatory in the provider " + _name);
_connectionClass = value;
}
}
/// <summary>
/// Does this ConnectionProvider require the use of a Named Prefix in the SQL
/// statement.
/// </summary>
/// <remarks>
/// The OLE DB/ODBC .NET Provider does not support named parameters for
/// passing parameters to an SQL Statement or a stored procedure called
/// by an IDbCommand when CommandType is set to Text.
///
/// For example, SqlClient requires select * from simple where simple_id = @simple_id
/// If this is false, like with the OleDb or Obdc provider, then it is assumed that
/// the ? can be a placeholder for the parameter in the SQL statement when CommandType
/// is set to Text.
/// </remarks>
[XmlAttribute("useParameterPrefixInSql")]
public bool UseParameterPrefixInSql
{
get { return _useParameterPrefixInSql; }
set { _useParameterPrefixInSql = value;}
}
/// <summary>
/// Does this ConnectionProvider require the use of the Named Prefix when trying
/// to reference the Parameter in the Command's Parameter collection.
/// </summary>
/// <remarks>
/// This is really only useful when the UseParameterPrefixInSql = true.
/// When this is true the code will look like IDbParameter param = cmd.Parameters["@paramName"],
/// if this is false the code will be IDbParameter param = cmd.Parameters["paramName"] - ie - Oracle.
/// </remarks>
[XmlAttribute("useParameterPrefixInParameter")]
public bool UseParameterPrefixInParameter
{
get { return _useParameterPrefixInParameter; }
set { _useParameterPrefixInParameter = value; }
}
/// <summary>
/// The OLE DB/OBDC .NET Provider uses positional parameters that are marked with a
/// question mark (?) instead of named parameters.
/// </summary>
[XmlAttribute("usePositionalParameters")]
public bool UsePositionalParameters
{
get { return _usePositionalParameters; }
set { _usePositionalParameters = value; }
}
/// <summary>
/// Used to indicate whether or not the provider
/// supports parameter size.
/// </summary>
/// <remarks>
/// See JIRA-49 about SQLite.Net provider not supporting parameter size.
/// </remarks>
[XmlAttribute("setDbParameterSize")]
public bool SetDbParameterSize
{
get { return _setDbParameterSize; }
set { _setDbParameterSize = value; }
}
/// <summary>
/// Used to indicate whether or not the provider
/// supports parameter precision.
/// </summary>
/// <remarks>
/// See JIRA-49 about SQLite.Net provider not supporting parameter precision.
/// </remarks>
[XmlAttribute("setDbParameterPrecision")]
public bool SetDbParameterPrecision
{
get { return _setDbParameterPrecision; }
set { _setDbParameterPrecision = value; }
}
/// <summary>
/// Used to indicate whether or not the provider
/// supports a parameter scale.
/// </summary>
/// <remarks>
/// See JIRA-49 about SQLite.Net provider not supporting parameter scale.
/// </remarks>
[XmlAttribute("setDbParameterScale")]
public bool SetDbParameterScale
{
get { return _setDbParameterScale; }
set { _setDbParameterScale = value; }
}
/// <summary>
/// Used to indicate whether or not the provider
/// supports DeriveParameters method for procedure.
/// </summary>
[XmlAttribute("useDeriveParameters")]
public bool UseDeriveParameters
{
get { return _useDeriveParameters; }
set { _useDeriveParameters = value; }
}
/// <summary>
/// The command class name to use.
/// </summary>
/// <example>
/// "System.Data.SqlClient.SqlCommand"
/// </example>
[XmlAttribute("commandClass")]
public string CommandClass
{
get { return _commandClass; }
set
{
if ((value == null) || (value.Length < 1))
throw new ArgumentNullException("The commandClass attribute is mandatory in the provider " + _name);
_commandClass = value;
}
}
/// <summary>
/// The parameter class name to use.
/// </summary>
/// <example>
/// "System.Data.SqlClient.SqlParameter"
/// </example>
[XmlAttribute("parameterClass")]
public string ParameterClass
{
get { return _dataParameter; }
set
{
if ((value == null) || (value.Length < 1))
throw new ArgumentNullException("The parameterClass attribute is mandatory in the provider " + _name);
_dataParameter = value;
}
}
/// <summary>
/// The ParameterDbType class name to use.
/// </summary>
/// <example>
/// "System.Data.SqlDbType"
/// </example>
[XmlAttribute("parameterDbTypeClass")]
public string ParameterDbTypeClass
{
get { return _parameterDbTypeClass; }
set
{
if ((value == null) || (value.Length < 1))
throw new ArgumentNullException("The parameterDbTypeClass attribute is mandatory in the provider " + _name);
_parameterDbTypeClass = value;
}
}
/// <summary>
/// The ParameterDbTypeProperty class name to use.
/// </summary>
/// <example >
/// SqlDbType in SqlParamater.SqlDbType,
/// OracleType in OracleParameter.OracleType.
/// </example>
[XmlAttribute("parameterDbTypeProperty")]
public string ParameterDbTypeProperty
{
get { return _parameterDbTypeProperty; }
set
{
if ((value == null) || (value.Length < 1))
throw new ArgumentNullException("The parameterDbTypeProperty attribute is mandatory in the provider " + _name);
_parameterDbTypeProperty = value;
}
}
/// <summary>
/// The dataAdapter class name to use.
/// </summary>
/// <example >
/// "System.Data.SqlDbType"
/// </example>
[XmlAttribute("dataAdapterClass")]
public string DataAdapterClass
{
get { return _dataAdapterClass; }
set
{
if ((value == null) || (value.Length < 1))
throw new ArgumentNullException("The dataAdapterClass attribute is mandatory in the provider " + _name);
_dataAdapterClass = value;
}
}
/// <summary>
/// The commandBuilder class name to use.
/// </summary>
/// <example >
/// "System.Data.OleDb.OleDbCommandBuilder",
/// "System.Data.SqlClient.SqlCommandBuilder",
/// "Microsoft.Data.Odbc.OdbcCommandBuilder"
/// </example>
[XmlAttribute("commandBuilderClass")]
public string CommandBuilderClass
{
get { return _commandBuilderClass; }
set
{
if ((value == null) || (value.Length < 1))
throw new ArgumentNullException("The commandBuilderClass attribute is mandatory in the provider " + _name);
_commandBuilderClass = value;
}
}
/// <summary>
/// Name used to identify the provider amongst the others.
/// </summary>
[XmlAttribute("name")]
public string Name
{
get { return _name; }
set
{
if ((value == null) || (value.Length < 1))
throw new ArgumentNullException("The name attribute is mandatory in the provider.");
_name = value;
}
}
/// <summary>
/// Description.
/// </summary>
[XmlAttribute("description")]
public string Description
{
get { return _description; }
set { _description = value;}
}
/// <summary>
/// Parameter prefix use in store procedure.
/// </summary>
/// <example> @ for Sql Server.</example>
[XmlAttribute("parameterPrefix")]
public string ParameterPrefix
{
get { return _parameterPrefix; }
set
{
if ((value == null) || (value.Length < 1))
{
_parameterPrefix = "";
//throw new ArgumentNullException("The parameterPrefix attribute is mandatory in the provider " + _name);
}
else
{
_parameterPrefix = value;
}
}
}
/// <summary>
/// Check if this provider is Odbc ?
/// </summary>
[XmlIgnore]
public bool IsObdc
{
get
{
return (_connectionClass.IndexOf(".Odbc.")>0);
}
}
#endregion
#region Constructor (s) / Destructor
/// <summary>
/// Do not use direclty, only for serialization.
/// </summary>
public Provider()
{
}
#endregion
#region Methods
/// <summary>
/// Init the provider.
/// </summary>
public void Initialize()
{
Assembly assembly;
Type type;
CachedTypeResolver cachedTypeResolver = new CachedTypeResolver();
try
{
assembly = Assembly.Load(_assemblyName);
// Build the Command template
type = assembly.GetType(_commandClass, true);
_templateCommand = (IDbCommand)type.GetConstructor(Type.EmptyTypes).Invoke(null);
// Build the DataAdapter template
type = assembly.GetType(_dataAdapterClass, true);
_templateDataAdapter = (IDbDataAdapter)type.GetConstructor(Type.EmptyTypes).Invoke(null);
// Build the connection template
type = assembly.GetType(_connectionClass, true);
_templateConnection = (IDbConnection)type.GetConstructor(Type.EmptyTypes).Invoke(null);
// Get the IDataParameter type
_dataParameterType = assembly.GetType(_dataParameter, true);
// Get the CommandBuilder Type
_commandBuilderType = assembly.GetType(_commandBuilderClass, true);
if (_parameterDbTypeClass.IndexOf(',')>0)
{
_parameterDbType = cachedTypeResolver.Resolve(_parameterDbTypeClass);
}
else
{
_parameterDbType = assembly.GetType(_parameterDbTypeClass, true);
}
_templateConnectionIsICloneable = _templateConnection is ICloneable;
_templateCommandIsICloneable = _templateCommand is ICloneable;
_templateDataAdapterIsICloneable = _templateDataAdapter is ICloneable;
}
catch(Exception e)
{
throw new ConfigurationException(
string.Format("Could not configure providers. Unable to load provider named \"{0}\" not found, failed. Cause: {1}", _name, e.Message), e
);
}
}
/// <summary>
/// Get a connection object for this provider.
/// </summary>
/// <returns>An 'IDbConnection' object.</returns>
public IDbConnection GetConnection()
{
// Cannot do that because on
// IDbCommand.Connection = cmdConnection
// .NET cast the cmdConnection to the real type (as SqlConnection)
// and we pass a proxy --> exception invalid cast !
// if (_connectionLogger.IsDebugEnabled)
// {
// connection = (IDbConnection)IDbConnectionProxy.NewInstance(connection, this);
// }
if (_templateConnectionIsICloneable)
{
return (IDbConnection) ((ICloneable)_templateConnection).Clone();
}
else
{
return (IDbConnection) Activator.CreateInstance(_templateConnection.GetType());
}
}
/// <summary>
/// Get a command object for this provider.
/// </summary>
/// <returns>An 'IDbCommand' object.</returns>
public IDbCommand GetCommand()
{
if (_templateCommandIsICloneable)
{
return (IDbCommand) ((ICloneable)_templateCommand).Clone();
}
else
{
return (IDbCommand) Activator.CreateInstance(_templateCommand.GetType());
}
}
/// <summary>
/// Get a dataAdapter object for this provider.
/// </summary>
/// <returns>An 'IDbDataAdapter' object.</returns>
public IDbDataAdapter GetDataAdapter()
{
if (_templateDataAdapterIsICloneable)
{
return (IDbDataAdapter) ((ICloneable)_templateDataAdapter).Clone();
}
else
{
return (IDbDataAdapter) Activator.CreateInstance(_templateDataAdapter.GetType());
}
}
/// <summary>
/// Get a IDataParameter object for this provider.
/// </summary>
/// <returns>An 'IDataParameter' object.</returns>
public IDataParameter GetDataParameter()
{
return (IDataParameter) Activator.CreateInstance(_dataParameterType);
}
/// <summary>
/// Get the CommandBuilder Type for this provider.
/// </summary>
/// <returns>An object.</returns>
public Type GetCommandBuilderType()
{
return _commandBuilderType;
}
/// <summary>
/// Get the ParameterDb Type for this provider.
/// </summary>
/// <returns>An object.</returns>
public Type ParameterDbType
{
get { return _parameterDbType; }
}
/// <summary>
/// Equals implemantation.
/// </summary>
/// <param name="obj">The test object.</param>
/// <returns>A boolean.</returns>
public override bool Equals(object obj)
{
if ((obj != null) && (obj is Provider))
{
Provider that = (Provider) obj;
return ((this._name == that._name) &&
(this._assemblyName == that._assemblyName) &&
(this._connectionClass == that._connectionClass));
}
return false;
}
/// <summary>
/// A hashcode for the provider.
/// </summary>
/// <returns>An integer.</returns>
public override int GetHashCode()
{
return (_name.GetHashCode() ^ _assemblyName.GetHashCode() ^ _connectionClass.GetHashCode());
}
/// <summary>
/// ToString implementation.
/// </summary>
/// <returns>A string that describes the provider.</returns>
public override string ToString()
{
return "Provider " + _name;
}
#endregion
}
}
| |
// Discoverer classes.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// 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.Net;
using System.Net.Sockets;
using System.Threading;
using Snmp.Core.Security;
using System.Threading.Tasks;
namespace Snmp.Core.Messaging
{
/// <summary>
/// Discoverer class to discover SNMP agents in the same network.
/// </summary>
public sealed class Discoverer
{
private int _active;
private int _bufferSize;
private int _requestId;
private static readonly UserRegistry Empty = new UserRegistry();
private readonly IList<Variable> _defaultVariables = new List<Variable> { new Variable(new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 2, 1, 1, 1, 0 })) };
private const int Active = 1;
private const int Inactive = 0;
/// <summary>
/// Occurs when an SNMP agent is found.
/// </summary>
public event EventHandler<AgentFoundEventArgs> AgentFound;
/// <summary>
/// Occurs when an exception is raised.
/// </summary>
/// <remarks>The exception is typical <see cref="SocketException"/> here.</remarks>
public event EventHandler<ExceptionRaisedEventArgs> ExceptionRaised;
/// <summary>
/// Discovers agents of the specified version in a specific time interval.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="broadcastAddress">The broadcast address.</param>
/// <param name="community">The community.</param>
/// <param name="interval">The discovering time interval, in milliseconds.</param>
/// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
public void Discover(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval)
{
if (broadcastAddress == null)
{
throw new ArgumentNullException("broadcastAddress");
}
if (version != VersionCode.V3 && community == null)
{
throw new ArgumentNullException("community");
}
var addressFamily = broadcastAddress.AddressFamily;
if (addressFamily == AddressFamily.InterNetworkV6)
{
throw new ArgumentException("IP v6 is not yet supported", "broadcastAddress");
}
byte[] bytes;
_requestId = Messenger.NextRequestId;
if (version == VersionCode.V3)
{
// throw new NotSupportedException("SNMP v3 is not supported");
var discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
bytes = discovery.ToBytes();
}
else
{
var message = new GetRequestMessage(_requestId, version, community, _defaultVariables);
bytes = message.ToBytes();
}
using (var udp = new UdpClient(addressFamily))
{
#if (!CF)
udp.EnableBroadcast = true;
#endif
#if !NETSTANDARD
udp.Send(bytes, bytes.Length, broadcastAddress);
#else
AsyncHelper.RunSync(() => udp.SendAsync(bytes, bytes.Length, broadcastAddress));
#endif
var activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive);
if (activeBefore == Active)
{
// If already started, we've nothing to do.
return;
}
_bufferSize = udp.Client.ReceiveBufferSize = Messenger.MaxMessageSize;
#if ASYNC
Task.Factory.StartNew(() => AsyncBeginReceive(udp.Client));
#else
Task.Factory.StartNew(() => AsyncReceive(udp.Client));
#endif
Thread.Sleep(interval);
Interlocked.CompareExchange(ref _active, Inactive, Active);
#if !NETSTANDARD
udp.Close();
#endif
}
}
#if ASYNC
private void AsyncBeginReceive(Socket socket)
{
while (true)
{
// If no more active, then stop.
if (Interlocked.Exchange(ref _active, _active) == Inactive)
{
return;
}
byte[] buffer = new byte[_bufferSize];
EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
IAsyncResult iar = null;
try
{
iar = socket.BeginReceiveFrom(buffer, 0, _bufferSize, SocketFlags.None, ref remote, AsyncEndReceive, new Tuple<Socket, byte[]>(socket, buffer));
}
catch (SocketException ex)
{
// ignore WSAECONNRESET, http://bytes.com/topic/c-sharp/answers/237558-strange-udp-socket-problem
if (ex.SocketErrorCode != SocketError.ConnectionReset)
{
// If the SnmpTrapListener was active, marks it as stopped and call HandleException.
// If it was inactive, the exception is likely to result from this, and we raise nothing.
long activeBefore = Interlocked.CompareExchange(ref _active, Inactive, Active);
if (activeBefore == Active)
{
HandleException(ex);
}
}
}
if (iar != null)
{
iar.AsyncWaitHandle.WaitOne();
}
}
}
private void AsyncEndReceive(IAsyncResult iar)
{
// If no more active, then stop. This discards the received packet, if any (indeed, we may be there either
// because we've received a packet, or because the socket has been closed).
if (Interlocked.Exchange(ref _active, _active) == Inactive)
{
return;
}
//// We start another receive operation.
//AsyncBeginReceive();
Tuple<Socket, byte[]> data = (Tuple<Socket, byte[]>)iar.AsyncState;
byte[] buffer = data.Item2;
try
{
EndPoint remote = data.Item1.AddressFamily == AddressFamily.InterNetwork ? new IPEndPoint(IPAddress.Any, 0) : new IPEndPoint(IPAddress.IPv6Any, 0);
int count = data.Item1.EndReceiveFrom(iar, ref remote);
HandleMessage(buffer, count, (IPEndPoint)remote);
}
catch (SocketException ex)
{
// ignore WSAECONNRESET, http://bytes.com/topic/c-sharp/answers/237558-strange-udp-socket-problem
if (ex.SocketErrorCode != SocketError.ConnectionReset)
{
// If the SnmpTrapListener was active, marks it as stopped and call HandleException.
// If it was inactive, the exception is likely to result from this, and we raise nothing.
long activeBefore = Interlocked.CompareExchange(ref _active, Inactive, Active);
if (activeBefore == Active)
{
HandleException(ex);
}
}
}
}
#else
private void AsyncReceive(Socket socket)
{
while (true)
{
// If no more active, then stop.
if (Interlocked.Exchange(ref _active, _active) == Inactive)
{
return;
}
try
{
var buffer = new byte[_bufferSize];
EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
var count = socket.ReceiveFrom(buffer, ref remote);
Task.Factory.StartNew(()=> HandleMessage(buffer, count, (IPEndPoint)remote));
}
catch (SocketException ex)
{
if (ex.SocketErrorCode != SocketError.ConnectionReset)
{
// If the SnmpTrapListener was active, marks it as stopped and call HandleException.
// If it was inactive, the exception is likely to result from this, and we raise nothing.
var activeBefore = Interlocked.CompareExchange(ref _active, Inactive, Active);
if (activeBefore == Active)
{
HandleException(ex);
}
}
}
}
}
#endif
private void HandleException(Exception exception)
{
var handler = ExceptionRaised;
if (handler == null)
{
return;
}
handler(this, new ExceptionRaisedEventArgs(exception));
}
private void HandleMessage(byte[] buffer, int count, IPEndPoint remote)
{
foreach (var message in MessageFactory.ParseMessages(buffer, 0, count, Empty))
{
EventHandler<AgentFoundEventArgs> handler;
var code = message.TypeCode();
if (code == SnmpType.ReportPdu)
{
var report = (ReportMessage)message;
if (report.RequestId() != _requestId)
{
continue;
}
if (report.Pdu().ErrorStatus.ToErrorCode() != ErrorCode.NoError)
{
continue;
}
handler = AgentFound;
if (handler != null)
{
handler(this, new AgentFoundEventArgs(remote, null));
}
}
if (code != SnmpType.ResponsePdu)
{
continue;
}
var response = (ResponseMessage)message;
if (response.RequestId() != _requestId)
{
continue;
}
if (response.ErrorStatus != ErrorCode.NoError)
{
continue;
}
handler = AgentFound;
if (handler != null)
{
handler(this, new AgentFoundEventArgs(remote, response.Variables()[0]));
}
}
}
/// <summary>
/// Discovers agents of the specified version in a specific time interval.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="broadcastAddress">The broadcast address.</param>
/// <param name="community">The community.</param>
/// <param name="interval">The discovering time interval, in milliseconds.</param>
/// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
public async Task DiscoverAsync(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval)
{
if (broadcastAddress == null)
{
throw new ArgumentNullException("broadcastAddress");
}
if (version != VersionCode.V3 && community == null)
{
throw new ArgumentNullException("community");
}
var addressFamily = broadcastAddress.AddressFamily;
if (addressFamily == AddressFamily.InterNetworkV6)
{
throw new ArgumentException("IP v6 is not yet supported", "broadcastAddress");
}
byte[] bytes;
_requestId = Messenger.NextRequestId;
if (version == VersionCode.V3)
{
// throw new NotSupportedException("SNMP v3 is not supported");
var discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
bytes = discovery.ToBytes();
}
else
{
var message = new GetRequestMessage(_requestId, version, community, _defaultVariables);
bytes = message.ToBytes();
}
using (var udp = new Socket(addressFamily, SocketType.Dgram, ProtocolType.Udp))
{
var info = SocketExtension.EventArgsFactory.Create();
info.RemoteEndPoint = broadcastAddress;
info.SetBuffer(bytes, 0, bytes.Length);
using (var awaitable1 = new SocketAwaitable(info))
{
await udp.SendToAsync(awaitable1);
}
var activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive);
if (activeBefore == Active)
{
// If already started, we've nothing to do.
return;
}
_bufferSize = udp.ReceiveBufferSize;
await ReceiveAsync(udp).ConfigureAwait(false);
await Task.Delay(interval).ConfigureAwait(false);
Interlocked.CompareExchange(ref _active, Inactive, Active);
udp.Shutdown(SocketShutdown.Both);
}
}
private async Task ReceiveAsync(Socket socket)
{
EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
// If no more active, then stop.
if (Interlocked.Exchange(ref _active, _active) == Inactive)
{
return;
}
int count;
var reply = new byte[_bufferSize];
var args = SocketExtension.EventArgsFactory.Create();
try
{
args.RemoteEndPoint = remote;
args.SetBuffer(reply, 0, _bufferSize);
using (var awaitable = new SocketAwaitable(args))
{
count = await socket.ReceiveAsync(awaitable);
}
await Task.Factory.StartNew(() => HandleMessage(reply, count, (IPEndPoint)remote)).ConfigureAwait(false);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode != SocketError.ConnectionReset)
{
// If the SnmpTrapListener was active, marks it as stopped and call HandleException.
// If it was inactive, the exception is likely to result from this, and we raise nothing.
var activeBefore = Interlocked.CompareExchange(ref _active, Inactive, Active);
if (activeBefore == Active)
{
HandleException(ex);
}
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal
{
internal class ManagedX509ExtensionProcessor
{
public virtual byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages)
{
// The numeric values of X509KeyUsageFlags mean that if we interpret it as a little-endian
// ushort it will line up with the flags in the spec.
ushort ushortValue = unchecked((ushort)(int)keyUsages);
byte[] data = BitConverter.GetBytes(ushortValue);
// RFC 3280 section 4.2.1.3 (https://tools.ietf.org/html/rfc3280#section-4.2.1.3) defines
// digitalSignature (0) through decipherOnly (8), making 9 named bits.
const int namedBitsCount = 9;
// The expected output of this method isn't the SEQUENCE value, but just the payload bytes.
byte[][] segments = DerEncoder.SegmentedEncodeNamedBitList(data, namedBitsCount);
Debug.Assert(segments.Length == 3);
return ConcatenateArrays(segments);
}
public virtual void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages)
{
DerSequenceReader reader = DerSequenceReader.CreateForPayload(encoded);
byte[] decoded = reader.ReadBitString();
// Only 9 bits are defined.
if (decoded.Length > 2)
{
throw new CryptographicException();
}
// DER encodings of BIT_STRING values number the bits as
// 01234567 89 (big endian), plus a number saying how many bits of the last byte were padding.
//
// So digitalSignature (0) doesn't mean 2^0 (0x01), it means the most significant bit
// is set in this byte stream.
//
// BIT_STRING values are compact. So a value of cRLSign (6) | keyEncipherment (2), which
// is 0b0010001 => 0b0010 0010 (1 bit padding) => 0x22 encoded is therefore
// 0x02 (length remaining) 0x01 (1 bit padding) 0x22.
//
// We will read that, and return 0x22. 0x22 lines up
// exactly with X509KeyUsageFlags.CrlSign (0x20) | X509KeyUsageFlags.KeyEncipherment (0x02)
//
// Once the decipherOnly (8) bit is added to the mix, the values become:
// 0b001000101 => 0b0010 0010 1000 0000 (7 bits padding)
// { 0x03 0x07 0x22 0x80 }
// And we read new byte[] { 0x22 0x80 }
//
// The value of X509KeyUsageFlags.DecipherOnly is 0x8000. 0x8000 in a little endian
// representation is { 0x00 0x80 }. This means that the DER storage mechanism has effectively
// ended up being little-endian for BIT_STRING values. Untwist the bytes, and now the bits all
// line up with the existing X509KeyUsageFlags.
int value = 0;
if (decoded.Length > 0)
{
value = decoded[0];
}
if (decoded.Length > 1)
{
value |= decoded[1] << 8;
}
keyUsages = (X509KeyUsageFlags)value;
}
public virtual byte[] EncodeX509BasicConstraints2Extension(
bool certificateAuthority,
bool hasPathLengthConstraint,
int pathLengthConstraint)
{
//BasicConstraintsSyntax::= SEQUENCE {
// cA BOOLEAN DEFAULT FALSE,
// pathLenConstraint INTEGER(0..MAX) OPTIONAL,
// ... }
List<byte[][]> segments = new List<byte[][]>(2);
if (certificateAuthority)
{
segments.Add(DerEncoder.SegmentedEncodeBoolean(true));
}
if (hasPathLengthConstraint)
{
byte[] pathLengthBytes = BitConverter.GetBytes(pathLengthConstraint);
// Little-Endian => Big-Endian
Array.Reverse(pathLengthBytes);
segments.Add(DerEncoder.SegmentedEncodeUnsignedInteger(pathLengthBytes));
}
return DerEncoder.ConstructSequence(segments);
}
public virtual bool SupportsLegacyBasicConstraintsExtension => false;
public virtual void DecodeX509BasicConstraintsExtension(
byte[] encoded,
out bool certificateAuthority,
out bool hasPathLengthConstraint,
out int pathLengthConstraint)
{
// No RFC nor ITU document describes the layout of the 2.5.29.10 structure,
// and OpenSSL doesn't have a decoder for it, either.
//
// Since it was never published as a standard (2.5.29.19 replaced it before publication)
// there shouldn't be too many people upset that we can't decode it for them on Unix.
throw new PlatformNotSupportedException(SR.NotSupported_LegacyBasicConstraints);
}
public virtual void DecodeX509BasicConstraints2Extension(
byte[] encoded,
out bool certificateAuthority,
out bool hasPathLengthConstraint,
out int pathLengthConstraint)
{
// BasicConstraints ::= SEQUENCE {
// cA BOOLEAN DEFAULT FALSE,
// pathLenConstraint INTEGER(0..MAX) OPTIONAL }
DerSequenceReader constraints = new DerSequenceReader(encoded);
if (!constraints.HasData)
{
certificateAuthority = false;
hasPathLengthConstraint = false;
pathLengthConstraint = 0;
return;
}
if (constraints.PeekTag() == (byte)DerSequenceReader.DerTag.Boolean)
{
certificateAuthority = constraints.ReadBoolean();
}
else
{
certificateAuthority = false;
}
if (constraints.HasData)
{
pathLengthConstraint = constraints.ReadInteger();
hasPathLengthConstraint = true;
}
else
{
pathLengthConstraint = 0;
hasPathLengthConstraint = false;
}
}
public virtual byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages)
{
//extKeyUsage EXTENSION ::= {
// SYNTAX SEQUENCE SIZE(1..MAX) OF KeyPurposeId
// IDENTIFIED BY id-ce-extKeyUsage }
//
//KeyPurposeId::= OBJECT IDENTIFIER
List<byte[][]> segments = new List<byte[][]>(usages.Count);
foreach (Oid usage in usages)
{
segments.Add(DerEncoder.SegmentedEncodeOid(usage));
}
return DerEncoder.ConstructSequence(segments);
}
public virtual void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages)
{
// ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
//
// KeyPurposeId::= OBJECT IDENTIFIER
OidCollection oids = new OidCollection();
DerSequenceReader reader = new DerSequenceReader(encoded);
while (reader.HasData)
{
oids.Add(reader.ReadOid());
}
usages = oids;
}
public virtual byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier)
{
//subjectKeyIdentifier EXTENSION ::= {
// SYNTAX SubjectKeyIdentifier
// IDENTIFIED BY id - ce - subjectKeyIdentifier }
//
//SubjectKeyIdentifier::= KeyIdentifier
//
//KeyIdentifier ::= OCTET STRING
byte[][] segments = DerEncoder.SegmentedEncodeOctetString(subjectKeyIdentifier);
// The extension is not a sequence, just the octet string
return ConcatenateArrays(segments);
}
public virtual void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier)
{
subjectKeyIdentifier = DecodeX509SubjectKeyIdentifierExtension(encoded);
}
internal static byte[] DecodeX509SubjectKeyIdentifierExtension(byte[] encoded)
{
DerSequenceReader reader = DerSequenceReader.CreateForPayload(encoded);
return reader.ReadOctetString();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 is required for Compat")]
public virtual byte[] ComputeCapiSha1OfPublicKey(PublicKey key)
{
// The CapiSha1 value is the SHA-1 of the SubjectPublicKeyInfo field, inclusive
// of the DER structural bytes.
//SubjectPublicKeyInfo::= SEQUENCE {
// algorithm AlgorithmIdentifier{ { SupportedAlgorithms} },
// subjectPublicKey BIT STRING,
// ... }
//
//AlgorithmIdentifier{ ALGORITHM: SupportedAlgorithms} ::= SEQUENCE {
// algorithm ALGORITHM.&id({ SupportedAlgorithms}),
// parameters ALGORITHM.&Type({ SupportedAlgorithms}
// { @algorithm}) OPTIONAL,
// ... }
//
//ALGORITHM::= CLASS {
// &Type OPTIONAL,
// &id OBJECT IDENTIFIER UNIQUE }
//WITH SYNTAX {
// [&Type]
//IDENTIFIED BY &id }
// key.EncodedKeyValue corresponds to SubjectPublicKeyInfo.subjectPublicKey, except it
// has had the BIT STRING envelope removed.
//
// key.EncodedParameters corresponds to AlgorithmIdentifier.Parameters precisely
// (DER NULL for RSA, DER Constructed SEQUENCE for DSA)
byte[] empty = Array.Empty<byte>();
byte[][] algorithmOid = DerEncoder.SegmentedEncodeOid(key.Oid);
// Because ConstructSegmentedSequence doesn't look to see that it really is tag+length+value (but does check
// that the array has length 3), just hide the joined TLV triplet in the last element.
byte[][] segmentedParameters = { empty, empty, key.EncodedParameters.RawData };
byte[][] algorithmIdentifier = DerEncoder.ConstructSegmentedSequence(algorithmOid, segmentedParameters);
byte[][] subjectPublicKey = DerEncoder.SegmentedEncodeBitString(key.EncodedKeyValue.RawData);
using (SHA1 hash = SHA1.Create())
{
return hash.ComputeHash(
DerEncoder.ConstructSequence(
algorithmIdentifier,
subjectPublicKey));
}
}
private static byte[] ConcatenateArrays(byte[][] segments)
{
int length = 0;
foreach (byte[] segment in segments)
{
length += segment.Length;
}
byte[] concatenated = new byte[length];
int offset = 0;
foreach (byte[] segment in segments)
{
Buffer.BlockCopy(segment, 0, concatenated, offset, segment.Length);
offset += segment.Length;
}
return concatenated;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Validation;
using Xunit;
using SetTriad = System.Tuple<System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>, bool>;
namespace System.Collections.Immutable.Test
{
#if !NET45PLUS
extern alias rax;
using rax::System.Collections.Generic;
#if !NET40PLUS
using rax::System.Diagnostics.Contracts;
#endif
#endif
public abstract class ImmutableSetTest : ImmutablesTestBase
{
[Fact]
public void AddTest()
{
this.AddTestHelper(this.Empty<int>(), 3, 5, 4, 3);
}
[Fact]
public void AddDuplicatesTest()
{
var arrayWithDuplicates = Enumerable.Range(1, 100).Concat(Enumerable.Range(1, 100)).ToArray();
this.AddTestHelper(this.Empty<int>(), arrayWithDuplicates);
}
[Fact]
public void RemoveTest()
{
this.RemoveTestHelper(this.Empty<int>().Add(3).Add(5), 5, 3);
}
[Fact]
public void AddRemoveLoadTest()
{
var data = this.GenerateDummyFillData();
this.AddRemoveLoadTestHelper(Empty<double>(), data);
}
[Fact]
public void RemoveNonExistingTest()
{
this.RemoveNonExistingTest(this.Empty<int>());
}
[Fact]
public void AddBulkFromImmutableToEmpty()
{
var set = this.Empty<int>().Add(5);
var empty2 = this.Empty<int>();
Assert.Same(set, empty2.Union(set)); // "Filling an empty immutable set with the contents of another immutable set with the exact same comparer should return the other set."
}
[Fact]
public void ExceptTest()
{
this.ExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), 3, 7);
}
[Fact]
public void SymmetricExceptTest()
{
this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 9).ToArray());
this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 5).ToArray());
}
#if !NET45PLUS
[Fact]
public void EnumeratorTest()
{
IComparer<double> comparer = null;
var set = this.Empty<double>();
var sortedSet = set as ISortKeyCollection<double>;
if (sortedSet != null)
{
comparer = sortedSet.KeyComparer;
}
this.EnumeratorTestHelper(set, comparer, 3, 5, 1);
double[] data = this.GenerateDummyFillData();
this.EnumeratorTestHelper(set, comparer, data);
}
#endif
[Fact]
public void IntersectTest()
{
this.IntersectTestHelper(Empty<int>().Union(Enumerable.Range(1, 10)), 8, 3, 5);
}
[Fact]
public void UnionTest()
{
this.UnionTestHelper(this.Empty<int>(), new[] { 1, 3, 5, 7 });
this.UnionTestHelper(this.Empty<int>().Union(new[] { 2, 4, 6 }), new[] { 1, 3, 5, 7 });
this.UnionTestHelper(this.Empty<int>().Union(new[] { 1, 2, 3 }), new int[0] { });
this.UnionTestHelper(this.Empty<int>().Union(new[] { 2 }), Enumerable.Range(0, 1000).ToArray());
}
[Fact]
public void SetEqualsTest()
{
Assert.True(this.Empty<int>().SetEquals(this.Empty<int>()));
var nonEmptySet = this.Empty<int>().Add(5);
Assert.True(nonEmptySet.SetEquals(nonEmptySet));
this.SetCompareTestHelper(s => s.SetEquals, s => s.SetEquals, this.GetSetEqualsScenarios());
}
[Fact]
public void IsProperSubsetOfTest()
{
this.SetCompareTestHelper(s => s.IsProperSubsetOf, s => s.IsProperSubsetOf, this.GetIsProperSubsetOfScenarios());
}
[Fact]
public void IsProperSupersetOfTest()
{
this.SetCompareTestHelper(s => s.IsProperSupersetOf, s => s.IsProperSupersetOf, this.GetIsProperSubsetOfScenarios().Select(Flip));
}
[Fact]
public void IsSubsetOfTest()
{
this.SetCompareTestHelper(s => s.IsSubsetOf, s => s.IsSubsetOf, this.GetIsSubsetOfScenarios());
}
[Fact]
public void IsSupersetOfTest()
{
this.SetCompareTestHelper(s => s.IsSupersetOf, s => s.IsSupersetOf, this.GetIsSubsetOfScenarios().Select(Flip));
}
[Fact]
public void OverlapsTest()
{
this.SetCompareTestHelper(s => s.Overlaps, s => s.Overlaps, this.GetOverlapsScenarios());
}
[Fact]
public void EqualsTest()
{
Assert.False(Empty<int>().Equals(null));
Assert.False(Empty<int>().Equals("hi"));
Assert.True(Empty<int>().Equals(Empty<int>()));
Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3)));
Assert.False(Empty<int>().Add(5).Equals(Empty<int>().Add(3)));
Assert.False(Empty<int>().Add(3).Add(5).Equals(Empty<int>().Add(3)));
Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3).Add(5)));
}
[Fact]
public void GetHashCodeTest()
{
// verify that get hash code is the default address based one.
Assert.Equal(EqualityComparer<object>.Default.GetHashCode(Empty<int>()), Empty<int>().GetHashCode());
}
[Fact]
public void ClearTest()
{
var originalSet = this.Empty<int>();
var nonEmptySet = originalSet.Add(5);
var clearedSet = nonEmptySet.Clear();
Assert.Same(originalSet, clearedSet);
}
[Fact]
public void ISetMutationMethods()
{
var set = (ISet<int>)this.Empty<int>();
Assert.Throws<NotSupportedException>(() => set.Add(0));
Assert.Throws<NotSupportedException>(() => set.ExceptWith(null));
Assert.Throws<NotSupportedException>(() => set.UnionWith(null));
Assert.Throws<NotSupportedException>(() => set.IntersectWith(null));
Assert.Throws<NotSupportedException>(() => set.SymmetricExceptWith(null));
}
[Fact]
public void ICollectionOfTMembers()
{
var set = (ICollection<int>)this.Empty<int>();
Assert.Throws<NotSupportedException>(() => set.Add(1));
Assert.Throws<NotSupportedException>(() => set.Clear());
Assert.Throws<NotSupportedException>(() => set.Remove(1));
Assert.True(set.IsReadOnly);
}
[Fact]
public void ICollectionMethods()
{
ICollection builder = (ICollection)this.Empty<string>();
string[] array = new string[0];
builder.CopyTo(array, 0);
builder = (ICollection)this.Empty<string>().Add("a");
array = new string[builder.Count + 1];
builder.CopyTo(array, 1);
Assert.Equal(new[] { null, "a" }, array);
Assert.True(builder.IsSynchronized);
Assert.NotNull(builder.SyncRoot);
Assert.Same(builder.SyncRoot, builder.SyncRoot);
}
protected abstract bool IncludesGetHashCodeDerivative { get; }
internal static List<T> ToListNonGeneric<T>(System.Collections.IEnumerable sequence)
{
Contract.Requires(sequence != null);
var list = new List<T>();
var enumerator = sequence.GetEnumerator();
while (enumerator.MoveNext())
{
list.Add((T)enumerator.Current);
}
return list;
}
protected abstract IImmutableSet<T> Empty<T>();
protected abstract ISet<T> EmptyMutable<T>();
#if !NET45PLUS
internal abstract IBinaryTree GetRootNode<T>(IImmutableSet<T> set);
#endif
protected void TryGetValueTestHelper(IImmutableSet<string> set)
{
#if !NET45PLUS
Requires.NotNull(set, "set");
#endif
string expected = "egg";
set = set.Add(expected);
string actual;
string lookupValue = expected.ToUpperInvariant();
Assert.True(set.TryGetValue(lookupValue, out actual));
Assert.Same(expected, actual);
Assert.False(set.TryGetValue("foo", out actual));
Assert.Equal("foo", actual);
Assert.False(set.Clear().TryGetValue("nonexistent", out actual));
Assert.Equal("nonexistent", actual);
}
protected IImmutableSet<T> SetWith<T>(params T[] items)
{
return this.Empty<T>().Union(items);
}
protected void CustomSortTestHelper<T>(IImmutableSet<T> emptySet, bool matchOrder, T[] injectedValues, T[] expectedValues)
{
Contract.Requires(emptySet != null);
Contract.Requires(injectedValues != null);
Contract.Requires(expectedValues != null);
var set = emptySet;
foreach (T value in injectedValues)
{
set = set.Add(value);
}
Assert.Equal(expectedValues.Length, set.Count);
if (matchOrder)
{
Assert.Equal<T>(expectedValues, set.ToList());
}
else
{
CollectionAssertAreEquivalent(expectedValues, set.ToList());
}
}
/// <summary>
/// Tests various aspects of a set. This should be called only from the unordered or sorted overloads of this method.
/// </summary>
/// <typeparam name="T">The type of element stored in the set.</typeparam>
/// <param name="emptySet">The empty set.</param>
protected void EmptyTestHelper<T>(IImmutableSet<T> emptySet)
{
Contract.Requires(emptySet != null);
Assert.Equal(0, emptySet.Count); //, "Empty set should have a Count of 0");
Assert.Equal(0, emptySet.Count()); //, "Enumeration of an empty set yielded elements.");
Assert.Same(emptySet, emptySet.Clear());
}
private IEnumerable<SetTriad> GetSetEqualsScenarios()
{
return new List<SetTriad>
{
new SetTriad(SetWith<int>(), new int[] { }, true),
new SetTriad(SetWith<int>(5), new int[] { 5 }, true),
new SetTriad(SetWith<int>(5), new int[] { 5, 5 }, true),
new SetTriad(SetWith<int>(5, 8), new int[] { 5, 5 }, false),
new SetTriad(SetWith<int>(5, 8), new int[] { 5, 7 }, false),
new SetTriad(SetWith<int>(5, 8), new int[] { 5, 8 }, true),
new SetTriad(SetWith<int>(5), new int[] { }, false),
new SetTriad(SetWith<int>(), new int[] { 5 }, false),
new SetTriad(SetWith<int>(5, 8), new int[] { 5 }, false),
new SetTriad(SetWith<int>(5), new int[] { 5, 8 }, false),
new SetTriad(SetWith<int>(5, 8), SetWith<int>(5, 8), true),
};
}
private IEnumerable<SetTriad> GetIsProperSubsetOfScenarios()
{
return new List<SetTriad>
{
new SetTriad(new int[] { }, new int[] { }, false),
new SetTriad(new int[] { 1 }, new int[] { }, false),
new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true),
new SetTriad(new int[] { }, new int[] { 1 }, true),
};
}
private IEnumerable<SetTriad> GetIsSubsetOfScenarios()
{
var results = new List<SetTriad>
{
new SetTriad(new int[] { }, new int[] { }, true),
new SetTriad(new int[] { 1 }, new int[] { 1 }, true),
new SetTriad(new int[] { 1, 2 }, new int[] { 1, 2 }, true),
new SetTriad(new int[] { 1 }, new int[] { }, false),
new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
};
// By definition, any proper subset is also a subset.
// But because a subset may not be a proper subset, we filter the proper- scenarios.
results.AddRange(this.GetIsProperSubsetOfScenarios().Where(s => s.Item3));
return results;
}
private IEnumerable<SetTriad> GetOverlapsScenarios()
{
return new List<SetTriad>
{
new SetTriad(new int[] { }, new int[] { }, false),
new SetTriad(new int[] { }, new int[] { 1 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
new SetTriad(new int[] { 1, 2 }, new int[] { 3 }, false),
new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true),
new SetTriad(new int[] { 1, 2 }, new int[] { 1 }, true),
new SetTriad(new int[] { 1 }, new int[] { 1 }, true),
new SetTriad(new int[] { 1, 2 }, new int[] { 2, 3, 4 }, true),
};
}
private void SetCompareTestHelper<T>(Func<IImmutableSet<T>, Func<IEnumerable<T>, bool>> operation, Func<ISet<T>, Func<IEnumerable<T>, bool>> baselineOperation, IEnumerable<Tuple<IEnumerable<T>, IEnumerable<T>, bool>> scenarios)
{
//const string message = "Scenario #{0}: Set 1: {1}, Set 2: {2}";
int iteration = 0;
foreach (var scenario in scenarios)
{
iteration++;
// Figure out the response expected based on the BCL mutable collections.
var baselineSet = this.EmptyMutable<T>();
baselineSet.UnionWith(scenario.Item1);
var expectedFunc = baselineOperation(baselineSet);
bool expected = expectedFunc(scenario.Item2);
Assert.Equal(expected, scenario.Item3); //, "Test scenario has an expected result that is inconsistent with BCL mutable collection behavior.");
var actualFunc = operation(this.SetWith(scenario.Item1.ToArray()));
var args = new object[] { iteration, ToStringDeferred(scenario.Item1), ToStringDeferred(scenario.Item2) };
Assert.Equal(scenario.Item3, actualFunc(this.SetWith(scenario.Item2.ToArray()))); //, message, args);
Assert.Equal(scenario.Item3, actualFunc(scenario.Item2)); //, message, args);
}
}
private static Tuple<IEnumerable<T>, IEnumerable<T>, bool> Flip<T>(Tuple<IEnumerable<T>, IEnumerable<T>, bool> scenario)
{
return new Tuple<IEnumerable<T>, IEnumerable<T>, bool>(scenario.Item2, scenario.Item1, scenario.Item3);
}
private void RemoveTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Contract.Requires(set != null);
Contract.Requires(values != null);
Assert.Same(set, set.Except(Enumerable.Empty<T>()));
int initialCount = set.Count;
int removedCount = 0;
foreach (T value in values)
{
var nextSet = set.Remove(value);
Assert.NotSame(set, nextSet);
Assert.Equal(initialCount - removedCount, set.Count);
Assert.Equal(initialCount - removedCount - 1, nextSet.Count);
Assert.Same(nextSet, nextSet.Remove(value)); //, "Removing a non-existing element should not change the set reference.");
removedCount++;
set = nextSet;
}
Assert.Equal(initialCount - removedCount, set.Count);
}
private void RemoveNonExistingTest(IImmutableSet<int> emptySet)
{
Assert.Same(emptySet, emptySet.Remove(5));
// Also fill up a set with many elements to build up the tree, then remove from various places in the tree.
const int Size = 200;
var set = emptySet;
for (int i = 0; i < Size; i += 2)
{ // only even numbers!
set = set.Add(i);
}
// Verify that removing odd numbers doesn't change anything.
for (int i = 1; i < Size; i += 2)
{
var setAfterRemoval = set.Remove(i);
Assert.Same(set, setAfterRemoval);
}
}
private void AddRemoveLoadTestHelper<T>(IImmutableSet<T> set, T[] data)
{
Contract.Requires(set != null);
Contract.Requires(data != null);
foreach (T value in data)
{
var newSet = set.Add(value);
Assert.NotSame(set, newSet);
set = newSet;
}
foreach (T value in data)
{
Assert.True(set.Contains(value));
}
foreach (T value in data)
{
var newSet = set.Remove(value);
Assert.NotSame(set, newSet);
set = newSet;
}
}
protected void EnumeratorTestHelper<T>(IImmutableSet<T> emptySet, IComparer<T> comparer, params T[] values)
{
var set = emptySet;
foreach (T value in values)
{
set = set.Add(value);
}
var nonGenericEnumerableList = ToListNonGeneric<T>(set);
CollectionAssertAreEquivalent(nonGenericEnumerableList, values);
var list = set.ToList();
CollectionAssertAreEquivalent(list, values);
if (comparer != null)
{
Array.Sort(values, comparer);
Assert.Equal<T>(values, list);
}
// Apply some less common uses to the enumerator to test its metal.
IEnumerator<T> enumerator;
using (enumerator = set.GetEnumerator())
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset(); // reset isn't usually called before MoveNext
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
ManuallyEnumerateTest(list, enumerator);
Assert.False(enumerator.MoveNext()); // call it again to make sure it still returns false
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
ManuallyEnumerateTest(list, enumerator);
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// this time only partially enumerate
enumerator.Reset();
enumerator.MoveNext();
enumerator.Reset();
ManuallyEnumerateTest(list, enumerator);
}
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
}
private void ExceptTestHelper<T>(IImmutableSet<T> set, params T[] valuesToRemove)
{
Contract.Requires(set != null);
Contract.Requires(valuesToRemove != null);
var expectedSet = new HashSet<T>(set);
expectedSet.ExceptWith(valuesToRemove);
var actualSet = set.Except(valuesToRemove);
CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
#if !NET45PLUS
this.VerifyAvlTreeState(actualSet);
#endif
}
private void SymmetricExceptTestHelper<T>(IImmutableSet<T> set, params T[] otherCollection)
{
Contract.Requires(set != null);
Contract.Requires(otherCollection != null);
var expectedSet = new HashSet<T>(set);
expectedSet.SymmetricExceptWith(otherCollection);
var actualSet = set.SymmetricExcept(otherCollection);
CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
#if !NET45PLUS
this.VerifyAvlTreeState(actualSet);
#endif
}
private void IntersectTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Contract.Requires(set != null);
Contract.Requires(values != null);
Assert.True(set.Intersect(Enumerable.Empty<T>()).Count == 0);
var expected = new HashSet<T>(set);
expected.IntersectWith(values);
var actual = set.Intersect(values);
CollectionAssertAreEquivalent(expected.ToList(), actual.ToList());
#if !NET45PLUS
this.VerifyAvlTreeState(actual);
#endif
}
private void UnionTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Contract.Requires(set != null);
Contract.Requires(values != null);
var expected = new HashSet<T>(set);
expected.UnionWith(values);
var actual = set.Union(values);
CollectionAssertAreEquivalent(expected.ToList(), actual.ToList());
#if !NET45PLUS
this.VerifyAvlTreeState(actual);
#endif
}
private void AddTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Contract.Requires(set != null);
Contract.Requires(values != null);
Assert.Same(set, set.Union(Enumerable.Empty<T>()));
int initialCount = set.Count;
var uniqueValues = new HashSet<T>(values);
var enumerateAddSet = set.Union(values);
Assert.Equal(initialCount + uniqueValues.Count, enumerateAddSet.Count);
foreach (T value in values)
{
Assert.True(enumerateAddSet.Contains(value));
}
int addedCount = 0;
foreach (T value in values)
{
bool duplicate = set.Contains(value);
var nextSet = set.Add(value);
Assert.True(nextSet.Count > 0);
Assert.Equal(initialCount + addedCount, set.Count);
int expectedCount = initialCount + addedCount;
if (!duplicate)
{
expectedCount++;
}
Assert.Equal(expectedCount, nextSet.Count);
Assert.Equal(duplicate, set.Contains(value));
Assert.True(nextSet.Contains(value));
if (!duplicate)
{
addedCount++;
}
// Next assert temporarily disabled because Roslyn's set doesn't follow this rule.
Assert.Same(nextSet, nextSet.Add(value)); //, "Adding duplicate value {0} should keep the original reference.", value);
set = nextSet;
}
}
#if !NET45PLUS
private void VerifyAvlTreeState<T>(IImmutableSet<T> set)
{
var rootNode = this.GetRootNode(set);
rootNode.VerifyBalanced();
rootNode.VerifyHeightIsWithinTolerance(set.Count);
}
#endif
}
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using Mono.Collections.Generic;
using SR = System.Reflection;
using Mono.Cecil.Metadata;
namespace Mono.Cecil {
#if !READ_ONLY
public interface IMetadataImporterProvider {
IMetadataImporter GetMetadataImporter (ModuleDefinition module);
}
public interface IMetadataImporter {
TypeReference ImportReference (TypeReference type, IGenericParameterProvider context);
FieldReference ImportReference (FieldReference field, IGenericParameterProvider context);
MethodReference ImportReference (MethodReference method, IGenericParameterProvider context);
}
#if !CF
public interface IReflectionImporterProvider {
IReflectionImporter GetReflectionImporter (ModuleDefinition module);
}
public interface IReflectionImporter {
TypeReference ImportReference (Type type, IGenericParameterProvider context);
FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context);
MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context);
}
#endif
struct ImportGenericContext {
Collection<IGenericParameterProvider> stack;
public bool IsEmpty { get { return stack == null; } }
public ImportGenericContext (IGenericParameterProvider provider)
{
if (provider == null)
throw new ArgumentNullException ("provider");
stack = null;
Push (provider);
}
public void Push (IGenericParameterProvider provider)
{
if (stack == null)
stack = new Collection<IGenericParameterProvider> (1) { provider };
else
stack.Add (provider);
}
public void Pop ()
{
stack.RemoveAt (stack.Count - 1);
}
public TypeReference MethodParameter (string declTypeFullName, string method, int position)
{
for (int i = stack.Count - 1; i >= 0; i--) {
var candidate = stack [i] as MethodReference;
if (candidate == null)
continue;
if (method != candidate.Name || declTypeFullName != candidate.DeclaringType.FullName)
continue;
return candidate.GenericParameters [position];
}
throw new InvalidOperationException ();
}
public TypeReference TypeParameter (string type, int position)
{
for (int i = stack.Count - 1; i >= 0; i--) {
var candidate = GenericTypeFor (stack [i]);
if (candidate.FullName != type)
continue;
return candidate.GenericParameters [position];
}
throw new InvalidOperationException ();
}
static TypeReference GenericTypeFor (IGenericParameterProvider context)
{
var type = context as TypeReference;
if (type != null)
return type.GetElementType ();
var method = context as MethodReference;
if (method != null)
return method.DeclaringType.GetElementType ();
throw new InvalidOperationException ();
}
public static ImportGenericContext For (IGenericParameterProvider context)
{
return context != null ? new ImportGenericContext (context) : default (ImportGenericContext);
}
}
#if !CF
public class ReflectionImporter : IReflectionImporter {
readonly ModuleDefinition module;
public ReflectionImporter (ModuleDefinition module)
{
Mixin.CheckModule (module);
this.module = module;
}
enum ImportGenericKind {
Definition,
Open,
}
static readonly Dictionary<Type, ElementType> type_etype_mapping = new Dictionary<Type, ElementType> (18) {
{ typeof (void), ElementType.Void },
{ typeof (bool), ElementType.Boolean },
{ typeof (char), ElementType.Char },
{ typeof (sbyte), ElementType.I1 },
{ typeof (byte), ElementType.U1 },
{ typeof (short), ElementType.I2 },
{ typeof (ushort), ElementType.U2 },
{ typeof (int), ElementType.I4 },
{ typeof (uint), ElementType.U4 },
{ typeof (long), ElementType.I8 },
{ typeof (ulong), ElementType.U8 },
{ typeof (float), ElementType.R4 },
{ typeof (double), ElementType.R8 },
{ typeof (string), ElementType.String },
{ typeof (TypedReference), ElementType.TypedByRef },
{ typeof (IntPtr), ElementType.I },
{ typeof (UIntPtr), ElementType.U },
{ typeof (object), ElementType.Object },
};
TypeReference ImportType (Type type, ImportGenericContext context)
{
return ImportType (type, context, ImportGenericKind.Open);
}
TypeReference ImportType (Type type, ImportGenericContext context, ImportGenericKind import_kind)
{
if (IsTypeSpecification (type) || ImportOpenGenericType (type, import_kind))
return ImportTypeSpecification (type, context);
var reference = new TypeReference (
string.Empty,
type.Name,
module,
ImportScope (type.Assembly),
type.IsValueType);
reference.etype = ImportElementType (type);
if (IsNestedType (type))
reference.DeclaringType = ImportType (type.DeclaringType, context, import_kind);
else
reference.Namespace = type.Namespace ?? string.Empty;
if (type.IsGenericType)
ImportGenericParameters (reference, type.GetGenericArguments ());
return reference;
}
static bool ImportOpenGenericType (Type type, ImportGenericKind import_kind)
{
return type.IsGenericType && type.IsGenericTypeDefinition && import_kind == ImportGenericKind.Open;
}
static bool ImportOpenGenericMethod (SR.MethodBase method, ImportGenericKind import_kind)
{
return method.IsGenericMethod && method.IsGenericMethodDefinition && import_kind == ImportGenericKind.Open;
}
static bool IsNestedType (Type type)
{
#if !SILVERLIGHT
return type.IsNested;
#else
return type.DeclaringType != null;
#endif
}
TypeReference ImportTypeSpecification (Type type, ImportGenericContext context)
{
if (type.IsByRef)
return new ByReferenceType (ImportType (type.GetElementType (), context));
if (type.IsPointer)
return new PointerType (ImportType (type.GetElementType (), context));
if (type.IsArray)
return new ArrayType (ImportType (type.GetElementType (), context), type.GetArrayRank ());
if (type.IsGenericType)
return ImportGenericInstance (type, context);
if (type.IsGenericParameter)
return ImportGenericParameter (type, context);
throw new NotSupportedException (type.FullName);
}
static TypeReference ImportGenericParameter (Type type, ImportGenericContext context)
{
if (context.IsEmpty)
throw new InvalidOperationException ();
if (type.DeclaringMethod != null)
{
return context.MethodParameter (type.DeclaringType.FullName, type.DeclaringMethod.Name, type.GenericParameterPosition);
}
if (type.DeclaringType != null)
{
return context.TypeParameter (NormalizedFullName (type.DeclaringType), type.GenericParameterPosition);
}
throw new InvalidOperationException();
}
private static string NormalizedFullName (Type type)
{
if (IsNestedType (type))
return NormalizedFullName (type.DeclaringType) + "/" + type.Name;
return type.FullName;
}
TypeReference ImportGenericInstance (Type type, ImportGenericContext context)
{
var element_type = ImportType (type.GetGenericTypeDefinition (), context, ImportGenericKind.Definition);
var instance = new GenericInstanceType (element_type);
var arguments = type.GetGenericArguments ();
var instance_arguments = instance.GenericArguments;
context.Push (element_type);
try {
for (int i = 0; i < arguments.Length; i++)
instance_arguments.Add (ImportType (arguments [i], context));
return instance;
} finally {
context.Pop ();
}
}
static bool IsTypeSpecification (Type type)
{
return type.HasElementType
|| IsGenericInstance (type)
|| type.IsGenericParameter;
}
static bool IsGenericInstance (Type type)
{
return type.IsGenericType && !type.IsGenericTypeDefinition;
}
static ElementType ImportElementType (Type type)
{
ElementType etype;
if (!type_etype_mapping.TryGetValue (type, out etype))
return ElementType.None;
return etype;
}
AssemblyNameReference ImportScope (SR.Assembly assembly)
{
AssemblyNameReference scope;
#if !SILVERLIGHT
var name = assembly.GetName ();
if (TryGetAssemblyNameReference (name, out scope))
return scope;
scope = new AssemblyNameReference (name.Name, name.Version) {
Culture = name.CultureInfo.Name,
PublicKeyToken = name.GetPublicKeyToken (),
HashAlgorithm = (AssemblyHashAlgorithm) name.HashAlgorithm,
};
module.AssemblyReferences.Add (scope);
return scope;
#else
var name = AssemblyNameReference.Parse (assembly.FullName);
if (module.TryGetAssemblyNameReference (name, out scope))
return scope;
module.AssemblyReferences.Add (name);
return name;
#endif
}
#if !SILVERLIGHT
bool TryGetAssemblyNameReference (SR.AssemblyName name, out AssemblyNameReference assembly_reference)
{
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (name.FullName != reference.FullName) // TODO compare field by field
continue;
assembly_reference = reference;
return true;
}
assembly_reference = null;
return false;
}
#endif
FieldReference ImportField (SR.FieldInfo field, ImportGenericContext context)
{
var declaring_type = ImportType (field.DeclaringType, context);
if (IsGenericInstance (field.DeclaringType))
field = ResolveFieldDefinition (field);
context.Push (declaring_type);
try {
return new FieldReference {
Name = field.Name,
DeclaringType = declaring_type,
FieldType = ImportType (field.FieldType, context),
};
} finally {
context.Pop ();
}
}
static SR.FieldInfo ResolveFieldDefinition (SR.FieldInfo field)
{
#if !SILVERLIGHT
return field.Module.ResolveField (field.MetadataToken);
#else
return field.DeclaringType.GetGenericTypeDefinition ().GetField (field.Name,
SR.BindingFlags.Public
| SR.BindingFlags.NonPublic
| (field.IsStatic ? SR.BindingFlags.Static : SR.BindingFlags.Instance));
#endif
}
MethodReference ImportMethod (SR.MethodBase method, ImportGenericContext context, ImportGenericKind import_kind)
{
if (IsMethodSpecification (method) || ImportOpenGenericMethod (method, import_kind))
return ImportMethodSpecification (method, context);
var declaring_type = ImportType (method.DeclaringType, context);
if (IsGenericInstance (method.DeclaringType))
method = method.Module.ResolveMethod (method.MetadataToken);
var reference = new MethodReference {
Name = method.Name,
HasThis = HasCallingConvention (method, SR.CallingConventions.HasThis),
ExplicitThis = HasCallingConvention (method, SR.CallingConventions.ExplicitThis),
DeclaringType = ImportType (method.DeclaringType, context, ImportGenericKind.Definition),
};
if (HasCallingConvention (method, SR.CallingConventions.VarArgs))
reference.CallingConvention &= MethodCallingConvention.VarArg;
if (method.IsGenericMethod)
ImportGenericParameters (reference, method.GetGenericArguments ());
context.Push (reference);
try {
var method_info = method as SR.MethodInfo;
reference.ReturnType = method_info != null
? ImportType (method_info.ReturnType, context)
: ImportType (typeof (void), default (ImportGenericContext));
var parameters = method.GetParameters ();
var reference_parameters = reference.Parameters;
for (int i = 0; i < parameters.Length; i++)
reference_parameters.Add (
new ParameterDefinition (ImportType (parameters [i].ParameterType, context)));
reference.DeclaringType = declaring_type;
return reference;
} finally {
context.Pop ();
}
}
static void ImportGenericParameters (IGenericParameterProvider provider, Type [] arguments)
{
var provider_parameters = provider.GenericParameters;
for (int i = 0; i < arguments.Length; i++)
provider_parameters.Add (new GenericParameter (arguments [i].Name, provider));
}
static bool IsMethodSpecification (SR.MethodBase method)
{
return method.IsGenericMethod && !method.IsGenericMethodDefinition;
}
MethodReference ImportMethodSpecification (SR.MethodBase method, ImportGenericContext context)
{
var method_info = method as SR.MethodInfo;
if (method_info == null)
throw new InvalidOperationException ();
var element_method = ImportMethod (method_info.GetGenericMethodDefinition (), context, ImportGenericKind.Definition);
var instance = new GenericInstanceMethod (element_method);
var arguments = method.GetGenericArguments ();
var instance_arguments = instance.GenericArguments;
context.Push (element_method);
try {
for (int i = 0; i < arguments.Length; i++)
instance_arguments.Add (ImportType (arguments [i], context));
return instance;
} finally {
context.Pop ();
}
}
static bool HasCallingConvention (SR.MethodBase method, SR.CallingConventions conventions)
{
return (method.CallingConvention & conventions) != 0;
}
public virtual TypeReference ImportReference (Type type, IGenericParameterProvider context)
{
Mixin.CheckType (type);
return ImportType (
type,
ImportGenericContext.For (context),
context != null ? ImportGenericKind.Open : ImportGenericKind.Definition);
}
public virtual FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context)
{
Mixin.CheckField (field);
return ImportField (field, ImportGenericContext.For (context));
}
public virtual MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context)
{
Mixin.CheckMethod (method);
return ImportMethod (method,
ImportGenericContext.For (context),
context != null ? ImportGenericKind.Open : ImportGenericKind.Definition);
}
}
#endif
public class MetadataImporter : IMetadataImporter {
readonly Dictionary<TypeRefKey, TypeReference> cache = new Dictionary<TypeRefKey, TypeReference>();
readonly ModuleDefinition module;
public MetadataImporter (ModuleDefinition module)
{
Mixin.CheckModule (module);
this.module = module;
}
struct TypeRefKey : IEquatable<TypeRefKey>
{
string fullname;
string assembly;
bool isValueType;
public static TypeRefKey From(TypeReference r)
{
return new TypeRefKey { fullname = r.FullName, assembly = r.Scope.ToString(), isValueType = r.IsValueType };
}
public override int GetHashCode()
{
return fullname.GetHashCode() + assembly.GetHashCode() + (isValueType ? 1 : 0);
}
public bool Equals(TypeRefKey other)
{
return other.fullname == fullname && other.assembly == assembly && other.isValueType == isValueType;
}
}
TypeReference ImportType (TypeReference type, ImportGenericContext context)
{
if (type.IsTypeSpecification ())
return ImportTypeSpecification (type, context);
var reference = default(TypeReference);
var key = TypeRefKey.From(type);
if (cache.TryGetValue(key, out reference))
{
// Cecil only fills TypeRef GenericParameters if used ( bug ?)
// Now that we cache them, we need to make sure the cached version has all of the needed ones
if (type.HasGenericParameters && reference.GenericParameters.Count != type.GenericParameters.Count)
{
for (int i = reference.GenericParameters.Count - 1; i < type.GenericParameters.Count; i++)
reference.GenericParameters.Add(new GenericParameter(reference));
}
return reference;
}
reference = new TypeReference (
type.Namespace,
type.Name,
module,
ImportScope (type.Scope),
type.IsValueType);
MetadataSystem.TryProcessPrimitiveTypeReference (reference);
if (type.IsNested)
reference.DeclaringType = ImportType (type.DeclaringType, context);
if (type.HasGenericParameters)
ImportGenericParameters (reference, type);
cache.Add(key, reference);
return reference;
}
IMetadataScope ImportScope (IMetadataScope scope)
{
switch (scope.MetadataScopeType) {
case MetadataScopeType.AssemblyNameReference:
return ImportAssemblyName ((AssemblyNameReference) scope);
case MetadataScopeType.ModuleDefinition:
if (scope == module) return scope;
return ImportAssemblyName (((ModuleDefinition) scope).Assembly.Name);
case MetadataScopeType.ModuleReference:
throw new NotImplementedException ();
}
throw new NotSupportedException ();
}
AssemblyNameReference ImportAssemblyName (AssemblyNameReference name)
{
AssemblyNameReference reference;
if (module.TryGetAssemblyNameReference (name, out reference))
return reference;
reference = new AssemblyNameReference (name.Name, name.Version) {
Culture = name.Culture,
HashAlgorithm = name.HashAlgorithm,
IsRetargetable = name.IsRetargetable
};
var pk_token = !name.PublicKeyToken.IsNullOrEmpty ()
? new byte [name.PublicKeyToken.Length]
: Empty<byte>.Array;
if (pk_token.Length > 0)
Buffer.BlockCopy (name.PublicKeyToken, 0, pk_token, 0, pk_token.Length);
reference.PublicKeyToken = pk_token;
module.AssemblyReferences.Add (reference);
return reference;
}
static void ImportGenericParameters (IGenericParameterProvider imported, IGenericParameterProvider original)
{
var parameters = original.GenericParameters;
var imported_parameters = imported.GenericParameters;
for (int i = 0; i < parameters.Count; i++)
imported_parameters.Add (new GenericParameter (parameters [i].Name, imported));
}
TypeReference ImportTypeSpecification (TypeReference type, ImportGenericContext context)
{
switch (type.etype) {
case ElementType.SzArray:
var vector = (ArrayType) type;
return new ArrayType (ImportType (vector.ElementType, context));
case ElementType.Ptr:
var pointer = (PointerType) type;
return new PointerType (ImportType (pointer.ElementType, context));
case ElementType.ByRef:
var byref = (ByReferenceType) type;
return new ByReferenceType (ImportType (byref.ElementType, context));
case ElementType.Pinned:
var pinned = (PinnedType) type;
return new PinnedType (ImportType (pinned.ElementType, context));
case ElementType.Sentinel:
var sentinel = (SentinelType) type;
return new SentinelType (ImportType (sentinel.ElementType, context));
case ElementType.FnPtr:
var fnptr = (FunctionPointerType) type;
var imported_fnptr = new FunctionPointerType () {
HasThis = fnptr.HasThis,
ExplicitThis = fnptr.ExplicitThis,
CallingConvention = fnptr.CallingConvention,
ReturnType = ImportType (fnptr.ReturnType, context),
};
if (!fnptr.HasParameters)
return imported_fnptr;
for (int i = 0; i < fnptr.Parameters.Count; i++)
imported_fnptr.Parameters.Add (new ParameterDefinition (
ImportType (fnptr.Parameters [i].ParameterType, context)));
return imported_fnptr;
case ElementType.CModOpt:
var modopt = (OptionalModifierType) type;
return new OptionalModifierType (
ImportType (modopt.ModifierType, context),
ImportType (modopt.ElementType, context));
case ElementType.CModReqD:
var modreq = (RequiredModifierType) type;
return new RequiredModifierType (
ImportType (modreq.ModifierType, context),
ImportType (modreq.ElementType, context));
case ElementType.Array:
var array = (ArrayType) type;
var imported_array = new ArrayType (ImportType (array.ElementType, context));
if (array.IsVector)
return imported_array;
var dimensions = array.Dimensions;
var imported_dimensions = imported_array.Dimensions;
imported_dimensions.Clear ();
for (int i = 0; i < dimensions.Count; i++) {
var dimension = dimensions [i];
imported_dimensions.Add (new ArrayDimension (dimension.LowerBound, dimension.UpperBound));
}
return imported_array;
case ElementType.GenericInst:
var instance = (GenericInstanceType) type;
var element_type = ImportType (instance.ElementType, context);
var imported_instance = new GenericInstanceType (element_type);
var arguments = instance.GenericArguments;
var imported_arguments = imported_instance.GenericArguments;
for (int i = 0; i < arguments.Count; i++)
imported_arguments.Add (ImportType (arguments [i], context));
return imported_instance;
case ElementType.Var:
var var_parameter = (GenericParameter) type;
if (var_parameter.DeclaringType == null)
throw new InvalidOperationException ();
return context.TypeParameter (var_parameter.DeclaringType.FullName, var_parameter.Position);
case ElementType.MVar:
var mvar_parameter = (GenericParameter) type;
if (mvar_parameter.DeclaringMethod == null)
throw new InvalidOperationException ();
return context.MethodParameter (((MethodReference)mvar_parameter.Owner).DeclaringType.FullName, mvar_parameter.DeclaringMethod.Name, mvar_parameter.Position);
}
throw new NotSupportedException (type.etype.ToString ());
}
FieldReference ImportField (FieldReference field, ImportGenericContext context)
{
var declaring_type = ImportType (field.DeclaringType, context);
context.Push (declaring_type);
try {
return new FieldReference {
Name = field.Name,
DeclaringType = declaring_type,
FieldType = ImportType (field.FieldType, context),
};
} finally {
context.Pop ();
}
}
MethodReference ImportMethod (MethodReference method, ImportGenericContext context)
{
if (method.IsGenericInstance)
return ImportMethodSpecification (method, context);
var declaring_type = ImportType (method.DeclaringType, context);
var reference = new MethodReference {
Name = method.Name,
HasThis = method.HasThis,
ExplicitThis = method.ExplicitThis,
DeclaringType = declaring_type,
CallingConvention = method.CallingConvention,
};
if (method.HasGenericParameters)
ImportGenericParameters (reference, method);
context.Push (reference);
try {
reference.ReturnType = ImportType (method.ReturnType, context);
if (!method.HasParameters)
return reference;
var parameters = method.Parameters;
var reference_parameters = reference.parameters = new ParameterDefinitionCollection (reference, parameters.Count);
for (int i = 0; i < parameters.Count; i++)
reference_parameters.Add (
new ParameterDefinition (ImportType (parameters [i].ParameterType, context)));
return reference;
} finally {
context.Pop();
}
}
MethodSpecification ImportMethodSpecification (MethodReference method, ImportGenericContext context)
{
if (!method.IsGenericInstance)
throw new NotSupportedException ();
var instance = (GenericInstanceMethod) method;
var element_method = ImportMethod (instance.ElementMethod, context);
var imported_instance = new GenericInstanceMethod (element_method);
var arguments = instance.GenericArguments;
var imported_arguments = imported_instance.GenericArguments;
for (int i = 0; i < arguments.Count; i++)
imported_arguments.Add (ImportType (arguments [i], context));
return imported_instance;
}
public virtual TypeReference ImportReference (TypeReference type, IGenericParameterProvider context)
{
Mixin.CheckType (type);
return ImportType (type, ImportGenericContext.For (context));
}
public virtual FieldReference ImportReference (FieldReference field, IGenericParameterProvider context)
{
Mixin.CheckField (field);
return ImportField (field, ImportGenericContext.For (context));
}
public virtual MethodReference ImportReference (MethodReference method, IGenericParameterProvider context)
{
Mixin.CheckMethod (method);
return ImportMethod (method, ImportGenericContext.For (context));
}
}
static partial class Mixin {
public static void CheckModule (ModuleDefinition module)
{
if (module == null)
throw new ArgumentNullException ("module");
}
public static bool TryGetAssemblyNameReference (this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)
{
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (!Equals (name_reference, reference))
continue;
assembly_reference = reference;
return true;
}
assembly_reference = null;
return false;
}
private static bool Equals (byte [] a, byte [] b)
{
if (ReferenceEquals (a, b))
return true;
if (a == null)
return false;
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
if (a [i] != b [i])
return false;
return true;
}
private static bool Equals<T> (T a, T b) where T : class, IEquatable<T>
{
if (ReferenceEquals (a, b))
return true;
if (a == null)
return false;
return a.Equals (b);
}
private static bool Equals (AssemblyNameReference a, AssemblyNameReference b)
{
if (ReferenceEquals (a, b))
return true;
if (a.Name != b.Name)
return false;
if (!Equals (a.Version, b.Version))
return false;
if (a.Culture != b.Culture)
return false;
if (!Equals (a.PublicKeyToken, b.PublicKeyToken))
return false;
return true;
}
}
#endif
}
| |
/*
* Copyright (c) 2013 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* 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;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace MiniJSON {
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using SkillzSDK;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class Json {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WORD_BREAK = "{}[],:\"";
public static bool IsWordBreak(char c) {
return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1;
}
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
StringReader json;
Parser(string jsonString) {
json = new StringReader(jsonString);
}
public static object Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return instance.ParseValue();
}
}
public void Dispose() {
json.Dispose();
json = null;
}
Dictionary<string, object> ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
table[name] = ParseValue();
break;
}
}
}
List<object> ParseArray() {
List<object> array = new List<object>();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new char[4];
for (int i=0; i< 4; i++) {
hex[i] = NextChar;
}
s.Append((char) Convert.ToInt32(new string(hex), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
if (number.IndexOf('.') == -1) {
long parsedInt;
Int64.TryParse(number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedInt);
return parsedInt;
}
double parsedDouble;
Double.TryParse(number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedDouble);
return parsedDouble;
}
void EatWhitespace() {
while (Char.IsWhiteSpace(PeekChar)) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (!IsWordBreak(PeekChar)) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
switch (PeekChar) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
switch (NextWord) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(object obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value) {
IList asList;
IDictionary asDict;
string asStr;
if (value == null) {
builder.Append("null");
} else if ((asStr = value as string) != null) {
SerializeString(asStr);
} else if (value is bool) {
builder.Append((bool) value ? "true" : "false");
} else if ((asList = value as IList) != null) {
SerializeArray(asList);
} else if ((asDict = value as IDictionary) != null) {
SerializeObject(asDict);
} else if (value is char) {
SerializeString(new string((char) value, 1));
} else {
SerializeOther(value);
}
}
void SerializeObject(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray) {
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
} else {
builder.Append("\\u");
builder.Append(codepoint.ToString("x4"));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value) {
// NOTE: decimals lose precision during serialization.
// They always have, I'm just letting you know.
// Previously floats and doubles lost precision too.
if (value is float) {
builder.Append(((float) value).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
} else if (value is int
|| value is uint
|| value is long
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong) {
builder.Append(value);
} else if (value is double
|| value is decimal) {
builder.Append(Convert.ToDouble(value).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
} else {
SerializeString(value.ToString());
}
}
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\WorldSettings.h:395
namespace UnrealEngine
{
public partial class AWorldSettings : AInfo
{
public AWorldSettings(IntPtr adress)
: base(adress)
{
}
public AWorldSettings(UObject Parent = null, string Name = "WorldSettings")
: base(IntPtr.Zero)
{
NativePointer = E_NewObject_AWorldSettings(Parent, Name);
NativeManager.AddNativeWrapper(NativePointer, this);
}
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bEnableAISystem_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bEnableAISystem_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bEnableWorldBoundsChecks_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bEnableWorldBoundsChecks_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bEnableWorldComposition_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bEnableWorldComposition_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bEnableWorldOriginRebasing_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bEnableWorldOriginRebasing_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bForceNoPrecomputedLighting_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bForceNoPrecomputedLighting_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bGlobalGravitySet_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bGlobalGravitySet_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bHighPriorityLoading_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bHighPriorityLoading_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bHighPriorityLoadingLocal_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bHighPriorityLoadingLocal_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bMinimizeBSPSections_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bMinimizeBSPSections_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bOverrideDefaultBroadphaseSettings_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bOverrideDefaultBroadphaseSettings_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bPlaceCellsOnlyAlongCameraTracks_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bPlaceCellsOnlyAlongCameraTracks_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bPrecomputeVisibility_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bPrecomputeVisibility_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_AWorldSettings_BroadphaseSettings_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_BroadphaseSettings_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bUseClientSideLevelStreamingVolumes_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bUseClientSideLevelStreamingVolumes_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_AWorldSettings_bWorldGravitySet_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_bWorldGravitySet_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_AWorldSettings_DefaultColorScale_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_DefaultColorScale_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_DefaultMaxDistanceFieldOcclusionDistance_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_DefaultMaxDistanceFieldOcclusionDistance_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_DemoPlayTimeDilation_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_DemoPlayTimeDilation_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_DynamicIndirectShadowsSelfShadowingIntensity_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_DynamicIndirectShadowsSelfShadowingIntensity_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_GlobalDistanceFieldViewDistance_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_GlobalDistanceFieldViewDistance_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_GlobalGravityZ_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_GlobalGravityZ_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_KillZ_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_KillZ_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_MatineeTimeDilation_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_MatineeTimeDilation_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_PROP_AWorldSettings_MAX_BOOKMARK_NUMBER_GET();
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_MaxGlobalTimeDilation_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_MaxGlobalTimeDilation_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_MaxUndilatedFrameTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_MaxUndilatedFrameTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_MinGlobalTimeDilation_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_MinGlobalTimeDilation_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_MinUndilatedFrameTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_MinUndilatedFrameTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_MonoCullingDistance_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_MonoCullingDistance_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_PROP_AWorldSettings_PackedLightAndShadowMapTextureSize_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_PackedLightAndShadowMapTextureSize_SET(IntPtr Ptr, int Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_PROP_AWorldSettings_Pauser_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_Pauser_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_TimeDilation_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_TimeDilation_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_PROP_AWorldSettings_VisibilityCellSize_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_VisibilityCellSize_SET(IntPtr Ptr, int Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_WorldGravityZ_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_WorldGravityZ_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_AWorldSettings_WorldToMeters_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_AWorldSettings_WorldToMeters_SET(IntPtr Ptr, float Value);
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_NewObject_AWorldSettings(IntPtr Parent, string Name);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_AWorldSettings_ClearAllBookmarks(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_AWorldSettings_CompactBookmarks(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_AWorldSettings_FixupDeltaSeconds(IntPtr self, float deltaSeconds, float realDeltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_AWorldSettings_GetEffectiveTimeDilation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_AWorldSettings_GetGravityZ(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_AWorldSettings_GetMaxNumberOfBookmarks(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_AWorldSettings_IsNavigationSystemEnabled(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_AWorldSettings_NotifyBeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_AWorldSettings_NotifyMatchStarted(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_AWorldSettings_OnRep_WorldGravityZ(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_AWorldSettings_SetTimeDilation(IntPtr self, float newTimeDilation);
#endregion
#region Property
/// <summary>
/// if set to false AI system will not get created. Use it to disable all AI-related activity on a map
/// </summary>
public byte bEnableAISystem
{
get => E_PROP_AWorldSettings_bEnableAISystem_GET(NativePointer);
set => E_PROP_AWorldSettings_bEnableAISystem_SET(NativePointer, value);
}
/// <summary>
/// If true, enables CheckStillInWorld checks
/// </summary>
public byte bEnableWorldBoundsChecks
{
get => E_PROP_AWorldSettings_bEnableWorldBoundsChecks_GET(NativePointer);
set => E_PROP_AWorldSettings_bEnableWorldBoundsChecks_SET(NativePointer, value);
}
/// <summary>
/// Enables tools for composing a tiled world.
/// <para>Level has to be saved and all sub-levels removed before enabling this option. </para>
/// </summary>
public byte bEnableWorldComposition
{
get => E_PROP_AWorldSettings_bEnableWorldComposition_GET(NativePointer);
set => E_PROP_AWorldSettings_bEnableWorldComposition_SET(NativePointer, value);
}
/// <summary>
/// World origin will shift to a camera position when camera goes far away from current origin
/// </summary>
public byte bEnableWorldOriginRebasing
{
get => E_PROP_AWorldSettings_bEnableWorldOriginRebasing_GET(NativePointer);
set => E_PROP_AWorldSettings_bEnableWorldOriginRebasing_SET(NativePointer, value);
}
/// <summary>
/// Whether to force lightmaps and other precomputed lighting to not be created even when the engine thinks they are needed.
/// <para>This is useful for improving iteration in levels with fully dynamic lighting and shadowing. </para>
/// Note that any lighting and shadowing interactions that are usually precomputed will be lost if this is enabled.
/// </summary>
public byte bForceNoPrecomputedLighting
{
get => E_PROP_AWorldSettings_bForceNoPrecomputedLighting_GET(NativePointer);
set => E_PROP_AWorldSettings_bForceNoPrecomputedLighting_SET(NativePointer, value);
}
/// <summary>
/// If set to true we will use GlobalGravityZ instead of project setting DefaultGravityZ
/// </summary>
public byte OverrideWorldGravity
{
get => E_PROP_AWorldSettings_bGlobalGravitySet_GET(NativePointer);
set => E_PROP_AWorldSettings_bGlobalGravitySet_SET(NativePointer, value);
}
public byte bHighPriorityLoading
{
get => E_PROP_AWorldSettings_bHighPriorityLoading_GET(NativePointer);
set => E_PROP_AWorldSettings_bHighPriorityLoading_SET(NativePointer, value);
}
public byte bHighPriorityLoadingLocal
{
get => E_PROP_AWorldSettings_bHighPriorityLoadingLocal_GET(NativePointer);
set => E_PROP_AWorldSettings_bHighPriorityLoadingLocal_SET(NativePointer, value);
}
/// <summary>
/// Causes the BSP build to generate as few sections as possible.
/// <para>This is useful when you need to reduce draw calls but can reduce texture streaming efficiency and effective lightmap resolution. </para>
/// Note - changes require a rebuild to propagate. Also, be sure to select all surfaces and make sure they all have the same flags to minimize section count.
/// </summary>
public byte bMinimizeBSPSections
{
get => E_PROP_AWorldSettings_bMinimizeBSPSections_GET(NativePointer);
set => E_PROP_AWorldSettings_bMinimizeBSPSections_SET(NativePointer, value);
}
public byte bOverrideDefaultBroadphaseSettings
{
get => E_PROP_AWorldSettings_bOverrideDefaultBroadphaseSettings_GET(NativePointer);
set => E_PROP_AWorldSettings_bOverrideDefaultBroadphaseSettings_SET(NativePointer, value);
}
/// <summary>
/// Whether to place visibility cells only along camera tracks or only above shadow casting surfaces.
/// </summary>
public byte bPlaceCellsOnlyAlongCameraTracks
{
get => E_PROP_AWorldSettings_bPlaceCellsOnlyAlongCameraTracks_GET(NativePointer);
set => E_PROP_AWorldSettings_bPlaceCellsOnlyAlongCameraTracks_SET(NativePointer, value);
}
/// <summary>
/// Whether to place visibility cells inside Precomputed Visibility Volumes and along camera tracks in this level.
/// <para>Precomputing visibility reduces rendering thread time at the cost of some runtime memory and somewhat increased lighting build times. </para>
/// </summary>
public byte bPrecomputeVisibility
{
get => E_PROP_AWorldSettings_bPrecomputeVisibility_GET(NativePointer);
set => E_PROP_AWorldSettings_bPrecomputeVisibility_SET(NativePointer, value);
}
public FBroadphaseSettings BroadphaseSettings
{
get => E_PROP_AWorldSettings_BroadphaseSettings_GET(NativePointer);
set => E_PROP_AWorldSettings_BroadphaseSettings_SET(NativePointer, value);
}
/// <summary>
/// Enables client-side streaming volumes instead of server-side.
/// <para>Expected usage scenario: server has all streaming levels always loaded, clients independently stream levels in/out based on streaming volumes. </para>
/// </summary>
public byte bUseClientSideLevelStreamingVolumes
{
get => E_PROP_AWorldSettings_bUseClientSideLevelStreamingVolumes_GET(NativePointer);
set => E_PROP_AWorldSettings_bUseClientSideLevelStreamingVolumes_SET(NativePointer, value);
}
public byte bWorldGravitySet
{
get => E_PROP_AWorldSettings_bWorldGravitySet_GET(NativePointer);
set => E_PROP_AWorldSettings_bWorldGravitySet_SET(NativePointer, value);
}
/// <summary>
/// Default color scale for the level
/// </summary>
public FVector DefaultColorScale
{
get => E_PROP_AWorldSettings_DefaultColorScale_GET(NativePointer);
set => E_PROP_AWorldSettings_DefaultColorScale_SET(NativePointer, value);
}
/// <summary>
/// Max occlusion distance used by mesh distance fields, overridden if there is a movable skylight.
/// </summary>
public float DefaultMaxDistanceFieldOcclusionDistance
{
get => E_PROP_AWorldSettings_DefaultMaxDistanceFieldOcclusionDistance_GET(NativePointer);
set => E_PROP_AWorldSettings_DefaultMaxDistanceFieldOcclusionDistance_SET(NativePointer, value);
}
public float DemoPlayTimeDilation
{
get => E_PROP_AWorldSettings_DemoPlayTimeDilation_GET(NativePointer);
set => E_PROP_AWorldSettings_DemoPlayTimeDilation_SET(NativePointer, value);
}
/// <summary>
/// Controls the intensity of self-shadowing from capsule indirect shadows.
/// <para>These types of shadows use approximate occluder representations, so reducing self-shadowing intensity can hide those artifacts. </para>
/// </summary>
public float DynamicIndirectShadowsSelfShadowingIntensity
{
get => E_PROP_AWorldSettings_DynamicIndirectShadowsSelfShadowingIntensity_GET(NativePointer);
set => E_PROP_AWorldSettings_DynamicIndirectShadowsSelfShadowingIntensity_SET(NativePointer, value);
}
/// <summary>
/// Distance from the camera that the global distance field should cover.
/// </summary>
public float GlobalDistanceFieldViewDistance
{
get => E_PROP_AWorldSettings_GlobalDistanceFieldViewDistance_GET(NativePointer);
set => E_PROP_AWorldSettings_GlobalDistanceFieldViewDistance_SET(NativePointer, value);
}
public float GlobalGravityZ
{
get => E_PROP_AWorldSettings_GlobalGravityZ_GET(NativePointer);
set => E_PROP_AWorldSettings_GlobalGravityZ_SET(NativePointer, value);
}
public float KillZ
{
get => E_PROP_AWorldSettings_KillZ_GET(NativePointer);
set => E_PROP_AWorldSettings_KillZ_SET(NativePointer, value);
}
public float MatineeTimeDilation
{
get => E_PROP_AWorldSettings_MatineeTimeDilation_GET(NativePointer);
set => E_PROP_AWorldSettings_MatineeTimeDilation_SET(NativePointer, value);
}
/// <summary>
/// Maximum number of bookmarks
/// </summary>
public static int MAX_BOOKMARK_NUMBER
{
get => E_PROP_AWorldSettings_MAX_BOOKMARK_NUMBER_GET();
}
/// <summary>
/// Highest acceptable global time dilation.
/// </summary>
public float MaxGlobalTimeDilation
{
get => E_PROP_AWorldSettings_MaxGlobalTimeDilation_GET(NativePointer);
set => E_PROP_AWorldSettings_MaxGlobalTimeDilation_SET(NativePointer, value);
}
/// <summary>
/// Largest possible frametime, not considering dilation. Equiv to 1/SlowestFPS.
/// </summary>
public float MaxUndilatedFrameTime
{
get => E_PROP_AWorldSettings_MaxUndilatedFrameTime_GET(NativePointer);
set => E_PROP_AWorldSettings_MaxUndilatedFrameTime_SET(NativePointer, value);
}
/// <summary>
/// Lowest acceptable global time dilation.
/// </summary>
public float MinGlobalTimeDilation
{
get => E_PROP_AWorldSettings_MinGlobalTimeDilation_GET(NativePointer);
set => E_PROP_AWorldSettings_MinGlobalTimeDilation_SET(NativePointer, value);
}
/// <summary>
/// Smallest possible frametime, not considering dilation. Equiv to 1/FastestFPS.
/// </summary>
public float MinUndilatedFrameTime
{
get => E_PROP_AWorldSettings_MinUndilatedFrameTime_GET(NativePointer);
set => E_PROP_AWorldSettings_MinUndilatedFrameTime_SET(NativePointer, value);
}
/// <summary>
/// Distance from the player after which content will be rendered in mono if monoscopic far field rendering is activated
/// </summary>
public float MonoCullingDistance
{
get => E_PROP_AWorldSettings_MonoCullingDistance_GET(NativePointer);
set => E_PROP_AWorldSettings_MonoCullingDistance_SET(NativePointer, value);
}
/// <summary>
/// Maximum size of textures for packed light and shadow maps
/// </summary>
public int PackedLightAndShadowMapTextureSize
{
get => E_PROP_AWorldSettings_PackedLightAndShadowMapTextureSize_GET(NativePointer);
set => E_PROP_AWorldSettings_PackedLightAndShadowMapTextureSize_SET(NativePointer, value);
}
public APlayerState Pauser
{
get => E_PROP_AWorldSettings_Pauser_GET(NativePointer);
set => E_PROP_AWorldSettings_Pauser_SET(NativePointer, value);
}
public float TimeDilation
{
get => E_PROP_AWorldSettings_TimeDilation_GET(NativePointer);
set => E_PROP_AWorldSettings_TimeDilation_SET(NativePointer, value);
}
/// <summary>
/// World space size of precomputed visibility cells in x and y.
/// <para>Smaller sizes produce more effective occlusion culling at the cost of increased runtime memory usage and lighting build times. </para>
/// </summary>
public int VisibilityCellSize
{
get => E_PROP_AWorldSettings_VisibilityCellSize_GET(NativePointer);
set => E_PROP_AWorldSettings_VisibilityCellSize_SET(NativePointer, value);
}
public float WorldGravityZ
{
get => E_PROP_AWorldSettings_WorldGravityZ_GET(NativePointer);
set => E_PROP_AWorldSettings_WorldGravityZ_SET(NativePointer, value);
}
/// <summary>
/// scale of 1uu to 1m in real world measurements, for HMD and other physically tracked devices (e.g. 1uu = 1cm would be 100.0)
/// </summary>
public float WorldToMeters
{
get => E_PROP_AWorldSettings_WorldToMeters_GET(NativePointer);
set => E_PROP_AWorldSettings_WorldToMeters_SET(NativePointer, value);
}
#endregion
#region ExternMethods
/// <summary>
/// Clears all references to current bookmarks.
/// </summary>
public void ClearAllBookmarks()
=> E_AWorldSettings_ClearAllBookmarks(this);
/// <summary>
/// Attempts to move bookmarks such that all bookmarks are adjacent in memory.
/// <para>Note, this will not rearrange any valid Bookmarks inside the mapped range, but </para>
/// may move bookmarks outside that range to fill up mapped bookmarks.
/// </summary>
public void CompactBookmarks()
=> E_AWorldSettings_CompactBookmarks(this);
/// <summary>
/// Returns the delta time to be used by the tick. Can be overridden if game specific logic is needed.
/// </summary>
public virtual float FixupDeltaSeconds(float deltaSeconds, float realDeltaSeconds)
=> E_AWorldSettings_FixupDeltaSeconds(this, deltaSeconds, realDeltaSeconds);
public virtual float GetEffectiveTimeDilation()
=> E_AWorldSettings_GetEffectiveTimeDilation(this);
/// <summary>
/// Returns the Z component of the current world gravity and initializes it to the default
/// <para>gravity if called for the first time. </para>
/// </summary>
/// <return>Z</return>
public virtual float GetGravityZ()
=> E_AWorldSettings_GetGravityZ(this);
public int GetMaxNumberOfBookmarks()
=> E_AWorldSettings_GetMaxNumberOfBookmarks(this);
/// <summary>
/// </summary>
/// <return>whether</return>
public bool IsNavigationSystemEnabled()
=> E_AWorldSettings_IsNavigationSystemEnabled(this);
/// <summary>
/// Called from GameStateBase, calls BeginPlay on all actors
/// </summary>
public virtual void NotifyBeginPlay()
=> E_AWorldSettings_NotifyBeginPlay(this);
/// <summary>
/// Called from GameStateBase, used to notify native classes of match startup (such as level scripting)
/// </summary>
public virtual void NotifyMatchStarted()
=> E_AWorldSettings_NotifyMatchStarted(this);
public virtual void OnRep_WorldGravityZ()
=> E_AWorldSettings_OnRep_WorldGravityZ(this);
/// <summary>
/// Sets the global time dilation value (subject to clamping). Returns the final value that was set.
/// </summary>
public virtual float SetTimeDilation(float newTimeDilation)
=> E_AWorldSettings_SetTimeDilation(this, newTimeDilation);
#endregion
public static implicit operator IntPtr(AWorldSettings self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator AWorldSettings(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<AWorldSettings>(PtrDesc);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*=============================================================================
**
** Class: Queue
**
** Purpose: Represents a first-in, first-out collection of objects.
**
=============================================================================*/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections
{
// A simple Queue of objects. Internally it is implemented as a circular
// buffer, so Enqueue can be O(n). Dequeue is O(1).
[DebuggerTypeProxy(typeof(System.Collections.Queue.QueueDebugView))]
[DebuggerDisplay("Count = {Count}")]
public class Queue : ICollection
{
private Object[] _array;
private int _head; // First valid element in the queue
private int _tail; // Last valid element in the queue
private int _size; // Number of elements.
private int _growFactor; // 100 == 1.0, 130 == 1.3, 200 == 2.0
private int _version;
private Object _syncRoot;
private const int _MinimumGrow = 4;
private const int _ShrinkThreshold = 32;
// Creates a queue with room for capacity objects. The default initial
// capacity and grow factor are used.
public Queue()
: this(32, (float)2.0)
{
}
// Creates a queue with room for capacity objects. The default grow factor
// is used.
//
public Queue(int capacity)
: this(capacity, (float)2.0)
{
}
// Creates a queue with room for capacity objects. When full, the new
// capacity is set to the old capacity * growFactor.
//
public Queue(int capacity, float growFactor)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedNonNegNum);
if (!(growFactor >= 1.0 && growFactor <= 10.0))
throw new ArgumentOutOfRangeException("growFactor", SR.Format(SR.ArgumentOutOfRange_QueueGrowFactor, 1, 10));
Contract.EndContractBlock();
_array = new Object[capacity];
_head = 0;
_tail = 0;
_size = 0;
_growFactor = (int)(growFactor * 100);
}
// Fills a Queue with the elements of an ICollection. Uses the enumerator
// to get each of the elements.
//
public Queue(ICollection col) : this((col == null ? 32 : col.Count))
{
if (col == null)
throw new ArgumentNullException("col");
Contract.EndContractBlock();
IEnumerator en = col.GetEnumerator();
while (en.MoveNext())
Enqueue(en.Current);
}
public virtual int Count
{
get { return _size; }
}
public virtual Object Clone()
{
Queue q = new Queue(_size);
q._size = _size;
int numToCopy = _size;
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, q._array, 0, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
Array.Copy(_array, 0, q._array, _array.Length - _head, numToCopy);
q._version = _version;
return q;
}
public virtual bool IsSynchronized
{
get { return false; }
}
public virtual Object SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the queue.
public virtual void Clear()
{
if (_head < _tail)
Array.Clear(_array, _head, _size);
else
{
Array.Clear(_array, _head, _array.Length - _head);
Array.Clear(_array, 0, _tail);
}
_head = 0;
_tail = 0;
_size = 0;
_version++;
}
// CopyTo copies a collection into an Array, starting at a particular
// index into the array.
//
public virtual void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
if (index < 0)
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
int arrayLen = array.Length;
if (arrayLen - index < _size)
throw new ArgumentException(SR.Argument_InvalidOffLen);
int numToCopy = _size;
if (numToCopy == 0)
return;
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, array, index, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy);
}
// Adds obj to the tail of the queue.
//
public virtual void Enqueue(Object obj)
{
if (_size == _array.Length)
{
int newcapacity = (int)((long)_array.Length * (long)_growFactor / 100);
if (newcapacity < _array.Length + _MinimumGrow)
{
newcapacity = _array.Length + _MinimumGrow;
}
SetCapacity(newcapacity);
}
_array[_tail] = obj;
_tail = (_tail + 1) % _array.Length;
_size++;
_version++;
}
// GetEnumerator returns an IEnumerator over this Queue. This
// Enumerator will support removing.
//
public virtual IEnumerator GetEnumerator()
{
return new QueueEnumerator(this);
}
// Removes the object at the head of the queue and returns it. If the queue
// is empty, this method simply returns null.
public virtual Object Dequeue()
{
if (Count == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
Contract.EndContractBlock();
Object removed = _array[_head];
_array[_head] = null;
_head = (_head + 1) % _array.Length;
_size--;
_version++;
return removed;
}
// Returns the object at the head of the queue. The object remains in the
// queue. If the queue is empty, this method throws an
// InvalidOperationException.
public virtual Object Peek()
{
if (Count == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
Contract.EndContractBlock();
return _array[_head];
}
// Returns a synchronized Queue. Returns a synchronized wrapper
// class around the queue - the caller must not use references to the
// original queue.
//
public static Queue Synchronized(Queue queue)
{
if (queue == null)
throw new ArgumentNullException("queue");
Contract.EndContractBlock();
return new SynchronizedQueue(queue);
}
// Returns true if the queue contains at least one object equal to obj.
// Equality is determined using obj.Equals().
//
// Exceptions: ArgumentNullException if obj == null.
public virtual bool Contains(Object obj)
{
int index = _head;
int count = _size;
while (count-- > 0)
{
if (obj == null)
{
if (_array[index] == null)
return true;
}
else if (_array[index] != null && _array[index].Equals(obj))
{
return true;
}
index = (index + 1) % _array.Length;
}
return false;
}
internal Object GetElement(int i)
{
return _array[(_head + i) % _array.Length];
}
// Iterates over the objects in the queue, returning an array of the
// objects in the Queue, or an empty array if the queue is empty.
// The order of elements in the array is first in to last in, the same
// order produced by successive calls to Dequeue.
public virtual Object[] ToArray()
{
if (_size == 0)
return Array.Empty<Object>();
Object[] arr = new Object[_size];
if (_head < _tail)
{
Array.Copy(_array, _head, arr, 0, _size);
}
else
{
Array.Copy(_array, _head, arr, 0, _array.Length - _head);
Array.Copy(_array, 0, arr, _array.Length - _head, _tail);
}
return arr;
}
// PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity
// must be >= _size.
private void SetCapacity(int capacity)
{
Object[] newarray = new Object[capacity];
if (_size > 0)
{
if (_head < _tail)
{
Array.Copy(_array, _head, newarray, 0, _size);
}
else
{
Array.Copy(_array, _head, newarray, 0, _array.Length - _head);
Array.Copy(_array, 0, newarray, _array.Length - _head, _tail);
}
}
_array = newarray;
_head = 0;
_tail = (_size == capacity) ? 0 : _size;
_version++;
}
public virtual void TrimToSize()
{
SetCapacity(_size);
}
// Implements a synchronization wrapper around a queue.
private class SynchronizedQueue : Queue
{
private Queue _q;
private Object _root;
internal SynchronizedQueue(Queue q)
{
_q = q;
_root = _q.SyncRoot;
}
public override bool IsSynchronized
{
get { return true; }
}
public override Object SyncRoot
{
get
{
return _root;
}
}
public override int Count
{
get
{
lock (_root)
{
return _q.Count;
}
}
}
public override void Clear()
{
lock (_root)
{
_q.Clear();
}
}
public override Object Clone()
{
lock (_root)
{
return new SynchronizedQueue((Queue)_q.Clone());
}
}
public override bool Contains(Object obj)
{
lock (_root)
{
return _q.Contains(obj);
}
}
public override void CopyTo(Array array, int arrayIndex)
{
lock (_root)
{
_q.CopyTo(array, arrayIndex);
}
}
public override void Enqueue(Object value)
{
lock (_root)
{
_q.Enqueue(value);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
public override Object Dequeue()
{
lock (_root)
{
return _q.Dequeue();
}
}
public override IEnumerator GetEnumerator()
{
lock (_root)
{
return _q.GetEnumerator();
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
public override Object Peek()
{
lock (_root)
{
return _q.Peek();
}
}
public override Object[] ToArray()
{
lock (_root)
{
return _q.ToArray();
}
}
public override void TrimToSize()
{
lock (_root)
{
_q.TrimToSize();
}
}
}
// Implements an enumerator for a Queue. The enumerator uses the
// internal version number of the list to ensure that no modifications are
// made to the list while an enumeration is in progress.
private class QueueEnumerator : IEnumerator
{
private Queue _q;
private int _index;
private int _version;
private Object _currentElement;
internal QueueEnumerator(Queue q)
{
_q = q;
_version = _q._version;
_index = 0;
_currentElement = _q._array;
if (_q._size == 0)
_index = -1;
}
public virtual bool MoveNext()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index < 0)
{
_currentElement = _q._array;
return false;
}
_currentElement = _q.GetElement(_index);
_index++;
if (_index == _q._size)
_index = -1;
return true;
}
public virtual Object Current
{
get
{
if (_currentElement == _q._array)
{
if (_index == 0)
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
else
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
}
return _currentElement;
}
}
public virtual void Reset()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_q._size == 0)
_index = -1;
else
_index = 0;
_currentElement = _q._array;
}
}
internal class QueueDebugView
{
private Queue _queue;
public QueueDebugView(Queue queue)
{
if (queue == null)
throw new ArgumentNullException("queue");
Contract.EndContractBlock();
_queue = queue;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public Object[] Items
{
get
{
return _queue.ToArray();
}
}
}
}
}
| |
// Artificial Intelligence for Humans
// Volume 2: Nature-Inspired Algorithms
// C# Version
// http://www.aifh.org
// http://www.jeffheaton.com
//
// Code repository:
// https://github.com/jeffheaton/aifh
//
// Copyright 2014 by Jeff Heaton
//
// 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using AIFH_Vol2.Core.General.Data;
using AIFH_Vol2.Core.Learning;
using AIFH_Vol2.Core.Learning.Score;
using AIFH_Vol2.Core.Randomize;
using AIFH_Vol2.Examples.Capstone.Model.Milestone1;
namespace AIFH_Vol2.Examples.Capstone.Model.Milestone2
{
/// <summary>
/// The second milestone for titanic is to fit and cross validate a model.
/// </summary>
public class FitTitanic
{
/// <summary>
/// The name of this example.
/// </summary>
public static string ExampleName = "Titanic Milestone 2: Fit the model.";
/// <summary>
/// The chapter this example is from.
/// </summary>
public static int ExampleChapter = 10;
/// <summary>
/// The best RBF network.
/// </summary>
private RBFNetwork _bestNetwork;
/// <summary>
/// The best score.
/// </summary>
private double _bestScore;
/// <summary>
/// The cross validation folds.
/// </summary>
private CrossValidate _cross;
/// <summary>
/// The best network from the folds.
/// </summary>
public RBFNetwork BestNetwork
{
get { return _bestNetwork; }
}
/// <summary>
/// The cross validation folds.
/// </summary>
public CrossValidate Crossvalidation
{
get { return _cross; }
}
/// <summary>
/// Train one fold.
/// </summary>
/// <param name="k">The fold id.</param>
/// <param name="fold">The fold.</param>
public void TrainFold(int k, CrossValidateFold fold)
{
int noImprove = 0;
double localBest = 0;
// Get the training and cross validation sets.
IList<BasicData> training = fold.TrainingSet;
IList<BasicData> validation = fold.ValidationSet;
// Create random particles for the RBF.
IGenerateRandom rnd = new MersenneTwisterGenerateRandom();
var particles = new RBFNetwork[TitanicConfig.ParticleCount];
for (int i = 0; i < particles.Length; i++)
{
particles[i] = new RBFNetwork(TitanicConfig.InputFeatureCount, TitanicConfig.RbfCount, 1);
particles[i].Reset(rnd);
}
/**
* Construct a network to hold the best network.
*/
if (_bestNetwork == null)
{
_bestNetwork = new RBFNetwork(TitanicConfig.InputFeatureCount, TitanicConfig.RbfCount, 1);
}
/**
* Setup the scoring function.
*/
IScoreFunction score = new ScoreTitanic(training);
IScoreFunction scoreValidate = new ScoreTitanic(validation);
/**
* Setup particle swarm.
*/
bool done = false;
var train = new TrainPSO(particles, score);
int iterationNumber = 0;
var line = new StringBuilder();
do
{
iterationNumber++;
train.Iteration();
var best = (RBFNetwork) train.BestParticle;
double trainingScore = train.LastError;
double validationScore = scoreValidate.CalculateScore(best);
if (validationScore > _bestScore)
{
Array.Copy(best.LongTermMemory, 0, _bestNetwork.LongTermMemory, 0, best.LongTermMemory.Length);
_bestScore = validationScore;
}
if (validationScore > localBest)
{
noImprove = 0;
localBest = validationScore;
}
else
{
noImprove++;
}
line.Length = 0;
line.Append("Fold #");
line.Append(k + 1);
line.Append(", Iteration #");
line.Append(iterationNumber);
line.Append(": training correct: ");
line.Append(trainingScore);
line.Append(", validation correct: ");
line.Append(validationScore);
line.Append(", no improvement: ");
line.Append(noImprove);
if (noImprove > TitanicConfig.AllowNoImprovement)
{
done = true;
}
Console.WriteLine(line.ToString());
} while (!done);
fold.Score = localBest;
}
/// <summary>
/// Fit a RBF model to the titanic.
/// </summary>
/// <param name="dataPath">The path that contains the data file.</param>
public void Process(string dataPath)
{
string trainingPath = Path.Combine(dataPath, TitanicConfig.TrainingFilename);
string testPath = Path.Combine(dataPath, TitanicConfig.TestFilename);
IGenerateRandom rnd = new MersenneTwisterGenerateRandom();
// Generate stats on the titanic.
var stats = new TitanicStats();
NormalizeTitanic.Analyze(stats, trainingPath);
NormalizeTitanic.Analyze(stats, testPath);
// Get the training data for the titanic.
IList<BasicData> training = NormalizeTitanic.Normalize(stats, trainingPath, null,
TitanicConfig.InputNormalizeLow,
TitanicConfig.InputNormalizeHigh,
TitanicConfig.PredictSurvive,
TitanicConfig.PredictPerish);
// Fold the data for cross validation.
_cross = new CrossValidate(TitanicConfig.FoldCount, training, rnd);
// Train each of the folds.
for (int k = 0; k < _cross.Count; k++)
{
Console.WriteLine("Cross validation fold #" + (k + 1) + "/" + _cross.Count);
TrainFold(k, _cross.Folds[k]);
}
// Show the cross validation summary.
Console.WriteLine("Crossvalidation summary:");
int kk = 1;
foreach (CrossValidateFold fold in _cross.Folds)
{
Console.WriteLine("Fold #" + kk + ": " + fold.Score);
kk++;
}
Console.WriteLine("Final, crossvalidated score:" + _cross.Score);
}
/// <summary>
/// The entry point for this example. If you would like to make this example
/// stand alone, then add to its own project and rename to Main.
/// </summary>
/// <param name="args">Not used.</param>
public static void ExampleMain(string[] args)
{
string filename = "";
if (args.Length > 0)
{
filename = args[0];
string dataPath = filename;
var fit = new FitTitanic();
fit.Process(dataPath);
}
else
{
Console.WriteLine("Please provide your data directory path as the first argument.");
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using V1=AssetBundleGraph;
using Model=UnityEngine.AssetGraph.DataModel.Version2;
namespace UnityEngine.AssetGraph {
[CustomNode("File/Mirror Directory", 110)]
public class MirrorDirectory : Node {
public enum MirrorOption : int {
KeepAlreadyCopiedFiles,
AlwaysRecreateDestination
}
[SerializeField] private SerializableMultiTargetString m_srcPath;
[SerializeField] private SerializableMultiTargetString m_dstPath;
[SerializeField] private SerializableMultiTargetInt m_mirrorOption;
public override string ActiveStyle {
get {
return "node 0 on";
}
}
public override string InactiveStyle {
get {
return "node 0";
}
}
public override string Category {
get {
return "File";
}
}
public override Model.NodeOutputSemantics NodeInputType {
get {
return Model.NodeOutputSemantics.Any;
}
}
public override Model.NodeOutputSemantics NodeOutputType {
get {
return Model.NodeOutputSemantics.Any;
}
}
public override void Initialize(Model.NodeData data) {
m_srcPath = new SerializableMultiTargetString();
m_dstPath = new SerializableMultiTargetString();
m_mirrorOption = new SerializableMultiTargetInt ();
data.AddDefaultInputPoint();
data.AddDefaultOutputPoint();
}
public override Node Clone(Model.NodeData newData) {
var newNode = new MirrorDirectory();
newNode.m_srcPath = new SerializableMultiTargetString(m_srcPath);
newNode.m_dstPath = new SerializableMultiTargetString(m_dstPath);
newNode.m_mirrorOption = new SerializableMultiTargetInt (m_mirrorOption);
newData.AddDefaultInputPoint();
newData.AddDefaultOutputPoint();
return newNode;
}
public override void OnInspectorGUI(NodeGUI node, AssetReferenceStreamManager streamManager, NodeGUIEditor editor, Action onValueChanged) {
if (m_srcPath == null) {
return;
}
var currentEditingGroup = editor.CurrentEditingGroup;
EditorGUILayout.HelpBox("Mirror Directory: Mirror source directory to destination. This node does not use assets passed by.", MessageType.Info);
editor.UpdateNodeName(node);
GUILayout.Space(10f);
//Show target configuration tab
editor.DrawPlatformSelector(node);
using (new EditorGUILayout.VerticalScope(GUI.skin.box)) {
var disabledScope = editor.DrawOverrideTargetToggle(node, m_srcPath.ContainsValueOf(currentEditingGroup), (bool enabled) => {
using(new RecordUndoScope("Remove Target Mirror Directory Settings", node, true)){
if(enabled) {
m_srcPath[currentEditingGroup] = m_srcPath.DefaultValue;
m_dstPath[currentEditingGroup] = m_dstPath.DefaultValue;
m_mirrorOption[currentEditingGroup] = m_mirrorOption.DefaultValue;
} else {
m_srcPath.Remove(currentEditingGroup);
m_dstPath.Remove(currentEditingGroup);
m_mirrorOption[currentEditingGroup] = m_mirrorOption.DefaultValue;
}
onValueChanged();
}
} );
using (disabledScope) {
MirrorOption opt = (MirrorOption)m_mirrorOption[currentEditingGroup];
var newOption = (MirrorOption)EditorGUILayout.EnumPopup("Mirror Option", opt);
if(newOption != opt) {
using(new RecordUndoScope("Change Mirror Option", node, true)){
m_mirrorOption[currentEditingGroup] = (int)newOption;
onValueChanged();
}
}
EditorGUILayout.LabelField("Source Directory Path:");
string newSrcPath = null;
string newDstPath = null;
newSrcPath = editor.DrawFolderSelector ("", "Select Source Folder",
m_srcPath[currentEditingGroup],
Directory.GetParent(Application.dataPath).ToString(),
(string folderSelected) => {
var projectPath = Directory.GetParent(Application.dataPath).ToString();
if(projectPath == folderSelected) {
folderSelected = string.Empty;
} else {
var index = folderSelected.IndexOf(projectPath);
if(index >= 0 ) {
folderSelected = folderSelected.Substring(projectPath.Length + index);
if(folderSelected.IndexOf('/') == 0) {
folderSelected = folderSelected.Substring(1);
}
}
}
return folderSelected;
}
);
if (newSrcPath != m_srcPath[currentEditingGroup]) {
using(new RecordUndoScope("Change Source Folder", node, true)){
m_srcPath[currentEditingGroup] = newSrcPath;
onValueChanged();
}
}
DrawDirectorySuggestion (GetNormalizedPath (m_srcPath[currentEditingGroup]), currentEditingGroup, onValueChanged);
GUILayout.Space (10f);
EditorGUILayout.LabelField("Destination Directory Path:");
newDstPath = editor.DrawFolderSelector ("", "Select Destination Folder",
m_dstPath[currentEditingGroup],
Directory.GetParent(Application.dataPath).ToString(),
(string folderSelected) => {
var projectPath = Directory.GetParent(Application.dataPath).ToString();
if(projectPath == folderSelected) {
folderSelected = string.Empty;
} else {
var index = folderSelected.IndexOf(projectPath);
if(index >= 0 ) {
folderSelected = folderSelected.Substring(projectPath.Length + index);
if(folderSelected.IndexOf('/') == 0) {
folderSelected = folderSelected.Substring(1);
}
}
}
return folderSelected;
}
);
if (newDstPath != m_dstPath[currentEditingGroup]) {
using(new RecordUndoScope("Change Destination Folder", node, true)){
m_dstPath[currentEditingGroup] = newDstPath;
onValueChanged();
}
}
DrawDirectorySuggestion (GetNormalizedPath (m_dstPath[currentEditingGroup]), currentEditingGroup, onValueChanged);
}
}
}
public override void Prepare (BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output Output)
{
if (string.IsNullOrEmpty(m_srcPath [target])) {
throw new NodeException("Mirror Directory can not set project directory as source.",
"Set valid source directory from inspector.",node);
}
if (string.IsNullOrEmpty(m_dstPath [target])) {
throw new NodeException("Mirror Directory can not set project directory as destination.",
"Set valid destination directory from inspector.",node);
}
if (!Directory.Exists (GetNormalizedPath (m_srcPath [target]))) {
throw new NodeException("Source Directory does not exist. Path:" + m_srcPath[target],
"Create source diretory or set valid source directory path from inspector.", node);
}
// MirrorDirectory does not add, filter or change structure of group, so just pass given group of assets
if(Output != null) {
var dst = (connectionsToOutput == null || !connectionsToOutput.Any())?
null : connectionsToOutput.First();
if(incoming != null) {
foreach(var ag in incoming) {
Output(dst, ag.assetGroups);
}
} else {
Output(dst, new Dictionary<string, List<AssetReference>>());
}
}
}
public override void Build (BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output Output,
Action<Model.NodeData, string, float> progressFunc)
{
Mirror(target, node, incoming, connectionsToOutput, progressFunc);
}
private void Mirror (BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
Action<Model.NodeData, string, float> progressFunc)
{
try {
var srcDir = GetNormalizedPath(m_srcPath[target]);
var dstDir = GetNormalizedPath(m_dstPath[target]);
if (Directory.Exists (dstDir)) {
if(m_mirrorOption[target] == (int)MirrorOption.AlwaysRecreateDestination) {
FileUtility.DeleteDirectory(dstDir, true);
}
else if(m_mirrorOption[target] == (int)MirrorOption.KeepAlreadyCopiedFiles)
{
var dstFilePaths = FileUtility.GetAllFilePathsInFolder (dstDir);
// checking destination files - remove files if not exist in source
foreach (var dstPath in dstFilePaths) {
var srcPath = dstPath.Replace (dstDir, srcDir);
if (!File.Exists (srcPath)) {
File.Delete (dstPath);
}
}
}
}
var targetFilePaths = FileUtility.GetAllFilePathsInFolder(srcDir);
int i = 0;
foreach (var srcPath in targetFilePaths) {
var dstPath = srcPath.Replace (srcDir, dstDir);
var dstParentDir = Directory.GetParent (dstPath);
if (!dstParentDir.Exists) {
var dirPath = dstParentDir.ToString();
Directory.CreateDirectory (dirPath);
}
var srcInfo = new FileInfo (srcPath);
var dstInfo = new FileInfo (dstPath);
if (!dstInfo.Exists ||
srcInfo.LastWriteTimeUtc > dstInfo.LastWriteTimeUtc)
{
File.Copy (srcPath, dstPath, true);
progressFunc (node, string.Format ("Copying {0}", Path.GetFileName (srcPath)), (float)(i++) / (float)targetFilePaths.Count);
}
}
} catch(Exception e) {
throw new NodeException(e.Message, "See description for detail.", node);
}
}
private string GetNormalizedPath(string path) {
if(string.IsNullOrEmpty(path)) {
return Directory.GetParent(Application.dataPath).ToString();
} else if(path[0] == '/') {
return path;
} else {
return FileUtility.GetPathWithProjectPath(path);
}
}
private void DrawDirectorySuggestion(string targetPath, BuildTargetGroup currentEditingGroup, Action onValueChanged) {
if (!Directory.Exists (targetPath)) {
using (new EditorGUILayout.HorizontalScope ()) {
EditorGUILayout.LabelField (targetPath + " does not exist.");
if (GUILayout.Button ("Create directory")) {
Directory.CreateDirectory (targetPath);
}
onValueChanged ();
}
EditorGUILayout.Space ();
string parentDir = Path.GetDirectoryName (targetPath);
if (Directory.Exists (parentDir)) {
EditorGUILayout.LabelField ("Available Directories:");
string[] dirs = Directory.GetDirectories (parentDir);
foreach (string s in dirs) {
EditorGUILayout.LabelField (s);
}
}
} else {
GUILayout.Space(10f);
using (new EditorGUILayout.HorizontalScope()) {
GUILayout.FlexibleSpace();
#if UNITY_EDITOR_OSX
string buttonName = "Reveal in Finder";
#else
string buttonName = "Show in Explorer";
#endif
if(GUILayout.Button(buttonName)) {
EditorUtility.RevealInFinder(targetPath);
}
}
}
}
public static bool ValidateDirectory (string combinedPath, Action DoesNotExist) {
if (!Directory.Exists(combinedPath)) {
DoesNotExist();
return false;
}
return true;
}
}
}
| |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using VoidEngine.Helpers;
using VoidEngine.VGame;
namespace Predator.Characters
{
public class Player : Sprite
{
protected Game1 myGame;
#region Player Stats
/// <summary>
/// Gets or sets the player's level.
/// </summary>
public int Level
{
get;
set;
}
/// <summary>
/// Gets or sets if the player is dead.
/// </summary>
public bool isDead
{
get;
set;
}
/// <summary>
/// Gets or sets the player's HP in float.
/// </summary>
public float MainHP
{
get;
set;
}
/// <summary>
/// Gets the player's HP rounded down.
/// </summary>
public int HP
{
get
{
return (int)MainHP;
}
}
/// <summary>
/// Gets or sets the Max HP of the player.
/// </summary>
public float MaxHP
{
get;
set;
}
/// <summary>
/// Gets or sets if the player fell out the map.
/// </summary>
public bool FellFromBottom
{
get;
set;
}
/// <summary>
/// Gets or sets the player's damage stat.
/// </summary>
public float Damage
{
get;
set;
}
/// <summary>
/// Gets or sets the player's defense stat.
/// </summary>
public float Defense
{
get;
set;
}
/// <summary>
/// Gets or sets the player's stat points.
/// </summary>
public int StatPoints
{
get;
set;
}
/// <summary>
/// Gets or sets the player's points to strength.
/// </summary>
public float PStrength
{
get;
set;
}
/// <summary>
/// Gets or sets the player's points to agility.
/// </summary>
public float PAgility
{
get;
set;
}
/// <summary>
/// Gets or sets the player's points to defense.
/// </summary>
public float PDefense
{
get;
set;
}
/// <summary>
/// Gets or sets the player's points to experiance.
/// </summary>
public int PExp
{
get;
set;
}
/// <summary>
/// Gets or sets the player's previous points to experiance.
/// </summary>
public int PreviousPExp
{
get;
set;
}
/// <summary>
/// Gets or sets the player's stat level.
/// </summary>
public int Lvl
{
get;
set;
}
/// <summary>
/// Gets or sets if the player is allowed to level up.
/// </summary>
public bool LvlUp
{
get;
set;
}
#endregion
#region Movement Stats
/// <summary>
/// Gets the players center based off of it's posititon.
/// </summary>
public Vector2 PositionCenter
{
get
{
return new Vector2(BoundingCollisions.Center.X, BoundingCollisions.Center.Y);
}
}
/// <summary>
/// Gets or sets the keys to move the player with.
/// </summary>
public Keys[,] MovementKeys
{
set;
get;
}
/// <summary>
/// The keyboardState that the player can detect it's keys with.
/// </summary>
public KeyboardState KeyboardState;
/// <summary>
/// Gets or sets the velocity to move the player at.
/// </summary>
public Vector2 Velocity
{
get
{
return velocity;
}
protected set
{
velocity = value;
}
}
/// <summary>
/// The velocity to move the player at.
/// </summary>
protected Vector2 velocity;
#region Constants for controling horizontal movement
/// <summary>
/// The acceleration to move the player at.
/// </summary>
protected float MoveAcceleration = 13000.0f;
/// <summary>
/// The max amount of speed the player can move at.
/// </summary>
protected float MaxMoveSpeed = 1750.0f;
/// <summary>
/// The friction that the player is experiencing when on the ground.
/// </summary>
protected float GroundDragFactor = 0.50f;
/// <summary>
/// The friction that the player is experiencing when in the air.
/// </summary>
protected float AirDragFactor = 0.58f;
/// <summary>
///
/// </summary>
protected float WaterDragFactor = 0.35f;
/// <summary>
///
/// </summary>
protected float JumpbackSpeed = 50000.0f;
#endregion
#region Constants for controlling vertical movement
/// <summary>
/// The max time the player can jump.
/// </summary>
protected float MaxJumpTime = 0.35f;
/// <summary>
/// The velocity that the player jumps at.
/// </summary>
protected float JumpLaunchVelocity = -3500.0f;
/// <summary>
/// The acceleration of gravity that the player is effected by.
/// </summary>
protected float GravityAcceleration = 3400f;
/// <summary>
/// The terminal velocity of the player's fall speed.
/// </summary>
protected float MaxFallSpeed = 550.0f;
/// <summary>
/// The control power of the jump.
/// </summary>
protected float JumpControlPower = 0.14f;
#endregion
/// <summary>
/// Gets or sets if the player is grounded.
/// </summary>
public bool IsGrounded
{
get;
protected set;
}
/// <summary>
/// Gets or sets the movement direction of the player on the X axis.
/// </summary>
public float Movement
{
get;
protected set;
}
/// <summary>
/// Gets or sets if the player is jumping.
/// </summary>
public bool IsJumping
{
get;
set;
}
/// <summary>
/// Gets or sets if the player was jumping.
/// </summary>
public bool WasJumping
{
get;
protected set;
}
/// <summary>
/// Gets or sets the jumpTime.
/// </summary>
public float JumpTime
{
get;
protected set;
}
/// <summary>
/// Gets or sets the Jumpback Timer.
/// </summary>
public int JumpbackTimer
{
get;
protected set;
}
/// <summary>
///
/// </summary>
public bool IsInWater
{
get;
set;
}
public float WaterCheckTimer;
public float dWaterCheckTimer;
public float WaterChecksTillDeath;
#endregion
#region Debug Stuff
/// <summary>
/// Used to debug the block the player is currently touching.
/// </summary>
public Rectangle DebugBlock;
#endregion
#region Combat Stuff
/// <summary>
/// Gets or sets the attack counter for the player.
/// </summary>
public float AttackCounter
{
get;
set;
}
/// <summary>
/// Gets or sets the player's attack delay.
/// </summary>
public int AttackDelay
{
get;
set;
}
#region Projectile Stuff
/// <summary>
/// Gets or sets the list of projectiles.
/// </summary>
public List<Projectile> ProjectileList
{
get;
protected set;
}
/// <summary>
/// Gets or sets the list of AnimationSets that the projectile has.
/// </summary>
public Texture2D ProjectileTexture
{
get;
set;
}
/// <summary>
/// Gets or sets if the player is shooting.
/// </summary>
public bool IsShooting
{
get;
set;
}
/// <summary>
/// Gets or sets if the player can shoot.
/// </summary>
public bool CanShoot
{
get;
set;
}
/// <summary>
/// Gets or sets if the player can create a new projectile.
/// </summary>
public bool CreateNewProjectile
{
get;
set;
}
#endregion
#region Mana Stuff
/// <summary>
/// Gets or sets the amount of mana the player has.
/// </summary>
protected float Mana
{
get;
set;
}
/// <summary>
/// Gets or sets the maxium mana the player can have.
/// </summary>
protected float MaxMana
{
get;
set;
}
/// <summary>
/// Gets or sets the amount of time it takes the mana to start recharging.
/// </summary>
protected float ManaRechargeTime
{
get;
set;
}
/// <summary>
/// Gets or sets the default amount of time it takes the mana to start recharging.
/// </summary>
protected float DefaultManaRechargeTime
{
get;
set;
}
/// <summary>
/// Gets or sets the amount of mana it will rechage every second.
/// </summary>
protected float ManaRechargeInterval
{
get;
set;
}
/// <summary>
/// Gets or sets the default mana recharge time.
/// </summary>
protected float DefaultManaRechargeInterval
{
get;
set;
}
/// <summary>
/// Gets or sets the ammount of mana it will decrease by.
/// </summary>
protected float ManaDecreaseAmount
{
get;
set;
}
#endregion
#endregion
public int justHit = 200;
/// <summary>
/// Creates the player class, with default animation set.
/// </summary>
/// <param name="texture">The texture to use with the player.</param>
/// <param name="position">The starting position to put the player at.</param>
/// <param name="movementKeys">The list of movement keys for the player.</param>
/// <param name="color">The color to mask the player with.</param>
/// <param name="myGame">The game that the player runs on.</param>
public Player(Texture2D texture, Vector2 position, Keys[,] movementKeys, Color color, Game1 myGame)
: base(position, color, texture)
{
this.myGame = myGame;
Scale = 0.29166666666666666666666666666667f;
//Scale = 0.3f;
AddAnimations(texture);
SetAnimation("IDLE1");
AttackDelay = 750;
JumpbackTimer = 1;
Level = 1;
StatPoints = 0;
PExp = 0;
PAgility = 3.375f;
PDefense = 2;
PStrength = 5;
MainHP = MaxHP = 100;
dWaterCheckTimer = WaterCheckTimer = 800;
Mana = MaxMana = 0;
ManaRechargeTime = DefaultManaRechargeTime = 0.09f;
ManaRechargeInterval = DefaultManaRechargeInterval = 0.1f;
ManaDecreaseAmount = 0f;
#region Set Projectile Factors
ProjectileList = new List<Projectile>();
CanShoot = true;
CreateNewProjectile = true;
#endregion
#region Set Movement and Collision Factors
MovementKeys = movementKeys;
int width = (int)(CurrentAnimation.frameSize.X * Scale);
int left = (int)(0);
int height = (int)(CurrentAnimation.frameSize.Y * Scale);
int top = (int)(0);
inbounds = new Rectangle(left, top, width, height);
#endregion
}
/// <summary>
/// Creats the player class, with custom animation set.
/// </summary>
/// <param name="animationSetList">The custom animation set to use with the player.</param>
/// <param name="defaultFrameName">The default frame to set the animation to.</param>
/// <param name="position">The position to set the player at.</param>
/// <param name="movementKeys">The list movement keys for the player.</param>
/// <param name="color">The color to mask the player with.</param>
/// <param name="myGame">The game that player runs on.</param>
public Player(List<AnimationSet> animationSetList, string defaultFrameName, Vector2 position, Keys[,] movementKeys, Color color, Game1 myGame)
: base(position, color, animationSetList)
{
this.myGame = myGame;
AnimationSets = animationSetList;
SetAnimation(defaultFrameName);
AttackDelay = 750;
JumpbackTimer = 1;
Level = 1;
StatPoints = 0;
PExp = 0;
PAgility = 3.375f;
PDefense = 2;
PStrength = 2;
MainHP = MaxHP = 50;
Mana = MaxMana = 0;
ManaRechargeTime = DefaultManaRechargeTime = 0.09f;
ManaRechargeInterval = DefaultManaRechargeInterval = 0.1f;
ManaDecreaseAmount = 0f;
#region Set Projectile Factors
ProjectileList = new List<Projectile>();
CanShoot = true;
CreateNewProjectile = true;
#endregion
#region Set Movement and Collision Factors
MovementKeys = movementKeys;
int width = (int)(CurrentAnimation.frameSize.X);
int left = (CurrentAnimation.frameSize.X - width);
int height = (int)(CurrentAnimation.frameSize.Y);
int top = CurrentAnimation.frameSize.Y - height;
inbounds = new Rectangle(left, top, width, height);
#endregion
}
/// <summary>
/// Creates the player class with the bare minimum.
/// Used for making child class for the player.
/// Projectile lists created already.
/// </summary>
/// <param name="position">The position to start the player at.</param>
/// <param name="color">The color to mask the player with.</param>
/// <param name="animationSetList">The animation set list for the player.</param>
public Player(Texture2D texture, Vector2 position, Color color)
: base(position, color, texture)
{
ProjectileList = new List<Projectile>();
}
/// <summary>
///
/// </summary>
/// <param name="animationSetList"></param>
/// <param name="position"></param>
/// <param name="color"></param>
public Player(List<AnimationSet> animationSetList, string defaultFrameName, Vector2 position, Color color)
: base(position, color, animationSetList)
{
ProjectileList = new List<Projectile>();
}
/// <summary>
/// Updates the keyboard state seprately.
/// </summary>
/// <param name="gameTime">The GameTime that the game runs off of.</param>
/// <param name="keyboardState">The game's KeyboardState.</param>
public void UpdateKeyboardState(GameTime gameTime, KeyboardState keyboardState)
{
this.KeyboardState = keyboardState;
}
/// <summary>
/// Updates the events in the player class.
/// </summary>
/// <param name="gameTime">The class GameTime that the game runs off of.</param>
/// <param name="EnemyList">The Enemy list.</param>
/// <param name="TileList">The list of Tiles.</param>
/// <param name="MapBoundries">The list of Rectangles that make up the boundries of the world.</param>
public override void Update(GameTime gameTime)
{
GetInput(gameTime);
HandleAnimations(gameTime);
HandleProjectile(gameTime);
ApplyPhysics(gameTime);
HandleHealth(gameTime);
UpdateStats(gameTime);
foreach (Projectile p in ProjectileList)
{
p.Update(gameTime);
}
if (!isDead && IsGrounded && !IsShooting)
{
if (Math.Abs(Velocity.X) - 0.02f > 0)
{
SetAnimation("WALK" + Level);
}
else
{
SetAnimation("IDLE" + Level);
}
}
if (IsShooting)
{
SetAnimation("ATK-1");
}
Movement = 0.0f;
IsJumping = false;
//isShooting = false;
}
/// <summary>
/// To draw the Player class.
/// </summary>
/// <param name="gameTime">To keep track of run time.</param>
/// <param name="spriteBatch">The spriteBatch to draw with.</param>
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
foreach (Projectile p in ProjectileList)
{
p.Draw(gameTime, spriteBatch);
}
if (Velocity.X > 0)
{
FlipSprite(Axis.NONE);
}
else if (Velocity.X < 0)
{
FlipSprite(Axis.Y);
}
base.Draw(gameTime, spriteBatch);
}
public virtual void UpdateStats(GameTime gameTime)
{
if (LvlUp == true)
{
StatPoints += 3;
LvlUp = false;
}
#region Level Table
if (PExp >= 0 && Lvl == 0)
{
Lvl = 1;
LvlUp = true;
}
if (PExp >= 1000 && Lvl == 1)
{
Lvl = 2;
LvlUp = true;
}
if (PExp >= 2000 && Lvl == 2)
{
Lvl = 3;
LvlUp = true;
}
if (PExp >= 4000 && Lvl == 3)
{
Lvl = 4;
LvlUp = true;
}
if (PExp >= 5000 && Lvl == 4)
{
Lvl = 5;
LvlUp = true;
}
if (PExp >= 6000 && Lvl == 5)
{
Lvl = 6;
LvlUp = true;
}
if (PExp >= 7000 && Lvl == 6)
{
Lvl = 7;
LvlUp = true;
}
if (PExp >= 8000 && Lvl == 7)
{
Lvl = 8;
LvlUp = true;
}
if (PExp >= 9000 && Lvl == 8)
{
Lvl = 9;
LvlUp = true;
}
if (PExp >= 10000 && Lvl == 9)
{
Lvl = 10;
LvlUp = true;
}
if (PExp >= 11000 && Lvl == 10)
{
Lvl = 11;
LvlUp = true;
}
if (PExp >= 12000 && Lvl == 11)
{
Lvl = 12;
LvlUp = true;
}
if (PExp >= 13000 && Lvl == 12)
{
Lvl = 13;
LvlUp = true;
}
if (PExp >= 14000 && Lvl == 13)
{
Lvl = 14;
LvlUp = true;
}
if (PExp >= 15000 && Lvl == 14)
{
Lvl = 15;
LvlUp = true;
}
if (PExp >= 16000 && Lvl == 15)
{
Lvl = 16;
LvlUp = true;
}
if (PExp >= 17000 && Lvl == 16)
{
Lvl = 17;
LvlUp = true;
}
if (PExp >= 18000 && Lvl == 17)
{
Lvl = 18;
LvlUp = true;
}
if (PExp >= 19000 && Lvl == 18)
{
Lvl = 19;
LvlUp = true;
}
if (PExp >= 20000 && Lvl == 19)
{
Lvl = 20;
LvlUp = true;
}
#endregion
if (KeyboardState.IsKeyDown(Keys.X) && KeyboardState.IsKeyDown(Keys.O) && KeyboardState.IsKeyDown(Keys.Multiply))
{
PExp += 1000;
}
MaxMoveSpeed *= PAgility;
Damage = PStrength;
Defense = PDefense;
MaxHP = 200 + (PDefense * 150);
GroundDragFactor = ((1.325f + (float)(PAgility * .02)) / PAgility);
AirDragFactor = ((1.325f + (float)(PAgility * .02)) / PAgility);
if (PAgility < 1.55)
{
PAgility = 1.55f;
}
}
protected virtual void HandleHealth(GameTime gameTime)
{
if (MainHP <= 0)
{
isDead = true;
}
if (isDead == true)
{
ProjectileList.RemoveRange(0, ProjectileList.Count);
}
MainHP = MathHelper.Clamp(MainHP, 0, MaxHP);
}
/// <summary>
/// Gets the keyboard input to control the player.
/// </summary>
protected virtual void GetInput(GameTime gameTime)
{
// Ignore small movements to prevent running in place.
if (Math.Abs(Movement) < 0.5f)
{
Movement = 0.0f;
}
// If any digital horizontal movement input is found, override the analog movement.-
if (KeyboardState.IsKeyDown(MovementKeys[0, 0]) || KeyboardState.IsKeyDown(MovementKeys[1, 0]))
{
Movement += -1.0f;
}
else if (KeyboardState.IsKeyDown(MovementKeys[0, 2]) || KeyboardState.IsKeyDown(MovementKeys[1, 2]))
{
Movement += 1.0f;
}
if (KeyboardState.IsKeyDown(Keys.P) && myGame.IsGameDebug)
{
MainHP += 1;
}
if (KeyboardState.IsKeyDown(Keys.L) && myGame.IsGameDebug)
{
MainHP -= 1;
}
if (KeyboardState.IsKeyDown(Keys.N) && myGame.IsGameDebug)
{
Movement = -1;
velocity = new Vector2(MoveAcceleration * (float)gameTime.ElapsedGameTime.TotalSeconds * Movement);
}
MouseState mouseState = Mouse.GetState();
if (mouseState.LeftButton == ButtonState.Pressed && myGame.IsGameDebug)
{
//if (new Rectangle(mouseState.X, mouseState.Y, 1, 1).Intersects(BoundingCollisions))
{
position = new Vector2(mouseState.X, mouseState.Y) + (myGame.gameManager.Camera.Position - (myGame.gameManager.Camera.viewportSize / 2));
}
}
Movement = MathHelper.Clamp(Movement, -1, 1);
IsShooting = KeyboardState.IsKeyDown(MovementKeys[0, 4]);
// Check if the player wants to jump.
IsJumping = KeyboardState.IsKeyDown(MovementKeys[0, 1]) || KeyboardState.IsKeyDown(MovementKeys[1, 1]);
}
/// <summary>
/// Updates the player's velocity and position based on input, gravity, etc.
/// </summary>
/// <param name="gameTime">The GameTime that the game runs off of.</param>
public virtual void ApplyPhysics(GameTime gameTime)
{
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
Vector2 previousPosition = Position;
// Base velocity is a combination of horizontal movement control and
// acceleration downward due to gravity.
velocity.X += Movement * MoveAcceleration * elapsed;
HandleEnemyCollisions(gameTime);
if (!IsGrounded)
{
velocity.Y = MathHelper.Clamp(velocity.Y + GravityAcceleration * elapsed, -MaxFallSpeed, MaxFallSpeed);
}
velocity.Y = DoJump(velocity.Y, gameTime);
// Apply pseudo-drag horizontally.
if (IsGrounded)
{
velocity.X *= GroundDragFactor;
}
else
{
velocity.X *= AirDragFactor;
SetAnimation("JUMP1");
}
if (IsInWater)
{
velocity *= WaterDragFactor;
}
// Prevent the player from running faster than his top speed.
velocity.X = MathHelper.Clamp(velocity.X, -MaxMoveSpeed, MaxMoveSpeed);
// Apply velocity.
Position += velocity * elapsed;
Position = new Vector2((float)Math.Round(Position.X), (float)Math.Round(Position.Y));
// If the player is now colliding with the level, separate them.
HandleCollisions(gameTime);
// If the collision stopped us from moving, reset the velocity to zero.
if (Position.X == previousPosition.X)
{
velocity.X = 0;
}
if (Position.Y == previousPosition.Y)
{
velocity.Y = 0;
}
}
/// <summary>
/// Calculates the Y velocity accounting for jumping and
/// animates accordingly.
/// </summary>
/// <remarks>
/// During the accent of a jump, the Y velocity is completely
/// overridden by a power curve. During the decent, gravity takes
/// over. The jump velocity is controlled by the jumpTime field
/// which measures time into the accent of the current jump.
/// </remarks>
/// <param name="velocityY">
/// The player's current velocity along the Y axis.
/// </param>
/// <returns>
/// A new Y velocity if beginning or continuing a jump.
/// Otherwise, the existing Y velocity.
/// </returns>
protected virtual float DoJump(float velocityY, GameTime gameTime)
{
// If the player wants to jump
if (IsJumping)
{
// Begin or continue a jump
if ((!WasJumping && IsGrounded) || JumpTime > 0.0f)
{
if (JumpTime == 0.0f)
{
//jumpSound.Play();
}
JumpTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
//SetAnimation("JUMP" + Level);
}
// If we are in the ascent of the jump
if (0.0f < JumpTime && JumpTime <= MaxJumpTime)
{
// Fully override the vertical velocity with a power curve that gives players more control over the top of the jump
velocityY = JumpLaunchVelocity * (1.0f - (float)Math.Pow(JumpTime / MaxJumpTime, JumpControlPower));
}
else
{
// Reached the apex of the jump
JumpTime = 0.0f;
}
}
else
{
// Continues not jumping or cancels a jump in progress
JumpTime = 0.0f;
}
WasJumping = IsJumping;
return velocityY;
}
/// <summary>
/// Handels the projectile for the player class.
/// </summary>
/// <param name="gameTime">The game time that the game runs.</param>
protected virtual void HandleProjectile(GameTime gameTime)
{
AttackDelay -= gameTime.ElapsedGameTime.Milliseconds;
if (AttackDelay == 0)
{
CanShoot = true;
}
if (IsShooting && CanShoot)
{
if (!isFlipped)
{
ProjectileList.Add(new Projectile(ProjectileTexture, new Vector2(Position.X + 25, Position.Y + 15), Vector2.Zero, Color.White, myGame));
}
else
{
ProjectileList.Add(new Projectile(ProjectileTexture, new Vector2(Position.X - 25, Position.Y + 15), Vector2.Zero, Color.White, myGame));
}
AttackDelay--;
CanShoot = false;
IsShooting = false;
}
if (AttackDelay <= 0)
{
AttackDelay = 750;
CanShoot = true;
if (ProjectileList.Count > 0)
{
ProjectileList.RemoveAt(ProjectileList.Count - 1);
}
}
}
#region [OLD]
// attackDelay -= gameTime.ElapsedGameTime.Milliseconds;
// if (attackDelay == 0)
// {
// CanShoot = true;
// }
// if (IsShooting && CanShoot)
// {
// ProjectileList.Add(new Projectile(ProjectileTexture, Position, Color.White, myGame));
// attackDelay--;
// CanShoot = false;
//
// }
// if (!CanShoot)
// {
// ManaRechargeTime -= (float)gameTime.ElapsedGameTime.TotalSeconds;
//
// if (ManaRechargeTime <= 0)
// {
// if (ProjectileList.Count > 0)
// {
// ProjectileList.RemoveAt(ProjectileList.Count - 1);
// }
//
// ManaRechargeInterval -= (float)gameTime.ElapsedGameTime.TotalSeconds;
//
// if (ManaRechargeInterval <= 0)
// {
// ManaRechargeTime = DefaultManaRechargeTime;
// ManaRechargeInterval = DefaultManaRechargeInterval;
// CanShoot = true;
// }
// }
// }
//}
#endregion
/// <summary>
/// Handles the enemy collisions for the player.
/// </summary>
/// <param name="gameTime">The game time that the game runs.</param>
protected virtual void HandleEnemyCollisions(GameTime gameTime)
{
if (myGame.gameManager.EnemyList != null)
{
foreach (Enemy e in myGame.gameManager.EnemyList)
{
if (BoundingCollisions.TouchLeftOf(e.BoundingCollisions) || BoundingCollisions.TouchTopOf(e.BoundingCollisions) || BoundingCollisions.TouchRightOf(e.BoundingCollisions) || BoundingCollisions.TouchBottomOf(e.BoundingCollisions))
{
AttackCounter -= (float)gameTime.ElapsedGameTime.TotalSeconds;
if (PositionCenter.X >= e.PositionCenter.X)
{
Movement += 1;
JumpbackTimer = 100;
MainHP -= 2;
}
else if (PositionCenter.X < e.PositionCenter.X)
{
JumpbackTimer = 100;
MainHP -= 2;
}
}
}
}
if (JumpbackTimer > 0)
{
JumpbackTimer -= gameTime.ElapsedGameTime.Milliseconds;
Movement = -1;
velocity = new Vector2(MoveAcceleration * ((float)gameTime.ElapsedGameTime.TotalSeconds + 1f) * Movement, -(MoveAcceleration * ((float)gameTime.ElapsedGameTime.TotalSeconds * 6)));
}
foreach (Enemy e in myGame.gameManager.EnemyList)
{
if (e.EnemyType == Enemy.EnemyTypes.SPITTER)
{
foreach (SlimeBullet s in e.EnemyProjectileList)
{
if (BoundingCollisions.TouchLeftOf(s.BoundingCollisions) || BoundingCollisions.TouchRightOf(s.BoundingCollisions) || BoundingCollisions.TouchBottomOf(s.BoundingCollisions) || BoundingCollisions.TouchTopOf(s.BoundingCollisions))
{
MainHP -= (e.EStrength + PDefense);
s.deleteMe = true;
}
}
}
}
if (JumpbackTimer > 0)
{
JumpbackTimer -= gameTime.ElapsedGameTime.Milliseconds;
Movement = -1;
velocity = new Vector2(MoveAcceleration * ((float)gameTime.ElapsedGameTime.TotalSeconds + 0.1f) * Movement, -(MoveAcceleration * ((float)gameTime.ElapsedGameTime.TotalSeconds * 6)));
}
}
/// <summary>
/// Detects and resolves all collisions between the player and his neighboring
/// tiles. When a collision is detected, the player is pushed away along one
/// axis to prevent overlapping. There is some special logic for the Y axis to
/// handle platforms which behave differently depending on direction of movement.
/// </summary>
protected virtual void HandleCollisions(GameTime gameTime)
{
// Reset flag to search for ground collision.
IsGrounded = false;
foreach (Tile t in myGame.gameManager.TilesList)
{
if (CheckInRadius(t.Position, 240))
{
if (BoundingCollisions.TouchTopOf(t.BoundingCollisions) && t.TileType == Tile.TileCollisions.Impassable)
{
IsGrounded = true;
position.Y = t.BoundingCollisions.Top - BoundingCollisions.Height;
DebugBlock = t.BoundingCollisions;
}
if (BoundingCollisions.TouchLeftOf(t.BoundingCollisions) && t.TileType == Tile.TileCollisions.Impassable)
{
position.X = t.BoundingCollisions.Left - BoundingCollisions.Width - 1;
DebugBlock = t.BoundingCollisions;
}
if (BoundingCollisions.TouchLeftOf(t.BoundingCollisions) && t.TileType == Tile.TileCollisions.Passable)
{
myGame.mapScreenManager.isTransitioningIn = true;
myGame.SetCurrentLevel(Game1.GameLevels.MAP);
}
if (BoundingCollisions.TouchRightOf(t.BoundingCollisions) && t.TileType == Tile.TileCollisions.Impassable)
{
position.X = t.BoundingCollisions.Right + 1;
DebugBlock = t.BoundingCollisions;
}
if (BoundingCollisions.TouchBottomOf(t.BoundingCollisions) && t.TileType == Tile.TileCollisions.Impassable)
{
IsJumping = false;
JumpTime = 0;
position.Y = t.BoundingCollisions.Bottom + 2;
DebugBlock = t.BoundingCollisions;
}
if (BoundingCollisions.TouchTopOf(t.BoundingCollisions) && t.TileType == Tile.TileCollisions.Water)
{
IsInWater = true;
}
if (IsInWater == true)
{
WaterCheckTimer -= gameTime.ElapsedGameTime.Milliseconds;
}
if (WaterCheckTimer <= 0)
{
IsInWater = false;
WaterChecksTillDeath += 1;
WaterCheckTimer = dWaterCheckTimer;
}
if (WaterChecksTillDeath >= 1)
{
WaterChecksTillDeath = 0;
MainHP -= 10;
}
}
}
for (int i = 0; i < myGame.gameManager.MapBoundries.Count; i++)
{
if (myGame.gameManager.MapBoundries[i].TouchTopOf(BoundingCollisions))
{
FellFromBottom = true;
DebugBlock = myGame.gameManager.MapBoundries[i];
position.Y = myGame.gameManager.MapBoundries[i].Bottom - BoundingCollisions.Height;
}
if (myGame.gameManager.MapBoundries[i].TouchRightOf(BoundingCollisions))
{
if (i == 1)
{
myGame.mapScreenManager.isTransitioningIn = true;
myGame.SetCurrentLevel(Game1.GameLevels.MAP);
}
position.X = myGame.gameManager.MapBoundries[i].Left - BoundingCollisions.Width - 1;
DebugBlock = myGame.gameManager.MapBoundries[i];
}
if (myGame.gameManager.MapBoundries[i].TouchLeftOf(BoundingCollisions))
{
position.X = myGame.gameManager.MapBoundries[i].Right + 1;
DebugBlock = myGame.gameManager.MapBoundries[i];
}
if (myGame.gameManager.MapBoundries[i].TouchBottomOf(BoundingCollisions))
{
IsJumping = false;
JumpTime = 0;
position.Y = myGame.gameManager.MapBoundries[i].Top - BoundingCollisions.Height;
DebugBlock = myGame.gameManager.MapBoundries[i];
}
}
}
/// <summary>
/// Creates the default animation frames for the player.
/// </summary>
/// <param name="texture">The texture to process.</param>
protected override void AddAnimations(Texture2D texture)
{
AddAnimation("IDLE1", texture, new Point(120, 240), new Point(1, 1), new Point(000, 000), 1600, false);
AddAnimation("WALK1", texture, new Point(120, 240), new Point(4, 1), new Point(120, 000), 80, true);
AddAnimation("JUMP1", texture, new Point(120, 240), new Point(1, 1), new Point(600, 240), 1600, false);
AddAnimation("FALL1", texture, new Point(35, 50), new Point(1, 1), new Point(105, 000), 1600, true);
AddAnimation("HURT1", texture, new Point(35, 50), new Point(1, 1), new Point(140, 000), 1600, true);
AddAnimation("ATK-1", texture, new Point(120, 240), new Point(4, 1), new Point(120, 240), 120, false);
AddAnimation("DIE-1", texture, new Point(35, 50), new Point(1, 1), new Point(210, 000), 1600, true);
AddAnimation("GAIN1", texture, new Point(35, 50), new Point(1, 1), new Point(245, 000), 1600, true);
AddAnimation("IDLE2", texture, new Point(35, 50), new Point(1, 1), new Point(000, 050), 1600, true);
AddAnimation("WALK2", texture, new Point(35, 50), new Point(1, 1), new Point(035, 050), 1600, true);
AddAnimation("JUMP2", texture, new Point(35, 50), new Point(1, 1), new Point(070, 050), 1600, true);
AddAnimation("FALL2", texture, new Point(35, 50), new Point(1, 1), new Point(105, 050), 1600, true);
AddAnimation("HURT2", texture, new Point(35, 50), new Point(1, 1), new Point(140, 050), 1600, true);
AddAnimation("ATK-2", texture, new Point(35, 50), new Point(1, 1), new Point(175, 050), 1600, true);
AddAnimation("DIE-2", texture, new Point(35, 50), new Point(1, 1), new Point(210, 050), 1600, true);
AddAnimation("GAIN2", texture, new Point(35, 50), new Point(1, 1), new Point(245, 050), 1600, true);
SetAnimation("IDLE1");
base.AddAnimations(texture);
}
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using BudgetAnalyser.Engine.Budget;
using BudgetAnalyser.Engine.Statement;
using BudgetAnalyser.Engine.UnitTest.TestHarness;
using Castle.Core.Internal;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace BudgetAnalyser.Engine.UnitTest.Statement
{
[TestClass]
public class BankImportUtilitiesTest
{
private Mock<IBudgetBucketRepository> BucketRepositoryMock { get; set; }
[TestMethod]
[ExpectedException(typeof(UnexpectedIndexException))]
public void FetchBudgetBucketWithNegativeOutOfRangeIndexShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchBudgetBucket(testArray, -12, BucketRepositoryMock.Object);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FetchBudgetBucketWithNullArrayShouldThrow()
{
BankImportUtilities subject = CreateSubject();
subject.FetchBudgetBucket(null, 2, BucketRepositoryMock.Object);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FetchBudgetBucketWithNullBucketRepositoryShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchBudgetBucket(testArray, 2, null);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(UnexpectedIndexException))]
public void FetchBudgetBucketWithOutOfRangeIndexShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchBudgetBucket(testArray, 12, BucketRepositoryMock.Object);
Assert.Fail();
}
[TestMethod]
public void FetchBudgetBucketWithValidParamsShouldReturnBucketObject()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
var expectedResult = new SpentMonthlyExpenseBucket("FUEL", "Fuel");
BucketRepositoryMock.Setup(m => m.GetByCode("FUEL")).Returns(expectedResult);
BudgetBucket result = subject.FetchBudgetBucket(testArray, 2, BucketRepositoryMock.Object);
BucketRepositoryMock.Verify();
Assert.AreSame(expectedResult, result);
}
[TestMethod]
[ExpectedException(typeof(InvalidDataException))]
public void FetchDateWithInvalidDateShouldReturnMinDateTime()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchDate(testArray, 3);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(UnexpectedIndexException))]
public void FetchDateWithNegativeOutOfRangeIndexShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchDate(testArray, -12);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FetchDateWithNullArrayShouldThrow()
{
BankImportUtilities subject = CreateSubject();
subject.FetchDate(null, 2);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(UnexpectedIndexException))]
public void FetchDateWithOutOfRangeIndexShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchDate(testArray, 12);
Assert.Fail();
}
[TestMethod]
public void FetchDateWithValidDateStringShouldReturnDate()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
DateTime result = subject.FetchDate(testArray, 1);
Assert.IsInstanceOfType(result, typeof(DateTime));
Assert.AreNotEqual(DateTime.MinValue, result);
}
[TestMethod]
[ExpectedException(typeof(InvalidDataException))]
public void FetchDecimalWithInvalidDecimalShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchDecimal(testArray, 2);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(UnexpectedIndexException))]
public void FetchDecimalWithNegativeOutOfRangeIndexShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchDecimal(testArray, -12);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FetchDecimalWithNullArrayShouldThrow()
{
BankImportUtilities subject = CreateSubject();
subject.FetchDecimal(null, 2);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(UnexpectedIndexException))]
public void FetchDecimalWithOutOfRangeIndexShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchDecimal(testArray, 12);
Assert.Fail();
}
[TestMethod]
public void FetchDecimalWithValidDecimalStringShouldReturnDecimal()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
decimal result = subject.FetchDecimal(testArray, 0);
Assert.IsInstanceOfType(result, typeof(decimal));
Assert.AreNotEqual(decimal.MinValue, result);
}
[TestMethod]
[ExpectedException(typeof(InvalidDataException))]
public void FetchGuidWithInvalidGuidShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchGuid(testArray, 2);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(UnexpectedIndexException))]
public void FetchGuidWithNegativeOutOfRangeIndexShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchGuid(testArray, -12);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FetchGuidWithNullArrayShouldThrow()
{
BankImportUtilities subject = CreateSubject();
subject.FetchGuid(null, 2);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(UnexpectedIndexException))]
public void FetchGuidWithOutOfRangeIndexShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchGuid(testArray, 12);
Assert.Fail();
}
[TestMethod]
public void FetchGuidWithValidGuidStringShouldReturnGuid()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
Guid result = subject.FetchGuid(testArray, 4);
Assert.IsInstanceOfType(result, typeof(Guid));
Assert.AreNotEqual(Guid.Empty, result);
}
[TestMethod]
[ExpectedException(typeof(UnexpectedIndexException))]
public void FetchStringWithNegativeOutOfRangeIndexShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchString(testArray, -12);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FetchStringWithNullArrayShouldThrow()
{
BankImportUtilities subject = CreateSubject();
subject.FetchString(null, 2);
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(UnexpectedIndexException))]
public void FetchStringWithOutOfRangeIndexShouldThrow()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
subject.FetchString(testArray, 12);
Assert.Fail();
}
[TestMethod]
public void FetchStringWithValidStringShouldReturnString()
{
BankImportUtilities subject = CreateSubject();
string[] testArray = CreateTestArray();
string result = subject.FetchString(testArray, 2);
Assert.IsInstanceOfType(result, typeof(string));
Assert.AreNotEqual(string.Empty, result);
Assert.IsNotNull(result);
}
[TestMethod]
public void FetchStringShouldRemoveQuotes()
{
var subject = CreateSubject();
var myData = new[] { "\"Test String\"","no quotes","-21.45" };
Console.WriteLine($"Input:");
myData.ForEach(x => Console.Write($"{x}, "));
var result1 = subject.FetchString(myData, 0);
Console.WriteLine();
Console.WriteLine($"{result1}");
Assert.AreEqual(-1, result1.IndexOf('"'));
}
private BankImportUtilities CreateSubject()
{
BucketRepositoryMock = new Mock<IBudgetBucketRepository>();
var subject = new BankImportUtilities(new FakeLogger());
subject.ConfigureLocale(CultureInfo.CreateSpecificCulture("en-NZ"));
return subject;
}
private string[] CreateTestArray()
{
return new[] { "123.34", "14/04/2014", "FUEL", "42/12/2088", "A94B4FE5-4F43-43A6-8CD2-8430F45FB58D" };
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.CognitiveServices.Vision.Face
{
using Microsoft.CognitiveServices;
using Microsoft.CognitiveServices.Vision;
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// FaceList operations.
/// </summary>
public partial class FaceList : IServiceOperations<FaceAPI>, IFaceList
{
/// <summary>
/// Initializes a new instance of the FaceList class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public FaceList(FaceAPI client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the FaceAPI
/// </summary>
public FaceAPI Client { get; private set; }
/// <summary>
/// Create an empty face list. Up to 64 face lists are allowed to exist in one
/// subscription.
/// </summary>
/// <param name='faceListId'>
/// Id referencing a particular face list.
/// </param>
/// <param name='name'>
/// Name of the face list, maximum length is 128.
/// </param>
/// <param name='userData'>
/// Optional user defined data for the face list. Length should not exceed
/// 16KB.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> CreateWithHttpMessagesAsync(string faceListId, string name = default(string), string userData = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (faceListId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "faceListId");
}
if (faceListId != null)
{
if (faceListId.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "faceListId", 64);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(faceListId, "^[a-z0-9-_]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "faceListId", "^[a-z0-9-_]+$");
}
}
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
if (name != null)
{
if (name.Length > 128)
{
throw new ValidationException(ValidationRules.MaxLength, "name", 128);
}
}
if (userData != null)
{
if (userData.Length > 16384)
{
throw new ValidationException(ValidationRules.MaxLength, "userData", 16384);
}
}
CreateFaceListRequest body = new CreateFaceListRequest();
if (name != null || userData != null)
{
body.Name = name;
body.UserData = userData;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("faceListId", faceListId);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "facelists/{faceListId}";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
_url = _url.Replace("{faceListId}", System.Uri.EscapeDataString(faceListId));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieve a face list's information.
/// </summary>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<GetFaceListResult>> GetWithHttpMessagesAsync(string faceListId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (faceListId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "faceListId");
}
if (faceListId != null)
{
if (faceListId.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "faceListId", 64);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(faceListId, "^[a-z0-9-_]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "faceListId", "^[a-z0-9-_]+$");
}
}
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("faceListId", faceListId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "facelists/{faceListId}";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
_url = _url.Replace("{faceListId}", System.Uri.EscapeDataString(faceListId));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<GetFaceListResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<GetFaceListResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Update information of a face list.
/// </summary>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='name'>
/// Name of the face list, maximum length is 128.
/// </param>
/// <param name='userData'>
/// Optional user defined data for the face list. Length should not exceed
/// 16KB.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> UpdateWithHttpMessagesAsync(string faceListId, string name = default(string), string userData = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (faceListId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "faceListId");
}
if (faceListId != null)
{
if (faceListId.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "faceListId", 64);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(faceListId, "^[a-z0-9-_]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "faceListId", "^[a-z0-9-_]+$");
}
}
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
if (name != null)
{
if (name.Length > 128)
{
throw new ValidationException(ValidationRules.MaxLength, "name", 128);
}
}
if (userData != null)
{
if (userData.Length > 16384)
{
throw new ValidationException(ValidationRules.MaxLength, "userData", 16384);
}
}
CreateFaceListRequest body = new CreateFaceListRequest();
if (name != null || userData != null)
{
body.Name = name;
body.UserData = userData;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("faceListId", faceListId);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "facelists/{faceListId}";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
_url = _url.Replace("{faceListId}", System.Uri.EscapeDataString(faceListId));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete an existing face list according to faceListId. Persisted face images
/// in the face list will also be deleted.
/// </summary>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string faceListId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (faceListId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "faceListId");
}
if (faceListId != null)
{
if (faceListId.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "faceListId", 64);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(faceListId, "^[a-z0-9-_]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "faceListId", "^[a-z0-9-_]+$");
}
}
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("faceListId", faceListId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "facelists/{faceListId}";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
_url = _url.Replace("{faceListId}", System.Uri.EscapeDataString(faceListId));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieve information about all existing face lists. Only faceListId, name
/// and userData will be returned.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<IList<GetFaceListResult>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "facelists";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IList<GetFaceListResult>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<GetFaceListResult>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete an existing face from a face list (given by a persisitedFaceId and a
/// faceListId). Persisted image related to the face will also be deleted.
/// </summary>
/// <param name='faceListId'>
/// faceListId of an existing face list.
/// </param>
/// <param name='persistedFaceId'>
/// persistedFaceId of an existing face.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> DeleteFaceWithHttpMessagesAsync(string faceListId, string persistedFaceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (faceListId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "faceListId");
}
if (faceListId != null)
{
if (faceListId.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "faceListId", 64);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(faceListId, "^[a-z0-9-_]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "faceListId", "^[a-z0-9-_]+$");
}
}
if (persistedFaceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "persistedFaceId");
}
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("faceListId", faceListId);
tracingParameters.Add("persistedFaceId", persistedFaceId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "DeleteFace", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "facelists/{faceListId}/persistedFaces/{persistedFaceId}";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
_url = _url.Replace("{faceListId}", System.Uri.EscapeDataString(faceListId));
_url = _url.Replace("{persistedFaceId}", System.Uri.EscapeDataString(persistedFaceId));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Add a face to a face list. The input face is specified as an image with a
/// targetFace rectangle. It returns a persistedFaceId representing the added
/// face, and persistedFaceId will not expire.
/// </summary>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='userData'>
/// User-specified data about the face list for any purpose. The maximum
/// length is 1KB.
/// </param>
/// <param name='targetFace'>
/// A face rectangle to specify the target face to be added into the face list,
/// in the format of "targetFace=left,top,width,height". E.g.
/// "targetFace=10,10,100,100". If there is more than one face in the image,
/// targetFace is required to specify which face to add. No targetFace means
/// there is only one face detected in the entire image.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> AddFaceWithHttpMessagesAsync(string faceListId, string userData = default(string), string targetFace = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (faceListId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "faceListId");
}
if (faceListId != null)
{
if (faceListId.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "faceListId", 64);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(faceListId, "^[a-z0-9-_]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "faceListId", "^[a-z0-9-_]+$");
}
}
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("faceListId", faceListId);
tracingParameters.Add("userData", userData);
tracingParameters.Add("targetFace", targetFace);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "AddFace", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "facelists/{faceListId}/persistedFaces";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
_url = _url.Replace("{faceListId}", System.Uri.EscapeDataString(faceListId));
List<string> _queryParameters = new List<string>();
if (userData != null)
{
_queryParameters.Add(string.Format("userData={0}", System.Uri.EscapeDataString(userData)));
}
if (targetFace != null)
{
_queryParameters.Add(string.Format("targetFace={0}", System.Uri.EscapeDataString(targetFace)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Add a face to a face list. The input face is specified as an image with a
/// targetFace rectangle. It returns a persistedFaceId representing the added
/// face, and persistedFaceId will not expire.
/// </summary>
/// <param name='faceListId'>
/// Id referencing a Face List.
/// </param>
/// <param name='userData'>
/// User-specified data about the face list for any purpose. The maximum
/// length is 1KB.
/// </param>
/// <param name='targetFace'>
/// A face rectangle to specify the target face to be added into the face list,
/// in the format of "targetFace=left,top,width,height". E.g.
/// "targetFace=10,10,100,100". If there is more than one face in the image,
/// targetFace is required to specify which face to add. No targetFace means
/// there is only one face detected in the entire image.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> AddFaceFromStreamWithHttpMessagesAsync(string faceListId, string userData = default(string), string targetFace = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (faceListId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "faceListId");
}
if (faceListId != null)
{
if (faceListId.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "faceListId", 64);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(faceListId, "^[a-z0-9-_]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "faceListId", "^[a-z0-9-_]+$");
}
}
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("faceListId", faceListId);
tracingParameters.Add("userData", userData);
tracingParameters.Add("targetFace", targetFace);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "AddFaceFromStream", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "facelists/{faceListId}/persistedFaces";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
_url = _url.Replace("{faceListId}", System.Uri.EscapeDataString(faceListId));
List<string> _queryParameters = new List<string>();
if (userData != null)
{
_queryParameters.Add(string.Format("userData={0}", System.Uri.EscapeDataString(userData)));
}
if (targetFace != null)
{
_queryParameters.Add(string.Format("targetFace={0}", System.Uri.EscapeDataString(targetFace)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using FarseerPhysics.Collision;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using Duality;
namespace FarseerPhysics.Dynamics.Contacts
{
/// <summary>
/// A contact edge is used to connect bodies and contacts together
/// in a contact graph where each body is a node and each contact
/// is an edge. A contact edge belongs to a doubly linked list
/// maintained in each attached body. Each contact has two contact
/// nodes, one for each attached body.
/// </summary>
public sealed class ContactEdge
{
/// <summary>
/// The contact
/// </summary>
public Contact Contact;
/// <summary>
/// The next contact edge in the body's contact list
/// </summary>
public ContactEdge Next;
/// <summary>
/// Provides quick access to the other body attached.
/// </summary>
public Body Other;
/// <summary>
/// The previous contact edge in the body's contact list
/// </summary>
public ContactEdge Prev;
}
[Flags]
public enum ContactFlags
{
None = 0,
/// <summary>
/// Used when crawling contact graph when forming islands.
/// </summary>
Island = 0x0001,
/// <summary>
/// Set when the shapes are touching.
/// </summary>
Touching = 0x0002,
/// <summary>
/// This contact can be disabled (by user)
/// </summary>
Enabled = 0x0004,
/// <summary>
/// This contact needs filtering because a fixture filter was changed.
/// </summary>
Filter = 0x0008,
/// <summary>
/// This bullet contact had a TOI event
/// </summary>
BulletHit = 0x0010,
/// <summary>
/// This contact has a valid TOI i the field TOI
/// </summary>
TOI = 0x0020
}
/// <summary>
/// The class manages contact between two shapes. A contact exists for each overlapping
/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist
/// that has no contact points.
/// </summary>
public class Contact
{
private static EdgeShape _edge = new EdgeShape();
private static ContactType[,] _registers = new[,]
{
{
ContactType.Circle,
ContactType.EdgeAndCircle,
ContactType.PolygonAndCircle,
ContactType.ChainAndCircle,
},
{
ContactType.EdgeAndCircle,
ContactType.NotSupported,
// 1,1 is invalid (no ContactType.Edge)
ContactType.EdgeAndPolygon,
ContactType.NotSupported,
// 1,3 is invalid (no ContactType.EdgeAndChain)
},
{
ContactType.PolygonAndCircle,
ContactType.EdgeAndPolygon,
ContactType.Polygon,
ContactType.ChainAndPolygon,
},
{
ContactType.ChainAndCircle,
ContactType.NotSupported,
// 3,1 is invalid (no ContactType.EdgeAndChain)
ContactType.ChainAndPolygon,
ContactType.NotSupported,
// 3,3 is invalid (no ContactType.Chain)
},
};
public Fixture FixtureA;
public Fixture FixtureB;
internal ContactFlags Flags;
public Manifold Manifold;
// Nodes for connecting bodies.
internal ContactEdge NodeA = new ContactEdge();
internal ContactEdge NodeB = new ContactEdge();
public float TOI;
internal int TOICount;
private ContactType _type;
private Contact(Fixture fA, int indexA, Fixture fB, int indexB)
{
Reset(fA, indexA, fB, indexB);
}
/// Enable/disable this contact. This can be used inside the pre-solve
/// contact listener. The contact is only disabled for the current
/// time step (or sub-step in continuous collisions).
public bool Enabled
{
set
{
if (value)
{
this.Flags |= ContactFlags.Enabled;
}
else
{
this.Flags &= ~ContactFlags.Enabled;
}
}
get { return (this.Flags & ContactFlags.Enabled) == ContactFlags.Enabled; }
}
/// <summary>
/// Get the child primitive index for fixture A.
/// </summary>
/// <value>The child index A.</value>
public int ChildIndexA { get; internal set; }
/// <summary>
/// Get the child primitive index for fixture B.
/// </summary>
/// <value>The child index B.</value>
public int ChildIndexB { get; internal set; }
/// <summary>
/// Get the contact manifold. Do not modify the manifold unless you understand the
/// internals of Box2D.
/// </summary>
/// <param name="manifold">The manifold.</param>
public void GetManifold(out Manifold manifold)
{
manifold = this.Manifold;
}
/// <summary>
/// Gets the world manifold.
/// </summary>
public void GetWorldManifold(out Vector2 normal, out FixedArray2<Vector2> points)
{
Body bodyA = this.FixtureA.Body;
Body bodyB = this.FixtureB.Body;
Shape shapeA = this.FixtureA.Shape;
Shape shapeB = this.FixtureB.Shape;
Collision.Collision.GetWorldManifold(ref this.Manifold, ref bodyA.Xf, shapeA.Radius, ref bodyB.Xf, shapeB.Radius,
out normal, out points);
}
/// <summary>
/// Determines whether this contact is touching.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is touching; otherwise, <c>false</c>.
/// </returns>
public bool IsTouching()
{
return (this.Flags & ContactFlags.Touching) == ContactFlags.Touching;
}
/// <summary>
/// Flag this contact for filtering. Filtering will occur the next time step.
/// </summary>
public void FlagForFiltering()
{
this.Flags |= ContactFlags.Filter;
}
private void Reset(Fixture fA, int indexA, Fixture fB, int indexB)
{
this.Flags = ContactFlags.Enabled;
this.FixtureA = fA;
this.FixtureB = fB;
this.ChildIndexA = indexA;
this.ChildIndexB = indexB;
this.Manifold.PointCount = 0;
this.NodeA.Contact = null;
this.NodeA.Prev = null;
this.NodeA.Next = null;
this.NodeA.Other = null;
this.NodeB.Contact = null;
this.NodeB.Prev = null;
this.NodeB.Next = null;
this.NodeB.Other = null;
this.TOICount = 0;
}
/// <summary>
/// Update the contact manifold and touching status.
/// Note: do not assume the fixture AABBs are overlapping or are valid.
/// </summary>
/// <param name="contactManager">The contact manager.</param>
internal void Update(ContactManager contactManager)
{
Manifold oldManifold = this.Manifold;
// Re-enable this contact.
this.Flags |= ContactFlags.Enabled;
bool touching;
bool wasTouching = (this.Flags & ContactFlags.Touching) == ContactFlags.Touching;
bool sensor = this.FixtureA.IsSensor || this.FixtureB.IsSensor;
Body bodyA = this.FixtureA.Body;
Body bodyB = this.FixtureB.Body;
// Is this contact a sensor?
if (sensor)
{
Shape shapeA = this.FixtureA.Shape;
Shape shapeB = this.FixtureB.Shape;
touching = AABB.TestOverlap(shapeA, this.ChildIndexA, shapeB, this.ChildIndexB, ref bodyA.Xf, ref bodyB.Xf);
// Sensors don't generate manifolds.
this.Manifold.PointCount = 0;
}
else
{
Evaluate(ref this.Manifold, ref bodyA.Xf, ref bodyB.Xf);
touching = this.Manifold.PointCount > 0;
// Match old contact ids to new contact ids and copy the
// stored impulses to warm start the solver.
for (int i = 0; i < this.Manifold.PointCount; ++i)
{
ManifoldPoint mp2 = this.Manifold.Points[i];
mp2.NormalImpulse = 0.0f;
mp2.TangentImpulse = 0.0f;
ContactID id2 = mp2.Id;
bool found = false;
for (int j = 0; j < oldManifold.PointCount; ++j)
{
ManifoldPoint mp1 = oldManifold.Points[j];
if (mp1.Id.Key == id2.Key)
{
mp2.NormalImpulse = mp1.NormalImpulse;
mp2.TangentImpulse = mp1.TangentImpulse;
found = true;
break;
}
}
if (found == false)
{
mp2.NormalImpulse = 0.0f;
mp2.TangentImpulse = 0.0f;
}
this.Manifold.Points[i] = mp2;
}
if (touching != wasTouching)
{
bodyA.Awake = true;
bodyB.Awake = true;
}
}
if (touching)
{
this.Flags |= ContactFlags.Touching;
}
else
{
this.Flags &= ~ContactFlags.Touching;
}
if (wasTouching == false && touching)
{
//Report the collision to both participants:
this.Enabled = this.Enabled && this.FixtureA.Body.OnCollision(this.FixtureA, this.FixtureB, this);
//Reverse the order of the reported fixtures. The first fixture is always the one that the
//user subscribed to.
this.Enabled = this.Enabled && this.FixtureB.Body.OnCollision(this.FixtureB, this.FixtureA, this);
//BeginContact can also return false and disable the contact
if (contactManager.BeginContact != null)
this.Enabled = contactManager.BeginContact(this);
//if the user disabled the contact (needed to exclude it in TOI solver), we also need to mark
//it as not touching.
if (this.Enabled == false)
this.Flags &= ~ContactFlags.Touching;
}
if (wasTouching && touching == false)
{
//Report the separation to both participants:
if (this.FixtureA != null) this.FixtureA.Body.OnSeparation(this.FixtureA, this.FixtureB);
//Reverse the order of the reported fixtures. The first fixture is always the one that the
//user subscribed to.
if (this.FixtureB != null) this.FixtureB.Body.OnSeparation(this.FixtureB, this.FixtureA);
if (contactManager.EndContact != null)
contactManager.EndContact(this);
}
if (sensor)
return;
if (contactManager.PreSolve != null)
contactManager.PreSolve(this, ref oldManifold);
}
/// <summary>
/// Evaluate this contact with your own manifold and transforms.
/// </summary>
/// <param name="manifold">The manifold.</param>
/// <param name="transformA">The first transform.</param>
/// <param name="transformB">The second transform.</param>
private void Evaluate(ref Manifold manifold, ref Transform transformA, ref Transform transformB)
{
switch (this._type)
{
case ContactType.Polygon:
Collision.Collision.CollidePolygons(ref manifold,
(PolygonShape)this.FixtureA.Shape, ref transformA,
(PolygonShape)this.FixtureB.Shape, ref transformB);
break;
case ContactType.PolygonAndCircle:
Collision.Collision.CollidePolygonAndCircle(ref manifold,
(PolygonShape)this.FixtureA.Shape, ref transformA,
(CircleShape)this.FixtureB.Shape, ref transformB);
break;
case ContactType.EdgeAndCircle:
Collision.Collision.CollideEdgeAndCircle(ref manifold,
(EdgeShape)this.FixtureA.Shape, ref transformA,
(CircleShape)this.FixtureB.Shape, ref transformB);
break;
case ContactType.EdgeAndPolygon:
Collision.Collision.CollideEdgeAndPolygon(ref manifold,
(EdgeShape)this.FixtureA.Shape, ref transformA,
(PolygonShape)this.FixtureB.Shape, ref transformB);
break;
case ContactType.ChainAndCircle:
ChainShape chain = (ChainShape)this.FixtureA.Shape;
chain.GetChildEdge(ref _edge, this.ChildIndexA);
Collision.Collision.CollideEdgeAndCircle(ref manifold, _edge, ref transformA,
(CircleShape)this.FixtureB.Shape, ref transformB);
break;
case ContactType.ChainAndPolygon:
ChainShape chain2 = (ChainShape)this.FixtureA.Shape;
chain2.GetChildEdge(ref _edge, this.ChildIndexA);
Collision.Collision.CollideEdgeAndPolygon(ref manifold, _edge, ref transformA,
(PolygonShape)this.FixtureB.Shape, ref transformB);
break;
case ContactType.Circle:
Collision.Collision.CollideCircles(ref manifold,
(CircleShape)this.FixtureA.Shape, ref transformA,
(CircleShape)this.FixtureB.Shape, ref transformB);
break;
}
}
internal static Contact Create(Fixture fixtureA, int indexA, Fixture fixtureB, int indexB)
{
ShapeType type1 = fixtureA.ShapeType;
ShapeType type2 = fixtureB.ShapeType;
Debug.Assert(ShapeType.Unknown < type1 && type1 < ShapeType.TypeCount);
Debug.Assert(ShapeType.Unknown < type2 && type2 < ShapeType.TypeCount);
Contact c;
Queue<Contact> pool = fixtureA.Body.World.ContactPool;
if (pool.Count > 0)
{
c = pool.Dequeue();
if ((type1 >= type2 || (type1 == ShapeType.Edge && type2 == ShapeType.Polygon))
&&
!(type2 == ShapeType.Edge && type1 == ShapeType.Polygon))
{
c.Reset(fixtureA, indexA, fixtureB, indexB);
}
else
{
c.Reset(fixtureB, indexB, fixtureA, indexA);
}
}
else
{
// Edge+Polygon is non-symetrical due to the way Erin handles collision type registration.
if ((type1 >= type2 || (type1 == ShapeType.Edge && type2 == ShapeType.Polygon))
&&
!(type2 == ShapeType.Edge && type1 == ShapeType.Polygon))
{
c = new Contact(fixtureA, indexA, fixtureB, indexB);
}
else
{
c = new Contact(fixtureB, indexB, fixtureA, indexA);
}
}
c._type = _registers[(int)type1, (int)type2];
return c;
}
internal void Destroy()
{
this.FixtureA.Body.World.ContactPool.Enqueue(this);
Reset(null, 0, null, 0);
}
#region Nested type: ContactType
private enum ContactType
{
NotSupported,
Polygon,
PolygonAndCircle,
Circle,
EdgeAndPolygon,
EdgeAndCircle,
ChainAndPolygon,
ChainAndCircle,
}
#endregion
}
}
| |
// ==========================================================
// FreeImage 3 .NET wrapper
// Original FreeImage 3 functions and .NET compatible derived functions
//
// Design and implementation by
// - Jean-Philippe Goerke ([email protected])
// - Carsten Klein ([email protected])
//
// Contributors:
// - David Boland ([email protected])
//
// Main reference : MSDN Knowlede Base
//
// This file is part of FreeImage 3
//
// COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
// THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
// OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
// CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
// THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
// SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
// PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// Use at your own risk!
// ==========================================================
// ==========================================================
// CVS
// $Revision: 1.7 $
// $Date: 2009/02/20 07:41:08 $
// $Id: fi_handle.cs,v 1.7 2009/02/20 07:41:08 cklein05 Exp $
// ==========================================================
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace FreeImageAPI.IO
{
/// <summary>
/// Wrapper for a custom handle.
/// </summary>
/// <remarks>
/// The <b>fi_handle</b> of FreeImage in C++ is a simple pointer, but in .NET
/// it's not that simple. This wrapper uses fi_handle in two different ways.
///
/// We implement a new plugin and FreeImage gives us a handle (pointer) that
/// we can simply pass through to the given functions in a 'FreeImageIO'
/// structure.
/// But when we want to use LoadFromhandle or SaveToHandle we need
/// a fi_handle (that we receive again in our own functions).
/// This handle is for example a stream (see LoadFromStream / SaveToStream)
/// that we want to work with. To know which stream a read/write is meant for
/// we could use a hash value that the wrapper itself handles or we can
/// go the unmanaged way of using a handle.
/// Therefor we use a <see cref="GCHandle"/> to receive a unique pointer that we can
/// convert back into a .NET object.
/// When the <b>fi_handle</b> instance is no longer needed the instance must be disposed
/// by the creater manually! It is recommended to use the <c>using</c> statement to
/// be sure the instance is always disposed:
///
/// <code>
/// using (fi_handle handle = new fi_handle(object))
/// {
/// callSomeFunctions(handle);
/// }
/// </code>
///
/// What does that mean?
/// If we get a <b>fi_handle</b> from unmanaged code we get a pointer to unmanaged
/// memory that we do not have to care about, and just pass ist back to FreeImage.
/// If we have to create a handle our own we use the standard constructur
/// that fills the <see cref="IntPtr"/> with an pointer that represents the given object.
/// With calling <see cref="GetObject"/> the <see cref="IntPtr"/> is used to retrieve the original
/// object we passed through the constructor.
///
/// This way we can implement a <b>fi_handle</b> that works with managed an unmanaged
/// code.
/// </remarks>
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct fi_handle : IComparable, IComparable<fi_handle>, IEquatable<fi_handle>, IDisposable
{
/// <summary>
/// The handle to wrap.
/// </summary>
public IntPtr handle;
/// <summary>
/// Initializes a new instance wrapping a managed object.
/// </summary>
/// <param name="obj">The object to wrap.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="obj"/> is null.</exception>
public fi_handle(object obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
GCHandle gch = GCHandle.Alloc(obj, GCHandleType.Normal);
handle = GCHandle.ToIntPtr(gch);
}
/// <summary>
/// Tests whether two specified <see cref="fi_handle"/> structures are equivalent.
/// </summary>
/// <param name="left">The <see cref="fi_handle"/> that is to the left of the equality operator.</param>
/// <param name="right">The <see cref="fi_handle"/> that is to the right of the equality operator.</param>
/// <returns>
/// <b>true</b> if the two <see cref="fi_handle"/> structures are equal; otherwise, <b>false</b>.
/// </returns>
public static bool operator ==(fi_handle left, fi_handle right)
{
return (left.handle == right.handle);
}
/// <summary>
/// Tests whether two specified <see cref="fi_handle"/> structures are different.
/// </summary>
/// <param name="left">The <see cref="fi_handle"/> that is to the left of the inequality operator.</param>
/// <param name="right">The <see cref="fi_handle"/> that is to the right of the inequality operator.</param>
/// <returns>
/// <b>true</b> if the two <see cref="fi_handle"/> structures are different; otherwise, <b>false</b>.
/// </returns>
public static bool operator !=(fi_handle left, fi_handle right)
{
return (left.handle != right.handle);
}
/// <summary>
/// Gets whether the pointer is a null pointer.
/// </summary>
public bool IsNull
{
get
{
return (handle == IntPtr.Zero);
}
}
/// <summary>
/// Returns the object assigned to the handle in case this instance
/// was created by managed code.
/// </summary>
/// <returns><see cref="Object"/> assigned to this handle or null on failure.</returns>
internal object GetObject()
{
object result = null;
if (handle != IntPtr.Zero)
{
try
{
result = GCHandle.FromIntPtr(handle).Target;
}
catch
{
}
}
return result;
}
/// <summary>
/// Converts the numeric value of the <see cref="fi_handle"/> object
/// to its equivalent string representation.
/// </summary>
/// <returns>The string representation of the value of this instance.</returns>
public override string ToString()
{
return handle.ToString();
}
/// <summary>
/// Returns a hash code for this <see cref="fi_handle"/> structure.
/// </summary>
/// <returns>An integer value that specifies the hash code for this <see cref="fi_handle"/>.</returns>
public override int GetHashCode()
{
return handle.GetHashCode();
}
/// <summary>
/// Tests whether the specified object is a <see cref="fi_handle"/> structure
/// and is equivalent to this <see cref="fi_handle"/> structure.
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><b>true</b> if <paramref name="obj"/> is a <see cref="fi_handle"/> structure
/// equivalent to this <see cref="fi_handle"/> structure; otherwise, <b>false</b>.</returns>
public override bool Equals(object obj)
{
return ((obj is fi_handle) && (this == ((fi_handle)obj)));
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>True if the current object is equal to the other parameter; otherwise, <b>false</b>.</returns>
public bool Equals(fi_handle other)
{
return (this == other);
}
/// <summary>
/// Compares this instance with a specified <see cref="Object"/>.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>A 32-bit signed integer indicating the lexical relationship between the two comparands.</returns>
/// <exception cref="ArgumentException"><paramref name="obj"/> is not a <see cref="fi_handle"/>.</exception>
public int CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
if (!(obj is fi_handle))
{
throw new ArgumentException("obj");
}
return CompareTo((fi_handle)obj);
}
/// <summary>
/// Compares this instance with a specified <see cref="fi_handle"/> object.
/// </summary>
/// <param name="other">A <see cref="fi_handle"/> to compare.</param>
/// <returns>A signed number indicating the relative values of this instance
/// and <paramref name="other"/>.</returns>
public int CompareTo(fi_handle other)
{
return handle.ToInt64().CompareTo(other.handle.ToInt64());
}
/// <summary>
/// Releases all resources used by the instance.
/// </summary>
public void Dispose()
{
if (this.handle != IntPtr.Zero)
{
try
{
GCHandle.FromIntPtr(handle).Free();
}
catch
{
}
finally
{
this.handle = IntPtr.Zero;
}
}
}
}
}
| |
#if UNITY_4_2 || UNITY_4_1 || UNITY_4_0 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3
#define UNITY_LE_4_3
#endif
using UnityEditor;
using UnityEngine;
namespace Pathfinding
{
public class GraphEditor : GraphEditorBase {
public AstarPathEditor editor;
public virtual void OnEnable () {
}
public virtual void OnDisable () {
}
public virtual void OnDestroy () {
}
public Object ObjectField (string label, Object obj, System.Type objType, bool allowSceneObjects) {
return ObjectField (new GUIContent (label),obj,objType,allowSceneObjects);
}
public Object ObjectField (GUIContent label, Object obj, System.Type objType, bool allowSceneObjects) {
#if UNITY_3_3
allowSceneObjects = true;
#endif
#if UNITY_3_3
obj = EditorGUILayout.ObjectField (label, obj, objType);
#else
obj = EditorGUILayout.ObjectField (label, obj, objType, allowSceneObjects);
#endif
if (obj != null) {
if (allowSceneObjects && !EditorUtility.IsPersistent (obj)) {
//Object is in the scene
Component com = obj as Component;
GameObject go = obj as GameObject;
if (com != null) {
go = com.gameObject;
}
if (go != null) {
UnityReferenceHelper urh = go.GetComponent<UnityReferenceHelper> ();
if (urh == null) {
if (FixLabel ("Object's GameObject must have a UnityReferenceHelper component attached")) {
go.AddComponent<UnityReferenceHelper>();
}
}
}
} else if (EditorUtility.IsPersistent (obj)) {
string path = AssetDatabase.GetAssetPath (obj);
System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"Resources[/|\\][^/]*$");
if (!rg.IsMatch(path)) {
if (FixLabel ("Object must be in the 'Resources' folder, top level")) {
if (!System.IO.Directory.Exists (Application.dataPath+"/Resources")) {
System.IO.Directory.CreateDirectory (Application.dataPath+"/Resources");
AssetDatabase.Refresh ();
}
string ext = System.IO.Path.GetExtension(path);
string error = AssetDatabase.MoveAsset (path,"Assets/Resources/"+obj.name+ext);
if (error == "") {
//Debug.Log ("Successful move");
path = AssetDatabase.GetAssetPath (obj);
} else {
Debug.LogError ("Couldn't move asset - "+error);
}
}
}
if (!AssetDatabase.IsMainAsset (obj) && obj.name != AssetDatabase.LoadMainAssetAtPath (path).name) {
if (FixLabel ("Due to technical reasons, the main asset must\nhave the same name as the referenced asset")) {
string error = AssetDatabase.RenameAsset (path,obj.name);
if (error == "") {
//Debug.Log ("Successful");
} else {
Debug.LogError ("Couldn't rename asset - "+error);
}
}
}
}
}
return obj;
}
/** Draws common graph settings */
public void OnBaseInspectorGUI (NavGraph target) {
int penalty = EditorGUILayout.IntField (new GUIContent ("Initial Penalty","Initial Penalty for nodes in this graph. Set during Scan."),(int)target.initialPenalty);
if (penalty < 0) penalty = 0;
target.initialPenalty = (uint)penalty;
}
/** Override to implement graph inspectors */
public virtual void OnInspectorGUI (NavGraph target) {
}
/** Override to implement scene GUI drawing for the graph */
public virtual void OnSceneGUI (NavGraph target) {
}
/** Override to implement scene Gizmos drawing for the graph editor */
public virtual void OnDrawGizmos () {
}
/** Draws a thin separator line */
public void Separator () {
GUIStyle separator = AstarPathEditor.astarSkin.FindStyle ("PixelBox3Separator");
if (separator == null) {
separator = new GUIStyle ();
}
Rect r = GUILayoutUtility.GetRect (new GUIContent (),separator);
if (Event.current.type == EventType.Repaint) {
separator.Draw (r,false,false,false,false);
}
}
/** Draws a small help box with a 'Fix' button to the right. \returns Boolean - Returns true if the button was clicked */
public bool FixLabel (string label, string buttonLabel = "Fix", int buttonWidth = 40) {
bool returnValue = false;
GUILayout.BeginHorizontal ();
GUILayout.Space (14*EditorGUI.indentLevel);
GUILayout.BeginHorizontal (AstarPathEditor.helpBox);
GUILayout.Label (label, EditorStyles.miniLabel,GUILayout.ExpandWidth (true));
if (GUILayout.Button (buttonLabel,EditorStyles.miniButton,GUILayout.Width (buttonWidth))) {
returnValue = true;
}
GUILayout.EndHorizontal ();
GUILayout.EndHorizontal ();
return returnValue;
}
/** Draws a small help box. Works with EditorGUI.indentLevel */
public void HelpBox (string label) {
GUILayout.BeginHorizontal ();
GUILayout.Space (14*EditorGUI.indentLevel);
GUILayout.Label (label, AstarPathEditor.helpBox);
GUILayout.EndHorizontal ();
}
/** Draws a toggle with a bold label to the right. Does not enable or disable GUI */
public bool ToggleGroup (string label, bool value) {
return ToggleGroup (new GUIContent (label),value);
}
/** Draws a toggle with a bold label to the right. Does not enable or disable GUI */
public bool ToggleGroup (GUIContent label, bool value) {
GUILayout.BeginHorizontal ();
GUILayout.Space (13*EditorGUI.indentLevel);
value = GUILayout.Toggle (value,"",GUILayout.Width (10));
GUIStyle boxHeader = AstarPathEditor.astarSkin.FindStyle ("CollisionHeader");
if (GUILayout.Button (label,boxHeader, GUILayout.Width (100))) {
value = !value;
}
GUILayout.EndHorizontal ();
return value;
}
/** Draws the inspector for a \link Pathfinding.GraphCollision GraphCollision class \endlink */
public void DrawCollisionEditor (GraphCollision collision) {
if (collision == null) {
collision = new GraphCollision ();
}
/*GUILayout.Space (5);
Rect r = EditorGUILayout.BeginVertical (AstarPathEditor.graphBoxStyle);
GUI.Box (r,"",AstarPathEditor.graphBoxStyle);
GUILayout.Space (2);*/
Separator ();
collision.use2D = EditorGUILayout.Toggle (new GUIContent ("Use 2D Physics", "Use the Physics2D API for collision checking"), collision.use2D );
#if UNITY_LE_4_3
if ( collision.use2D ) EditorGUILayout.HelpBox ("2D Physics is only supported from Unity 4.3 and up", MessageType.Error);
#endif
/*GUILayout.BeginHorizontal ();
GUIStyle boxHeader = AstarPathEditor.astarSkin.FindStyle ("CollisionHeader");
GUILayout.Label ("Collision testing",boxHeader);
collision.collisionCheck = GUILayout.Toggle (collision.collisionCheck,"");
bool preEnabledRoot = GUI.enabled;
GUI.enabled = collision.collisionCheck;
GUILayout.EndHorizontal ();*/
collision.collisionCheck = ToggleGroup ("Collision testing",collision.collisionCheck);
bool preEnabledRoot = GUI.enabled;
GUI.enabled = collision.collisionCheck;
//GUILayout.BeginHorizontal ();
collision.type = (ColliderType)EditorGUILayout.EnumPopup("Collider type",collision.type);
//new string[3] {"Sphere","Capsule","Ray"}
bool preEnabled = GUI.enabled;
if (collision.type != ColliderType.Capsule && collision.type != ColliderType.Sphere) {
GUI.enabled = false;
}
collision.diameter = EditorGUILayout.FloatField (new GUIContent ("Diameter","Diameter of the capsule or sphere. 1 equals one node width"),collision.diameter);
GUI.enabled = preEnabled;
if (collision.type != ColliderType.Capsule && collision.type != ColliderType.Ray) {
GUI.enabled = false;
}
collision.height = EditorGUILayout.FloatField (new GUIContent ("Height/Length","Height of cylinder or length of ray in world units"),collision.height);
GUI.enabled = preEnabled;
collision.collisionOffset = EditorGUILayout.FloatField (new GUIContent("Offset","Offset upwards from the node. Can be used so that obstacles can be used as ground and at the same time as obstacles for lower positioned nodes"),collision.collisionOffset);
//collision.mask = 1 << EditorGUILayout.LayerField ("Mask",Mathf.Clamp ((int)Mathf.Log (collision.mask,2),0,31));
collision.mask = EditorGUILayoutx.LayerMaskField ("Mask",collision.mask);
GUILayout.Space (2);
GUI.enabled = preEnabledRoot;
if ( collision.use2D ) {
GUI.enabled = false;
}
collision.heightCheck = ToggleGroup ("Height testing",collision.heightCheck);
GUI.enabled = collision.heightCheck && GUI.enabled;
/*GUILayout.BeginHorizontal ();
GUILayout.Label ("Height testing",boxHeader);
collision.heightCheck = GUILayout.Toggle (collision.heightCheck,"");
GUI.enabled = collision.heightCheck;
GUILayout.EndHorizontal ();*/
collision.fromHeight = EditorGUILayout.FloatField (new GUIContent ("Ray length","The height from which to check for ground"),collision.fromHeight);
collision.heightMask = EditorGUILayoutx.LayerMaskField ("Mask",collision.heightMask);
//collision.heightMask = 1 << EditorGUILayout.LayerField ("Mask",Mathf.Clamp ((int)Mathf.Log (collision.heightMask,2),0,31));
collision.thickRaycast = EditorGUILayout.Toggle (new GUIContent ("Thick Raycast", "Use a thick line instead of a thin line"),collision.thickRaycast);
editor.GUILayoutx.BeginFadeArea (collision.thickRaycast,"thickRaycastDiameter");
if (editor.GUILayoutx.DrawID ("thickRaycastDiameter")) {
EditorGUI.indentLevel++;
collision.thickRaycastDiameter = EditorGUILayout.FloatField (new GUIContent ("Diameter","Diameter of the thick raycast"),collision.thickRaycastDiameter);
EditorGUI.indentLevel--;
}
editor.GUILayoutx.EndFadeArea ();
collision.unwalkableWhenNoGround = EditorGUILayout.Toggle (new GUIContent ("Unwalkable when no ground","Make nodes unwalkable when no ground was found with the height raycast. If height raycast is turned off, this doesn't affect anything"), collision.unwalkableWhenNoGround);
GUI.enabled = preEnabledRoot;
//GUILayout.Space (2);
//EditorGUILayout.EndVertical ();
//GUILayout.Space (5);
}
/** Draws a wire cube using handles */
public static void DrawWireCube (Vector3 center, Vector3 size) {
size *= 0.5F;
Vector3 dx = new Vector3 (size.x,0,0);
Vector3 dy = new Vector3 (0,size.y,0);
Vector3 dz = new Vector3 (0,0,size.z);
Vector3 p1 = center-dy-dz-dx;
Vector3 p2 = center-dy-dz+dx;
Vector3 p3 = center-dy+dz+dx;
Vector3 p4 = center-dy+dz-dx;
Vector3 p5 = center+dy-dz-dx;
Vector3 p6 = center+dy-dz+dx;
Vector3 p7 = center+dy+dz+dx;
Vector3 p8 = center+dy+dz-dx;
/*Handles.DrawAAPolyLine (new Vector3[4] {p1,p2,p3,p4});
Handles.DrawAAPolyLine (new Vector3[4] {p5,p6,p7,p8});
Handles.DrawAAPolyLine (new Vector3[2] {p1,p5});
Handles.DrawAAPolyLine (new Vector3[2] {p2,p6});
Handles.DrawAAPolyLine (new Vector3[2] {p3,p7});
Handles.DrawAAPolyLine (new Vector3[2] {p4,p8});*/
Handles.DrawLine (p1,p2);
Handles.DrawLine (p2,p3);
Handles.DrawLine (p3,p4);
Handles.DrawLine (p4,p1);
Handles.DrawLine (p5,p6);
Handles.DrawLine (p6,p7);
Handles.DrawLine (p7,p8);
Handles.DrawLine (p8,p5);
Handles.DrawLine (p1,p5);
Handles.DrawLine (p2,p6);
Handles.DrawLine (p3,p7);
Handles.DrawLine (p4,p8);
}
/** \cond */
public static Texture2D lineTex;
/** \deprecated Test function, might not work. Uses undocumented editor features */
public static void DrawAALine (Vector3 a, Vector3 b) {
if (lineTex == null) {
lineTex = new Texture2D (1,4);
lineTex.SetPixels (new Color[4] {
Color.clear,
Color.black,
Color.black,
Color.clear,
});
lineTex.Apply ();
}
SceneView c = SceneView.lastActiveSceneView;
Vector3 tangent1 = Vector3.Cross ((b-a).normalized, c.camera.transform.position-a).normalized;
Handles.DrawAAPolyLine (lineTex,new Vector3[3] {a,b,b+tangent1*10});//,b+tangent1,a+tangent1});
}
/** \endcond */
}
}
| |
// MIT License 2017 joylei([email protected])
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace NFly.BitsTransfer
{
/// <summary>
/// a wrapper for IBackgroundCopyJob
/// </summary>
public partial class BitsJob : IDisposable
{
private readonly IBackgroundCopyJob _job;
public event Action<BitsProgress> OnProgress;
private BitsProgressWatch _progressWatch;
internal BitsJob(IBackgroundCopyJob job)
{
if (job == null)
{
throw new ArgumentNullException("job");
}
_job = job;
_progressWatch = new BitsProgressWatch(this);
}
protected internal void ReportProgress(BitsProgress progress)
{
var ev = OnProgress;
if (ev != null)
{
ev(progress);
}
}
/// <summary>
/// get job id
/// </summary>
public Guid Id
{
get
{
return CheckError(delegate
{
Guid jobId;
_job.GetId(out jobId);
return jobId;
});
}
}
/// <summary>
/// get or set job name
/// </summary>
public string DisplayName
{
get
{
return CheckError(delegate
{
string name;
_job.GetDisplayName(out name);
return name;
});
}
set { CheckError(delegate { _job.SetDisplayName(value); }); }
}
/// <summary>
/// get or set job name
/// </summary>
public string Description
{
get
{
return CheckError(delegate
{
string desc;
_job.GetDescription(out desc);
return desc;
});
}
set { CheckError(delegate { _job.SetDescription(value); }); }
}
/// <summary>
/// get or set priority
/// </summary>
public BG_JOB_PRIORITY Priority
{
get
{
return CheckError(delegate
{
BG_JOB_PRIORITY priority;
_job.GetPriority(out priority);
return priority;
});
}
set { CheckError(delegate { _job.SetPriority(value); }); }
}
/// <summary>
/// get or set minimum retry delay
/// </summary>
public uint MinimumRetryDelay
{
get
{
return CheckError(delegate
{
uint delay;
_job.GetMinimumRetryDelay(out delay);
return delay;
});
}
set { CheckError(delegate { _job.SetMinimumRetryDelay(value); }); }
}
/// <summary>
/// owner of job
/// </summary>
public string Owner
{
get
{
return CheckError(delegate
{
string owner;
_job.GetOwner(out owner);
return owner;
});
}
}
/// <summary>
/// total bytes of all files
/// </summary>
public ulong BytesTotal
{
get
{
return CheckError(delegate
{
_BG_JOB_PROGRESS progress;
_job.GetProgress(out progress);
return progress.BytesTotal;
});
}
}
/// <summary>
/// bytes already transferred
/// </summary>
public ulong BytesTransferred
{
get
{
return CheckError(delegate
{
_BG_JOB_PROGRESS progress;
_job.GetProgress(out progress);
return progress.BytesTransferred;
});
}
}
/// <summary>
/// total files count
/// </summary>
public uint FilesTotal
{
get
{
return CheckError(delegate
{
_BG_JOB_PROGRESS progress;
_job.GetProgress(out progress);
return progress.FilesTotal;
});
}
}
/// <summary>
/// transferred file count
/// </summary>
public uint FilesTransferred
{
get
{
return CheckError(delegate
{
_BG_JOB_PROGRESS progress;
_job.GetProgress(out progress);
return progress.FilesTransferred;
});
}
}
/// <summary>
/// transfer state
/// </summary>
public BG_JOB_STATE State
{
get
{
return CheckError(delegate
{
BG_JOB_STATE state;
_job.GetState(out state);
return state;
});
}
}
/// <summary>
/// transfer completed?
/// </summary>
public bool Transferred
{
get { return State == BG_JOB_STATE.BG_JOB_STATE_TRANSFERRED; }
}
/// <summary>
/// job creation time
/// </summary>
public DateTime CreationTime
{
get
{
return CheckError(delegate
{
_BG_JOB_TIMES times;
_job.GetTimes(out times);
return times.CreationTime;
});
}
}
/// <summary>
/// job modification time
/// </summary>
public DateTime ModificationTime
{
get
{
return CheckError(delegate
{
_BG_JOB_TIMES times;
_job.GetTimes(out times);
return times.ModificationTime;
});
}
}
/// <summary>
/// job transfer complete time
/// </summary>
public DateTime TransferCompletionTime
{
get
{
return CheckError(delegate
{
_BG_JOB_TIMES times;
_job.GetTimes(out times);
return times.TransferCompletionTime;
});
}
}
internal void CheckError(Action action)
{
try
{
action();
}
catch (COMException ex)
{
throw new BitsException(this.Error, ex);
}
}
internal TResult CheckError<TResult>(Func<TResult> action)
{
try
{
return action();
}
catch (COMException ex)
{
throw new BitsException(this.Error, ex);
}
}
/// <summary>
/// error if any
/// </summary>
private BitsError Error
{
get
{
BitsError error = new BitsError();
BG_JOB_STATE jobState;
this._job.GetState(out jobState);
if (BG_JOB_STATE.BG_JOB_STATE_ERROR == jobState
|| BG_JOB_STATE.BG_JOB_STATE_TRANSIENT_ERROR == jobState)
{
try
{
IBackgroundCopyError ppError;
this._job.GetError(out ppError);
if (null != ppError)
{
int code;
string pErrorDescription;
BG_ERROR_CONTEXT context;
ppError.GetErrorDescription(Convert.ToUInt32(Thread.CurrentThread.CurrentUICulture.LCID),
out pErrorDescription);
ppError.GetError(out context, out code);
error.Code = code;
error.Context = context;
error.Message = pErrorDescription;
}
}
catch (Exception e)
{
Debug.WriteLine(e);
}
}
return error;
}
}
/// <summary>
/// cancel the job
/// </summary>
public void Cancel()
{
CheckError(delegate
{
try
{
_job.Cancel();
}
finally
{
_progressWatch.Stop();
}
});
}
/// <summary>
/// Suspend the job
/// </summary>
public void Suspend()
{
CheckError(delegate
{
try
{
_job.Suspend();
}
finally
{
_progressWatch.Stop();
}
});
}
/// <summary>
/// resume the job
/// </summary>
public void Resume()
{
CheckError(delegate
{
_job.Resume();
_progressWatch.Start();
});
}
/// <summary>
/// since files has been transferred, mark the job as completed
/// </summary>
public void Complete()
{
CheckError(delegate
{
_progressWatch.Stop();
_job.Complete();
});
}
/// <summary>
/// add file to the job
/// </summary>
/// <param name="remoteFile"></param>
/// <param name="localFile"></param>
public void AddFile(string remoteFile, string localFile)
{
CheckError(delegate { _job.AddFile(remoteFile, localFile); });
}
/// <summary>
/// all files
/// </summary>
public IEnumerable<BitsFile> Files
{
get { return CheckError(() => GetFiles()); }
}
private IEnumerable<BitsFile> GetFiles()
{
IEnumBackgroundCopyFiles files;
_job.EnumFiles(out files);
if (files != null)
{
uint fileCount;
files.GetCount(out fileCount);
for (uint i = 0; i < fileCount; i++)
{
IBackgroundCopyFile file;
uint fetchCount;
files.Next(i, out file, out fetchCount);
if (fetchCount == 1)
{
yield return new BitsFile(this, file);
}
}
}
}
public void Dispose()
{
_progressWatch.Dispose();
}
private static WeakReference _weakBCM = null;
static IBackgroundCopyManager Manager
{
get
{
IBackgroundCopyManager bcm;
if (_weakBCM != null)
{
bcm = _weakBCM.Target as IBackgroundCopyManager;
if (bcm != null)
{
return bcm;
}
}
// ReSharper disable once SuspiciousTypeConversion.Global
bcm = (IBackgroundCopyManager) new BackgroundCopyManager();
_weakBCM = new WeakReference(bcm);
return bcm;
}
}
public static IEnumerable<BitsJob> AllJobs(JobOwner owner)
{
var bcm = Manager;
uint count;
IEnumBackgroundCopyJobs currentUserjobs;
bcm.EnumJobs((uint) owner, out currentUserjobs);
currentUserjobs.GetCount(out count);
for (int i = 0; i < count; i++)
{
uint fetchedCount = 0;
BitsJob.IBackgroundCopyJob currentJob;
currentUserjobs.Next(1, out currentJob, out fetchedCount);
if (fetchedCount == 1)
{
yield return new BitsJob(currentJob);
}
}
}
public static BitsJob GetJob(Guid jobId)
{
return AllJobs(JobOwner.AllUsers).FirstOrDefault(x => x.Id == jobId);
}
public static BitsJob GetJob(string jobName)
{
return AllJobs(JobOwner.AllUsers).FirstOrDefault(x => x.DisplayName == jobName);
}
public static BitsJob CreateJob(string jobName)
{
Guid jobId;
IBackgroundCopyJob job;
Manager.CreateJob(jobName, BG_JOB_TYPE.BG_JOB_TYPE_DOWNLOAD, out jobId, out job);
return new BitsJob(job);
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using Avalonia.Controls.Platform;
using Avalonia.Platform;
using Avalonia.VisualTree;
using Avalonia.Win32.Interop;
namespace Avalonia.Win32
{
class Win32NativeControlHost : INativeControlHostImpl
{
private readonly bool _useLayeredWindow;
public WindowImpl Window { get; }
public Win32NativeControlHost(WindowImpl window, bool useLayeredWindow)
{
_useLayeredWindow = useLayeredWindow;
Window = window;
}
void AssertCompatible(IPlatformHandle handle)
{
if (!IsCompatibleWith(handle))
throw new ArgumentException($"Don't know what to do with {handle.HandleDescriptor}");
}
public INativeControlHostDestroyableControlHandle CreateDefaultChild(IPlatformHandle parent)
{
AssertCompatible(parent);
return new DumbWindow(false, parent.Handle);
}
public INativeControlHostControlTopLevelAttachment CreateNewAttachment(Func<IPlatformHandle, IPlatformHandle> create)
{
var holder = new DumbWindow(_useLayeredWindow, Window.Handle.Handle);
Win32NativeControlAttachment attachment = null;
try
{
var child = create(holder);
// ReSharper disable once UseObjectOrCollectionInitializer
// It has to be assigned to the variable before property setter is called so we dispose it on exception
attachment = new Win32NativeControlAttachment(holder, child);
attachment.AttachedTo = this;
return attachment;
}
catch
{
attachment?.Dispose();
holder?.Destroy();
throw;
}
}
public INativeControlHostControlTopLevelAttachment CreateNewAttachment(IPlatformHandle handle)
{
AssertCompatible(handle);
return new Win32NativeControlAttachment(new DumbWindow(_useLayeredWindow, Window.Handle.Handle),
handle) { AttachedTo = this };
}
public bool IsCompatibleWith(IPlatformHandle handle) => handle.HandleDescriptor == "HWND";
class DumbWindow : IDisposable, INativeControlHostDestroyableControlHandle
{
public IntPtr Handle { get;}
public string HandleDescriptor => "HWND";
public void Destroy() => Dispose();
UnmanagedMethods.WndProc _wndProcDelegate;
private readonly string _className;
public DumbWindow(bool layered = false, IntPtr? parent = null)
{
_wndProcDelegate = WndProc;
var wndClassEx = new UnmanagedMethods.WNDCLASSEX
{
cbSize = Marshal.SizeOf<UnmanagedMethods.WNDCLASSEX>(),
hInstance = UnmanagedMethods.GetModuleHandle(null),
lpfnWndProc = _wndProcDelegate,
lpszClassName = _className = "AvaloniaDumbWindow-" + Guid.NewGuid(),
};
var atom = UnmanagedMethods.RegisterClassEx(ref wndClassEx);
Handle = UnmanagedMethods.CreateWindowEx(
layered ? (int)UnmanagedMethods.WindowStyles.WS_EX_LAYERED : 0,
atom,
null,
(int)UnmanagedMethods.WindowStyles.WS_CHILD,
0,
0,
640,
480,
parent ?? OffscreenParentWindow.Handle,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
if (layered)
UnmanagedMethods.SetLayeredWindowAttributes(Handle, 0, 255,
UnmanagedMethods.LayeredWindowFlags.LWA_ALPHA);
}
protected virtual unsafe IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
return UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam);
}
private void ReleaseUnmanagedResources()
{
UnmanagedMethods.DestroyWindow(Handle);
UnmanagedMethods.UnregisterClass(_className, UnmanagedMethods.GetModuleHandle(null));
}
public void Dispose()
{
ReleaseUnmanagedResources();
GC.SuppressFinalize(this);
}
~DumbWindow()
{
ReleaseUnmanagedResources();
}
}
class Win32NativeControlAttachment : INativeControlHostControlTopLevelAttachment
{
private DumbWindow _holder;
private IPlatformHandle _child;
private Win32NativeControlHost _attachedTo;
public Win32NativeControlAttachment(DumbWindow holder, IPlatformHandle child)
{
_holder = holder;
_child = child;
UnmanagedMethods.SetParent(child.Handle, _holder.Handle);
UnmanagedMethods.ShowWindow(child.Handle, UnmanagedMethods.ShowWindowCommand.Show);
}
void CheckDisposed()
{
if (_holder == null)
throw new ObjectDisposedException(nameof(Win32NativeControlAttachment));
}
public void Dispose()
{
if (_child != null)
UnmanagedMethods.SetParent(_child.Handle, OffscreenParentWindow.Handle);
_holder?.Dispose();
_holder = null;
_child = null;
_attachedTo = null;
}
public INativeControlHostImpl AttachedTo
{
get => _attachedTo;
set
{
CheckDisposed();
_attachedTo = (Win32NativeControlHost) value;
if (_attachedTo == null)
{
UnmanagedMethods.ShowWindow(_holder.Handle, UnmanagedMethods.ShowWindowCommand.Hide);
UnmanagedMethods.SetParent(_holder.Handle, OffscreenParentWindow.Handle);
}
else
UnmanagedMethods.SetParent(_holder.Handle, _attachedTo.Window.Handle.Handle);
}
}
public bool IsCompatibleWith(INativeControlHostImpl host) => host is Win32NativeControlHost;
public void HideWithSize(Size size)
{
UnmanagedMethods.SetWindowPos(_holder.Handle, IntPtr.Zero,
-100, -100, 1, 1,
UnmanagedMethods.SetWindowPosFlags.SWP_HIDEWINDOW |
UnmanagedMethods.SetWindowPosFlags.SWP_NOACTIVATE);
if (_attachedTo == null || _child == null)
return;
size *= _attachedTo.Window.RenderScaling;
UnmanagedMethods.MoveWindow(_child.Handle, 0, 0,
Math.Max(1, (int)size.Width), Math.Max(1, (int)size.Height), false);
}
public unsafe void ShowInBounds(Rect bounds)
{
CheckDisposed();
if (_attachedTo == null)
throw new InvalidOperationException("The control isn't currently attached to a toplevel");
bounds *= _attachedTo.Window.RenderScaling;
var pixelRect = new PixelRect((int)bounds.X, (int)bounds.Y, Math.Max(1, (int)bounds.Width),
Math.Max(1, (int)bounds.Height));
UnmanagedMethods.MoveWindow(_child.Handle, 0, 0, pixelRect.Width, pixelRect.Height, true);
UnmanagedMethods.SetWindowPos(_holder.Handle, IntPtr.Zero, pixelRect.X, pixelRect.Y, pixelRect.Width,
pixelRect.Height,
UnmanagedMethods.SetWindowPosFlags.SWP_SHOWWINDOW
| UnmanagedMethods.SetWindowPosFlags.SWP_NOZORDER
| UnmanagedMethods.SetWindowPosFlags.SWP_NOACTIVATE);
UnmanagedMethods.InvalidateRect(_attachedTo.Window.Handle.Handle, null, false);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.