context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using CuttingEdge.Conditions;
using Netco.ActionPolicyServices.Exceptions;
using Netco.Syntaxis;
namespace Netco.ActionPolicyServices
{
/// <summary> Fluent API for defining <see cref="ActionPolicyAsync"/>
/// that allows to handle exceptions. </summary>
public static class ExceptionHandlerSyntaxAsync
{
/* Development notes
* =================
* If a stateful policy is returned by the syntax,
* it must be wrapped with the sync lock
*/
private static void DoNothing2( Exception ex, int count )
{
}
private static void DoNothing2( Exception ex, TimeSpan sleep )
{
}
private static Task DoNothing2Async( Exception ex, TimeSpan sleep )
{
var task = new TaskCompletionSource< bool >();
task.SetResult( true );
return task.Task;
}
/// <summary>
/// Builds <see cref="ActionPolicyAsync"/> that will retry exception handling
/// for a couple of times before giving up.
/// </summary>
/// <param name="syntax">The syntax.</param>
/// <param name="retryCount">The retry count.</param>
/// <returns>reusable instance of policy</returns>
public static ActionPolicyAsync Retry( this SyntaxAsync< ExceptionHandler > syntax, int retryCount )
{
Condition.Requires( syntax, "syntax" ).IsNotNull();
Func< IRetryState > state = () => new RetryStateWithCount( retryCount, DoNothing2 );
return new ActionPolicyAsync( action => RetryPolicy.ImplementationAsync( action, syntax.Target, state ) );
}
/// <summary>
/// Builds <see cref="ActionPolicyAsync"/> that will retry exception handling
/// for a couple of times before giving up.
/// </summary>
/// <param name="syntax">The syntax.</param>
/// <param name="retryCount">The retry count.</param>
/// <param name="onRetry">The action to perform on retry (i.e.: write to log).
/// First parameter is the exception and second one is its number in sequence. </param>
/// <returns>reusable policy instance </returns>
public static ActionPolicyAsync Retry( this SyntaxAsync< ExceptionHandler > syntax, int retryCount, Action< Exception, int > onRetry )
{
Condition.Requires( syntax, "syntax" ).IsNotNull();
Condition.Requires( onRetry, "onRetry" ).IsNotNull();
Condition.Requires( retryCount, "retryCount" ).IsGreaterThan( 0 );
Func< IRetryState > state = () => new RetryStateWithCount( retryCount, onRetry );
return new ActionPolicyAsync( action => RetryPolicy.ImplementationAsync( action, syntax.Target, state ) );
}
/// <summary>
/// Builds <see cref="ActionPolicyAsync"/> that will retry exception handling
/// for a couple of times before giving up.
/// </summary>
/// <param name="syntax">The syntax.</param>
/// <param name="retryCount">The retry count.</param>
/// <param name="onRetry">The action to perform on retry (i.e.: write to log).
/// First parameter is the exception and second one is its number in sequence. </param>
/// <returns>reusable policy instance </returns>
public static ActionPolicyAsync RetryAsync( this SyntaxAsync< ExceptionHandler > syntax, int retryCount, Func< Exception, int, Task > onRetry )
{
Condition.Requires( syntax, "syntax" ).IsNotNull();
Condition.Requires( onRetry, "onRetry" ).IsNotNull();
Condition.Requires( retryCount, "retryCount" ).IsGreaterThan( 0 );
Func< IRetryStateAsync > state = () => new RetryStateWithCountAsync( retryCount, onRetry );
return new ActionPolicyAsync( action => RetryPolicy.ImplementationAsync( action, syntax.Target, state ) );
}
/// <summary> Builds <see cref="ActionPolicyAsync"/> that will keep retrying forever </summary>
/// <param name="syntax">The syntax to extend.</param>
/// <param name="onRetry">The action to perform when the exception could be retried.</param>
/// <returns> reusable instance of policy</returns>
public static ActionPolicyAsync RetryForever( this SyntaxAsync< ExceptionHandler > syntax, Action< Exception > onRetry )
{
Condition.Requires( syntax, "syntax" ).IsNotNull();
Condition.Requires( onRetry, "onRetry" ).IsNotNull();
var state = new RetryState( onRetry );
return new ActionPolicyAsync( action => RetryPolicy.ImplementationAsync( action, syntax.Target, () => state ) );
}
/// <summary> Builds <see cref="ActionPolicyAsync"/> that will keep retrying forever </summary>
/// <param name="syntax">The syntax to extend.</param>
/// <param name="onRetry">The action to perform when the exception could be retried.</param>
/// <returns> reusable instance of policy</returns>
public static ActionPolicyAsync RetryForeverAsync( this SyntaxAsync< ExceptionHandler > syntax, Func< Exception, Task > onRetry )
{
Condition.Requires( syntax, "syntax" ).IsNotNull();
Condition.Requires( onRetry, "onRetry" ).IsNotNull();
var state = new RetryStateAsync( onRetry );
return new ActionPolicyAsync( action => RetryPolicy.ImplementationAsync( action, syntax.Target, () => state ) );
}
/// <summary> <para>Builds the policy that will keep retrying as long as
/// the exception could be handled by the <paramref name="syntax"/> being
/// built and <paramref name="sleepDurations"/> is providing the sleep intervals.
/// </para>
/// </summary>
/// <param name="syntax">The syntax.</param>
/// <param name="sleepDurations">The sleep durations.</param>
/// <param name="onRetry">The action to perform on retry (i.e.: write to log).
/// First parameter is the exception and second one is the planned sleep duration. </param>
/// <returns>new policy instance</returns>
public static ActionPolicyAsync WaitAndRetry( this SyntaxAsync< ExceptionHandler > syntax, IEnumerable< TimeSpan > sleepDurations,
Action< Exception, TimeSpan > onRetry )
{
Condition.Requires( syntax, "syntax" ).IsNotNull();
Condition.Requires( sleepDurations, "sleepDurations" ).IsNotNull();
Condition.Requires( onRetry, "onRetry" ).IsNotNull();
Func< IRetryState > state = () => new RetryStateWithSleep( sleepDurations, onRetry );
return new ActionPolicyAsync( action => RetryPolicy.ImplementationAsync( action, syntax.Target, state ) );
}
/// <summary> <para>Builds the policy that will keep retrying as long as
/// the exception could be handled by the <paramref name="syntax"/> being
/// built and <paramref name="sleepDurations"/> is providing the sleep intervals.
/// </para>
/// </summary>
/// <param name="syntax">The syntax.</param>
/// <param name="sleepDurations">The sleep durations.</param>
/// <param name="onRetry">The action to perform on retry (i.e.: write to log).
/// First parameter is the exception and second one is the planned sleep duration. </param>
/// <returns>new policy instance</returns>
public static ActionPolicyAsync WaitAndRetryAsync( this SyntaxAsync< ExceptionHandler > syntax, IEnumerable< TimeSpan > sleepDurations,
Func< Exception, TimeSpan, Task > onRetry )
{
Condition.Requires( syntax, "syntax" ).IsNotNull();
Condition.Requires( sleepDurations, "sleepDurations" ).IsNotNull();
Condition.Requires( onRetry, "onRetry" ).IsNotNull();
Func< IRetryStateAsync > state = () => new RetryStateWithSleepAsync( sleepDurations, onRetry );
return new ActionPolicyAsync( action => RetryPolicy.ImplementationAsync( action, syntax.Target, state ) );
}
/// <summary>
/// Builds the policy that will keep retrying as long as
/// the exception could be handled by the <paramref name="syntax" /> being
/// built and <paramref name="sleepDurations" /> is providing the sleep intervals.
/// </summary>
/// <param name="syntax">The syntax.</param>
/// <param name="sleepDurations">The sleep durations.</param>
/// <param name="onRetry">The action to perform on retry (i.e.: write to log).
/// First parameter is the exception and second one is the planned sleep duration.</param>
/// <param name="token">The delay cancellation token.</param>
/// <returns>
/// new policy instance
/// </returns>
public static ActionPolicyAsync WaitAndRetryAsync( this SyntaxAsync< ExceptionHandler > syntax, IEnumerable< TimeSpan > sleepDurations,
Func< Exception, TimeSpan, Task > onRetry, CancellationToken token )
{
Condition.Requires( syntax, "syntax" ).IsNotNull();
Condition.Requires( sleepDurations, "sleepDurations" ).IsNotNull();
Condition.Requires( onRetry, "onRetry" ).IsNotNull();
Func< IRetryStateAsync > state = () => new RetryStateWithSleepAsync( sleepDurations, onRetry, token );
return new ActionPolicyAsync( action => RetryPolicy.ImplementationAsync( action, syntax.Target, state ) );
}
/// <summary> <para>Builds the policy that will keep retrying as long as
/// the exception could be handled by the <paramref name="syntax"/> being
/// built and <paramref name="sleepDurations"/> is providing the sleep intervals.
/// </para>
/// </summary>
/// <param name="syntax">The syntax.</param>
/// <param name="sleepDurations">The sleep durations.</param>
/// <returns>new policy instance</returns>
public static ActionPolicyAsync WaitAndRetry( this SyntaxAsync< ExceptionHandler > syntax, IEnumerable< TimeSpan > sleepDurations )
{
Condition.Requires( syntax, "syntax" ).IsNotNull();
Condition.Requires( sleepDurations, "sleepDurations" ).IsNotNull();
Func< IRetryState > state = () => new RetryStateWithSleep( sleepDurations, DoNothing2 );
return new ActionPolicyAsync( action => RetryPolicy.ImplementationAsync( action, syntax.Target, state ) );
}
/// <summary> <para>Builds the policy that will keep retrying as long as
/// the exception could be handled by the <paramref name="syntax"/> being
/// built and <paramref name="sleepDurations"/> is providing the sleep intervals.
/// </para>
/// </summary>
/// <param name="syntax">The syntax.</param>
/// <param name="sleepDurations">The sleep durations.</param>
/// <returns>new policy instance</returns>
public static ActionPolicyAsync WaitAndRetryAsync( this SyntaxAsync< ExceptionHandler > syntax, IEnumerable< TimeSpan > sleepDurations )
{
Condition.Requires( syntax, "syntax" ).IsNotNull();
Condition.Requires( sleepDurations, "sleepDurations" ).IsNotNull();
Func< IRetryStateAsync > state = () => new RetryStateWithSleepAsync( sleepDurations, DoNothing2Async );
return new ActionPolicyAsync( action => RetryPolicy.ImplementationAsync( action, syntax.Target, state ) );
}
#if !SILVERLIGHT2
/// <summary>
/// <para>Builds the policy that will "break the circuit" after <paramref name="countBeforeBreaking"/>
/// exceptions that could be handled by the <paramref name="syntax"/> being built. The circuit
/// stays broken for the <paramref name="duration"/>. Any attempt to
/// invoke method within the policy, while the circuit is broken, will immediately re-throw
/// the last exception. </para>
/// <para>If the action fails within the policy after the block period, then the breaker
/// is blocked again for the next <paramref name="duration"/>.
/// It will be reset, otherwise.</para>
/// </summary>
/// <param name="syntax">The syntax.</param>
/// <param name="duration">How much time the breaker will stay open before resetting</param>
/// <param name="countBeforeBreaking">How many exceptions are needed to break the circuit</param>
/// <returns>shared policy instance</returns>
/// <remarks>(see "ReleaseIT!" for the details)</remarks>
public static ActionPolicyWithStateAsync CircuitBreaker( this SyntaxAsync< ExceptionHandler > syntax, TimeSpan duration, int countBeforeBreaking )
{
Condition.Requires( syntax, "syntax" ).IsNotNull();
Condition.Requires( duration, "duration" ).IsNotEqualTo( TimeSpan.MinValue, "{0} should be defined" );
Condition.Requires( countBeforeBreaking, "countBeforeBreaking" ).IsGreaterThan( 0, "{0} should be greater than 0" );
var state = new CircuitBreakerState( duration, countBeforeBreaking );
var syncLock = new CircuitBreakerStateLock( state );
return new ActionPolicyWithStateAsync( action => CircuitBreakerPolicy.ImplementationAsync( action, syntax.Target, syncLock ) );
}
#endif
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.SiteRecovery;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;
namespace Microsoft.WindowsAzure.Management.SiteRecovery
{
/// <summary>
/// Definition of Site operations for the Site Recovery extension.
/// </summary>
internal partial class SiteOperations : IServiceOperations<SiteRecoveryManagementClient>, ISiteOperations
{
/// <summary>
/// Initializes a new instance of the SiteOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SiteOperations(SiteRecoveryManagementClient client)
{
this._client = client;
}
private SiteRecoveryManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.SiteRecoveryManagementClient.
/// </summary>
public SiteRecoveryManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Get the Site object by Id.
/// </summary>
/// <param name='input'>
/// Required. Site Creation Input.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public async Task<JobResponse> CreateAsync(SiteCreationInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (input == null)
{
throw new ArgumentNullException("input");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("input", input);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + "WAHyperVRecoveryManager";
url = url + "/~/";
url = url + "HyperVRecoveryManagerVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/Sites/Create";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-04-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement siteCreationInputElement = new XElement(XName.Get("SiteCreationInput", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(siteCreationInputElement);
if (input.Name != null)
{
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = input.Name;
siteCreationInputElement.Add(nameElement);
}
if (input.FabricType != null)
{
XElement fabricTypeElement = new XElement(XName.Get("FabricType", "http://schemas.microsoft.com/windowsazure"));
fabricTypeElement.Value = input.FabricType;
siteCreationInputElement.Add(fabricTypeElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement jobElement = responseDoc.Element(XName.Get("Job", "http://schemas.microsoft.com/windowsazure"));
if (jobElement != null)
{
Job jobInstance = new Job();
result.Job = jobInstance;
XElement activityIdElement = jobElement.Element(XName.Get("ActivityId", "http://schemas.microsoft.com/windowsazure"));
if (activityIdElement != null)
{
string activityIdInstance = activityIdElement.Value;
jobInstance.ActivityId = activityIdInstance;
}
XElement startTimeElement = jobElement.Element(XName.Get("StartTime", "http://schemas.microsoft.com/windowsazure"));
if (startTimeElement != null && !string.IsNullOrEmpty(startTimeElement.Value))
{
DateTime startTimeInstance = DateTime.Parse(startTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
jobInstance.StartTime = startTimeInstance;
}
XElement endTimeElement = jobElement.Element(XName.Get("EndTime", "http://schemas.microsoft.com/windowsazure"));
if (endTimeElement != null && !string.IsNullOrEmpty(endTimeElement.Value))
{
DateTime endTimeInstance = DateTime.Parse(endTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
jobInstance.EndTime = endTimeInstance;
}
XElement displayNameElement = jobElement.Element(XName.Get("DisplayName", "http://schemas.microsoft.com/windowsazure"));
if (displayNameElement != null)
{
string displayNameInstance = displayNameElement.Value;
jobInstance.DisplayName = displayNameInstance;
}
XElement targetObjectIdElement = jobElement.Element(XName.Get("TargetObjectId", "http://schemas.microsoft.com/windowsazure"));
if (targetObjectIdElement != null)
{
string targetObjectIdInstance = targetObjectIdElement.Value;
jobInstance.TargetObjectId = targetObjectIdInstance;
}
XElement targetObjectTypeElement = jobElement.Element(XName.Get("TargetObjectType", "http://schemas.microsoft.com/windowsazure"));
if (targetObjectTypeElement != null)
{
string targetObjectTypeInstance = targetObjectTypeElement.Value;
jobInstance.TargetObjectType = targetObjectTypeInstance;
}
XElement targetObjectNameElement = jobElement.Element(XName.Get("TargetObjectName", "http://schemas.microsoft.com/windowsazure"));
if (targetObjectNameElement != null)
{
string targetObjectNameInstance = targetObjectNameElement.Value;
jobInstance.TargetObjectName = targetObjectNameInstance;
}
XElement allowedActionsSequenceElement = jobElement.Element(XName.Get("AllowedActions", "http://schemas.microsoft.com/windowsazure"));
if (allowedActionsSequenceElement != null)
{
foreach (XElement allowedActionsElement in allowedActionsSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")))
{
jobInstance.AllowedActions.Add(allowedActionsElement.Value);
}
}
XElement stateElement = jobElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
jobInstance.State = stateInstance;
}
XElement stateDescriptionElement = jobElement.Element(XName.Get("StateDescription", "http://schemas.microsoft.com/windowsazure"));
if (stateDescriptionElement != null)
{
string stateDescriptionInstance = stateDescriptionElement.Value;
jobInstance.StateDescription = stateDescriptionInstance;
}
XElement tasksSequenceElement = jobElement.Element(XName.Get("Tasks", "http://schemas.microsoft.com/windowsazure"));
if (tasksSequenceElement != null)
{
foreach (XElement tasksElement in tasksSequenceElement.Elements(XName.Get("Task", "http://schemas.microsoft.com/windowsazure")))
{
AsrTask taskInstance = new AsrTask();
jobInstance.Tasks.Add(taskInstance);
XElement startTimeElement2 = tasksElement.Element(XName.Get("StartTime", "http://schemas.microsoft.com/windowsazure"));
if (startTimeElement2 != null)
{
DateTime startTimeInstance2 = DateTime.Parse(startTimeElement2.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
taskInstance.StartTime = startTimeInstance2;
}
XElement endTimeElement2 = tasksElement.Element(XName.Get("EndTime", "http://schemas.microsoft.com/windowsazure"));
if (endTimeElement2 != null)
{
DateTime endTimeInstance2 = DateTime.Parse(endTimeElement2.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
taskInstance.EndTime = endTimeInstance2;
}
XElement actionsSequenceElement = tasksElement.Element(XName.Get("Actions", "http://schemas.microsoft.com/windowsazure"));
if (actionsSequenceElement != null)
{
foreach (XElement actionsElement in actionsSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")))
{
taskInstance.Actions.Add(actionsElement.Value);
}
}
XElement taskTypeElement = tasksElement.Element(XName.Get("TaskType", "http://schemas.microsoft.com/windowsazure"));
if (taskTypeElement != null)
{
string taskTypeInstance = taskTypeElement.Value;
taskInstance.TaskType = taskTypeInstance;
}
XElement taskNameElement = tasksElement.Element(XName.Get("TaskName", "http://schemas.microsoft.com/windowsazure"));
if (taskNameElement != null)
{
string taskNameInstance = taskNameElement.Value;
taskInstance.TaskName = taskNameInstance;
}
XElement stateElement2 = tasksElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement2 != null)
{
string stateInstance2 = stateElement2.Value;
taskInstance.State = stateInstance2;
}
XElement stateDescriptionElement2 = tasksElement.Element(XName.Get("StateDescription", "http://schemas.microsoft.com/windowsazure"));
if (stateDescriptionElement2 != null)
{
string stateDescriptionInstance2 = stateDescriptionElement2.Value;
taskInstance.StateDescription = stateDescriptionInstance2;
}
XElement extendedDetailsElement = tasksElement.Element(XName.Get("ExtendedDetails", "http://schemas.microsoft.com/windowsazure"));
if (extendedDetailsElement != null)
{
string extendedDetailsInstance = extendedDetailsElement.Value;
taskInstance.ExtendedDetails = extendedDetailsInstance;
}
XElement nameElement2 = tasksElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance = nameElement2.Value;
taskInstance.Name = nameInstance;
}
XElement idElement = tasksElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
taskInstance.ID = idInstance;
}
}
}
XElement errorsSequenceElement = jobElement.Element(XName.Get("Errors", "http://schemas.microsoft.com/windowsazure"));
if (errorsSequenceElement != null)
{
foreach (XElement errorsElement in errorsSequenceElement.Elements(XName.Get("ErrorDetails", "http://schemas.microsoft.com/windowsazure")))
{
ErrorDetails errorDetailsInstance = new ErrorDetails();
jobInstance.Errors.Add(errorDetailsInstance);
XElement serviceErrorDetailsElement = errorsElement.Element(XName.Get("ServiceErrorDetails", "http://schemas.microsoft.com/windowsazure"));
if (serviceErrorDetailsElement != null)
{
ServiceError serviceErrorDetailsInstance = new ServiceError();
errorDetailsInstance.ServiceErrorDetails = serviceErrorDetailsInstance;
XElement codeElement = serviceErrorDetailsElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
serviceErrorDetailsInstance.Code = codeInstance;
}
XElement messageElement = serviceErrorDetailsElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
serviceErrorDetailsInstance.Message = messageInstance;
}
XElement possibleCausesElement = serviceErrorDetailsElement.Element(XName.Get("PossibleCauses", "http://schemas.microsoft.com/windowsazure"));
if (possibleCausesElement != null)
{
string possibleCausesInstance = possibleCausesElement.Value;
serviceErrorDetailsInstance.PossibleCauses = possibleCausesInstance;
}
XElement recommendedActionElement = serviceErrorDetailsElement.Element(XName.Get("RecommendedAction", "http://schemas.microsoft.com/windowsazure"));
if (recommendedActionElement != null)
{
string recommendedActionInstance = recommendedActionElement.Value;
serviceErrorDetailsInstance.RecommendedAction = recommendedActionInstance;
}
XElement activityIdElement2 = serviceErrorDetailsElement.Element(XName.Get("ActivityId", "http://schemas.microsoft.com/windowsazure"));
if (activityIdElement2 != null)
{
string activityIdInstance2 = activityIdElement2.Value;
serviceErrorDetailsInstance.ActivityId = activityIdInstance2;
}
}
XElement providerErrorDetailsElement = errorsElement.Element(XName.Get("ProviderErrorDetails", "http://schemas.microsoft.com/windowsazure"));
if (providerErrorDetailsElement != null)
{
ProviderError providerErrorDetailsInstance = new ProviderError();
errorDetailsInstance.ProviderErrorDetails = providerErrorDetailsInstance;
XElement errorCodeElement = providerErrorDetailsElement.Element(XName.Get("ErrorCode", "http://schemas.microsoft.com/windowsazure"));
if (errorCodeElement != null)
{
int errorCodeInstance = int.Parse(errorCodeElement.Value, CultureInfo.InvariantCulture);
providerErrorDetailsInstance.ErrorCode = errorCodeInstance;
}
XElement errorMessageElement = providerErrorDetailsElement.Element(XName.Get("ErrorMessage", "http://schemas.microsoft.com/windowsazure"));
if (errorMessageElement != null)
{
string errorMessageInstance = errorMessageElement.Value;
providerErrorDetailsInstance.ErrorMessage = errorMessageInstance;
}
XElement errorIdElement = providerErrorDetailsElement.Element(XName.Get("ErrorId", "http://schemas.microsoft.com/windowsazure"));
if (errorIdElement != null)
{
string errorIdInstance = errorIdElement.Value;
providerErrorDetailsInstance.ErrorId = errorIdInstance;
}
XElement workflowIdElement = providerErrorDetailsElement.Element(XName.Get("WorkflowId", "http://schemas.microsoft.com/windowsazure"));
if (workflowIdElement != null)
{
string workflowIdInstance = workflowIdElement.Value;
providerErrorDetailsInstance.WorkflowId = workflowIdInstance;
}
XElement creationTimeUtcElement = providerErrorDetailsElement.Element(XName.Get("CreationTimeUtc", "http://schemas.microsoft.com/windowsazure"));
if (creationTimeUtcElement != null)
{
DateTime creationTimeUtcInstance = DateTime.Parse(creationTimeUtcElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
providerErrorDetailsInstance.CreationTimeUtc = creationTimeUtcInstance;
}
XElement errorLevelElement = providerErrorDetailsElement.Element(XName.Get("ErrorLevel", "http://schemas.microsoft.com/windowsazure"));
if (errorLevelElement != null)
{
string errorLevelInstance = errorLevelElement.Value;
providerErrorDetailsInstance.ErrorLevel = errorLevelInstance;
}
XElement affectedObjectsSequenceElement = providerErrorDetailsElement.Element(XName.Get("AffectedObjects", "http://schemas.microsoft.com/windowsazure"));
if (affectedObjectsSequenceElement != null)
{
foreach (XElement affectedObjectsElement in affectedObjectsSequenceElement.Elements(XName.Get("KeyValueOfstringstring", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")))
{
string affectedObjectsKey = affectedObjectsElement.Element(XName.Get("Key", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")).Value;
string affectedObjectsValue = affectedObjectsElement.Element(XName.Get("Value", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")).Value;
providerErrorDetailsInstance.AffectedObjects.Add(affectedObjectsKey, affectedObjectsValue);
}
}
}
XElement taskIdElement = errorsElement.Element(XName.Get("TaskId", "http://schemas.microsoft.com/windowsazure"));
if (taskIdElement != null)
{
string taskIdInstance = taskIdElement.Value;
errorDetailsInstance.TaskId = taskIdInstance;
}
}
}
XElement nameElement3 = jobElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement3 != null)
{
string nameInstance2 = nameElement3.Value;
jobInstance.Name = nameInstance2;
}
XElement idElement2 = jobElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement2 != null)
{
string idInstance2 = idElement2.Value;
jobInstance.ID = idInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the Site object by Id.
/// </summary>
/// <param name='siteId'>
/// Required. Site ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public async Task<JobResponse> DeleteAsync(string siteId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (siteId == null)
{
throw new ArgumentNullException("siteId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("siteId", siteId);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + "WAHyperVRecoveryManager";
url = url + "/~/";
url = url + "HyperVRecoveryManagerVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/Sites/";
url = url + Uri.EscapeDataString(siteId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-04-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement jobElement = responseDoc.Element(XName.Get("Job", "http://schemas.microsoft.com/windowsazure"));
if (jobElement != null)
{
Job jobInstance = new Job();
result.Job = jobInstance;
XElement activityIdElement = jobElement.Element(XName.Get("ActivityId", "http://schemas.microsoft.com/windowsazure"));
if (activityIdElement != null)
{
string activityIdInstance = activityIdElement.Value;
jobInstance.ActivityId = activityIdInstance;
}
XElement startTimeElement = jobElement.Element(XName.Get("StartTime", "http://schemas.microsoft.com/windowsazure"));
if (startTimeElement != null && !string.IsNullOrEmpty(startTimeElement.Value))
{
DateTime startTimeInstance = DateTime.Parse(startTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
jobInstance.StartTime = startTimeInstance;
}
XElement endTimeElement = jobElement.Element(XName.Get("EndTime", "http://schemas.microsoft.com/windowsazure"));
if (endTimeElement != null && !string.IsNullOrEmpty(endTimeElement.Value))
{
DateTime endTimeInstance = DateTime.Parse(endTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
jobInstance.EndTime = endTimeInstance;
}
XElement displayNameElement = jobElement.Element(XName.Get("DisplayName", "http://schemas.microsoft.com/windowsazure"));
if (displayNameElement != null)
{
string displayNameInstance = displayNameElement.Value;
jobInstance.DisplayName = displayNameInstance;
}
XElement targetObjectIdElement = jobElement.Element(XName.Get("TargetObjectId", "http://schemas.microsoft.com/windowsazure"));
if (targetObjectIdElement != null)
{
string targetObjectIdInstance = targetObjectIdElement.Value;
jobInstance.TargetObjectId = targetObjectIdInstance;
}
XElement targetObjectTypeElement = jobElement.Element(XName.Get("TargetObjectType", "http://schemas.microsoft.com/windowsazure"));
if (targetObjectTypeElement != null)
{
string targetObjectTypeInstance = targetObjectTypeElement.Value;
jobInstance.TargetObjectType = targetObjectTypeInstance;
}
XElement targetObjectNameElement = jobElement.Element(XName.Get("TargetObjectName", "http://schemas.microsoft.com/windowsazure"));
if (targetObjectNameElement != null)
{
string targetObjectNameInstance = targetObjectNameElement.Value;
jobInstance.TargetObjectName = targetObjectNameInstance;
}
XElement allowedActionsSequenceElement = jobElement.Element(XName.Get("AllowedActions", "http://schemas.microsoft.com/windowsazure"));
if (allowedActionsSequenceElement != null)
{
foreach (XElement allowedActionsElement in allowedActionsSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")))
{
jobInstance.AllowedActions.Add(allowedActionsElement.Value);
}
}
XElement stateElement = jobElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
jobInstance.State = stateInstance;
}
XElement stateDescriptionElement = jobElement.Element(XName.Get("StateDescription", "http://schemas.microsoft.com/windowsazure"));
if (stateDescriptionElement != null)
{
string stateDescriptionInstance = stateDescriptionElement.Value;
jobInstance.StateDescription = stateDescriptionInstance;
}
XElement tasksSequenceElement = jobElement.Element(XName.Get("Tasks", "http://schemas.microsoft.com/windowsazure"));
if (tasksSequenceElement != null)
{
foreach (XElement tasksElement in tasksSequenceElement.Elements(XName.Get("Task", "http://schemas.microsoft.com/windowsazure")))
{
AsrTask taskInstance = new AsrTask();
jobInstance.Tasks.Add(taskInstance);
XElement startTimeElement2 = tasksElement.Element(XName.Get("StartTime", "http://schemas.microsoft.com/windowsazure"));
if (startTimeElement2 != null)
{
DateTime startTimeInstance2 = DateTime.Parse(startTimeElement2.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
taskInstance.StartTime = startTimeInstance2;
}
XElement endTimeElement2 = tasksElement.Element(XName.Get("EndTime", "http://schemas.microsoft.com/windowsazure"));
if (endTimeElement2 != null)
{
DateTime endTimeInstance2 = DateTime.Parse(endTimeElement2.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
taskInstance.EndTime = endTimeInstance2;
}
XElement actionsSequenceElement = tasksElement.Element(XName.Get("Actions", "http://schemas.microsoft.com/windowsazure"));
if (actionsSequenceElement != null)
{
foreach (XElement actionsElement in actionsSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")))
{
taskInstance.Actions.Add(actionsElement.Value);
}
}
XElement taskTypeElement = tasksElement.Element(XName.Get("TaskType", "http://schemas.microsoft.com/windowsazure"));
if (taskTypeElement != null)
{
string taskTypeInstance = taskTypeElement.Value;
taskInstance.TaskType = taskTypeInstance;
}
XElement taskNameElement = tasksElement.Element(XName.Get("TaskName", "http://schemas.microsoft.com/windowsazure"));
if (taskNameElement != null)
{
string taskNameInstance = taskNameElement.Value;
taskInstance.TaskName = taskNameInstance;
}
XElement stateElement2 = tasksElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement2 != null)
{
string stateInstance2 = stateElement2.Value;
taskInstance.State = stateInstance2;
}
XElement stateDescriptionElement2 = tasksElement.Element(XName.Get("StateDescription", "http://schemas.microsoft.com/windowsazure"));
if (stateDescriptionElement2 != null)
{
string stateDescriptionInstance2 = stateDescriptionElement2.Value;
taskInstance.StateDescription = stateDescriptionInstance2;
}
XElement extendedDetailsElement = tasksElement.Element(XName.Get("ExtendedDetails", "http://schemas.microsoft.com/windowsazure"));
if (extendedDetailsElement != null)
{
string extendedDetailsInstance = extendedDetailsElement.Value;
taskInstance.ExtendedDetails = extendedDetailsInstance;
}
XElement nameElement = tasksElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
taskInstance.Name = nameInstance;
}
XElement idElement = tasksElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
taskInstance.ID = idInstance;
}
}
}
XElement errorsSequenceElement = jobElement.Element(XName.Get("Errors", "http://schemas.microsoft.com/windowsazure"));
if (errorsSequenceElement != null)
{
foreach (XElement errorsElement in errorsSequenceElement.Elements(XName.Get("ErrorDetails", "http://schemas.microsoft.com/windowsazure")))
{
ErrorDetails errorDetailsInstance = new ErrorDetails();
jobInstance.Errors.Add(errorDetailsInstance);
XElement serviceErrorDetailsElement = errorsElement.Element(XName.Get("ServiceErrorDetails", "http://schemas.microsoft.com/windowsazure"));
if (serviceErrorDetailsElement != null)
{
ServiceError serviceErrorDetailsInstance = new ServiceError();
errorDetailsInstance.ServiceErrorDetails = serviceErrorDetailsInstance;
XElement codeElement = serviceErrorDetailsElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
serviceErrorDetailsInstance.Code = codeInstance;
}
XElement messageElement = serviceErrorDetailsElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
serviceErrorDetailsInstance.Message = messageInstance;
}
XElement possibleCausesElement = serviceErrorDetailsElement.Element(XName.Get("PossibleCauses", "http://schemas.microsoft.com/windowsazure"));
if (possibleCausesElement != null)
{
string possibleCausesInstance = possibleCausesElement.Value;
serviceErrorDetailsInstance.PossibleCauses = possibleCausesInstance;
}
XElement recommendedActionElement = serviceErrorDetailsElement.Element(XName.Get("RecommendedAction", "http://schemas.microsoft.com/windowsazure"));
if (recommendedActionElement != null)
{
string recommendedActionInstance = recommendedActionElement.Value;
serviceErrorDetailsInstance.RecommendedAction = recommendedActionInstance;
}
XElement activityIdElement2 = serviceErrorDetailsElement.Element(XName.Get("ActivityId", "http://schemas.microsoft.com/windowsazure"));
if (activityIdElement2 != null)
{
string activityIdInstance2 = activityIdElement2.Value;
serviceErrorDetailsInstance.ActivityId = activityIdInstance2;
}
}
XElement providerErrorDetailsElement = errorsElement.Element(XName.Get("ProviderErrorDetails", "http://schemas.microsoft.com/windowsazure"));
if (providerErrorDetailsElement != null)
{
ProviderError providerErrorDetailsInstance = new ProviderError();
errorDetailsInstance.ProviderErrorDetails = providerErrorDetailsInstance;
XElement errorCodeElement = providerErrorDetailsElement.Element(XName.Get("ErrorCode", "http://schemas.microsoft.com/windowsazure"));
if (errorCodeElement != null)
{
int errorCodeInstance = int.Parse(errorCodeElement.Value, CultureInfo.InvariantCulture);
providerErrorDetailsInstance.ErrorCode = errorCodeInstance;
}
XElement errorMessageElement = providerErrorDetailsElement.Element(XName.Get("ErrorMessage", "http://schemas.microsoft.com/windowsazure"));
if (errorMessageElement != null)
{
string errorMessageInstance = errorMessageElement.Value;
providerErrorDetailsInstance.ErrorMessage = errorMessageInstance;
}
XElement errorIdElement = providerErrorDetailsElement.Element(XName.Get("ErrorId", "http://schemas.microsoft.com/windowsazure"));
if (errorIdElement != null)
{
string errorIdInstance = errorIdElement.Value;
providerErrorDetailsInstance.ErrorId = errorIdInstance;
}
XElement workflowIdElement = providerErrorDetailsElement.Element(XName.Get("WorkflowId", "http://schemas.microsoft.com/windowsazure"));
if (workflowIdElement != null)
{
string workflowIdInstance = workflowIdElement.Value;
providerErrorDetailsInstance.WorkflowId = workflowIdInstance;
}
XElement creationTimeUtcElement = providerErrorDetailsElement.Element(XName.Get("CreationTimeUtc", "http://schemas.microsoft.com/windowsazure"));
if (creationTimeUtcElement != null)
{
DateTime creationTimeUtcInstance = DateTime.Parse(creationTimeUtcElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
providerErrorDetailsInstance.CreationTimeUtc = creationTimeUtcInstance;
}
XElement errorLevelElement = providerErrorDetailsElement.Element(XName.Get("ErrorLevel", "http://schemas.microsoft.com/windowsazure"));
if (errorLevelElement != null)
{
string errorLevelInstance = errorLevelElement.Value;
providerErrorDetailsInstance.ErrorLevel = errorLevelInstance;
}
XElement affectedObjectsSequenceElement = providerErrorDetailsElement.Element(XName.Get("AffectedObjects", "http://schemas.microsoft.com/windowsazure"));
if (affectedObjectsSequenceElement != null)
{
foreach (XElement affectedObjectsElement in affectedObjectsSequenceElement.Elements(XName.Get("KeyValueOfstringstring", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")))
{
string affectedObjectsKey = affectedObjectsElement.Element(XName.Get("Key", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")).Value;
string affectedObjectsValue = affectedObjectsElement.Element(XName.Get("Value", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")).Value;
providerErrorDetailsInstance.AffectedObjects.Add(affectedObjectsKey, affectedObjectsValue);
}
}
}
XElement taskIdElement = errorsElement.Element(XName.Get("TaskId", "http://schemas.microsoft.com/windowsazure"));
if (taskIdElement != null)
{
string taskIdInstance = taskIdElement.Value;
errorDetailsInstance.TaskId = taskIdInstance;
}
}
}
XElement nameElement2 = jobElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance2 = nameElement2.Value;
jobInstance.Name = nameInstance2;
}
XElement idElement2 = jobElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement2 != null)
{
string idInstance2 = idElement2.Value;
jobInstance.ID = idInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the Site object by Id.
/// </summary>
/// <param name='siteId'>
/// Required. Site ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Site object
/// </returns>
public async Task<SiteResponse> GetAsync(string siteId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (siteId == null)
{
throw new ArgumentNullException("siteId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("siteId", siteId);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + "WAHyperVRecoveryManager";
url = url + "/~/";
url = url + "HyperVRecoveryManagerVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/Sites/";
url = url + Uri.EscapeDataString(siteId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-04-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
SiteResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SiteResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement siteElement = responseDoc.Element(XName.Get("Site", "http://schemas.microsoft.com/windowsazure"));
if (siteElement != null)
{
Site siteInstance = new Site();
result.Site = siteInstance;
XElement typeElement = siteElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
siteInstance.Type = typeInstance;
}
XElement nameElement = siteElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
siteInstance.Name = nameInstance;
}
XElement idElement = siteElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
siteInstance.ID = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of all Sites under the vault.
/// </summary>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list Sites operation.
/// </returns>
public async Task<SiteListResponse> ListAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + "WAHyperVRecoveryManager";
url = url + "/~/";
url = url + "HyperVRecoveryManagerVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/Sites";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-04-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
SiteListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SiteListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement arrayOfSiteSequenceElement = responseDoc.Element(XName.Get("ArrayOfSite", "http://schemas.microsoft.com/windowsazure"));
if (arrayOfSiteSequenceElement != null)
{
foreach (XElement arrayOfSiteElement in arrayOfSiteSequenceElement.Elements(XName.Get("Site", "http://schemas.microsoft.com/windowsazure")))
{
Site siteInstance = new Site();
result.Sites.Add(siteInstance);
XElement typeElement = arrayOfSiteElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
siteInstance.Type = typeInstance;
}
XElement nameElement = arrayOfSiteElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
siteInstance.Name = nameInstance;
}
XElement idElement = arrayOfSiteElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
siteInstance.ID = idInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;
namespace Abp.Dependency
{
/// <summary>
/// This class is used to directly perform dependency injection tasks.
/// </summary>
public class IocManager : IIocManager
{
/// <summary>
/// The Singleton instance.
/// </summary>
public static IocManager Instance { get; private set; }
/// <summary>
/// Reference to the Castle Windsor Container.
/// </summary>
public IWindsorContainer IocContainer { get; private set; }
/// <summary>
/// List of all registered conventional registrars.
/// </summary>
private readonly List<IConventionalDependencyRegistrar> _conventionalRegistrars;
static IocManager()
{
Instance = new IocManager();
}
internal IocManager()
{
IocContainer = new WindsorContainer();
_conventionalRegistrars = new List<IConventionalDependencyRegistrar>();
//Register self!
IocContainer.Register(
Component.For<IocManager, IIocManager, IIocRegistrar, IIocResolver>().UsingFactoryMethod(() => this)
);
}
/// <summary>
/// Adds a dependency registrar for conventional registration.
/// </summary>
/// <param name="registrar">dependency registrar</param>
public void AddConventionalRegistrar(IConventionalDependencyRegistrar registrar)
{
_conventionalRegistrars.Add(registrar);
}
/// <summary>
/// Registers types of given assembly by all conventional registrars. See <see cref="AddConventionalRegistrar"/> method.
/// </summary>
/// <param name="assembly">Assembly to register</param>
public void RegisterAssemblyByConvention(Assembly assembly)
{
RegisterAssemblyByConvention(assembly, new ConventionalRegistrationConfig());
}
/// <summary>
/// Registers types of given assembly by all conventional registrars. See <see cref="AddConventionalRegistrar"/> method.
/// </summary>
/// <param name="assembly">Assembly to register</param>
/// <param name="config">Additional configuration</param>
public void RegisterAssemblyByConvention(Assembly assembly, ConventionalRegistrationConfig config)
{
var context = new ConventionalRegistrationContext(assembly, this, config);
foreach (var registerer in _conventionalRegistrars)
{
registerer.RegisterAssembly(context);
}
if (config.InstallInstallers)
{
IocContainer.Install(FromAssembly.Instance(assembly));
}
}
/// <summary>
/// Registers a type as self registration.
/// </summary>
/// <typeparam name="TService">Type of the class</typeparam>
/// <param name="lifeStyle">Lifestyle of the objects of this type</param>
public void Register<TType>(DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton) where TType : class
{
IocContainer.Register(ApplyLifestyle(Component.For<TType>(), lifeStyle));
}
/// <summary>
/// Registers a type as self registration.
/// </summary>
/// <param name="type">Type of the class</param>
/// <param name="lifeStyle">Lifestyle of the objects of this type</param>
public void Register(Type type, DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton)
{
IocContainer.Register(ApplyLifestyle(Component.For(type), lifeStyle));
}
/// <summary>
/// Registers a type with it's implementation.
/// </summary>
/// <typeparam name="TType">Registering type</typeparam>
/// <typeparam name="TImpl">The type that implements <see cref="TType"/></typeparam>
/// <param name="lifeStyle">Lifestyle of the objects of this type</param>
public void Register<TType, TImpl>(DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton)
where TType : class
where TImpl : class, TType
{
IocContainer.Register(ApplyLifestyle(Component.For<TType>().ImplementedBy<TImpl>(), lifeStyle));
}
/// <summary>
/// Registers a class as self registration.
/// </summary>
/// <param name="type">Type of the class</param>
/// <param name="impl">The type that implements <see cref="type"/></param>
/// <param name="lifeStyle">Lifestyle of the objects of this type</param>
public void Register(Type type, Type impl, DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton)
{
IocContainer.Register(ApplyLifestyle(Component.For(type).ImplementedBy(impl), lifeStyle));
}
/// <summary>
/// Checks whether given type is registered before.
/// </summary>
/// <param name="type">Type to check</param>
public bool IsRegistered(Type type)
{
return IocContainer.Kernel.HasComponent(type);
}
/// <summary>
/// Checks whether given type is registered before.
/// </summary>
/// <typeparam name="TType">Type to check</typeparam>
public bool IsRegistered<TType>()
{
return IocContainer.Kernel.HasComponent(typeof(TType));
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="IocHelper.Release"/>) after usage.
/// </summary>
/// <typeparam name="T">Type of the object to get</typeparam>
/// <returns>The instance object</returns>
public T Resolve<T>()
{
return IocContainer.Resolve<T>();
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="IocHelper.Release"/>) after usage.
/// </summary>
/// <typeparam name="T">Type of the object to get</typeparam>
/// <param name="argumentsAsAnonymousType">Constructor arguments</param>
/// <returns>The instance object</returns>
public T Resolve<T>(object argumentsAsAnonymousType)
{
return IocContainer.Resolve<T>(argumentsAsAnonymousType);
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="IocHelper.Release"/>) after usage.
/// </summary>
/// <param name="type">Type of the object to get</param>
/// <returns>The instance object</returns>
public object Resolve(Type type)
{
return IocContainer.Resolve(type);
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="IocHelper.Release"/>) after usage.
/// </summary>
/// <param name="type">Type of the object to get</param>
/// <param name="argumentsAsAnonymousType">Constructor arguments</param>
/// <returns>The instance object</returns>
public object Resolve(Type type, object argumentsAsAnonymousType)
{
return IocContainer.Resolve(type, argumentsAsAnonymousType);
}
/// <summary>
/// Releases a pre-resolved object. See Resolve methods.
/// </summary>
/// <param name="obj">Object to be released</param>
public void Release(object obj)
{
IocContainer.Release(obj);
}
public void Dispose()
{
IocContainer.Dispose();
}
private static ComponentRegistration<T> ApplyLifestyle<T>(ComponentRegistration<T> registration, DependencyLifeStyle lifeStyle)
where T : class
{
switch (lifeStyle)
{
case DependencyLifeStyle.Transient:
return registration.LifestyleTransient();
case DependencyLifeStyle.Singleton:
return registration.LifestyleSingleton();
default:
return registration;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Its.Log.Instrumentation;
using Microsoft.Its.Domain;
using Its.Validation;
using Sample.Domain.Ordering.Commands;
namespace Sample.Domain.Ordering
{
public partial class Order
{
public void EnactCommand(CreateOrder create)
{
RecordEvent(new Created
{
CustomerName = create.CustomerName,
CustomerId = create.CustomerId
});
RecordEvent(new CustomerInfoChanged
{
CustomerName = create.CustomerName
});
}
public void EnactCommand(AddItem addItem)
{
RecordEvent(new ItemAdded
{
Price = addItem.Price,
ProductName = addItem.ProductName,
Quantity = addItem.Quantity
});
}
public void EnactCommand(ChangeCustomerInfo command)
{
RecordEvent(new CustomerInfoChanged
{
CustomerName = command.CustomerName,
Address = command.Address,
PhoneNumber = command.PhoneNumber,
PostalCode = command.PostalCode,
RegionOrCountry = command.RegionOrCountry
});
}
public void EnactCommand(ChangeFufillmentMethod change)
{
RecordEvent(new FulfillmentMethodSelected
{
FulfillmentMethod = change.FulfillmentMethod
});
}
public class OrderCancelCommandHandler : ICommandHandler<Order, Cancel>
{
private readonly ICommandScheduler<CustomerAccount> scheduler;
public OrderCancelCommandHandler(
ICommandScheduler<CustomerAccount> scheduler)
{
if (scheduler == null)
{
throw new ArgumentNullException("scheduler");
}
this.scheduler = scheduler;
}
public async Task EnactCommand(Order order, Cancel cancel)
{
var command = new NotifyOrderCanceled
{
OrderNumber = order.OrderNumber
};
await scheduler.Schedule(
order.CustomerId,
command,
deliveryDependsOn: order.RecordEvent(new Cancelled()));
}
public async Task HandleScheduledCommandException(Order order, CommandFailed<Cancel> command)
{
// Tests depend on this being an empty handler - don't modify.
Debug.WriteLine("[HandleScheduledCommandException] " + command.ToLogString());
}
}
public void EnactCommand(Deliver cancel)
{
RecordEvent(new Delivered());
RecordEvent(new Fulfilled());
}
public void EnactCommand(ProvideCreditCardInfo command)
{
RecordEvent(new CreditCardInfoProvided
{
CreditCardCvv2 = command.CreditCardCvv2,
CreditCardExpirationMonth = command.CreditCardExpirationMonth,
CreditCardExpirationYear = command.CreditCardExpirationYear,
CreditCardName = command.CreditCardName,
CreditCardNumber = command.CreditCardNumber
});
}
public void HandleCommandValidationFailure(ChargeCreditCard command, ValidationReport validationReport)
{
if (validationReport.Failures.All(failure => failure.IsRetryable()))
{
// this will terminate further attempts
RecordEvent(new CreditCardChargeRejected());
}
else
{
ThrowCommandValidationException(command, validationReport);
}
}
public class OrderChargeCreditCardHandler : ICommandHandler<Order, ChargeCreditCard>
{
public async Task EnactCommand(Order order, ChargeCreditCard command)
{
order.RecordEvent(new CreditCardCharged
{
Amount = command.Amount
});
}
public async Task HandleScheduledCommandException(Order order, CommandFailed<ChargeCreditCard> command)
{
if (command.NumberOfPreviousAttempts < 3)
{
command.Retry(after: command.Command.ChargeRetryPeriod);
}
else
{
order.RecordEvent(new Cancelled
{
Reason = "Final credit card charge attempt failed."
});
}
}
}
public void EnactCommand(ChargeCreditCardOn command)
{
ScheduleCommand(new ChargeCreditCard
{
Amount = command.Amount,
PaymentId = command.PaymentId,
ChargeRetryPeriod = command.ChargeRetryPeriod
}, command.ChargeDate);
}
public void EnactCommand(SpecifyShippingInfo command)
{
RecordEvent(new ShippingMethodSelected
{
Address = command.Address,
City = command.City,
StateOrProvince = command.StateOrProvince,
Country = command.Country,
DeliverBy = command.DeliverBy,
RecipientName = command.RecipientName,
});
}
public void EnactCommand(Place command)
{
RecordEvent(new Placed(orderNumber: Guid.NewGuid().ToString().Substring(0, 8)));
}
public void EnactCommand(ShipOn command)
{
ScheduleCommand(new Ship
{
ShipmentId = command.ShipmentId
}, command.ShipDate);
}
public void EnactCommand(RenameEvent command)
{
pendingRenames.Add(new EventMigrations.Rename(command.sequenceNumber, command.newName));
}
public class OrderShipCommandHandler : ICommandHandler<Order, Ship>
{
public async Task HandleScheduledCommandException(Order order, CommandFailed<Ship> command)
{
Debug.WriteLine("OrderShipCommandHandler.HandleScheduledCommandException");
if (command.Exception is CommandValidationException)
{
if (order.IsCancelled)
{
order.RecordEvent(new ShipmentCancelled());
}
if (order.IsShipped)
{
command.Cancel();
}
}
}
public async Task EnactCommand(Order order, Ship command)
{
Debug.WriteLine("OrderShipCommandHandler.EnactCommand");
order.RecordEvent(new Shipped
{
ShipmentId = command.ShipmentId
});
}
}
public void EnactCommand(ConfirmPayment command)
{
RecordEvent(new PaymentConfirmed
{
PaymentId = command.PaymentId
});
}
public class ChargeAccountHandler : ICommandHandler<Order, ChargeAccount>
{
private readonly IPaymentService paymentService;
public ChargeAccountHandler(IPaymentService paymentService)
{
if (paymentService == null)
{
throw new ArgumentNullException("paymentService");
}
this.paymentService = paymentService;
}
public async Task EnactCommand(Order aggregate, ChargeAccount command)
{
try
{
var paymentId = await paymentService.Charge(aggregate.Balance);
aggregate.RecordEvent(new PaymentConfirmed
{
PaymentId = paymentId
});
}
catch (InvalidOperationException)
{
aggregate.RecordEvent(new ChargeAccountChargeRejected());
}
}
public async Task HandleScheduledCommandException(Order order, CommandFailed<ChargeAccount> command)
{
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Text;
namespace System.IO
{
public sealed partial class DriveInfo
{
private static string NormalizeDriveName(string driveName)
{
Debug.Assert(driveName != null);
string name;
if (driveName.Length == 1)
name = driveName + ":\\";
else
{
// GetPathRoot does not check all invalid characters
if (PathInternal.HasIllegalCharacters(driveName))
throw new ArgumentException(SR.Format(SR.Arg_InvalidDriveChars, driveName), "driveName");
name = Path.GetPathRoot(driveName);
// Disallow null or empty drive letters and UNC paths
if (name == null || name.Length == 0 || name.StartsWith("\\\\", StringComparison.Ordinal))
throw new ArgumentException(SR.Arg_MustBeDriveLetterOrRootDir);
}
// We want to normalize to have a trailing backslash so we don't have two equivalent forms and
// because some Win32 API don't work without it.
if (name.Length == 2 && name[1] == ':')
{
name = name + "\\";
}
// Now verify that the drive letter could be a real drive name.
// On Windows this means it's between A and Z, ignoring case.
char letter = driveName[0];
if (!((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z')))
throw new ArgumentException(SR.Arg_MustBeDriveLetterOrRootDir);
return name;
}
public DriveType DriveType
{
[System.Security.SecuritySafeCritical]
get
{
// GetDriveType can't fail
return (DriveType)Interop.mincore.GetDriveType(Name);
}
}
public String DriveFormat
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
const int volNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
const int fileSystemNameLen = 50;
StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
int serialNumber, maxFileNameLen, fileSystemFlags;
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.mincore.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
if (!r)
{
throw Error.GetExceptionForLastWin32DriveError(Name);
}
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
return fileSystemName.ToString();
}
}
public long AvailableFreeSpace
{
[System.Security.SecuritySafeCritical]
get
{
long userBytes, totalBytes, freeBytes;
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.mincore.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
throw Error.GetExceptionForLastWin32DriveError(Name);
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
return userBytes;
}
}
public long TotalFreeSpace
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
long userBytes, totalBytes, freeBytes;
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.mincore.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
throw Error.GetExceptionForLastWin32DriveError(Name);
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
return freeBytes;
}
}
public long TotalSize
{
[System.Security.SecuritySafeCritical]
get
{
// Don't cache this, to handle variable sized floppy drives
// or other various removable media drives.
long userBytes, totalBytes, freeBytes;
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.mincore.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
throw Error.GetExceptionForLastWin32DriveError(Name);
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
return totalBytes;
}
}
public static DriveInfo[] GetDrives()
{
int drives = Interop.mincore.GetLogicalDrives();
if (drives == 0)
throw Win32Marshal.GetExceptionForLastWin32Error();
// GetLogicalDrives returns a bitmask starting from
// position 0 "A" indicating whether a drive is present.
// Loop over each bit, creating a DriveInfo for each one
// that is set.
uint d = (uint)drives;
int count = 0;
while (d != 0)
{
if (((int)d & 1) != 0) count++;
d >>= 1;
}
DriveInfo[] result = new DriveInfo[count];
char[] root = new char[] { 'A', ':', '\\' };
d = (uint)drives;
count = 0;
while (d != 0)
{
if (((int)d & 1) != 0)
{
result[count++] = new DriveInfo(new String(root));
}
d >>= 1;
root[0]++;
}
return result;
}
// Null is a valid volume label.
public String VolumeLabel
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
// NTFS uses a limit of 32 characters for the volume label,
// as of Windows Server 2003.
const int volNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
const int fileSystemNameLen = 50;
StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
int serialNumber, maxFileNameLen, fileSystemFlags;
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.mincore.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
// Win9x appears to return ERROR_INVALID_DATA when a
// drive doesn't exist.
if (errorCode == Interop.mincore.Errors.ERROR_INVALID_DATA)
errorCode = Interop.mincore.Errors.ERROR_INVALID_DRIVE;
throw Error.GetExceptionForWin32DriveError(errorCode, Name);
}
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
return volumeName.ToString();
}
[System.Security.SecuritySafeCritical] // auto-generated
set
{
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.mincore.SetVolumeLabel(Name, value);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
// Provide better message
if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED)
throw new UnauthorizedAccessException(SR.InvalidOperation_SetVolumeLabelFailed);
throw Error.GetExceptionForWin32DriveError(errorCode, Name);
}
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
}
}
}
}
| |
// 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.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using ZErrorCode = System.IO.Compression.ZLibNative.ErrorCode;
using ZFlushCode = System.IO.Compression.ZLibNative.FlushCode;
namespace System.IO.Compression
{
/// <summary>
/// Provides a wrapper around the ZLib compression API
/// </summary>
internal sealed class Deflater : IDisposable
{
private ZLibNative.ZLibStreamHandle _zlibStream;
private GCHandle _inputBufferHandle;
private bool _isDisposed;
private const int minWindowBits = -15; // WindowBits must be between -8..-15 to write no header, 8..15 for a
private const int maxWindowBits = 31; // zlib header, or 24..31 for a GZip header
// Note, DeflateStream or the deflater do not try to be thread safe.
// The lock is just used to make writing to unmanaged structures atomic to make sure
// that they do not get inconsistent fields that may lead to an unmanaged memory violation.
// To prevent *managed* buffer corruption or other weird behaviour users need to synchronise
// on the stream explicitly.
private readonly object _syncLock = new object();
#region exposed members
internal Deflater(CompressionLevel compressionLevel, int windowBits)
{
Debug.Assert(windowBits >= minWindowBits && windowBits <= maxWindowBits);
ZLibNative.CompressionLevel zlibCompressionLevel;
int memLevel;
switch (compressionLevel)
{
// See the note in ZLibNative.CompressionLevel for the recommended combinations.
case CompressionLevel.Optimal:
zlibCompressionLevel = ZLibNative.CompressionLevel.DefaultCompression;
memLevel = ZLibNative.Deflate_DefaultMemLevel;
break;
case CompressionLevel.Fastest:
zlibCompressionLevel = ZLibNative.CompressionLevel.BestSpeed;
memLevel = ZLibNative.Deflate_DefaultMemLevel;
break;
case CompressionLevel.NoCompression:
zlibCompressionLevel = ZLibNative.CompressionLevel.NoCompression;
memLevel = ZLibNative.Deflate_NoCompressionMemLevel;
break;
default:
throw new ArgumentOutOfRangeException(nameof(compressionLevel));
}
ZLibNative.CompressionStrategy strategy = ZLibNative.CompressionStrategy.DefaultStrategy;
DeflateInit(zlibCompressionLevel, windowBits, memLevel, strategy);
}
~Deflater()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[SecuritySafeCritical]
private void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
_zlibStream.Dispose();
if (_inputBufferHandle.IsAllocated)
DeallocateInputBufferHandle();
_isDisposed = true;
}
}
public bool NeedsInput()
{
return 0 == _zlibStream.AvailIn;
}
internal void SetInput(byte[] inputBuffer, int startIndex, int count)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(null != inputBuffer);
Debug.Assert(startIndex >= 0 && count >= 0 && count + startIndex <= inputBuffer.Length);
Debug.Assert(!_inputBufferHandle.IsAllocated);
if (0 == count)
return;
lock (_syncLock)
{
_inputBufferHandle = GCHandle.Alloc(inputBuffer, GCHandleType.Pinned);
_zlibStream.NextIn = _inputBufferHandle.AddrOfPinnedObject() + startIndex;
_zlibStream.AvailIn = (uint)count;
}
}
internal int GetDeflateOutput(byte[] outputBuffer)
{
Contract.Ensures(Contract.Result<int>() >= 0 && Contract.Result<int>() <= outputBuffer.Length);
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(!NeedsInput(), "GetDeflateOutput should only be called after providing input");
Debug.Assert(_inputBufferHandle.IsAllocated);
try
{
int bytesRead;
ReadDeflateOutput(outputBuffer, ZFlushCode.NoFlush, out bytesRead);
return bytesRead;
}
finally
{
// Before returning, make sure to release input buffer if necessary:
if (0 == _zlibStream.AvailIn && _inputBufferHandle.IsAllocated)
DeallocateInputBufferHandle();
}
}
private unsafe ZErrorCode ReadDeflateOutput(byte[] outputBuffer, ZFlushCode flushCode, out int bytesRead)
{
lock (_syncLock)
{
fixed (byte* bufPtr = outputBuffer)
{
_zlibStream.NextOut = (IntPtr)bufPtr;
_zlibStream.AvailOut = (uint)outputBuffer.Length;
ZErrorCode errC = Deflate(flushCode);
bytesRead = outputBuffer.Length - (int)_zlibStream.AvailOut;
return errC;
}
}
}
internal bool Finish(byte[] outputBuffer, out int bytesRead)
{
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!");
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(!_inputBufferHandle.IsAllocated);
// Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn.
// If there is still input left we should never be getting here; instead we
// should be calling GetDeflateOutput.
ZErrorCode errC = ReadDeflateOutput(outputBuffer, ZFlushCode.Finish, out bytesRead);
return errC == ZErrorCode.StreamEnd;
}
/// <summary>
/// Returns true if there was something to flush. Otherwise False.
/// </summary>
internal bool Flush(byte[] outputBuffer, out int bytesRead)
{
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!");
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(!_inputBufferHandle.IsAllocated);
// Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn.
// If there is still input left we should never be getting here; instead we
// should be calling GetDeflateOutput.
return ReadDeflateOutput(outputBuffer, ZFlushCode.SyncFlush, out bytesRead) == ZErrorCode.Ok;
}
#endregion
#region helpers & native call wrappers
private void DeallocateInputBufferHandle()
{
Debug.Assert(_inputBufferHandle.IsAllocated);
lock (_syncLock)
{
_zlibStream.AvailIn = 0;
_zlibStream.NextIn = ZLibNative.ZNullPtr;
_inputBufferHandle.Free();
}
}
[SecuritySafeCritical]
private void DeflateInit(ZLibNative.CompressionLevel compressionLevel, int windowBits, int memLevel,
ZLibNative.CompressionStrategy strategy)
{
ZErrorCode errC;
try
{
errC = ZLibNative.CreateZLibStreamForDeflate(out _zlibStream, compressionLevel,
windowBits, memLevel, strategy);
}
catch (Exception cause)
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
}
switch (errC)
{
case ZErrorCode.Ok:
return;
case ZErrorCode.MemError:
throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
case ZErrorCode.VersionError:
throw new ZLibException(SR.ZLibErrorVersionMismatch, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
case ZErrorCode.StreamError:
throw new ZLibException(SR.ZLibErrorIncorrectInitParameters, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
}
}
[SecuritySafeCritical]
private ZErrorCode Deflate(ZFlushCode flushCode)
{
ZErrorCode errC;
try
{
errC = _zlibStream.Deflate(flushCode);
}
catch (Exception cause)
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
}
switch (errC)
{
case ZErrorCode.Ok:
case ZErrorCode.StreamEnd:
return errC;
case ZErrorCode.BufError:
return errC; // This is a recoverable error
case ZErrorCode.StreamError:
throw new ZLibException(SR.ZLibErrorInconsistentStream, "deflate", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "deflate", (int)errC, _zlibStream.GetErrorMessage());
}
}
#endregion
}
}
| |
#region license
// Copyright (c) 2004, 2005, 2006, 2007 Rodrigo B. de Oliveira ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Boo.Lang.Compiler.Ast;
using System.Collections.Generic;
using System;
using System.Linq;
using Boo.Lang.Compiler.TypeSystem.Core;
namespace Boo.Lang.Compiler.TypeSystem.Generics
{
public class GenericsServices : AbstractCompilerComponent
{
public GenericsServices() : base(CompilerContext.Current)
{
}
/// <summary>
/// Constructs an entity from a generic definition and arguments, after ensuring the construction is valid.
/// </summary>
/// <param name="definition">The generic definition entity.</param>
/// <param name="constructionNode">The node in which construction occurs.</param>
/// <param name="typeArguments">The generic type arguments to substitute for generic parameters.</param>
/// <returns>The constructed entity.</returns>
public IEntity ConstructEntity(Node constructionNode, IEntity definition, IType[] typeArguments)
{
// Ensure definition is a valid entity
if (definition == null || TypeSystemServices.IsError(definition))
{
return TypeSystemServices.ErrorEntity;
}
// Ambiguous generic constructions are handled separately
if (definition.IsAmbiguous())
{
return ConstructAmbiguousEntity(constructionNode, (Ambiguous)definition, typeArguments);
}
// Check that the construction is valid
if (!CheckGenericConstruction(constructionNode, definition, typeArguments, true))
{
return TypeSystemServices.ErrorEntity;
}
return MakeGenericEntity(definition, typeArguments);
}
/// <summary>
/// Validates and constructs generic entities out of an ambiguous generic definition entity.
/// </summary>
private IEntity ConstructAmbiguousEntity(Node constructionNode, Ambiguous ambiguousDefinition, IType[] typeArguments)
{
var checker = new GenericConstructionChecker(typeArguments, constructionNode);
var matches = new List<IEntity>(ambiguousDefinition.Entities);
bool reportErrors = false;
foreach (Predicate<IEntity> check in checker.Checks)
{
matches = matches.Collect(check);
if (matches.Count == 0)
{
Errors.Add(checker.Errors[0]); // only report first error, assuming the rest are superfluous
return TypeSystemServices.ErrorEntity;
}
if (reportErrors)
checker.ReportErrors(Errors);
checker.DiscardErrors();
// We only want full error reporting once we get down to a single candidate
if (matches.Count == 1)
reportErrors = true;
}
IEntity[] constructedMatches = Array.ConvertAll<IEntity, IEntity>(matches.ToArray(), def => MakeGenericEntity(def, typeArguments));
return Entities.EntityFromList(constructedMatches);
}
private IEntity MakeGenericEntity(IEntity definition, IType[] typeArguments)
{
if (IsGenericType(definition))
return ((IType)definition).GenericInfo.ConstructType(typeArguments);
if (IsGenericMethod(definition))
return ((IMethod)definition).GenericInfo.ConstructMethod(typeArguments);
// Should never be reached
return TypeSystemServices.ErrorEntity;
}
/// <summary>
/// Checks whether a given set of arguments can be used to construct a generic type or method from a specified definition.
/// </summary>
public bool CheckGenericConstruction(IEntity definition, IType[] typeArguments)
{
return CheckGenericConstruction(null, definition, typeArguments, false);
}
/// <summary>
/// Checks whether a given set of arguments can be used to construct a generic type or method from a specified definition.
/// </summary>
public bool CheckGenericConstruction(Node node, IEntity definition, IType[] typeArguments, bool reportErrors)
{
var checker = new GenericConstructionChecker(typeArguments, node);
foreach (Predicate<IEntity> check in checker.Checks)
{
if (check(definition)) continue;
if (reportErrors) checker.ReportErrors(Errors);
return false;
}
return true;
}
/// <summary>
/// Attempts to infer the generic parameters of a method from a set of arguments.
/// </summary>
/// <returns>
/// An array consisting of inferred types for the method's generic arguments,
/// or null if type inference failed.
/// </returns>
public IType[] InferMethodGenericArguments(IMethod method, ExpressionCollection arguments)
{
if (method.GenericInfo == null) return null;
GenericParameterInferrer inferrerr = new GenericParameterInferrer(Context, method, arguments);
if (inferrerr.Run())
{
return inferrerr.GetInferredTypes();
}
return null;
}
public static bool IsGenericMethod(IEntity entity)
{
IMethod method = entity as IMethod;
return (method != null && method.GenericInfo != null);
}
public static bool IsGenericType(IEntity entity)
{
IType type = entity as IType;
return (type != null && type.GenericInfo != null);
}
public static bool IsGenericParameter(IEntity entity)
{
return (entity is IGenericParameter);
}
public static bool AreOfSameGenerity(IMethod lhs, IMethod rhs)
{
return (GetMethodGenerity(lhs) == GetMethodGenerity(rhs));
}
/// <summary>
/// Yields the generic parameters used in a (bound) type.
/// </summary>
public static IEnumerable<IGenericParameter> FindGenericParameters(IType type)
{
IGenericParameter genericParameter = type as IGenericParameter;
if (genericParameter != null)
{
yield return genericParameter;
yield break;
}
if (type is IArrayType)
{
foreach (IGenericParameter gp in FindGenericParameters(type.ElementType)) yield return gp;
yield break;
}
if (type.ConstructedInfo != null)
{
foreach (IType typeArgument in type.ConstructedInfo.GenericArguments)
{
foreach (IGenericParameter gp in FindGenericParameters(typeArgument)) yield return gp;
}
yield break;
}
ICallableType callableType = type as ICallableType;
if (callableType != null)
{
CallableSignature signature = callableType.GetSignature();
foreach (IGenericParameter gp in FindGenericParameters(signature.ReturnType)) yield return gp;
foreach (IParameter parameter in signature.Parameters)
{
foreach (IGenericParameter gp in FindGenericParameters(parameter.Type)) yield return gp;
}
yield break;
}
}
/// <summary>
/// Finds types constructed from the specified definition in the specified type's interfaces and base types.
/// </summary>
/// <param name="type">The type in whose hierarchy to search for constructed types.</param>
/// <param name="definition">The generic type definition whose constructed versions to search for.</param>
/// <returns>Yields the matching types.</returns>
public static IEnumerable<IType> FindConstructedTypes(IType type, IType definition)
{
while (type != null)
{
if (type.ConstructedInfo != null &&
type.ConstructedInfo.GenericDefinition == definition)
{
yield return type;
}
IType[] interfaces = type.GetInterfaces();
if (interfaces != null)
{
foreach (IType interfaceType in interfaces)
{
foreach (IType match in FindConstructedTypes(interfaceType, definition))
{
yield return match;
}
}
}
type = type.BaseType;
}
}
/// <summary>
/// Finds a single constructed occurance of a specified generic definition
/// in the specified type's inheritence hierarchy.
/// </summary>
/// <param name="type">The type in whose hierarchy to search for constructed types.</param>
/// <param name="definition">The generic type definition whose constructed versions to search for.</param>
/// <returns>
/// The single constructed occurance of the generic definition in the
/// specified type, or null if there are none or more than one.
/// </returns>
public static IType FindConstructedType(IType type, IType definition)
{
IType result = null;
foreach (IType candidate in FindConstructedTypes(type, definition))
{
if (result == null) result = candidate;
else if (result != candidate) return null;
}
return result;
}
/// <summary>
/// Checks that at least one constructed occurence of a specified generic
/// definition is present in the specified type's inheritance hierarchy.
/// </summary>
/// <param name="type">The type in whose hierarchy to search for constructed type.</param>
/// <param name="definition">The generic type definition whose constructed versions to search for.</param>
/// <returns>
/// True if a occurence has been found, False otherwise.
/// </returns>
public static bool HasConstructedType(IType type, IType definition)
{
return FindConstructedTypes(type, definition).GetEnumerator().MoveNext();
}
/// <summary>
/// Determines whether a specified type is an open generic type -
/// that is, if it contains generic parameters.
/// </summary>
public static bool IsOpenGenericType(IType type)
{
return (GetTypeGenerity(type) != 0);
}
/// <summary>
/// Gets the generic parameters associated with a generic type or generic method definition.
/// </summary>
/// <returns>An array of IGenericParameter objects, or null if the specified entity isn't a generic definition.</returns>
public static IGenericParameter[] GetGenericParameters(IEntity definition)
{
if (IsGenericType(definition))
return ((IType) definition).GenericInfo.GenericParameters;
if (IsGenericMethod(definition))
return ((IMethod) definition).GenericInfo.GenericParameters;
return null;
}
public static int GetTypeConcreteness(IType type)
{
if (type.IsByRef || type.IsArray)
return GetTypeConcreteness(type.ElementType);
if (type is IGenericParameter)
return 0;
if (type.ConstructedInfo != null)
{
var result = 0;
foreach (IType typeArg in type.ConstructedInfo.GenericArguments)
result += GetTypeConcreteness(typeArg);
return result;
}
return 1;
}
/// <summary>
/// Determines the number of open generic parameters in the specified type.
/// </summary>
public static int GetTypeGenerity(IType type)
{
if (type.IsByRef || type.IsArray)
return GetTypeGenerity(type.ElementType);
if (type is IGenericParameter)
return 1;
// Generic parameters and generic arguments both contribute
// to a types genrity. Note that a nested type can be both a generic definition
// and a constructed type: Outer[of int].Inner[of T]
int generity = 0;
if (type.GenericInfo != null)
generity += type.GenericInfo.GenericParameters.Length;
if (type.ConstructedInfo != null)
foreach (IType typeArg in type.ConstructedInfo.GenericArguments)
generity += GetTypeGenerity(typeArg);
return generity;
}
/// <summary>
/// Determines the number of total generic parameters in the specified type.
/// </summary>
public static int GetTypeGenericDepth(IType type)
{
if (type.IsByRef || type.IsArray)
return GetTypeGenericDepth(type.ElementType);
if (type is IGenericParameter)
return 1;
// Generic parameters and generic arguments both contribute
// to a types genrity. Note that a nested type can be both a generic definition
// and a constructed type: Outer[of int].Inner[of T]
int generity = 0;
if (type.GenericInfo != null)
generity += type.GenericInfo.GenericParameters.Length;
if (type.ConstructedInfo != null)
foreach (IType typeArg in type.ConstructedInfo.GenericArguments)
generity += GetTypeGenericDepth(typeArg) + 1;
return generity;
}
public static int GetMethodGenerity(IMethod method)
{
IConstructedMethodInfo constructedInfo = method.ConstructedInfo;
if (constructedInfo != null)
return constructedInfo.GenericArguments.Length;
IGenericMethodInfo genericInfo = method.GenericInfo;
if (genericInfo != null)
return genericInfo.GenericParameters.Length;
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 Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Principal;
using System.Diagnostics.Contracts;
namespace System.Security.AccessControl
{
internal static class Win32
{
//
// Wrapper around advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW
//
internal static int ConvertSdToSddl(
byte[] binaryForm,
int requestedRevision,
SecurityInfos si,
out string resultSddl)
{
int errorCode;
IntPtr ByteArray;
uint ByteArraySize = 0;
if (!Interop.mincore.ConvertSdToStringSd(binaryForm, (uint)requestedRevision, (uint)si, out ByteArray, ref ByteArraySize))
{
errorCode = Marshal.GetLastWin32Error();
goto Error;
}
//
// Extract data from the returned pointer
//
resultSddl = Marshal.PtrToStringUni(ByteArray);
//
// Now is a good time to get rid of the returned pointer
//
Interop.mincore_obsolete.LocalFree(ByteArray);
return 0;
Error:
resultSddl = null;
if (errorCode == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
return errorCode;
}
//
// Wrapper around advapi32.GetSecurityInfo
//
internal static int GetSecurityInfo(
ResourceType resourceType,
string name,
SafeHandle handle,
AccessControlSections accessControlSections,
out RawSecurityDescriptor resultSd
)
{
resultSd = null;
int errorCode;
IntPtr SidOwner, SidGroup, Dacl, Sacl, ByteArray;
SecurityInfos SecurityInfos = 0;
Privilege privilege = null;
if ((accessControlSections & AccessControlSections.Owner) != 0)
{
SecurityInfos |= SecurityInfos.Owner;
}
if ((accessControlSections & AccessControlSections.Group) != 0)
{
SecurityInfos |= SecurityInfos.Group;
}
if ((accessControlSections & AccessControlSections.Access) != 0)
{
SecurityInfos |= SecurityInfos.DiscretionaryAcl;
}
if ((accessControlSections & AccessControlSections.Audit) != 0)
{
SecurityInfos |= SecurityInfos.SystemAcl;
privilege = new Privilege(Privilege.Security);
}
try
{
if (privilege != null)
{
try
{
privilege.Enable();
}
catch (PrivilegeNotHeldException)
{
// we will ignore this exception and press on just in case this is a remote resource
}
}
if (name != null)
{
errorCode = (int)Interop.mincore.GetSecurityInfoByName(name, (uint)resourceType, (uint)SecurityInfos, out SidOwner, out SidGroup, out Dacl, out Sacl, out ByteArray);
}
else if (handle != null)
{
if (handle.IsInvalid)
{
throw new ArgumentException(
SR.Argument_InvalidSafeHandle,
nameof(handle));
}
else
{
errorCode = (int)Interop.mincore.GetSecurityInfoByHandle(handle, (uint)resourceType, (uint)SecurityInfos, out SidOwner, out SidGroup, out Dacl, out Sacl, out ByteArray);
}
}
else
{
// both are null, shouldn't happen
// Changing from SystemException to ArgumentException as this code path is indicative of a null name argument
// as well as an accessControlSections argument with an audit flag
throw new ArgumentException();
}
if (errorCode == Interop.mincore.Errors.ERROR_SUCCESS && IntPtr.Zero.Equals(ByteArray))
{
//
// This means that the object doesn't have a security descriptor. And thus we throw
// a specific exception for the caller to catch and handle properly.
//
throw new InvalidOperationException(SR.InvalidOperation_NoSecurityDescriptor);
}
else if (errorCode == Interop.mincore.Errors.ERROR_NOT_ALL_ASSIGNED ||
errorCode == Interop.mincore.Errors.ERROR_PRIVILEGE_NOT_HELD)
{
throw new PrivilegeNotHeldException(Privilege.Security);
}
else if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED ||
errorCode == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS)
{
throw new UnauthorizedAccessException();
}
if (errorCode != Interop.mincore.Errors.ERROR_SUCCESS)
{
goto Error;
}
}
catch
{
// protection against exception filter-based luring attacks
if (privilege != null)
{
privilege.Revert();
}
throw;
}
finally
{
if (privilege != null)
{
privilege.Revert();
}
}
//
// Extract data from the returned pointer
//
uint Length = Interop.mincore.GetSecurityDescriptorLength(ByteArray);
byte[] BinaryForm = new byte[Length];
Marshal.Copy(ByteArray, BinaryForm, 0, (int)Length);
Interop.mincore_obsolete.LocalFree(ByteArray);
resultSd = new RawSecurityDescriptor(BinaryForm, 0);
return Interop.mincore.Errors.ERROR_SUCCESS;
Error:
if (errorCode == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
return errorCode;
}
//
// Wrapper around advapi32.SetNamedSecurityInfoW and advapi32.SetSecurityInfo
//
internal static int SetSecurityInfo(
ResourceType type,
string name,
SafeHandle handle,
SecurityInfos securityInformation,
SecurityIdentifier owner,
SecurityIdentifier group,
GenericAcl sacl,
GenericAcl dacl)
{
int errorCode;
int Length;
byte[] OwnerBinary = null, GroupBinary = null, SaclBinary = null, DaclBinary = null;
Privilege securityPrivilege = null;
if (owner != null)
{
Length = owner.BinaryLength;
OwnerBinary = new byte[Length];
owner.GetBinaryForm(OwnerBinary, 0);
}
if (group != null)
{
Length = group.BinaryLength;
GroupBinary = new byte[Length];
group.GetBinaryForm(GroupBinary, 0);
}
if (dacl != null)
{
Length = dacl.BinaryLength;
DaclBinary = new byte[Length];
dacl.GetBinaryForm(DaclBinary, 0);
}
if (sacl != null)
{
Length = sacl.BinaryLength;
SaclBinary = new byte[Length];
sacl.GetBinaryForm(SaclBinary, 0);
}
if ((securityInformation & SecurityInfos.SystemAcl) != 0)
{
//
// Enable security privilege if trying to set a SACL.
// Note: even setting it by handle needs this privilege enabled!
//
securityPrivilege = new Privilege(Privilege.Security);
}
try
{
if (securityPrivilege != null)
{
try
{
securityPrivilege.Enable();
}
catch (PrivilegeNotHeldException)
{
// we will ignore this exception and press on just in case this is a remote resource
}
}
if (name != null)
{
errorCode = (int)Interop.mincore.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
}
else if (handle != null)
{
if (handle.IsInvalid)
{
throw new ArgumentException(
SR.Argument_InvalidSafeHandle,
nameof(handle));
}
else
{
errorCode = (int)Interop.mincore.SetSecurityInfoByHandle(handle, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
}
}
else
{
// both are null, shouldn't happen
Contract.Assert(false, "Internal error: both name and handle are null");
throw new ArgumentException();
}
if (errorCode == Interop.mincore.Errors.ERROR_NOT_ALL_ASSIGNED ||
errorCode == Interop.mincore.Errors.ERROR_PRIVILEGE_NOT_HELD)
{
throw new PrivilegeNotHeldException(Privilege.Security);
}
else if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED ||
errorCode == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS)
{
throw new UnauthorizedAccessException();
}
else if (errorCode != Interop.mincore.Errors.ERROR_SUCCESS)
{
goto Error;
}
}
catch
{
// protection against exception filter-based luring attacks
if (securityPrivilege != null)
{
securityPrivilege.Revert();
}
throw;
}
finally
{
if (securityPrivilege != null)
{
securityPrivilege.Revert();
}
}
return 0;
Error:
if (errorCode == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
return errorCode;
}
}
}
| |
/*****************************************************************************
* *
* OpenNI 1.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OpenNI;
using System.Threading;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
namespace UserTracker.net
{
public partial class MainWindow : Form
{
public MainWindow()
{
InitializeComponent();
this.context = Context.CreateFromXmlFile(SAMPLE_XML_FILE, out scriptNode);
this.depth = context.FindExistingNode(NodeType.Depth) as DepthGenerator;
if (this.depth == null)
{
throw new Exception("Viewer must have a depth node!");
}
this.userGenerator = new UserGenerator(this.context);
this.skeletonCapbility = this.userGenerator.SkeletonCapability;
this.poseDetectionCapability = this.userGenerator.PoseDetectionCapability;
this.calibPose = this.skeletonCapbility.CalibrationPose;
this.userGenerator.NewUser += userGenerator_NewUser;
this.userGenerator.LostUser += userGenerator_LostUser;
this.poseDetectionCapability.PoseDetected += poseDetectionCapability_PoseDetected;
this.skeletonCapbility.CalibrationComplete += skeletonCapbility_CalibrationComplete;
this.skeletonCapbility.SetSkeletonProfile(SkeletonProfile.All);
this.joints = new Dictionary<int,Dictionary<SkeletonJoint,SkeletonJointPosition>>();
this.userGenerator.StartGenerating();
this.histogram = new int[this.depth.DeviceMaxDepth];
MapOutputMode mapMode = this.depth.MapOutputMode;
this.bitmap = new Bitmap((int)mapMode.XRes, (int)mapMode.YRes/*, System.Drawing.Imaging.PixelFormat.Format24bppRgb*/);
this.shouldRun = true;
this.readerThread = new Thread(ReaderThread);
this.readerThread.Start();
}
void skeletonCapbility_CalibrationComplete(object sender, CalibrationProgressEventArgs e)
{
if (e.Status == CalibrationStatus.OK)
{
this.skeletonCapbility.StartTracking(e.ID);
this.joints.Add(e.ID, new Dictionary<SkeletonJoint, SkeletonJointPosition>());
}
else if (e.Status != CalibrationStatus.ManualAbort)
{
if (this.skeletonCapbility.DoesNeedPoseForCalibration)
{
this.poseDetectionCapability.StartPoseDetection(calibPose, e.ID);
}
else
{
this.skeletonCapbility.RequestCalibration(e.ID, true);
}
}
}
void poseDetectionCapability_PoseDetected(object sender, PoseDetectedEventArgs e)
{
this.poseDetectionCapability.StopPoseDetection(e.ID);
this.skeletonCapbility.RequestCalibration(e.ID, true);
}
void userGenerator_NewUser(object sender, NewUserEventArgs e)
{
if (this.skeletonCapbility.DoesNeedPoseForCalibration)
{
this.poseDetectionCapability.StartPoseDetection(this.calibPose, e.ID);
}
else
{
this.skeletonCapbility.RequestCalibration(e.ID, true);
}
}
void userGenerator_LostUser(object sender, UserLostEventArgs e)
{
this.joints.Remove(e.ID);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
lock (this)
{
e.Graphics.DrawImage(this.bitmap,
this.panelView.Location.X,
this.panelView.Location.Y,
this.panelView.Size.Width,
this.panelView.Size.Height);
}
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
//Don't allow the background to paint
}
protected override void OnClosing(CancelEventArgs e)
{
this.shouldRun = false;
this.readerThread.Join();
base.OnClosing(e);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == 27)
{
Close();
}
switch (e.KeyChar)
{
case (char)27:
break;
case 'b':
this.shouldDrawBackground = !this.shouldDrawBackground;
break;
case 'x':
this.shouldDrawPixels = !this.shouldDrawPixels;
break;
case 's':
this.shouldDrawSkeleton = !this.shouldDrawSkeleton;
break;
case 'i':
this.shouldPrintID = !this.shouldPrintID;
break;
case 'l':
this.shouldPrintState = !this.shouldPrintState;
break;
}
base.OnKeyPress(e);
}
private unsafe void CalcHist(DepthMetaData depthMD)
{
// reset
for (int i = 0; i < this.histogram.Length; ++i)
this.histogram[i] = 0;
ushort* pDepth = (ushort*)depthMD.DepthMapPtr.ToPointer();
int points = 0;
for (int y = 0; y < depthMD.YRes; ++y)
{
for (int x = 0; x < depthMD.XRes; ++x, ++pDepth)
{
ushort depthVal = *pDepth;
if (depthVal != 0)
{
this.histogram[depthVal]++;
points++;
}
}
}
for (int i = 1; i < this.histogram.Length; i++)
{
this.histogram[i] += this.histogram[i-1];
}
if (points > 0)
{
for (int i = 1; i < this.histogram.Length; i++)
{
this.histogram[i] = (int)(256 * (1.0f - (this.histogram[i] / (float)points)));
}
}
}
private Color[] colors = { Color.Red, Color.Blue, Color.ForestGreen, Color.Yellow, Color.Orange, Color.Purple, Color.White };
private Color[] anticolors = { Color.Green, Color.Orange, Color.Red, Color.Purple, Color.Blue, Color.Yellow, Color.Black };
private int ncolors = 6;
private void GetJoint(int user, SkeletonJoint joint)
{
SkeletonJointPosition pos = this.skeletonCapbility.GetSkeletonJointPosition(user, joint);
if (pos.Position.Z == 0)
{
pos.Confidence = 0;
}
else
{
pos.Position = this.depth.ConvertRealWorldToProjective(pos.Position);
}
this.joints[user][joint] = pos;
}
private void GetJoints(int user)
{
GetJoint(user, SkeletonJoint.Head);
GetJoint(user, SkeletonJoint.Neck);
GetJoint(user, SkeletonJoint.LeftShoulder);
GetJoint(user, SkeletonJoint.LeftElbow);
GetJoint(user, SkeletonJoint.LeftHand);
GetJoint(user, SkeletonJoint.RightShoulder);
GetJoint(user, SkeletonJoint.RightElbow);
GetJoint(user, SkeletonJoint.RightHand);
GetJoint(user, SkeletonJoint.Torso);
GetJoint(user, SkeletonJoint.LeftHip);
GetJoint(user, SkeletonJoint.LeftKnee);
GetJoint(user, SkeletonJoint.LeftFoot);
GetJoint(user, SkeletonJoint.RightHip);
GetJoint(user, SkeletonJoint.RightKnee);
GetJoint(user, SkeletonJoint.RightFoot);
}
private void DrawLine(Graphics g, Color color, Dictionary<SkeletonJoint, SkeletonJointPosition> dict, SkeletonJoint j1, SkeletonJoint j2)
{
Point3D pos1 = dict[j1].Position;
Point3D pos2 = dict[j2].Position;
if (dict[j1].Confidence == 0 || dict[j2].Confidence == 0)
return;
g.DrawLine(new Pen(color),
new Point((int)pos1.X, (int)pos1.Y),
new Point((int)pos2.X, (int)pos2.Y));
}
private void DrawSkeleton(Graphics g, Color color, int user)
{
GetJoints(user);
Dictionary<SkeletonJoint, SkeletonJointPosition> dict = this.joints[user];
DrawLine(g, color, dict, SkeletonJoint.Head, SkeletonJoint.Neck);
DrawLine(g, color, dict, SkeletonJoint.LeftShoulder, SkeletonJoint.Torso);
DrawLine(g, color, dict, SkeletonJoint.RightShoulder, SkeletonJoint.Torso);
DrawLine(g, color, dict, SkeletonJoint.Neck, SkeletonJoint.LeftShoulder);
DrawLine(g, color, dict, SkeletonJoint.LeftShoulder, SkeletonJoint.LeftElbow);
DrawLine(g, color, dict, SkeletonJoint.LeftElbow, SkeletonJoint.LeftHand);
DrawLine(g, color, dict, SkeletonJoint.Neck, SkeletonJoint.RightShoulder);
DrawLine(g, color, dict, SkeletonJoint.RightShoulder, SkeletonJoint.RightElbow);
DrawLine(g, color, dict, SkeletonJoint.RightElbow, SkeletonJoint.RightHand);
DrawLine(g, color, dict, SkeletonJoint.LeftHip, SkeletonJoint.Torso);
DrawLine(g, color, dict, SkeletonJoint.RightHip, SkeletonJoint.Torso);
DrawLine(g, color, dict, SkeletonJoint.LeftHip, SkeletonJoint.RightHip);
DrawLine(g, color, dict, SkeletonJoint.LeftHip, SkeletonJoint.LeftKnee);
DrawLine(g, color, dict, SkeletonJoint.LeftKnee, SkeletonJoint.LeftFoot);
DrawLine(g, color, dict, SkeletonJoint.RightHip, SkeletonJoint.RightKnee);
DrawLine(g, color, dict, SkeletonJoint.RightKnee, SkeletonJoint.RightFoot);
}
private unsafe void ReaderThread()
{
DepthMetaData depthMD = new DepthMetaData();
while (this.shouldRun)
{
try
{
this.context.WaitOneUpdateAll(this.depth);
}
catch (Exception)
{
}
this.depth.GetMetaData(depthMD);
CalcHist(depthMD);
lock (this)
{
Rectangle rect = new Rectangle(0, 0, this.bitmap.Width, this.bitmap.Height);
BitmapData data = this.bitmap.LockBits(rect, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
if (this.shouldDrawPixels)
{
ushort* pDepth = (ushort*)this.depth.DepthMapPtr.ToPointer();
ushort* pLabels = (ushort*)this.userGenerator.GetUserPixels(0).LabelMapPtr.ToPointer();
// set pixels
for (int y = 0; y < depthMD.YRes; ++y)
{
byte* pDest = (byte*)data.Scan0.ToPointer() + y * data.Stride;
for (int x = 0; x < depthMD.XRes; ++x, ++pDepth, ++pLabels, pDest += 3)
{
pDest[0] = pDest[1] = pDest[2] = 0;
ushort label = *pLabels;
if (this.shouldDrawBackground || *pLabels != 0)
{
Color labelColor = Color.White;
if (label != 0)
{
labelColor = colors[label % ncolors];
}
byte pixel = (byte)this.histogram[*pDepth];
pDest[0] = (byte)(pixel * (labelColor.B / 256.0));
pDest[1] = (byte)(pixel * (labelColor.G / 256.0));
pDest[2] = (byte)(pixel * (labelColor.R / 256.0));
}
}
}
}
this.bitmap.UnlockBits(data);
Graphics g = Graphics.FromImage(this.bitmap);
int[] users = this.userGenerator.GetUsers();
foreach (int user in users)
{
if (this.shouldPrintID)
{
Point3D com = this.userGenerator.GetCoM(user);
com = this.depth.ConvertRealWorldToProjective(com);
string label = "";
if (!this.shouldPrintState)
label += user;
else if (this.skeletonCapbility.IsTracking(user))
label += user + " - Tracking";
else if (this.skeletonCapbility.IsCalibrating(user))
label += user + " - Calibrating...";
else
label += user + " - Looking for pose";
g.DrawString(label, new Font("Arial", 6), new SolidBrush(anticolors[user % ncolors]), com.X, com.Y);
}
if (this.shouldDrawSkeleton && this.skeletonCapbility.IsTracking(user))
// if (this.skeletonCapbility.IsTracking(user))
DrawSkeleton(g, anticolors[user % ncolors], user);
}
g.Dispose();
}
this.Invalidate();
}
}
private readonly string SAMPLE_XML_FILE = @"../../../../Data/SamplesConfig.xml";
private Context context;
private ScriptNode scriptNode;
private DepthGenerator depth;
private UserGenerator userGenerator;
private SkeletonCapability skeletonCapbility;
private PoseDetectionCapability poseDetectionCapability;
private string calibPose;
private Thread readerThread;
private bool shouldRun;
private Bitmap bitmap;
private int[] histogram;
private Dictionary<int, Dictionary<SkeletonJoint, SkeletonJointPosition>> joints;
private bool shouldDrawPixels = true;
private bool shouldDrawBackground = true;
private bool shouldPrintID = true;
private bool shouldPrintState = true;
private bool shouldDrawSkeleton = true;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web;
using Funq;
using ServiceStack.Common.Utils;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
namespace ServiceStack.WebHost.Endpoints.Extensions
{
public class HttpRequestWrapper
: IHttpRequest
{
private static readonly string physicalFilePath;
public Container Container { get; set; }
private readonly HttpRequest request;
static HttpRequestWrapper()
{
physicalFilePath = "~".MapHostAbsolutePath();
}
public HttpRequest Request
{
get { return request; }
}
public object OriginalRequest
{
get { return request; }
}
public HttpRequestWrapper(HttpRequest request)
: this(null, request)
{
}
public HttpRequestWrapper(string operationName, HttpRequest request)
{
this.OperationName = operationName;
this.request = request;
this.Container = Container;
}
public T TryResolve<T>()
{
return Container == null
? EndpointHost.AppHost.TryResolve<T>()
: Container.TryResolve<T>();
}
public string OperationName { get; set; }
public string ContentType
{
get { return request.ContentType; }
}
private string httpMethod;
public string HttpMethod
{
get { return httpMethod
?? (httpMethod = request.Headers[HttpHeaders.XHttpMethodOverride] ?? request.HttpMethod);
}
}
public string UserAgent
{
get { return request.UserAgent; }
}
private Dictionary<string, object> items;
public Dictionary<string, object> Items
{
get
{
if (items == null)
{
items = new Dictionary<string, object>();
}
return items;
}
}
private string responseContentType;
public string ResponseContentType
{
get
{
if (responseContentType == null)
{
responseContentType = this.GetResponseContentType();
}
return responseContentType;
}
set
{
this.responseContentType = value;
}
}
private Dictionary<string, Cookie> cookies;
public IDictionary<string, Cookie> Cookies
{
get
{
if (cookies == null)
{
cookies = new Dictionary<string, Cookie>();
for (var i = 0; i < this.request.Cookies.Count; i++)
{
var httpCookie = this.request.Cookies[i];
var cookie = new Cookie(
httpCookie.Name, httpCookie.Value, httpCookie.Path, httpCookie.Domain)
{
HttpOnly = httpCookie.HttpOnly,
Secure = httpCookie.Secure,
Expires = httpCookie.Expires,
};
cookies[httpCookie.Name] = cookie;
}
}
return cookies;
}
}
public NameValueCollection Headers
{
get { return request.Headers; }
}
public NameValueCollection QueryString
{
get { return request.QueryString; }
}
public NameValueCollection FormData
{
get { return request.Form; }
}
public string GetRawBody()
{
using (var reader = new StreamReader(request.InputStream))
{
return reader.ReadToEnd();
}
}
public string RawUrl
{
get { return request.RawUrl; }
}
public string AbsoluteUri
{
get
{
try
{
return request.Url.AbsoluteUri.TrimEnd('/');
}
catch (Exception)
{
//fastcgi mono, do a 2nd rounds best efforts
return "http://" + request.UserHostName + request.RawUrl;
}
}
}
public string UserHostAddress
{
get { return request.UserHostAddress; }
}
private string remoteIp;
public string RemoteIp
{
get
{
return remoteIp ?? (remoteIp = request.Headers[HttpHeaders.XForwardedFor] ?? (request.Headers[HttpHeaders.XRealIp] ?? request.UserHostAddress));
}
}
public bool IsSecureConnection
{
get { return request.IsSecureConnection; }
}
public string[] AcceptTypes
{
get { return request.AcceptTypes; }
}
public string PathInfo
{
get { return request.GetPathInfo(); }
}
public string UrlHostName
{
get { return request.GetUrlHostName(); }
}
public Stream InputStream
{
get { return request.InputStream; }
}
public long ContentLength
{
get { return request.ContentLength; }
}
private IFile[] files;
public IFile[] Files
{
get
{
if (files == null)
{
files = new IFile[request.Files.Count];
for (var i = 0; i < request.Files.Count; i++)
{
var reqFile = request.Files[i];
files[i] = new HttpFile
{
ContentType = reqFile.ContentType,
ContentLength = reqFile.ContentLength,
FileName = reqFile.FileName,
InputStream = reqFile.InputStream,
};
}
}
return files;
}
}
public string ApplicationFilePath
{
get { return physicalFilePath; }
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security.Cryptography; // for computing md5 hash
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType;
using Ionic.Zlib;
// You will need to uncomment these lines if you are adding a region module to some other assembly which does not already
// specify its assembly. Otherwise, the region modules in the assembly will not be picked up when OpenSimulator scans
// the available DLLs
//[assembly: Addin("MaterialsModule", "1.0")]
//[assembly: AddinDependency("OpenSim", "0.8.1")]
namespace OpenSim.Region.OptionalModules.Materials
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MaterialsModule")]
public class MaterialsModule : INonSharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Name { get { return "MaterialsModule"; } }
public Type ReplaceableInterface { get { return null; } }
private Scene m_scene = null;
private bool m_enabled = false;
public Dictionary<UUID, OSDMap> m_regionMaterials = new Dictionary<UUID, OSDMap>();
public void Initialise(IConfigSource source)
{
m_enabled = true; // default is enabled
IConfig config = source.Configs["Materials"];
if (config != null)
m_enabled = config.GetBoolean("enable_materials", m_enabled);
if (m_enabled)
m_log.DebugFormat("[Materials]: Initialized");
}
public void Close()
{
if (!m_enabled)
return;
}
public void AddRegion(Scene scene)
{
if (!m_enabled)
return;
m_scene = scene;
m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
m_scene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene;
}
private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj)
{
foreach (var part in obj.Parts)
if (part != null)
GetStoredMaterialsInPart(part);
}
private void OnRegisterCaps(OpenMetaverse.UUID agentID, OpenSim.Framework.Capabilities.Caps caps)
{
string capsBase = "/CAPS/" + caps.CapsObjectPath;
IRequestHandler renderMaterialsPostHandler
= new RestStreamHandler("POST", capsBase + "/",
(request, path, param, httpRequest, httpResponse)
=> RenderMaterialsPostCap(request, agentID),
"RenderMaterials", null);
caps.RegisterHandler("RenderMaterials", renderMaterialsPostHandler);
// OpenSimulator CAPs infrastructure seems to be somewhat hostile towards any CAP that requires both GET
// and POST handlers, (at least at the time this was originally written), so we first set up a POST
// handler normally and then add a GET handler via MainServer
IRequestHandler renderMaterialsGetHandler
= new RestStreamHandler("GET", capsBase + "/",
(request, path, param, httpRequest, httpResponse)
=> RenderMaterialsGetCap(request),
"RenderMaterials", null);
MainServer.Instance.AddStreamHandler(renderMaterialsGetHandler);
// materials viewer seems to use either POST or PUT, so assign POST handler for PUT as well
IRequestHandler renderMaterialsPutHandler
= new RestStreamHandler("PUT", capsBase + "/",
(request, path, param, httpRequest, httpResponse)
=> RenderMaterialsPostCap(request, agentID),
"RenderMaterials", null);
MainServer.Instance.AddStreamHandler(renderMaterialsPutHandler);
}
public void RemoveRegion(Scene scene)
{
if (!m_enabled)
return;
m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
m_scene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene;
}
public void RegionLoaded(Scene scene)
{
}
/// <summary>
/// Finds any legacy materials stored in DynAttrs that may exist for this part and add them to 'm_regionMaterials'.
/// </summary>
/// <param name="part"></param>
private void GetLegacyStoredMaterialsInPart(SceneObjectPart part)
{
if (part.DynAttrs == null)
return;
OSD OSMaterials = null;
OSDArray matsArr = null;
lock (part.DynAttrs)
{
if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
{
OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
if (materialsStore == null)
return;
materialsStore.TryGetValue("Materials", out OSMaterials);
}
if (OSMaterials != null && OSMaterials is OSDArray)
matsArr = OSMaterials as OSDArray;
else
return;
}
if (matsArr == null)
return;
foreach (OSD elemOsd in matsArr)
{
if (elemOsd != null && elemOsd is OSDMap)
{
OSDMap matMap = elemOsd as OSDMap;
if (matMap.ContainsKey("ID") && matMap.ContainsKey("Material"))
{
try
{
lock (m_regionMaterials)
m_regionMaterials[matMap["ID"].AsUUID()] = (OSDMap)matMap["Material"];
}
catch (Exception e)
{
m_log.Warn("[Materials]: exception decoding persisted legacy material: " + e.ToString());
}
}
}
}
}
/// <summary>
/// Find the materials used in the SOP, and add them to 'm_regionMaterials'.
/// </summary>
private void GetStoredMaterialsInPart(SceneObjectPart part)
{
if (part.Shape == null)
return;
var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length);
if (te == null)
return;
GetLegacyStoredMaterialsInPart(part);
if (te.DefaultTexture != null)
GetStoredMaterialInFace(part, te.DefaultTexture);
else
m_log.WarnFormat(
"[Materials]: Default texture for part {0} (part of object {1)) in {2} unexpectedly null. Ignoring.",
part.Name, part.ParentGroup.Name, m_scene.Name);
foreach (Primitive.TextureEntryFace face in te.FaceTextures)
{
if (face != null)
GetStoredMaterialInFace(part, face);
}
}
/// <summary>
/// Find the materials used in one Face, and add them to 'm_regionMaterials'.
/// </summary>
private void GetStoredMaterialInFace(SceneObjectPart part, Primitive.TextureEntryFace face)
{
UUID id = face.MaterialID;
if (id == UUID.Zero)
return;
lock (m_regionMaterials)
{
if (m_regionMaterials.ContainsKey(id))
return;
byte[] data = m_scene.AssetService.GetData(id.ToString());
if (data == null)
{
m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id);
return;
}
OSDMap mat;
try
{
mat = (OSDMap)OSDParser.DeserializeLLSDXml(data);
}
catch (Exception e)
{
m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", id, e.Message);
return;
}
m_regionMaterials[id] = mat;
}
}
public string RenderMaterialsPostCap(string request, UUID agentID)
{
OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
OSDMap resp = new OSDMap();
OSDMap materialsFromViewer = null;
OSDArray respArr = new OSDArray();
if (req.ContainsKey("Zipped"))
{
OSD osd = null;
byte[] inBytes = req["Zipped"].AsBinary();
try
{
osd = ZDecompressBytesToOsd(inBytes);
if (osd != null)
{
if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries
{
foreach (OSD elem in (OSDArray)osd)
{
try
{
UUID id = new UUID(elem.AsBinary(), 0);
lock (m_regionMaterials)
{
if (m_regionMaterials.ContainsKey(id))
{
OSDMap matMap = new OSDMap();
matMap["ID"] = OSD.FromBinary(id.GetBytes());
matMap["Material"] = m_regionMaterials[id];
respArr.Add(matMap);
}
else
{
m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString());
// Theoretically we could try to load the material from the assets service,
// but that shouldn't be necessary because the viewer should only request
// materials that exist in a prim on the region, and all of these materials
// are already stored in m_regionMaterials.
}
}
}
catch (Exception e)
{
m_log.Error("Error getting materials in response to viewer request", e);
continue;
}
}
}
else if (osd is OSDMap) // request to assign a material
{
materialsFromViewer = osd as OSDMap;
if (materialsFromViewer.ContainsKey("FullMaterialsPerFace"))
{
OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"];
if (matsOsd is OSDArray)
{
OSDArray matsArr = matsOsd as OSDArray;
try
{
foreach (OSDMap matsMap in matsArr)
{
uint primLocalID = 0;
try {
primLocalID = matsMap["ID"].AsUInteger();
}
catch (Exception e) {
m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message);
continue;
}
OSDMap mat = null;
try
{
mat = matsMap["Material"] as OSDMap;
}
catch (Exception e)
{
m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message);
continue;
}
SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID);
if (sop == null)
{
m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString());
continue;
}
if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID))
{
m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID);
continue;
}
Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
if (te == null)
{
m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID);
continue;
}
UUID id;
if (mat == null)
{
// This happens then the user removes a material from a prim
id = UUID.Zero;
}
else
{
id = StoreMaterialAsAsset(agentID, mat, sop);
}
int face = -1;
if (matsMap.ContainsKey("Face"))
{
face = matsMap["Face"].AsInteger();
Primitive.TextureEntryFace faceEntry = te.CreateFace((uint)face);
faceEntry.MaterialID = id;
}
else
{
if (te.DefaultTexture == null)
m_log.WarnFormat("[Materials]: TextureEntry.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID);
else
te.DefaultTexture.MaterialID = id;
}
//m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id);
// We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually
sop.Shape.TextureEntry = te.GetBytes();
if (sop.ParentGroup != null)
{
sop.TriggerScriptChangedEvent(Changed.TEXTURE);
sop.UpdateFlag = UpdateRequired.FULL;
sop.ParentGroup.HasGroupChanged = true;
sop.ScheduleFullUpdate();
}
}
}
catch (Exception e)
{
m_log.Warn("[Materials]: exception processing received material ", e);
}
}
}
}
}
}
catch (Exception e)
{
m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
//return "";
}
}
resp["Zipped"] = ZCompressOSD(respArr, false);
string response = OSDParser.SerializeLLSDXmlString(resp);
//m_log.Debug("[Materials]: cap request: " + request);
//m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
//m_log.Debug("[Materials]: cap response: " + response);
return response;
}
private UUID StoreMaterialAsAsset(UUID agentID, OSDMap mat, SceneObjectPart sop)
{
UUID id;
// Material UUID = hash of the material's data.
// This makes materials deduplicate across the entire grid (but isn't otherwise required).
byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat));
using (var md5 = MD5.Create())
id = new UUID(md5.ComputeHash(data), 0);
lock (m_regionMaterials)
{
if (!m_regionMaterials.ContainsKey(id))
{
m_regionMaterials[id] = mat;
// This asset might exist already, but it's ok to try to store it again
string name = "Material " + ChooseMaterialName(mat, sop);
name = name.Substring(0, Math.Min(64, name.Length)).Trim();
AssetBase asset = new AssetBase(id, name, (sbyte)OpenSimAssetType.Material, agentID.ToString());
asset.Data = data;
m_scene.AssetService.Store(asset);
}
}
return id;
}
/// <summary>
/// Use heuristics to choose a good name for the material.
/// </summary>
private string ChooseMaterialName(OSDMap mat, SceneObjectPart sop)
{
UUID normMap = mat["NormMap"].AsUUID();
if (normMap != UUID.Zero)
{
AssetBase asset = m_scene.AssetService.GetCached(normMap.ToString());
if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR"))
return asset.Name;
}
UUID specMap = mat["SpecMap"].AsUUID();
if (specMap != UUID.Zero)
{
AssetBase asset = m_scene.AssetService.GetCached(specMap.ToString());
if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR"))
return asset.Name;
}
if (sop.Name != "Primitive")
return sop.Name;
if ((sop.ParentGroup != null) && (sop.ParentGroup.Name != "Primitive"))
return sop.ParentGroup.Name;
return "";
}
public string RenderMaterialsGetCap(string request)
{
OSDMap resp = new OSDMap();
int matsCount = 0;
OSDArray allOsd = new OSDArray();
lock (m_regionMaterials)
{
foreach (KeyValuePair<UUID, OSDMap> kvp in m_regionMaterials)
{
OSDMap matMap = new OSDMap();
matMap["ID"] = OSD.FromBinary(kvp.Key.GetBytes());
matMap["Material"] = kvp.Value;
allOsd.Add(matMap);
matsCount++;
}
}
resp["Zipped"] = ZCompressOSD(allOsd, false);
return OSDParser.SerializeLLSDXmlString(resp);
}
private static string ZippedOsdBytesToString(byte[] bytes)
{
try
{
return OSDParser.SerializeJsonString(ZDecompressBytesToOsd(bytes));
}
catch (Exception e)
{
return "ZippedOsdBytesToString caught an exception: " + e.ToString();
}
}
/// <summary>
/// computes a UUID by hashing a OSD object
/// </summary>
/// <param name="osd"></param>
/// <returns></returns>
private static UUID HashOsd(OSD osd)
{
byte[] data = OSDParser.SerializeLLSDBinary(osd, false);
using (var md5 = MD5.Create())
return new UUID(md5.ComputeHash(data), 0);
}
public static OSD ZCompressOSD(OSD inOsd, bool useHeader)
{
OSD osd = null;
byte[] data = OSDParser.SerializeLLSDBinary(inOsd, useHeader);
using (MemoryStream msSinkCompressed = new MemoryStream())
{
using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed,
Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true))
{
zOut.Write(data, 0, data.Length);
}
msSinkCompressed.Seek(0L, SeekOrigin.Begin);
osd = OSD.FromBinary(msSinkCompressed.ToArray());
}
return osd;
}
public static OSD ZDecompressBytesToOsd(byte[] input)
{
OSD osd = null;
using (MemoryStream msSinkUnCompressed = new MemoryStream())
{
using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkUnCompressed, CompressionMode.Decompress, true))
{
zOut.Write(input, 0, input.Length);
}
msSinkUnCompressed.Seek(0L, SeekOrigin.Begin);
osd = OSDParser.DeserializeLLSDBinary(msSinkUnCompressed.ToArray());
}
return osd;
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableSortedDictionaryTest : ImmutableDictionaryTestBase
{
private enum Operation
{
Add,
Set,
Remove,
Last,
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new SortedDictionary<int, bool>();
var actual = ImmutableSortedDictionary<int, bool>.Empty;
int seed = unchecked((int)DateTime.Now.Ticks);
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int key;
do
{
key = random.Next();
}
while (expected.ContainsKey(key));
bool value = random.Next() % 2 == 0;
Debug.WriteLine("Adding \"{0}\"={1} to the set.", key, value);
expected.Add(key, value);
actual = actual.Add(key, value);
break;
case Operation.Set:
bool overwrite = expected.Count > 0 && random.Next() % 2 == 0;
if (overwrite)
{
int position = random.Next(expected.Count);
key = expected.Skip(position).First().Key;
}
else
{
do
{
key = random.Next();
}
while (expected.ContainsKey(key));
}
value = random.Next() % 2 == 0;
Debug.WriteLine("Setting \"{0}\"={1} to the set (overwrite={2}).", key, value, overwrite);
expected[key] = value;
actual = actual.SetItem(key, value);
break;
case Operation.Remove:
if (expected.Count > 0)
{
int position = random.Next(expected.Count);
key = expected.Skip(position).First().Key;
Debug.WriteLine("Removing element \"{0}\" from the set.", key);
Assert.True(expected.Remove(key));
actual = actual.Remove(key);
}
break;
}
Assert.Equal<KeyValuePair<int, bool>>(expected.ToList(), actual.ToList());
}
}
[Fact]
public void AddExistingKeySameValueTest()
{
AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "Microsoft");
AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void AddExistingKeyDifferentValueTest()
{
AddExistingKeyDifferentValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void ToUnorderedTest()
{
var sortedMap = Empty<int, GenericParameterHelper>().AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper(n))));
var unsortedMap = sortedMap.ToImmutableDictionary();
Assert.IsAssignableFrom(typeof(ImmutableDictionary<int, GenericParameterHelper>), unsortedMap);
Assert.Equal(sortedMap.Count, unsortedMap.Count);
Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(sortedMap.ToList(), unsortedMap.ToList());
}
[Fact]
public void SortChangeTest()
{
var map = Empty<string, string>(StringComparer.Ordinal)
.Add("Johnny", "Appleseed")
.Add("JOHNNY", "Appleseed");
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("Johnny"));
Assert.False(map.ContainsKey("johnny"));
var newMap = map.ToImmutableSortedDictionary(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, newMap.Count);
Assert.True(newMap.ContainsKey("Johnny"));
Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive
}
[Fact]
public void InitialBulkAddUniqueTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("c", "d"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
var actual = map.AddRange(uniqueEntries);
Assert.Equal(2, actual.Count);
}
[Fact]
public void InitialBulkAddWithExactDuplicatesTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("a", "b"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
var actual = map.AddRange(uniqueEntries);
Assert.Equal(1, actual.Count);
}
[Fact]
public void ContainsValueTest()
{
this.ContainsValueTestHelper(ImmutableSortedDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper());
}
[Fact]
public void InitialBulkAddWithKeyCollisionTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("a", "d"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
AssertExtensions.Throws<ArgumentException>(null, () => map.AddRange(uniqueEntries));
}
[Fact]
public void Create()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var valueComparer = StringComparer.CurrentCulture;
var dictionary = ImmutableSortedDictionary.Create<string, string>();
Assert.Equal(0, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.Create<string, string>(keyComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.Create(keyComparer, valueComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, valueComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
}
[Fact]
public void ToImmutableSortedDictionary()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var valueComparer = StringComparer.CurrentCulture;
ImmutableSortedDictionary<string, string> dictionary = pairs.ToImmutableSortedDictionary();
Assert.Equal(1, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(keyComparer, valueComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant());
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer, valueComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
}
[Fact]
public void WithComparers()
{
var map = ImmutableSortedDictionary.Create<string, string>().Add("a", "1").Add("B", "1");
Assert.Same(Comparer<string>.Default, map.KeyComparer);
Assert.True(map.ContainsKey("a"));
Assert.False(map.ContainsKey("A"));
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
var cultureComparer = StringComparer.CurrentCulture;
map = map.WithComparers(StringComparer.OrdinalIgnoreCase, cultureComparer);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Same(cultureComparer, map.ValueComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void WithComparersCollisions()
{
// First check where collisions have matching values.
var map = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "1");
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(1, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.Equal("1", map["a"]);
// Now check where collisions have conflicting values.
map = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "2").Add("b", "3");
AssertExtensions.Throws<ArgumentException>(null, () => map.WithComparers(StringComparer.OrdinalIgnoreCase));
// Force all values to be considered equal.
map = map.WithComparers(StringComparer.OrdinalIgnoreCase, EverythingEqual<string>.Default);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Same(EverythingEqual<string>.Default, map.ValueComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void CollisionExceptionMessageContainsKey()
{
var map = ImmutableSortedDictionary.Create<string, string>()
.Add("firstKey", "1").Add("secondKey", "2");
var exception = AssertExtensions.Throws<ArgumentException>(null, () => map.Add("firstKey", "3"));
if (!PlatformDetection.IsNetNative) //.Net Native toolchain removes exception messages.
{
Assert.Contains("firstKey", exception.Message);
}
}
[Fact]
public void WithComparersEmptyCollection()
{
var map = ImmutableSortedDictionary.Create<string, string>();
Assert.Same(Comparer<string>.Default, map.KeyComparer);
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedDictionary.Create<int, int>().Add(3, 5);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void Remove_KeyExists_RemovesKeyValuePair()
{
ImmutableSortedDictionary<int, string> dictionary = new Dictionary<int, string>
{
{ 1, "a" }
}.ToImmutableSortedDictionary();
Assert.Equal(0, dictionary.Remove(1).Count);
}
[Fact]
public void Remove_FirstKey_RemovesKeyValuePair()
{
ImmutableSortedDictionary<int, string> dictionary = new Dictionary<int, string>
{
{ 1, "a" },
{ 2, "b" }
}.ToImmutableSortedDictionary();
Assert.Equal(1, dictionary.Remove(1).Count);
}
[Fact]
public void Remove_SecondKey_RemovesKeyValuePair()
{
ImmutableSortedDictionary<int, string> dictionary = new Dictionary<int, string>
{
{ 1, "a" },
{ 2, "b" }
}.ToImmutableSortedDictionary();
Assert.Equal(1, dictionary.Remove(2).Count);
}
[Fact]
public void Remove_KeyDoesntExist_DoesNothing()
{
ImmutableSortedDictionary<int, string> dictionary = new Dictionary<int, string>
{
{ 1, "a" }
}.ToImmutableSortedDictionary();
Assert.Equal(1, dictionary.Remove(2).Count);
Assert.Equal(1, dictionary.Remove(-1).Count);
}
[Fact]
public void Remove_EmptyDictionary_DoesNothing()
{
ImmutableSortedDictionary<int, string> dictionary = ImmutableSortedDictionary<int, string>.Empty;
Assert.Equal(0, dictionary.Remove(2).Count);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedDictionary.Create<string, int>());
ImmutableSortedDictionary<int, int> dict = ImmutableSortedDictionary.Create<int, int>().Add(1, 2).Add(2, 3).Add(3, 4);
var info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(dict);
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableSortedDictionary.Create<string, string>(), "_root");
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
KeyValuePair<int, int>[] items = itemProperty.GetValue(info.Instance) as KeyValuePair<int, int>[];
Assert.Equal(dict, items);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableSortedDictionary.Create<int, int>());
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces.
public void EnumerationPerformance()
{
var dictionary = Enumerable.Range(1, 1000).ToImmutableSortedDictionary(k => k, k => k);
var timing = new TimeSpan[3];
var sw = new Stopwatch();
for (int j = 0; j < timing.Length; j++)
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
foreach (var entry in dictionary)
{
}
}
timing[j] = sw.Elapsed;
sw.Reset();
}
string timingText = string.Join(Environment.NewLine, timing);
Debug.WriteLine("Timing:{0}{1}", Environment.NewLine, timingText);
}
////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces.
public void EnumerationPerformance_Empty()
{
var dictionary = ImmutableSortedDictionary<int, int>.Empty;
var timing = new TimeSpan[3];
var sw = new Stopwatch();
for (int j = 0; j < timing.Length; j++)
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
foreach (var entry in dictionary)
{
}
}
timing[j] = sw.Elapsed;
sw.Reset();
}
string timingText = string.Join(Environment.NewLine, timing);
Debug.WriteLine("Timing_Empty:{0}{1}", Environment.NewLine, timingText);
}
[Fact]
public void ValueRef()
{
var dictionary = new Dictionary<string, int>()
{
{ "a", 1 },
{ "b", 2 }
}.ToImmutableSortedDictionary();
ref readonly var safeRef = ref dictionary.ValueRef("a");
ref var unsafeRef = ref Unsafe.AsRef(safeRef);
Assert.Equal(1, dictionary.ValueRef("a"));
unsafeRef = 5;
Assert.Equal(5, dictionary.ValueRef("a"));
}
[Fact]
public void ValueRef_NonExistentKey()
{
var dictionary = new Dictionary<string, int>()
{
{ "a", 1 },
{ "b", 2 }
}.ToImmutableSortedDictionary();
Assert.Throws<KeyNotFoundException>(() => dictionary.ValueRef("c"));
}
protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>()
{
return ImmutableSortedDictionaryTest.Empty<TKey, TValue>();
}
protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer)
{
return ImmutableSortedDictionary.Create<string, TValue>(comparer);
}
protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).ValueComparer;
}
internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).Root;
}
protected void ContainsValueTestHelper<TKey, TValue>(ImmutableSortedDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.ContainsValue(value));
Assert.True(map.Add(key, value).ContainsValue(value));
}
private static IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(IComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null)
{
return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer);
}
}
}
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions.Compiler
{
/// <summary>
/// Expression rewriting to spill the CLR stack into temporary variables
/// in order to guarantee some properties of code generation, for
/// example that we always enter try block on empty stack.
/// </summary>
internal sealed partial class StackSpiller
{
/// <summary>
/// Indicates whether the evaluation stack is empty.
/// </summary>
private enum Stack
{
Empty,
NonEmpty,
};
/// <summary>
/// Should the parent nodes be rewritten, and in what way?
/// </summary>
/// <remarks>
/// Designed so bitwise-or produces the correct result when merging two
/// subtrees. In particular, SpillStack is preferred over Copy which is
/// preferred over None.
/// </remarks>
[Flags]
private enum RewriteAction
{
/// <summary>
/// No rewrite needed.
/// </summary>
None = 0,
/// <summary>
/// Copy into a new node.
/// </summary>
Copy = 1,
/// <summary>
/// Spill stack into temps.
/// </summary>
SpillStack = 3,
}
/// <summary>
/// Result of a rewrite operation. Always contains an action and a node.
/// </summary>
private struct Result
{
internal readonly RewriteAction Action;
internal readonly Expression Node;
internal Result(RewriteAction action, Expression node)
{
Action = action;
Node = node;
}
}
/// <summary>
/// Initial stack state. Normally empty, but when inlining the lambda
/// we might have a non-empty starting stack state.
/// </summary>
private readonly Stack _startingStack;
/// <summary>
/// Lambda rewrite result. We need this for inlined lambdas to figure
/// out whether we need to guarantee it an empty stack.
/// </summary>
private RewriteAction _lambdaRewrite;
/// <summary>
/// Analyzes a lambda, producing a new one that has correct invariants
/// for codegen. In particular, it spills the IL stack to temps in
/// places where it's invalid to have a non-empty stack (for example,
/// entering a try statement).
/// </summary>
internal static LambdaExpression AnalyzeLambda(LambdaExpression lambda)
{
return lambda.Accept(new StackSpiller(Stack.Empty));
}
private StackSpiller(Stack stack)
{
_startingStack = stack;
}
// Called by Expression<T>.Accept(StackSpiller).
internal Expression<T> Rewrite<T>(Expression<T> lambda)
{
VerifyTemps();
// Lambda starts with an empty stack.
Result body = RewriteExpressionFreeTemps(lambda.Body, _startingStack);
_lambdaRewrite = body.Action;
VerifyTemps();
if (body.Action != RewriteAction.None)
{
// Create a new scope for temps.
// Note that none of these will be hoisted so there is no closure impact.
Expression newBody = body.Node;
if (_tm.Temps.Count > 0)
{
newBody = Expression.Block(_tm.Temps, new TrueReadOnlyCollection<Expression>(newBody));
}
// Clone the lambda, replacing the body & variables.
return Expression<T>.Create(newBody, lambda.Name, lambda.TailCall, new ParameterList(lambda));
}
return lambda;
}
#region Expressions
[Conditional("DEBUG")]
private static void VerifyRewrite(Result result, Expression node)
{
Debug.Assert(result.Node != null);
// (result.Action == RewriteAction.None) if and only if (node == result.Node)
Debug.Assert((result.Action == RewriteAction.None) ^ (node != result.Node), "rewrite action does not match node object identity");
// if the original node is an extension node, it should have been rewritten
Debug.Assert(result.Node.NodeType != ExpressionType.Extension, "extension nodes must be rewritten");
// if we have Copy, then node type must match
Debug.Assert(
result.Action != RewriteAction.Copy || node.NodeType == result.Node.NodeType || node.CanReduce,
"rewrite action does not match node object kind"
);
// New type must be reference assignable to the old type
// (our rewrites preserve type exactly, but the rules for rewriting
// an extension node are more lenient, see Expression.ReduceAndCheck())
Debug.Assert(
TypeUtils.AreReferenceAssignable(node.Type, result.Node.Type),
"rewritten object must be reference assignable to the original type"
);
}
private Result RewriteExpressionFreeTemps(Expression expression, Stack stack)
{
int mark = Mark();
Result result = RewriteExpression(expression, stack);
Free(mark);
return result;
}
private Result RewriteDynamicExpression(Expression expr)
{
var node = (IDynamicExpression)expr;
// CallSite is on the stack.
var cr = new ChildRewriter(this, Stack.NonEmpty, node.ArgumentCount);
cr.AddArguments(node);
if (cr.Action == RewriteAction.SpillStack)
{
RequireNoRefArgs(node.DelegateType.GetInvokeMethod());
}
return cr.Finish(cr.Rewrite ? node.Rewrite(cr[0, -1]) : expr);
}
private Result RewriteIndexAssignment(BinaryExpression node, Stack stack)
{
var index = (IndexExpression)node.Left;
var cr = new ChildRewriter(this, stack, 2 + index.ArgumentCount);
cr.Add(index.Object);
cr.AddArguments(index);
cr.Add(node.Right);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefInstance(index.Object);
}
if (cr.Rewrite)
{
node = new AssignBinaryExpression(
new IndexExpression(
cr[0], // Object
index.Indexer,
cr[1, -2] // arguments
),
cr[-1] // value
);
}
return cr.Finish(node);
}
// BinaryExpression: AndAlso, OrElse
private Result RewriteLogicalBinaryExpression(Expression expr, Stack stack)
{
var node = (BinaryExpression)expr;
// Left expression runs on a stack as left by parent
Result left = RewriteExpression(node.Left, stack);
// ... and so does the right one
Result right = RewriteExpression(node.Right, stack);
//conversion is a lambda. stack state will be ignored.
Result conversion = RewriteExpression(node.Conversion, stack);
RewriteAction action = left.Action | right.Action | conversion.Action;
if (action != RewriteAction.None)
{
// We don't have to worry about byref parameters here, because the
// factory doesn't allow it (it requires identical parameters and
// return type from the AndAlso/OrElse method)
expr = BinaryExpression.Create(
node.NodeType,
left.Node,
right.Node,
node.Type,
node.Method,
(LambdaExpression)conversion.Node
);
}
return new Result(action, expr);
}
private Result RewriteReducibleExpression(Expression expr, Stack stack)
{
Result result = RewriteExpression(expr.Reduce(), stack);
// It's at least Copy because we reduced the node.
return new Result(result.Action | RewriteAction.Copy, result.Node);
}
private Result RewriteBinaryExpression(Expression expr, Stack stack)
{
var node = (BinaryExpression)expr;
var cr = new ChildRewriter(this, stack, 3);
// Left expression executes on the stack as left by parent
cr.Add(node.Left);
// Right expression always has non-empty stack (left is on it)
cr.Add(node.Right);
// conversion is a lambda, stack state will be ignored
cr.Add(node.Conversion);
if (cr.Action == RewriteAction.SpillStack)
{
RequireNoRefArgs(node.Method);
}
return cr.Finish(cr.Rewrite ?
BinaryExpression.Create(
node.NodeType,
cr[0],
cr[1],
node.Type,
node.Method,
(LambdaExpression)cr[2]) :
expr);
}
private Result RewriteVariableAssignment(BinaryExpression node, Stack stack)
{
// Expression is evaluated on a stack in current state.
Result right = RewriteExpression(node.Right, stack);
if (right.Action != RewriteAction.None)
{
node = new AssignBinaryExpression(node.Left, right.Node);
}
return new Result(right.Action, node);
}
private Result RewriteAssignBinaryExpression(Expression expr, Stack stack)
{
var node = (BinaryExpression)expr;
switch (node.Left.NodeType)
{
case ExpressionType.Index:
return RewriteIndexAssignment(node, stack);
case ExpressionType.MemberAccess:
return RewriteMemberAssignment(node, stack);
case ExpressionType.Parameter:
return RewriteVariableAssignment(node, stack);
case ExpressionType.Extension:
return RewriteExtensionAssignment(node, stack);
default:
throw Error.InvalidLvalue(node.Left.NodeType);
}
}
private Result RewriteExtensionAssignment(BinaryExpression node, Stack stack)
{
node = new AssignBinaryExpression(node.Left.ReduceExtensions(), node.Right);
Result result = RewriteAssignBinaryExpression(node, stack);
// it's at least Copy because we reduced the node
return new Result(result.Action | RewriteAction.Copy, result.Node);
}
private static Result RewriteLambdaExpression(Expression expr)
{
var node = (LambdaExpression)expr;
// Call back into the rewriter
expr = AnalyzeLambda(node);
// If the lambda gets rewritten, we don't need to spill the stack,
// but we do need to rebuild the tree above us so it includes the new node.
RewriteAction action = (expr == node) ? RewriteAction.None : RewriteAction.Copy;
return new Result(action, expr);
}
private Result RewriteConditionalExpression(Expression expr, Stack stack)
{
var node = (ConditionalExpression)expr;
// Test executes at the stack as left by parent.
Result test = RewriteExpression(node.Test, stack);
// The test is popped by conditional jump so branches execute
// at the stack as left by parent too.
Result ifTrue = RewriteExpression(node.IfTrue, stack);
Result ifFalse = RewriteExpression(node.IfFalse, stack);
RewriteAction action = test.Action | ifTrue.Action | ifFalse.Action;
if (action != RewriteAction.None)
{
expr = ConditionalExpression.Make(test.Node, ifTrue.Node, ifFalse.Node, node.Type);
}
return new Result(action, expr);
}
private Result RewriteMemberAssignment(BinaryExpression node, Stack stack)
{
var lvalue = (MemberExpression)node.Left;
var cr = new ChildRewriter(this, stack, 2);
// If there's an instance, it executes on the stack in current state
// and rest is executed on non-empty stack.
// Otherwise the stack is left unchanged.
cr.Add(lvalue.Expression);
cr.Add(node.Right);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefInstance(lvalue.Expression);
}
if (cr.Rewrite)
{
return cr.Finish(
new AssignBinaryExpression(
MemberExpression.Make(cr[0], lvalue.Member),
cr[1]
)
);
}
return new Result(RewriteAction.None, node);
}
private Result RewriteMemberExpression(Expression expr, Stack stack)
{
var node = (MemberExpression)expr;
// Expression is emitted on top of the stack in current state.
Result expression = RewriteExpression(node.Expression, stack);
if (expression.Action != RewriteAction.None)
{
if (expression.Action == RewriteAction.SpillStack &&
node.Member is PropertyInfo)
{
// Only need to validate properties because reading a field
// is always side-effect free.
RequireNotRefInstance(node.Expression);
}
expr = MemberExpression.Make(expression.Node, node.Member);
}
return new Result(expression.Action, expr);
}
private Result RewriteIndexExpression(Expression expr, Stack stack)
{
var node = (IndexExpression)expr;
var cr = new ChildRewriter(this, stack, node.ArgumentCount + 1);
// For instance methods, the instance executes on the
// stack as is, but stays on the stack, making it non-empty.
cr.Add(node.Object);
cr.AddArguments(node);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefInstance(node.Object);
}
if (cr.Rewrite)
{
expr = new IndexExpression(
cr[0],
node.Indexer,
cr[1, -1]
);
}
return cr.Finish(expr);
}
private Result RewriteMethodCallExpression(Expression expr, Stack stack)
{
MethodCallExpression node = (MethodCallExpression)expr;
var cr = new ChildRewriter(this, stack, node.ArgumentCount + 1);
// For instance methods, the instance executes on the
// stack as is, but stays on the stack, making it non-empty.
cr.Add(node.Object);
cr.AddArguments(node);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefInstance(node.Object);
cr.MarkRefArgs(node.Method, startIndex: 1);
}
if (cr.Rewrite)
{
if (node.Object != null)
{
expr = new InstanceMethodCallExpressionN(node.Method, cr[0], cr[1, -1]);
}
else
{
expr = new MethodCallExpressionN(node.Method, cr[1, -1]);
}
}
return cr.Finish(expr);
}
private Result RewriteNewArrayExpression(Expression expr, Stack stack)
{
var node = (NewArrayExpression)expr;
if (node.NodeType == ExpressionType.NewArrayInit)
{
// In a case of array construction with element initialization
// the element expressions are never emitted on an empty stack because
// the array reference and the index are on the stack.
stack = Stack.NonEmpty;
}
else
{
// In a case of NewArrayBounds we make no modifications to the stack
// before emitting bounds expressions.
}
var cr = new ChildRewriter(this, stack, node.Expressions.Count);
cr.Add(node.Expressions);
if (cr.Rewrite)
{
expr = NewArrayExpression.Make(node.NodeType, node.Type, new TrueReadOnlyCollection<Expression>(cr[0, -1]));
}
return cr.Finish(expr);
}
private Result RewriteInvocationExpression(Expression expr, Stack stack)
{
var node = (InvocationExpression)expr;
ChildRewriter cr;
// See if the lambda will be inlined.
LambdaExpression lambda = node.LambdaOperand;
if (lambda != null)
{
// Arguments execute on current stack.
cr = new ChildRewriter(this, stack, node.ArgumentCount);
cr.AddArguments(node);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefArgs(Expression.GetInvokeMethod(node.Expression), startIndex: 0);
}
// Lambda body also executes on current stack.
var spiller = new StackSpiller(stack);
lambda = lambda.Accept(spiller);
if (cr.Rewrite || spiller._lambdaRewrite != RewriteAction.None)
{
node = new InvocationExpressionN(lambda, cr[0, -1], node.Type);
}
Result result = cr.Finish(node);
return new Result(result.Action | spiller._lambdaRewrite, result.Node);
}
cr = new ChildRewriter(this, stack, node.ArgumentCount + 1);
// First argument starts on stack as provided.
cr.Add(node.Expression);
// Rest of arguments have non-empty stack (the delegate instance is on the stack).
cr.AddArguments(node);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefArgs(Expression.GetInvokeMethod(node.Expression), startIndex: 1);
}
return cr.Finish(cr.Rewrite ? new InvocationExpressionN(cr[0], cr[1, -1], node.Type) : expr);
}
private Result RewriteNewExpression(Expression expr, Stack stack)
{
var node = (NewExpression)expr;
// The first expression starts on a stack as provided by parent,
// rest are definitely non-empty (which ChildRewriter guarantees).
var cr = new ChildRewriter(this, stack, node.ArgumentCount);
cr.AddArguments(node);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefArgs(node.Constructor, startIndex: 0);
}
return cr.Finish(cr.Rewrite ? new NewExpression(node.Constructor, cr[0, -1], node.Members) : expr);
}
private Result RewriteTypeBinaryExpression(Expression expr, Stack stack)
{
var node = (TypeBinaryExpression)expr;
// The expression is emitted on top of current stack.
Result expression = RewriteExpression(node.Expression, stack);
if (expression.Action != RewriteAction.None)
{
expr = new TypeBinaryExpression(expression.Node, node.TypeOperand, node.NodeType);
}
return new Result(expression.Action, expr);
}
private Result RewriteThrowUnaryExpression(Expression expr, Stack stack)
{
var node = (UnaryExpression)expr;
// Throw statement itself does not care about the stack
// but it will empty the stack and it may cause stack imbalance
// it so we need to restore stack after unconditional throw to make JIT happy
// this has an effect of executing Throw on an empty stack.
Result value = RewriteExpressionFreeTemps(node.Operand, Stack.Empty);
RewriteAction action = value.Action;
if (stack != Stack.Empty)
{
action = RewriteAction.SpillStack;
}
if (action != RewriteAction.None)
{
expr = new UnaryExpression(ExpressionType.Throw, value.Node, node.Type, null);
}
return new Result(action, expr);
}
private Result RewriteUnaryExpression(Expression expr, Stack stack)
{
var node = (UnaryExpression)expr;
Debug.Assert(node.NodeType != ExpressionType.Quote, "unexpected Quote");
Debug.Assert(node.NodeType != ExpressionType.Throw, "unexpected Throw");
// Operand is emitted on top of the stack as-is.
Result expression = RewriteExpression(node.Operand, stack);
if (expression.Action == RewriteAction.SpillStack)
{
RequireNoRefArgs(node.Method);
}
if (expression.Action != RewriteAction.None)
{
expr = new UnaryExpression(node.NodeType, expression.Node, node.Type, node.Method);
}
return new Result(expression.Action, expr);
}
private Result RewriteListInitExpression(Expression expr, Stack stack)
{
var node = (ListInitExpression)expr;
// Constructor runs on initial stack.
Result newResult = RewriteExpression(node.NewExpression, stack);
Expression rewrittenNew = newResult.Node;
RewriteAction action = newResult.Action;
ReadOnlyCollection<ElementInit> inits = node.Initializers;
int count = inits.Count;
ChildRewriter[] cloneCrs = new ChildRewriter[count];
for (int i = 0; i < count; i++)
{
ElementInit init = inits[i];
// Initializers all run on non-empty stack (the list instance is on it).
var cr = new ChildRewriter(this, Stack.NonEmpty, init.Arguments.Count);
cr.Add(init.Arguments);
action |= cr.Action;
cloneCrs[i] = cr;
}
switch (action)
{
case RewriteAction.None:
break;
case RewriteAction.Copy:
ElementInit[] newInits = new ElementInit[count];
for (int i = 0; i < count; i++)
{
ChildRewriter cr = cloneCrs[i];
if (cr.Action == RewriteAction.None)
{
newInits[i] = inits[i];
}
else
{
newInits[i] = new ElementInit(inits[i].AddMethod, new TrueReadOnlyCollection<Expression>(cr[0, -1]));
}
}
expr = new ListInitExpression((NewExpression)rewrittenNew, new TrueReadOnlyCollection<ElementInit>(newInits));
break;
case RewriteAction.SpillStack:
bool isRefNew = IsRefInstance(node.NewExpression);
var comma = new ArrayBuilder<Expression>(count + 2 + (isRefNew ? 1 : 0));
ParameterExpression tempNew = MakeTemp(rewrittenNew.Type);
comma.UncheckedAdd(new AssignBinaryExpression(tempNew, rewrittenNew));
ParameterExpression refTempNew = tempNew;
if (isRefNew)
{
refTempNew = MakeTemp(tempNew.Type.MakeByRefType());
comma.UncheckedAdd(new ByRefAssignBinaryExpression(refTempNew, tempNew));
}
for (int i = 0; i < count; i++)
{
ChildRewriter cr = cloneCrs[i];
Result add = cr.Finish(new InstanceMethodCallExpressionN(inits[i].AddMethod, refTempNew, cr[0, -1]));
comma.UncheckedAdd(add.Node);
}
comma.UncheckedAdd(tempNew);
expr = MakeBlock(comma);
break;
default:
throw ContractUtils.Unreachable;
}
return new Result(action, expr);
}
private Result RewriteMemberInitExpression(Expression expr, Stack stack)
{
var node = (MemberInitExpression)expr;
// Constructor runs on initial stack.
Result result = RewriteExpression(node.NewExpression, stack);
Expression rewrittenNew = result.Node;
RewriteAction action = result.Action;
ReadOnlyCollection<MemberBinding> bindings = node.Bindings;
int count = bindings.Count;
BindingRewriter[] bindingRewriters = new BindingRewriter[count];
for (int i = 0; i < count; i++)
{
MemberBinding binding = bindings[i];
// Bindings run on non-empty stack (the object instance is on it).
BindingRewriter rewriter = BindingRewriter.Create(binding, this, Stack.NonEmpty);
bindingRewriters[i] = rewriter;
action |= rewriter.Action;
}
switch (action)
{
case RewriteAction.None:
break;
case RewriteAction.Copy:
MemberBinding[] newBindings = new MemberBinding[count];
for (int i = 0; i < count; i++)
{
newBindings[i] = bindingRewriters[i].AsBinding();
}
expr = new MemberInitExpression((NewExpression)rewrittenNew, new TrueReadOnlyCollection<MemberBinding>(newBindings));
break;
case RewriteAction.SpillStack:
bool isRefNew = IsRefInstance(node.NewExpression);
var comma = new ArrayBuilder<Expression>(count + 2 + (isRefNew ? 1 : 0));
ParameterExpression tempNew = MakeTemp(rewrittenNew.Type);
comma.UncheckedAdd(new AssignBinaryExpression(tempNew, rewrittenNew));
ParameterExpression refTempNew = tempNew;
if (isRefNew)
{
refTempNew = MakeTemp(tempNew.Type.MakeByRefType());
comma.UncheckedAdd(new ByRefAssignBinaryExpression(refTempNew, tempNew));
}
for (int i = 0; i < count; i++)
{
BindingRewriter cr = bindingRewriters[i];
Expression initExpr = cr.AsExpression(refTempNew);
comma.UncheckedAdd(initExpr);
}
comma.UncheckedAdd(tempNew);
expr = MakeBlock(comma);
break;
default:
throw ContractUtils.Unreachable;
}
return new Result(action, expr);
}
#endregion
#region Statements
private Result RewriteBlockExpression(Expression expr, Stack stack)
{
var node = (BlockExpression)expr;
int count = node.ExpressionCount;
RewriteAction action = RewriteAction.None;
Expression[] clone = null;
for (int i = 0; i < count; i++)
{
Expression expression = node.GetExpression(i);
// All statements within the block execute at the
// same stack state.
Result rewritten = RewriteExpression(expression, stack);
action |= rewritten.Action;
if (clone == null && rewritten.Action != RewriteAction.None)
{
clone = Clone(node.Expressions, i);
}
if (clone != null)
{
clone[i] = rewritten.Node;
}
}
if (action != RewriteAction.None)
{
// Okay to wrap since we know no one can mutate the clone array.
expr = node.Rewrite(null, clone);
}
return new Result(action, expr);
}
private Result RewriteLabelExpression(Expression expr, Stack stack)
{
var node = (LabelExpression)expr;
Result expression = RewriteExpression(node.DefaultValue, stack);
if (expression.Action != RewriteAction.None)
{
expr = new LabelExpression(node.Target, expression.Node);
}
return new Result(expression.Action, expr);
}
private Result RewriteLoopExpression(Expression expr, Stack stack)
{
var node = (LoopExpression)expr;
// The loop statement requires empty stack for itself, so it
// can guarantee it to the child nodes.
Result body = RewriteExpression(node.Body, Stack.Empty);
RewriteAction action = body.Action;
// However, the loop itself requires that it executes on an empty stack
// so we need to rewrite if the stack is not empty.
if (stack != Stack.Empty)
{
action = RewriteAction.SpillStack;
}
if (action != RewriteAction.None)
{
expr = new LoopExpression(body.Node, node.BreakLabel, node.ContinueLabel);
}
return new Result(action, expr);
}
// Note: goto does not necessarily need an empty stack. We could always
// emit it as a "leave" which would clear the stack for us. That would
// prevent us from doing certain optimizations we might want to do,
// however, like the switch-case-goto pattern. For now, be conservative.
private Result RewriteGotoExpression(Expression expr, Stack stack)
{
var node = (GotoExpression)expr;
// Goto requires empty stack to execute so the expression is
// going to execute on an empty stack.
Result value = RewriteExpressionFreeTemps(node.Value, Stack.Empty);
// However, the statement itself needs an empty stack for itself
// so if stack is not empty, rewrite to empty the stack.
RewriteAction action = value.Action;
if (stack != Stack.Empty)
{
action = RewriteAction.SpillStack;
}
if (action != RewriteAction.None)
{
expr = Expression.MakeGoto(node.Kind, node.Target, value.Node, node.Type);
}
return new Result(action, expr);
}
private Result RewriteSwitchExpression(Expression expr, Stack stack)
{
var node = (SwitchExpression)expr;
// The switch statement test is emitted on the stack in current state.
Result switchValue = RewriteExpressionFreeTemps(node.SwitchValue, stack);
RewriteAction action = switchValue.Action;
ReadOnlyCollection<SwitchCase> cases = node.Cases;
SwitchCase[] clone = null;
for (int i = 0; i < cases.Count; i++)
{
SwitchCase @case = cases[i];
Expression[] cloneTests = null;
ReadOnlyCollection<Expression> testValues = @case.TestValues;
for (int j = 0; j < testValues.Count; j++)
{
// All tests execute at the same stack state as the switch.
// This is guaranteed by the compiler (to simplify spilling).
Result test = RewriteExpression(testValues[j], stack);
action |= test.Action;
if (cloneTests == null && test.Action != RewriteAction.None)
{
cloneTests = Clone(testValues, j);
}
if (cloneTests != null)
{
cloneTests[j] = test.Node;
}
}
// And all the cases also run on the same stack level.
Result body = RewriteExpression(@case.Body, stack);
action |= body.Action;
if (body.Action != RewriteAction.None || cloneTests != null)
{
if (cloneTests != null)
{
testValues = new ReadOnlyCollection<Expression>(cloneTests);
}
@case = new SwitchCase(body.Node, testValues);
if (clone == null)
{
clone = Clone(cases, i);
}
}
if (clone != null)
{
clone[i] = @case;
}
}
// default body also runs on initial stack
Result defaultBody = RewriteExpression(node.DefaultBody, stack);
action |= defaultBody.Action;
if (action != RewriteAction.None)
{
if (clone != null)
{
// okay to wrap because we aren't modifying the array
cases = new ReadOnlyCollection<SwitchCase>(clone);
}
expr = new SwitchExpression(node.Type, switchValue.Node, defaultBody.Node, node.Comparison, cases);
}
return new Result(action, expr);
}
private Result RewriteTryExpression(Expression expr, Stack stack)
{
var node = (TryExpression)expr;
// Try statement definitely needs an empty stack so its
// child nodes execute at empty stack.
Result body = RewriteExpression(node.Body, Stack.Empty);
ReadOnlyCollection<CatchBlock> handlers = node.Handlers;
CatchBlock[] clone = null;
RewriteAction action = body.Action;
if (handlers != null)
{
for (int i = 0; i < handlers.Count; i++)
{
RewriteAction curAction = body.Action;
CatchBlock handler = handlers[i];
Expression filter = handler.Filter;
if (handler.Filter != null)
{
// Our code gen saves the incoming filter value and provides it as a variable so the stack is empty
Result rfault = RewriteExpression(handler.Filter, Stack.Empty);
action |= rfault.Action;
curAction |= rfault.Action;
filter = rfault.Node;
}
// Catch block starts with an empty stack (guaranteed by TryStatement).
Result rbody = RewriteExpression(handler.Body, Stack.Empty);
action |= rbody.Action;
curAction |= rbody.Action;
if (curAction != RewriteAction.None)
{
handler = Expression.MakeCatchBlock(handler.Test, handler.Variable, rbody.Node, filter);
if (clone == null)
{
clone = Clone(handlers, i);
}
}
if (clone != null)
{
clone[i] = handler;
}
}
}
Result fault = RewriteExpression(node.Fault, Stack.Empty);
action |= fault.Action;
Result @finally = RewriteExpression(node.Finally, Stack.Empty);
action |= @finally.Action;
// If the stack is initially not empty, rewrite to spill the stack
if (stack != Stack.Empty)
{
action = RewriteAction.SpillStack;
}
if (action != RewriteAction.None)
{
if (clone != null)
{
// Okay to wrap because we aren't modifying the array.
handlers = new ReadOnlyCollection<CatchBlock>(clone);
}
expr = new TryExpression(node.Type, body.Node, @finally.Node, fault.Node, handlers);
}
return new Result(action, expr);
}
private Result RewriteExtensionExpression(Expression expr, Stack stack)
{
Result result = RewriteExpression(expr.ReduceExtensions(), stack);
// it's at least Copy because we reduced the node
return new Result(result.Action | RewriteAction.Copy, result.Node);
}
#endregion
#region Cloning
/// <summary>
/// Will clone an IList into an array of the same size, and copy
/// all values up to (and NOT including) the max index.
/// </summary>
/// <returns>The cloned array.</returns>
private static T[] Clone<T>(ReadOnlyCollection<T> original, int max)
{
Debug.Assert(original != null);
Debug.Assert(max < original.Count);
T[] clone = new T[original.Count];
for (int j = 0; j < max; j++)
{
clone[j] = original[j];
}
return clone;
}
#endregion
/// <summary>
/// If we are spilling, requires that there are no byref arguments to
/// the method call.
///
/// Used for:
/// DynamicExpression,
/// UnaryExpression,
/// BinaryExpression.
/// </summary>
/// <remarks>
/// We could support this if spilling happened later in the compiler.
/// Other expressions that can emit calls with arguments (such as
/// ListInitExpression and IndexExpression) don't allow byref arguments.
/// </remarks>
private static void RequireNoRefArgs(MethodBase method)
{
if (method != null && method.GetParametersCached().Any(p => p.ParameterType.IsByRef))
{
throw Error.TryNotSupportedForMethodsWithRefArgs(method);
}
}
/// <summary>
/// Requires that the instance is not a value type (primitive types are
/// okay because they're immutable).
///
/// Used for:
/// MemberExpression (for properties).
/// </summary>
/// <remarks>
/// We could support this if spilling happened later in the compiler.
/// </remarks>
private static void RequireNotRefInstance(Expression instance)
{
if (IsRefInstance(instance))
{
throw Error.TryNotSupportedForValueTypeInstances(instance.Type);
}
}
private static bool IsRefInstance(Expression instance)
{
// Primitive value types are okay because they are all read-only,
// but we can't rely on this for non-primitive types. So we have
// to either throw NotSupported or use ref locals.
return instance != null && instance.Type.IsValueType && instance.Type.GetTypeCode() == TypeCode.Object;
}
}
}
| |
// 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.
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
using Microsoft.Diagnostics.Tracing.Session;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
#if USE_MDT_EVENTSOURCE
using Microsoft.Diagnostics.Tracing;
#else
using System.Diagnostics.Tracing;
#endif
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace BasicEventSourceTests
{
/// <summary>
/// A listener can represent an out of process ETW listener (real time or not) or an EventListener
/// </summary>
public abstract class Listener : IDisposable
{
public Action<Event> OnEvent; // Called when you get events.
public abstract void Dispose();
/// <summary>
/// Send a command to an eventSource. Be careful this is async. You may wish to do a WaitForEnable
/// </summary>
public abstract void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null);
public void EventSourceSynchronousEnable(EventSource eventSource, FilteringOptions options = null)
{
EventSourceCommand(eventSource.Name, EventCommand.Enable, options);
WaitForEnable(eventSource);
}
public void WaitForEnable(EventSource logger)
{
if (!SpinWait.SpinUntil(() => logger.IsEnabled(), TimeSpan.FromSeconds(10)))
{
throw new InvalidOperationException("EventSource not enabled after 5 seconds");
}
}
internal void EnableTimer(EventSource eventSource, double pollingTime)
{
FilteringOptions options = new FilteringOptions();
options.Args = new Dictionary<string, string>();
options.Args.Add("EventCounterIntervalSec", pollingTime.ToString());
EventSourceCommand(eventSource.Name, EventCommand.Enable, options);
}
}
/// <summary>
/// Used to control what options the harness sends to the EventSource when turning it on. If not given
/// it turns on all keywords, Verbose level, and no args.
/// </summary>
public class FilteringOptions
{
public FilteringOptions() { Keywords = EventKeywords.All; Level = EventLevel.Verbose; }
public EventKeywords Keywords;
public EventLevel Level;
public IDictionary<string, string> Args;
public override string ToString()
{
return string.Format("<Options Keywords='{0}' Level'{1}' ArgsCount='{2}'",
((ulong)Keywords).ToString("x"), Level, Args.Count);
}
}
/// <summary>
/// Because events can be written to a EventListener as well as to ETW, we abstract what the result
/// of an event coming out of the pipe. Basically there are properties that fetch the name
/// and the payload values, and we subclass this for the ETW case and for the EventListener case.
/// </summary>
public abstract class Event
{
public virtual bool IsEtw { get { return false; } }
public virtual bool IsEventListener { get { return false; } }
public abstract string ProviderName { get; }
public abstract string EventName { get; }
public abstract object PayloadValue(int propertyIndex, string propertyName);
public abstract int PayloadCount { get; }
public virtual string PayloadString(int propertyIndex, string propertyName)
{
var obj = PayloadValue(propertyIndex, propertyName);
var asDict = obj as IDictionary<string, object>;
if (asDict != null)
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
bool first = true;
foreach (var key in asDict.Keys)
{
if (!first)
sb.Append(",");
first = false;
var value = asDict[key];
sb.Append(key).Append(":").Append(value != null ? value.ToString() : "NULL");
}
sb.Append("}");
return sb.ToString();
}
if (obj != null)
return obj.ToString();
return "";
}
public abstract IList<string> PayloadNames { get; }
#if DEBUG
/// <summary>
/// This is a convenience function for the debugger. It is not used typically
/// </summary>
public List<object> PayloadValues
{
get
{
var ret = new List<object>();
for (int i = 0; i < PayloadCount; i++)
ret.Add(PayloadValue(i, null));
return ret;
}
}
#endif
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(ProviderName).Append('/').Append(EventName).Append('(');
for (int i = 0; i < PayloadCount; i++)
{
if (i != 0)
sb.Append(',');
sb.Append(PayloadString(i, null));
}
sb.Append(')');
return sb.ToString();
}
}
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/**************************************************************************/
/* Concrete implementation of the Listener abstraction */
/// <summary>
/// Implementation of the Listener abstraction for ETW.
/// </summary>
public class EtwListener : Listener
{
internal static void EnsureStopped()
{
using (var session = new TraceEventSession("EventSourceTestSession", "EventSourceTestData.etl"))
session.Stop();
}
public EtwListener(string dataFileName = "EventSourceTestData.etl", string sessionName = "EventSourceTestSession")
{
_dataFileName = dataFileName;
// Today you have to be Admin to turn on ETW events (anyone can write ETW events).
if (TraceEventSession.IsElevated() != true)
{
throw new ApplicationException("Need to be elevated to run. ");
}
if (dataFileName == null)
{
Debug.WriteLine("Creating a real time session " + sessionName);
Task.Factory.StartNew(delegate ()
{
var session = new TraceEventSession(sessionName, dataFileName);
session.Source.AllEvents += OnEventHelper;
Debug.WriteLine("Listening for real time events");
_session = session; // Indicate that we are alive.
_session.Source.Process();
Debug.WriteLine("Real time listening stopping.");
});
SpinWait.SpinUntil(() => _session != null); // Wait for real time thread to wake up.
}
else
{
// Normalize to a full path name.
dataFileName = Path.GetFullPath(dataFileName);
Debug.WriteLine("Creating ETW data file " + Path.GetFullPath(dataFileName));
_session = new TraceEventSession(sessionName, dataFileName);
}
}
public override void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null)
{
if (command == EventCommand.Enable)
{
if (options == null)
options = new FilteringOptions();
_session.EnableProvider(eventSourceName, (TraceEventLevel)options.Level, (ulong)options.Keywords,
new TraceEventProviderOptions() { Arguments = options.Args });
}
else if (command == EventCommand.Disable)
{
_session.DisableProvider(TraceEventProviders.GetEventSourceGuidFromName(eventSourceName));
}
else
throw new NotImplementedException();
Thread.Sleep(200); // Calls are async, give them time to work.
}
public override void Dispose()
{
_session.Flush();
Thread.Sleep(1010); // Let it drain.
_session.Dispose(); // This also will kill the real time thread
if (_dataFileName != null)
{
using (var traceEventSource = new ETWTraceEventSource(_dataFileName))
{
Debug.WriteLine("Processing data file " + Path.GetFullPath(_dataFileName));
// Parse all the events as best we can, and also send unhandled events there as well.
traceEventSource.Registered.All += OnEventHelper;
traceEventSource.Dynamic.All += OnEventHelper;
traceEventSource.UnhandledEvents += OnEventHelper;
// Process all the events in the file.
traceEventSource.Process();
Debug.WriteLine("Done processing data file " + Path.GetFullPath(_dataFileName));
}
}
}
#region private
private void OnEventHelper(TraceEvent data)
{
// Ignore manifest events.
if ((int)data.ID == 0xFFFE)
return;
this.OnEvent(new EtwEvent(data));
}
/// <summary>
/// EtwEvent implements the 'Event' abstraction for ETW events (it has a TraceEvent in it)
/// </summary>
internal class EtwEvent : Event
{
public override bool IsEtw { get { return true; } }
public override string ProviderName { get { return _data.ProviderName; } }
public override string EventName { get { return _data.EventName; } }
public override object PayloadValue(int propertyIndex, string propertyName)
{
if (propertyName != null)
Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]);
return _data.PayloadValue(propertyIndex);
}
public override string PayloadString(int propertyIndex, string propertyName)
{
Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]);
return _data.PayloadString(propertyIndex);
}
public override int PayloadCount { get { return _data.PayloadNames.Length; } }
public override IList<string> PayloadNames { get { return _data.PayloadNames; } }
#region private
internal EtwEvent(TraceEvent data) { _data = data.Clone(); }
private TraceEvent _data;
#endregion
}
private string _dataFileName;
private volatile TraceEventSession _session;
#endregion
}
#endif //USE_ETW
public class EventListenerListener : Listener
{
private EventListener _listener;
private Action<EventSource> _onEventSourceCreated;
#if FEATURE_ETLEVENTS
public event EventHandler<EventSourceCreatedEventArgs> EventSourceCreated
{
add
{
if (this._listener != null)
this._listener.EventSourceCreated += value;
}
remove
{
if (this._listener != null)
this._listener.EventSourceCreated -= value;
}
}
public event EventHandler<EventWrittenEventArgs> EventWritten
{
add
{
if (this._listener != null)
this._listener.EventWritten += value;
}
remove
{
if (this._listener != null)
this._listener.EventWritten -= value;
}
}
#endif
public EventListenerListener(bool useEventsToListen = false)
{
#if FEATURE_ETLEVENTS
if (useEventsToListen)
{
_listener = new HelperEventListener(null);
_listener.EventSourceCreated += (sender, eventSourceCreatedEventArgs)
=> _onEventSourceCreated?.Invoke(eventSourceCreatedEventArgs.EventSource);
_listener.EventWritten += mListenerEventWritten;
}
else
#endif
{
_listener = new HelperEventListener(this);
}
}
public override void Dispose()
{
EventTestHarness.LogWriteLine("Disposing Listener");
_listener.Dispose();
}
private void DoCommand(EventSource source, EventCommand command, FilteringOptions options)
{
if (command == EventCommand.Enable)
_listener.EnableEvents(source, options.Level, options.Keywords, options.Args);
else if (command == EventCommand.Disable)
_listener.DisableEvents(source);
else
throw new NotImplementedException();
}
public override void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null)
{
EventTestHarness.LogWriteLine("Sending command {0} to EventSource {1} Options {2}", eventSourceName, command, options);
if (options == null)
options = new FilteringOptions();
foreach (EventSource source in EventSource.GetSources())
{
if (source.Name == eventSourceName)
{
DoCommand(source, command, options);
return;
}
}
_onEventSourceCreated += delegate (EventSource sourceBeingCreated)
{
if (eventSourceName != null && eventSourceName == sourceBeingCreated.Name)
{
DoCommand(sourceBeingCreated, command, options);
eventSourceName = null; // so we only do it once.
}
};
}
private void mListenerEventWritten(object sender, EventWrittenEventArgs eventData)
{
OnEvent(new EventListenerEvent(eventData));
}
private class HelperEventListener : EventListener
{
private readonly EventListenerListener _forwardTo;
public HelperEventListener(EventListenerListener forwardTo)
{
_forwardTo = forwardTo;
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
base.OnEventSourceCreated(eventSource);
_forwardTo?._onEventSourceCreated?.Invoke(eventSource);
}
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
#if FEATURE_ETLEVENTS
// OnEventWritten is abstract in netfx <= 461
base.OnEventWritten(eventData);
#endif
_forwardTo?.OnEvent?.Invoke(new EventListenerEvent(eventData));
}
}
/// <summary>
/// EtwEvent implements the 'Event' abstraction for TraceListene events (it has a EventWrittenEventArgs in it)
/// </summary>
internal class EventListenerEvent : Event
{
private readonly EventWrittenEventArgs _data;
public override bool IsEventListener { get { return true; } }
public override string ProviderName { get { return _data.EventSource.Name; } }
public override string EventName { get { return _data.EventName; } }
public override IList<string> PayloadNames { get { return _data.PayloadNames; } }
public override int PayloadCount
{
get { return _data.Payload?.Count ?? 0; }
}
internal EventListenerEvent(EventWrittenEventArgs data)
{
_data = data;
}
public override object PayloadValue(int propertyIndex, string propertyName)
{
if (propertyName != null)
Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]);
return _data.Payload[propertyIndex];
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace PlayFab.PfEditor
{
public class PlayFabEditorSDKTools : UnityEditor.Editor
{
private const int buttonWidth = 150;
public static bool IsInstalled { get { return GetPlayFabSettings() != null; } }
private static Type playFabSettingsType = null;
private static string installedSdkVersion = string.Empty;
private static string latestSdkVersion = string.Empty;
private static UnityEngine.Object sdkFolder;
private static UnityEngine.Object _previousSdkFolderPath;
private static bool isObjectFieldActive;
private static bool isInitialized; //used to check once, gets reset after each compile;
public static bool isSdkSupported = true;
public static void DrawSdkPanel()
{
if (!isInitialized)
{
//SDK is installed.
CheckSdkVersion();
isInitialized = true;
GetLatestSdkVersion();
sdkFolder = FindSdkAsset();
if (sdkFolder != null)
{
PlayFabEditorPrefsSO.Instance.SdkPath = AssetDatabase.GetAssetPath(sdkFolder);
PlayFabEditorDataService.SaveEnvDetails();
}
}
if (IsInstalled)
ShowSdkInstalledMenu();
else
ShowSdkNotInstalledMenu();
}
private static void ShowSdkInstalledMenu()
{
isObjectFieldActive = sdkFolder == null;
if (_previousSdkFolderPath != sdkFolder)
{
// something changed, better save the result.
_previousSdkFolderPath = sdkFolder;
PlayFabEditorPrefsSO.Instance.SdkPath = (AssetDatabase.GetAssetPath(sdkFolder));
PlayFabEditorDataService.SaveEnvDetails();
isObjectFieldActive = false;
}
var labelStyle = new GUIStyle(PlayFabEditorHelper.uiStyle.GetStyle("titleLabel"));
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
EditorGUILayout.LabelField(string.Format("SDK {0} is installed", string.IsNullOrEmpty(installedSdkVersion) ? "Unknown" : installedSdkVersion),
labelStyle, GUILayout.MinWidth(EditorGUIUtility.currentViewWidth));
if (!isObjectFieldActive)
{
GUI.enabled = false;
}
else
{
EditorGUILayout.LabelField(
"An SDK was detected, but we were unable to find the directory. Drag-and-drop the top-level PlayFab SDK folder below.",
PlayFabEditorHelper.uiStyle.GetStyle("orTxt"));
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
sdkFolder = EditorGUILayout.ObjectField(sdkFolder, typeof(UnityEngine.Object), false, GUILayout.MaxWidth(200));
GUILayout.FlexibleSpace();
}
if (!isObjectFieldActive)
{
// this is a hack to prevent our "block while loading technique" from breaking up at this point.
GUI.enabled = !EditorApplication.isCompiling && PlayFabEditor.blockingRequests.Count == 0;
}
if (isSdkSupported && sdkFolder != null)
{
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("REMOVE SDK", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32), GUILayout.MinWidth(200)))
{
RemoveSdk();
}
GUILayout.FlexibleSpace();
}
}
}
if (sdkFolder != null)
{
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
isSdkSupported = false;
string[] versionNumber = !string.IsNullOrEmpty(installedSdkVersion) ? installedSdkVersion.Split('.') : new string[0];
var numerical = 0;
if (string.IsNullOrEmpty(installedSdkVersion) || versionNumber == null || versionNumber.Length == 0 ||
(versionNumber.Length > 0 && int.TryParse(versionNumber[0], out numerical) && numerical < 2))
{
//older version of the SDK
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
EditorGUILayout.LabelField("Most of the Editor Extensions depend on SDK versions >2.0. Consider upgrading to the get most features.", PlayFabEditorHelper.uiStyle.GetStyle("orTxt"));
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("READ THE UPGRADE GUIDE", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32)))
{
Application.OpenURL("https://github.com/PlayFab/UnitySDK/blob/master/UPGRADE.md");
}
GUILayout.FlexibleSpace();
}
}
else if (numerical >= 2)
{
isSdkSupported = true;
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
if (ShowSDKUpgrade() && isSdkSupported)
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Upgrade to " + latestSdkVersion, PlayFabEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MinHeight(32)))
{
UpgradeSdk();
}
GUILayout.FlexibleSpace();
}
else if (isSdkSupported)
{
GUILayout.FlexibleSpace();
EditorGUILayout.LabelField("You have the latest SDK!", labelStyle, GUILayout.MinHeight(32));
GUILayout.FlexibleSpace();
}
}
}
}
if (isSdkSupported && string.IsNullOrEmpty(PlayFabEditorDataService.SharedSettings.TitleId))
{
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
EditorGUILayout.LabelField("Before making PlayFab API calls, the SDK must be configured to your PlayFab Title.", PlayFabEditorHelper.uiStyle.GetStyle("orTxt"));
using (new UnityHorizontal())
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("SET MY TITLE", PlayFabEditorHelper.uiStyle.GetStyle("textButton")))
{
PlayFabEditorMenu.OnSettingsClicked();
}
GUILayout.FlexibleSpace();
}
}
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("VIEW RELEASE NOTES", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32), GUILayout.MinWidth(200)))
{
Application.OpenURL("https://docs.microsoft.com/en-us/gaming/playfab/release-notes/");
}
GUILayout.FlexibleSpace();
}
}
private static void ShowSdkNotInstalledMenu()
{
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
var labelStyle = new GUIStyle(PlayFabEditorHelper.uiStyle.GetStyle("titleLabel"));
EditorGUILayout.LabelField("No SDK is installed.", labelStyle, GUILayout.MinWidth(EditorGUIUtility.currentViewWidth));
GUILayout.Space(20);
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Refresh", PlayFabEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MaxWidth(buttonWidth), GUILayout.MinHeight(32)))
playFabSettingsType = null;
GUILayout.FlexibleSpace();
if (GUILayout.Button("Install PlayFab SDK", PlayFabEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MaxWidth(buttonWidth), GUILayout.MinHeight(32)))
ImportLatestSDK();
GUILayout.FlexibleSpace();
}
}
}
public static void ImportLatestSDK()
{
PlayFabEditorHttp.MakeDownloadCall("https://aka.ms/PlayFabUnitySdk", (fileName) =>
{
Debug.Log("PlayFab SDK Install: Complete");
AssetDatabase.ImportPackage(fileName, false);
// attempts to re-import any changed assets (which ImportPackage doesn't implicitly do)
AssetDatabase.Refresh();
PlayFabEditorPrefsSO.Instance.SdkPath = PlayFabEditorHelper.DEFAULT_SDK_LOCATION;
PlayFabEditorDataService.SaveEnvDetails();
});
}
public static Type GetPlayFabSettings()
{
if (playFabSettingsType == typeof(object))
return null; // Sentinel value to indicate that PlayFabSettings doesn't exist
if (playFabSettingsType != null)
return playFabSettingsType;
playFabSettingsType = typeof(object); // Sentinel value to indicate that PlayFabSettings doesn't exist
var allAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in allAssemblies)
{
Type[] assemblyTypes;
try
{
assemblyTypes = assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
assemblyTypes = e.Types;
}
foreach (var eachType in assemblyTypes)
if (eachType != null)
if (eachType.Name == PlayFabEditorHelper.PLAYFAB_SETTINGS_TYPENAME)
playFabSettingsType = eachType;
}
//if (playFabSettingsType == typeof(object))
// Debug.LogWarning("Should not have gotten here: " + allAssemblies.Length);
//else
// Debug.Log("Found Settings: " + allAssemblies.Length + ", " + playFabSettingsType.Assembly.FullName);
return playFabSettingsType == typeof(object) ? null : playFabSettingsType;
}
private static void CheckSdkVersion()
{
if (!string.IsNullOrEmpty(installedSdkVersion))
return;
var types = new List<Type>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
foreach (var type in assembly.GetTypes())
if (type.Name == "PlayFabVersion" || type.Name == PlayFabEditorHelper.PLAYFAB_SETTINGS_TYPENAME)
types.Add(type);
}
catch (ReflectionTypeLoadException)
{
// For this failure, silently skip this assembly unless we have some expectation that it contains PlayFab
if (assembly.FullName.StartsWith("Assembly-CSharp")) // The standard "source-code in unity proj" assembly name
Debug.LogWarning("PlayFab EdEx Error, failed to access the main CSharp assembly that probably contains PlayFab. Please report this on the PlayFab Forums");
continue;
}
}
foreach (var type in types)
{
foreach (var property in type.GetProperties())
if (property.Name == "SdkVersion" || property.Name == "SdkRevision")
installedSdkVersion += property.GetValue(property, null).ToString();
foreach (var field in type.GetFields())
if (field.Name == "SdkVersion" || field.Name == "SdkRevision")
installedSdkVersion += field.GetValue(field).ToString();
}
}
private static UnityEngine.Object FindSdkAsset()
{
UnityEngine.Object sdkAsset = null;
// look in editor prefs
if (PlayFabEditorPrefsSO.Instance.SdkPath != null)
{
sdkAsset = AssetDatabase.LoadAssetAtPath(PlayFabEditorPrefsSO.Instance.SdkPath, typeof(UnityEngine.Object));
}
if (sdkAsset != null)
return sdkAsset;
sdkAsset = AssetDatabase.LoadAssetAtPath(PlayFabEditorHelper.DEFAULT_SDK_LOCATION, typeof(UnityEngine.Object));
if (sdkAsset != null)
return sdkAsset;
var fileList = Directory.GetDirectories(Application.dataPath, "*PlayFabSdk", SearchOption.AllDirectories);
if (fileList.Length == 0)
return null;
var relPath = fileList[0].Substring(fileList[0].LastIndexOf("Assets"));
return AssetDatabase.LoadAssetAtPath(relPath, typeof(UnityEngine.Object));
}
private static bool ShowSDKUpgrade()
{
if (string.IsNullOrEmpty(latestSdkVersion) || latestSdkVersion == "Unknown")
{
return false;
}
if (string.IsNullOrEmpty(installedSdkVersion) || installedSdkVersion == "Unknown")
{
return true;
}
string[] currrent = installedSdkVersion.Split('.');
string[] latest = latestSdkVersion.Split('.');
if (int.Parse(currrent[0]) < 2)
{
return false;
}
return int.Parse(latest[0]) > int.Parse(currrent[0])
|| int.Parse(latest[1]) > int.Parse(currrent[1])
|| int.Parse(latest[2]) > int.Parse(currrent[2]);
}
private static void UpgradeSdk()
{
if (EditorUtility.DisplayDialog("Confirm SDK Upgrade", "This action will remove the current PlayFab SDK and install the lastet version. Related plug-ins will need to be manually upgraded.", "Confirm", "Cancel"))
{
RemoveSdk(false);
ImportLatestSDK();
}
}
private static void RemoveSdk(bool prompt = true)
{
if (prompt && !EditorUtility.DisplayDialog("Confirm SDK Removal", "This action will remove the current PlayFab SDK. Related plug-ins will need to be manually removed.", "Confirm", "Cancel"))
return;
//try to clean-up the plugin dirs
if (Directory.Exists(Application.dataPath + "/Plugins"))
{
var folders = Directory.GetDirectories(Application.dataPath + "/Plugins", "PlayFabShared", SearchOption.AllDirectories);
foreach (var folder in folders)
FileUtil.DeleteFileOrDirectory(folder);
//try to clean-up the plugin files (if anything is left)
var files = Directory.GetFiles(Application.dataPath + "/Plugins", "PlayFabErrors.cs", SearchOption.AllDirectories);
foreach (var file in files)
FileUtil.DeleteFileOrDirectory(file);
}
if (!string.IsNullOrEmpty(PlayFabEditorPrefsSO.Instance.SdkPath) && FileUtil.DeleteFileOrDirectory(PlayFabEditorPrefsSO.Instance.SdkPath))
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnSuccess, "PlayFab SDK Removed!");
// HACK for 5.4, AssetDatabase.Refresh(); seems to cause the install to fail.
if (prompt)
{
AssetDatabase.Refresh();
}
}
else
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, "An unknown error occured and the PlayFab SDK could not be removed.");
}
}
private static void GetLatestSdkVersion()
{
var threshold = PlayFabEditorPrefsSO.Instance.EdSet_lastSdkVersionCheck != DateTime.MinValue ? PlayFabEditorPrefsSO.Instance.EdSet_lastSdkVersionCheck.AddHours(1) : DateTime.MinValue;
if (DateTime.Today > threshold)
{
PlayFabEditorHttp.MakeGitHubApiCall("https://api.github.com/repos/PlayFab/UnitySDK/git/refs/tags", (version) =>
{
latestSdkVersion = version ?? "Unknown";
PlayFabEditorPrefsSO.Instance.EdSet_latestSdkVersion = latestSdkVersion;
});
}
else
{
latestSdkVersion = PlayFabEditorPrefsSO.Instance.EdSet_latestSdkVersion;
}
}
}
}
| |
using System.Collections.Generic;
using System.Globalization;
namespace Masb.Languages.Experimentals.PolyMethodic
{
public class Tokenizer
{
private static readonly string CrLf = "\r\n";
private static readonly string Separators = "\f\n\r\t\v\x85";
private static readonly string[] TripleCharSymbols = { "<<=", ">>=" };
private static readonly string[] TwinCharSymbols = { ".?", "++", "--", "->", "||", "&&", ">=", "<=", "!=", "==", "??", "=>", "<<", ">>", "+=", "-=", "*=", "/=", "|=", "&=", "%=", "^=" };
private static readonly string SingleCharSymbols = ":+-*/|&{}()[]<>,;?=!~%^.";
private static readonly string NumberPostfixesWithDot = "mfdMFD";
private static readonly string NumberPostfixesWithoutDot = "ulmfdULMFD";
private static readonly string NumberPostfixesHex = "ulUL";
private static readonly string HexDigits = "0123456789abcdefABCDEF";
public static IEnumerable<Token> Read(string code)
{
var pos = 0;
if (code != null)
{
yield return new StartFileToken(code);
while (true)
{
var oldPos = pos;
var token = ReadSpace(code, ref pos) as Token
?? ReadIdentifierOrKeyword(code, ref pos) as Token
?? ReadSymbol(code, ref pos) as Token
?? ReadNumber(code, ref pos) as Token
?? ReadEndFile(code, ref pos) as Token;
if (token == null)
break;
yield return token;
if (pos == oldPos)
break;
}
}
}
private static EndFileToken ReadEndFile(string code, ref int pos)
{
return pos == code.Length ? new EndFileToken(code) : null;
}
private static SymbolToken ReadSymbol(string code, ref int pos)
{
if (pos + 1 < code.Length)
for (int it = 0; it < TwinCharSymbols.Length; it++)
if (TwinCharSymbols[it][0] == code[pos] && TwinCharSymbols[it][1] == code[pos + 1])
{
var subtype = TokenSubtypeHelper.FromTokenText(code.Substring(pos, 2));
pos += 2;
return new SymbolToken(code, pos - 2, 2, subtype ?? TokenSubtype.Error);
}
if (pos < code.Length)
if (SingleCharSymbols.IndexOf(code[pos]) >= 0)
{
var subtype = TokenSubtypeHelper.FromTokenText(code.Substring(pos, 1));
return new SymbolToken(code, pos++, 1, subtype ?? TokenSubtype.Error);
}
return null;
}
private static IdentifierOrKeywordToken ReadIdentifierOrKeyword(string code, ref int pos)
{
var oldPos = pos;
if (pos < code.Length && (char.IsLetter(code[pos]) || code[pos] == '_'))
{
pos++;
while (pos < code.Length && (char.IsLetterOrDigit(code[pos]) || code[pos] == '_'))
pos++;
}
var subtype = TokenSubtypeHelper.FromTokenText(code.Substring(oldPos, pos - oldPos))
?? TokenSubtype.IdentifierOrContextualKeyword;
return pos == oldPos ? null : new IdentifierOrKeywordToken(code, oldPos, pos - oldPos, subtype);
}
private static NumberToken ReadNumber(string code, ref int pos)
{
var oldPos = pos;
bool isHex = false;
if (pos + 2 < code.Length && (code[pos + 1] == 'x' || code[pos + 1] == 'X') && code[pos] == '0')
if (HexDigits.IndexOf(code[pos + 2]) >= 0)
{
isHex = true;
pos += 3;
}
while (pos < code.Length && char.IsDigit(code[pos]))
pos++;
bool hasDot = false;
if (!isHex && pos + 1 < code.Length && code[pos] == '.')
{
if (char.IsDigit(code[pos + 1]))
{
hasDot = true;
pos += 2;
while (pos < code.Length && char.IsDigit(code[pos]))
pos++;
}
}
bool isExpNotation = false;
if (pos + 1 < code.Length && (code[pos] == 'e' || code[pos] == 'E'))
{
if (pos + 2 < code.Length && (code[pos + 1] == '+' || code[pos + 1] == '-'))
{
if (char.IsDigit(code[pos + 2]))
{
isExpNotation = true;
pos += 3;
}
}
else if (char.IsDigit(code[pos + 1]))
{
isExpNotation = true;
pos += 2;
}
while (pos < code.Length && char.IsDigit(code[pos]))
pos++;
}
if (hasDot || isExpNotation)
{
if (pos < code.Length && NumberPostfixesWithDot.IndexOf(code[pos]) >= 0)
pos++;
return new NumberToken(code, oldPos, pos - oldPos, TokenSubtype.FloatNumber);
}
if (isHex)
{
if (pos < code.Length && NumberPostfixesHex.IndexOf(code[pos]) >= 0)
pos++;
return new NumberToken(code, oldPos, pos - oldPos, TokenSubtype.HexNumber);
}
// ends with "ul", "Ul", "uL", "UL", "lu", "Lu", "lU", "LU"
if (pos + 1 < code.Length && (
((code[pos] == 'U' || code[pos] == 'u') && (code[pos + 1] == 'L' || code[pos + 1] == 'l')) ||
((code[pos] == 'L' || code[pos] == 'l') && (code[pos + 1] == 'U' || code[pos + 1] == 'u'))))
{
pos += 2;
}
else if (pos < code.Length && NumberPostfixesWithoutDot.IndexOf(code[pos]) >= 0)
{
pos++;
}
if (pos > oldPos)
return new NumberToken(code, oldPos, pos - oldPos, TokenSubtype.IntegerNumber);
return null;
}
private static SpaceToken ReadSpace(string code, ref int pos)
{
var oldPos = pos;
if (pos + 1 < code.Length && code[pos] == '/')
{
if (code[pos + 1] == '/')
{
pos += 2;
while (pos < code.Length && CrLf.IndexOf(code[pos]) < 0)
pos++;
return new SpaceToken(code, oldPos, pos - oldPos, TokenSubtype.SingleLineCommentSpace);
}
if (code[pos + 1] == '*')
{
pos += 2;
while (pos + 1 < code.Length && code[pos] != '*' && code[pos + 1] != '/')
pos++;
pos += 2;
return pos == oldPos ? null : new SpaceToken(code, oldPos, pos - oldPos, TokenSubtype.MultiLineCommentSpace);
}
}
else
{
while (pos < code.Length &&
(Separators.IndexOf(code[pos]) >= 0 || char.GetUnicodeCategory(code[pos]) == UnicodeCategory.SpaceSeparator))
pos++;
return pos == oldPos ? null : new SpaceToken(code, oldPos, pos - oldPos, TokenSubtype.SpaceChars);
}
return null;
}
}
}
| |
#region License
// Copyright (c) 2007-2018, Sean Chambers <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.IO;
using System.Text;
using FluentMigrator.Console;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Runners
{
[TestFixture]
public class MigratorConsoleTests
{
private const string Database = "SQLite";
private const string Connection = "Data Source=:memory:";
private const string Target = "FluentMigrator.Tests.dll";
[Test]
public void CanInitMigratorConsoleWithValidArguments()
{
var console = new MigratorConsole();
console.Run(
"/db", Database,
"/connection", Connection,
"/target", Target,
"/namespace", "FluentMigrator.Tests.Integration.Migrations",
"/nested",
"/task", "migrate:up",
"/version", "1");
console.Connection.ShouldBe(Connection);
console.Namespace.ShouldBe("FluentMigrator.Tests.Integration.Migrations");
console.NestedNamespaces.ShouldBeTrue();
console.Task.ShouldBe("migrate:up");
console.Version.ShouldBe(1);
}
[Test]
public void CanInitMigratorConsoleWithValidArgumentsRegardlessOfCase()
{
var console = new MigratorConsole();
console.Run(
"/db", Database,
"/Connection", Connection,
"/target", Target,
"/namespace", "FluentMigrator.Tests.Integration.Migrations",
"/nested",
"/TASK", "migrate:up",
"/vErSiOn", "1");
console.Connection.ShouldBe(Connection);
console.Namespace.ShouldBe("FluentMigrator.Tests.Integration.Migrations");
console.NestedNamespaces.ShouldBeTrue();
console.Task.ShouldBe("migrate:up");
console.Version.ShouldBe(1);
}
[Test]
public void ConsoleAnnouncerHasMoreOutputWhenVerbose()
{
var sbNonVerbose = new StringBuilder();
var stringWriterNonVerbose = new StringWriter(sbNonVerbose);
System.Console.SetOut(stringWriterNonVerbose);
System.Console.SetError(stringWriterNonVerbose);
new MigratorConsole().Run(
"/db", Database,
"/connection", Connection,
"/target", Target,
"/namespace", "FluentMigrator.Tests.Integration.Migrations",
"/task", "migrate:up",
"/version", "1");
var sbVerbose = new StringBuilder();
var stringWriterVerbose = new StringWriter(sbVerbose);
System.Console.SetOut(stringWriterVerbose);
new MigratorConsole().Run(
"/db", Database,
"/connection", Connection,
"/verbose", "1",
"/target", Target,
"/namespace", "FluentMigrator.Tests.Integration.Migrations",
"/task", "migrate:up",
"/version", "1");
Assert.Greater(sbVerbose.ToString().Length, sbNonVerbose.ToString().Length);
}
[Test]
public void ConsoleAnnouncerHasOutput()
{
var sb = new StringBuilder();
var stringWriter = new StringWriter(sb);
System.Console.SetOut(stringWriter);
System.Console.SetError(stringWriter);
new MigratorConsole().Run(
"/db", Database,
"/connection", Connection,
"/target", Target,
"/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations",
"/task", "migrate:up",
"/version", "0");
var output = sb.ToString();
Assert.AreNotEqual(0, output.Length);
}
[Test]
public void ConsoleAnnouncerHasOutputEvenIfMarkedAsPreviewOnlyMigrateUp()
{
var sb = new StringBuilder();
var stringWriter = new StringWriter(sb);
System.Console.SetOut(stringWriter);
System.Console.SetError(stringWriter);
new MigratorConsole().Run(
"/db", Database,
"/connection", Connection,
"/target", Target,
"/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations",
"/verbose", "true",
"/task", "migrate:up",
"/preview");
var output = sb.ToString();
Assert.That(output.Contains("PREVIEW-ONLY MODE"));
Assert.AreNotEqual(0, output.Length);
}
[Test]
public void ConsoleAnnouncerHasOutputEvenIfMarkedAsPreviewOnlyMigrateDown()
{
var sb = new StringBuilder();
var stringWriter = new StringWriter(sb);
System.Console.SetOut(stringWriter);
System.Console.SetError(stringWriter);
new MigratorConsole().Run(
"/db", Database,
"/connection", Connection,
"/target", Target,
"/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations",
"/verbose", "true",
"/task", "migrate:down",
"/version", "2",
"/preview");
var output = sb.ToString();
Assert.That(output.Contains("PREVIEW-ONLY MODE"));
Assert.AreNotEqual(0, output.Length);
}
[Test]
public void FileAnnouncerHasOutputToDefaultOutputFile()
{
var outputFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Target + ".sql");
if (File.Exists(outputFileName))
{
File.Delete(outputFileName);
}
Assert.IsFalse(File.Exists(outputFileName));
new MigratorConsole().Run(
"/db", Database,
"/connection", Connection,
"/target", Target,
"/output",
"/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations",
"/task", "migrate:up",
"/version", "0");
Assert.IsTrue(File.Exists(outputFileName));
File.Delete(outputFileName);
}
[Test]
public void FileAnnouncerHasOutputToSpecifiedOutputFile()
{
var outputFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.sql");
if (File.Exists(outputFileName))
{
File.Delete(outputFileName);
}
Assert.IsFalse(File.Exists(outputFileName));
new MigratorConsole().Run(
"/db", Database,
"/connection", Connection,
"/target", Target,
"/output",
"/outputFilename", outputFileName,
"/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations",
"/task", "migrate:up",
"/version", "0");
Assert.IsTrue(File.Exists(outputFileName));
File.Delete(outputFileName);
}
[Test]
public void MustInitializeConsoleWithConnectionArgument()
{
var exitCode = new MigratorConsole().Run("/db", Database);
Assert.That(exitCode, Is.EqualTo(1));
}
[Test]
public void MustInitializeConsoleWithDatabaseArgument()
{
var exitCode = new MigratorConsole().Run("/connection", Connection);
Assert.That(exitCode, Is.EqualTo(1));
}
[Test]
public void TagsPassedToRunnerContextOnExecuteMigrations()
{
var migratorConsole = new MigratorConsole();
migratorConsole.Run(
"/db", Database,
"/connection", Connection,
"/verbose", "1",
"/target", Target,
"/namespace", "FluentMigrator.Tests.Integration.Migrations",
"/task", "migrate:up",
"/version", "1",
"/tag", "uk",
"/tag", "production");
var expectedTags = new[] { "uk", "production" };
CollectionAssert.AreEquivalent(expectedTags, migratorConsole.Tags);
}
[Test]
public void TransactionPerSessionShouldBeSetOnRunnerContextWithShortSwitch()
{
var console = new MigratorConsole();
console.Run(
"/db", Database,
"/connection", Connection,
"/target", Target,
"/task", "migrate:up",
"/tps");
console.TransactionPerSession.ShouldBeTrue();
}
[Test]
public void TransactionPerSessionShouldBeSetOnRunnerContextWithLongSwitch()
{
var console = new MigratorConsole();
console.Run(
"/db", Database,
"/connection", Connection,
"/target", Target,
"/task", "migrate:up",
"/transaction-per-session");
console.TransactionPerSession.ShouldBeTrue();
}
[Test]
public void ProviderSwitchesPassedToRunnerContextOnExecuteMigrations()
{
var migratorConsole = new MigratorConsole();
migratorConsole.Run(
"/db", Database,
"/connection", Connection,
"/target", Target,
"/output",
"/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations",
"/task", "migrate:up",
"/version", "0",
"/providerswitches", "QuotedIdentifiers=true");
const string expectedProviderSwitces = "QuotedIdentifiers=true";
CollectionAssert.AreEquivalent(expectedProviderSwitces, migratorConsole.ProviderSwitches);
}
}
}
| |
namespace Merchello.Web.Pluggable
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Web;
using Merchello.Core;
using Merchello.Core.Cache;
using Merchello.Core.Configuration;
using Merchello.Core.Logging;
using Merchello.Core.Models;
using Merchello.Core.Services;
using Merchello.Web.Models.Customer;
using Merchello.Web.Workflow;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Web;
/// <summary>
/// A base class for defining customer contexts for various membership providers.
/// </summary>
public abstract class CustomerContextBase : ICustomerContext
{
#region Fields
/// <summary>
/// The key used to store the Umbraco Member Id in CustomerContextData.
/// </summary>
protected const string UmbracoMemberIdDataKey = "umbMemberId";
/// <summary>
/// The consumer cookie key.
/// </summary>
protected const string CustomerCookieName = "merchello";
/// <summary>
/// The merchello context.
/// </summary>
private readonly IMerchelloContext _merchelloContext;
/// <summary>
/// The customer service.
/// </summary>
private readonly ICustomerService _customerService;
/// <summary>
/// The <see cref="UmbracoContext"/>.
/// </summary>
private readonly UmbracoContext _umbracoContext;
/// <summary>
/// The <see cref="CacheHelper"/>.
/// </summary>
private readonly CacheHelper _cache;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CustomerContextBase"/> class.
/// </summary>
/// <param name="umbracoContext">
/// The <see cref="UmbracoContext"/>.
/// </param>
protected CustomerContextBase(UmbracoContext umbracoContext)
: this(MerchelloContext.Current, umbracoContext)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CustomerContextBase"/> class.
/// </summary>
/// <param name="merchelloContext">
/// The <see cref="IMerchelloContext"/>.
/// </param>
/// <param name="umbracoContext">
/// The <see cref="UmbracoContext"/>.
/// </param>
protected CustomerContextBase(IMerchelloContext merchelloContext, UmbracoContext umbracoContext)
{
Mandate.ParameterNotNull(merchelloContext, "merchelloContext");
Mandate.ParameterNotNull(umbracoContext, "umbracoContext");
this._merchelloContext = merchelloContext;
this._umbracoContext = umbracoContext;
this._customerService = merchelloContext.Services.CustomerService;
this._cache = merchelloContext.Cache;
this.Initialize();
}
#endregion
/// <summary>
/// Gets or sets the current customer.
/// </summary>
public ICustomerBase CurrentCustomer { get; protected set; }
/// <summary>
/// Gets the context data.
/// </summary>
protected CustomerContextData ContextData { get; private set; }
/// <summary>
/// Gets the <see cref="UmbracoContext"/>.
/// </summary>
protected UmbracoContext UmbracoContext
{
get
{
return this._umbracoContext;
}
}
/// <summary>
/// Gets the cache.
/// </summary>
protected CacheHelper Cache
{
get
{
return this._cache;
}
}
/// <summary>
/// Gets the <see cref="ICustomerService"/>.
/// </summary>
protected ICustomerService CustomerService
{
get
{
return this._customerService;
}
}
#region ContextData
/// <summary>
/// Sets a value in the encrypted Merchello cookie
/// </summary>
/// <param name="key">
/// The key for the value
/// </param>
/// <param name="value">
/// The actual value to be save.
/// </param>
/// <remarks>
/// Keep in mind this is just a cookie which has limited size. This is intended for
/// small bits of information.
/// </remarks>
public void SetValue(string key, string value)
{
if (this.ContextData.Values.Any(x => x.Key == key))
{
var idx = this.ContextData.Values.FindIndex(x => x.Key == key);
this.ContextData.Values.RemoveAt(idx);
}
this.ContextData.Values.Add(new KeyValuePair<string, string>(key, value));
this.CacheCustomer(this.CurrentCustomer);
}
/// <summary>
/// Gets a value from the encrypted Merchello cookie
/// </summary>
/// <param name="key">
/// The key of the value to retrieve
/// </param>
/// <returns>
/// The value stored in the cookie as a string.
/// </returns>
public string GetValue(string key)
{
return this.ContextData.Values.FirstOrDefault(x => x.Key == key).Value;
}
#endregion
/// <summary>
/// Reinitializes the customer context
/// </summary>
/// <param name="customer">
/// The <see cref="CustomerBase"/>
/// </param>
/// <remarks>
/// Sometimes useful to clear the various caches used internally in the customer context
/// </remarks>
public virtual void Reinitialize(ICustomerBase customer)
{
// customer has logged out, so we need to go back to an anonymous customer
var cookie = this._umbracoContext.HttpContext.Request.Cookies[CustomerCookieName];
if (cookie == null)
{
this.Initialize();
return;
}
cookie.Expires = DateTime.Now.AddDays(-1);
this._cache.RequestCache.ClearCacheItem(CustomerCookieName);
this._cache.RuntimeCache.ClearCacheItem(CacheKeys.CustomerCacheKey(customer.Key));
this.Initialize();
}
/// <summary>
/// Returns true or false indicating whether or not the current membership user is logged in.
/// </summary>
/// <returns>
/// The <see cref="bool"/> indicating whether the current user is logged in.
/// </returns>
protected abstract bool GetIsCurrentlyLoggedIn();
/// <summary>
/// Gets the member/user login or user name used to sign in
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
/// <remarks>
/// Merchello makes the association between membership provider users and Merchello customers by username
/// </remarks>
protected abstract string GetMembershipProviderUserName();
/// <summary>
/// Gets the unique ID from the Membership Provider
/// </summary>
/// <returns>
/// The ID or key from the Membership provider as a string value
/// </returns>
protected abstract string GetMembershipProviderKey();
/// <summary>
/// Attempts to either retrieve an anonymous customer or an existing customer
/// </summary>
/// <param name="key">The key of the customer to retrieve</param>
protected virtual void TryGetCustomer(Guid key)
{
var customer = (ICustomerBase)Cache.RuntimeCache.GetCacheItem(CacheKeys.CustomerCacheKey(key));
// use the IsLoggedIn method to check which gets/sets the value in the Request Cache
var isLoggedIn = this.IsLoggedIn(key);
// Check the cache for a previously retrieved customer.
// There can be many requests for the current customer during a single request.
if (customer != null)
{
CurrentCustomer = customer;
// No we need to assert whether or not the authentication status has changed
// during this request - the user either logged in or has logged out.
if (customer.IsAnonymous)
{
// We have an anonymous customer but the user is now authenticated so we may want to create an
// customer and convert the basket
if (isLoggedIn)
{
this.EnsureCustomerCreationAndConvertBasket(customer);
}
}
else if (customer.IsAnonymous == false && isLoggedIn == false)
{
// The customer that was found was not anonymous and yet the member is
// not logged in.
CreateAnonymousCustomer();
return;
}
else if (customer.IsAnonymous == false && isLoggedIn)
{
// User may have logged out and logged in with a different customer
// Addresses issue http://issues.merchello.com/youtrack/issue/M-454
this.EnsureIsLoggedInCustomer(customer, this.GetMembershipProviderKey());
return;
}
// The customer key MUST be set in the ContextData
ContextData.Key = customer.Key;
return;
}
// Customer has not been cached so we have to start from scratch.
customer = CustomerService.GetAnyByKey(key);
if (customer != null)
{
//// There is either a Customer or Anonymous Customer record
CurrentCustomer = customer;
ContextData.Key = customer.Key;
// The current Membership Providers "ID or Key" is stored in the ContextData so that we can "ensure" that the current logged
// in member is the same as the reference we have to a previously logged in member in the same browser.
if (isLoggedIn) ContextData.Values.Add(new KeyValuePair<string, string>(UmbracoMemberIdDataKey, this.GetMembershipProviderKey()));
// Cache the customer so that for each request we don't have to do a bunch of
// DB lookups.
CacheCustomer(customer);
}
else
{
//// No records were found - create a new Anonymous Customer
CreateAnonymousCustomer();
}
}
/// <summary>
/// The ensure customer and convert basket.
/// </summary>
/// <param name="customer">
/// The customer.
/// </param>
protected virtual void EnsureCustomerCreationAndConvertBasket(ICustomerBase customer)
{
ConvertBasket(customer, this.GetMembershipProviderKey(), this.GetMembershipProviderUserName());
}
/// <summary>
/// Converts an anonymous customer's basket to a customer basket
/// </summary>
/// <param name="customer">
/// The anonymous customer - <see cref="ICustomerBase"/>.
/// </param>
/// <param name="membershipId">
/// The Membership Providers .
/// </param>
/// <param name="customerLoginName">
/// The customer login name.
/// </param>
protected void ConvertBasket(ICustomerBase customer, string membershipId, string customerLoginName)
{
var anonymousBasket = Basket.GetBasket(this._merchelloContext, customer);
customer = this.CustomerService.GetByLoginName(customerLoginName) ??
this.CustomerService.CreateCustomerWithKey(customerLoginName);
this.ContextData.Key = customer.Key;
this.ContextData.Values.Add(new KeyValuePair<string, string>(UmbracoMemberIdDataKey, membershipId));
var customerBasket = Basket.GetBasket(this._merchelloContext, customer);
//// convert the customer basket
ConvertBasket(anonymousBasket, customerBasket);
this.CacheCustomer(customer);
this.CurrentCustomer = customer;
}
/// <summary>
/// Wrapper to cache the logged in status in the request cache
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
protected bool IsLoggedIn(Guid key)
{
return (bool)Cache.RequestCache.GetCacheItem(CacheKeys.CustomerIsLoggedIn(key), () => this.GetIsCurrentlyLoggedIn());
}
/// <summary>
/// Wrapper to cache the membership username in the request cache
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
protected string MembershipUserName(Guid key)
{
return (string)Cache.RequestCache.GetCacheItem(CacheKeys.CustomerMembershipUserName(key), this.GetMembershipProviderUserName);
}
/// <summary>
/// Wrapper to cache the membership provider key (id) from the request cache
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
protected string MembershipProviderKey(Guid key)
{
return (string)Cache.RequestCache.GetCacheItem(CacheKeys.CustomerMembershipProviderKey(key), this.GetMembershipProviderKey);
}
/// <summary>
/// Converts an anonymous basket to a customer basket.
/// </summary>
/// <param name="anonymousBasket">
/// The anonymous basket.
/// </param>
/// <param name="customerBasket">
/// The customer basket.
/// </param>
private static void ConvertBasket(IBasket anonymousBasket, IBasket customerBasket)
{
var type = Type.GetType(
MerchelloConfiguration.Current.GetStrategyElement(
"DefaultAnonymousBasketConversionStrategy").Type);
var attempt = ActivatorHelper.CreateInstance<BasketConversionBase>(
type,
new object[] { anonymousBasket, customerBasket });
if (!attempt.Success)
{
MultiLogHelper.Error<CustomerContext>("Failed to convert anonymous basket to customer basket", attempt.Exception);
return;
}
attempt.Result.Merge();
}
/// <summary>
/// Creates an anonymous customer
/// </summary>
private void CreateAnonymousCustomer()
{
var customer = this._customerService.CreateAnonymousCustomerWithKey();
this.CurrentCustomer = customer;
this.ContextData = new CustomerContextData()
{
Key = customer.Key
};
this.CacheCustomer(customer);
}
/// <summary>
/// Provides an assertion that the customer cookie is associated with the correct customer Umbraco member relation.
/// </summary>
/// <param name="customer">
/// The customer.
/// </param>
/// <param name="membershipId">The Membership Provider's id used. Usually an int or Guid value</param>
/// <remarks>
/// Addresses issue http://issues.merchello.com/youtrack/issue/M-454
/// </remarks>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
private void EnsureIsLoggedInCustomer(ICustomerBase customer, string membershipId)
{
if (this._cache.RequestCache.GetCacheItem(CacheKeys.EnsureIsLoggedInCustomerValidated(customer.Key)) != null) return;
var dataValue = this.ContextData.Values.FirstOrDefault(x => x.Key == UmbracoMemberIdDataKey);
// If the dataValues do not contain the umbraco member id reinitialize
if (!string.IsNullOrEmpty(dataValue.Value))
{
// Assert are equal
if (!dataValue.Value.Equals(membershipId)) this.Reinitialize(customer);
return;
}
if (dataValue.Value != membershipId) this.Reinitialize(customer);
}
/// <summary>
/// Initializes this class with default values
/// </summary>
private void Initialize()
{
// see if the key is already in the request cache
var cachedContextData = this._cache.RequestCache.GetCacheItem(CustomerCookieName);
if (cachedContextData != null)
{
this.ContextData = (CustomerContextData)cachedContextData;
var key = this.ContextData.Key;
this.TryGetCustomer(key);
return;
}
// retrieve the merchello consumer cookie
var cookie = this._umbracoContext.HttpContext.Request.Cookies[CustomerCookieName];
if (cookie != null)
{
try
{
this.ContextData = cookie.ToCustomerContextData();
this.TryGetCustomer(this.ContextData.Key);
}
catch (Exception ex)
{
MultiLogHelper.Error<CustomerContext>("Decrypted guid did not parse", ex);
this.CreateAnonymousCustomer();
}
}
else
{
this.CreateAnonymousCustomer();
} // a cookie was not found
}
/// <summary>
/// The caches the customer.
/// </summary>
/// <param name="customer">
/// The customer.
/// </param>
private void CacheCustomer(ICustomerBase customer)
{
// set/reset the cookie
// TODO decide how we want to deal with cookie persistence options
var cookie = new HttpCookie(CustomerCookieName)
{
Value = this.ContextData.ToJson()
};
// Ensure a session cookie for Anonymous customers
// TODO - on persisted authenticcation, we need to synch the cookie expiration
if (customer.IsAnonymous) cookie.Expires = DateTime.MinValue;
this._umbracoContext.HttpContext.Response.Cookies.Add(cookie);
this._cache.RequestCache.GetCacheItem(CustomerCookieName, () => this.ContextData);
this._cache.RuntimeCache.GetCacheItem(CacheKeys.CustomerCacheKey(customer.Key), () => customer, TimeSpan.FromMinutes(5), true);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// An abstraction for holding and aggregating exceptions.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// Disable the "reference to volatile field not treated as volatile" error.
#pragma warning disable 0420
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
namespace System.Threading.Tasks
{
/// <summary>
/// An exception holder manages a list of exceptions for one particular task.
/// It offers the ability to aggregate, but more importantly, also offers intrinsic
/// support for propagating unhandled exceptions that are never observed. It does
/// this by aggregating and throwing if the holder is ever GC'd without the holder's
/// contents ever having been requested (e.g. by a Task.Wait, Task.get_Exception, etc).
/// This behavior is prominent in .NET 4 but is suppressed by default beyond that release.
/// </summary>
internal class TaskExceptionHolder
{
/// <summary>Whether we should propagate exceptions on the finalizer.</summary>
private static readonly bool s_failFastOnUnobservedException = ShouldFailFastOnUnobservedException();
/// <summary>The task with which this holder is associated.</summary>
private readonly Task m_task;
/// <summary>
/// The lazily-initialized list of faulting exceptions. Volatile
/// so that it may be read to determine whether any exceptions were stored.
/// </summary>
private volatile LowLevelListWithIList<ExceptionDispatchInfo> m_faultExceptions;
/// <summary>An exception that triggered the task to cancel.</summary>
private ExceptionDispatchInfo m_cancellationException;
/// <summary>Whether the holder was "observed" and thus doesn't cause finalization behavior.</summary>
private volatile bool m_isHandled;
/// <summary>
/// Creates a new holder; it will be registered for finalization.
/// </summary>
/// <param name="task">The task this holder belongs to.</param>
internal TaskExceptionHolder(Task task)
{
Debug.Assert(task != null, "Expected a non-null task.");
m_task = task;
}
private static bool ShouldFailFastOnUnobservedException()
{
bool shouldFailFast = false;
//shouldFailFast = System.CLRConfig.CheckThrowUnobservedTaskExceptions();
return shouldFailFast;
}
/// <summary>
/// A finalizer that repropagates unhandled exceptions.
/// </summary>
~TaskExceptionHolder()
{
// Raise unhandled exceptions only when we know that neither the process or nor the appdomain is being torn down.
// We need to do this filtering because all TaskExceptionHolders will be finalized during shutdown or unload
// regardles of reachability of the task (i.e. even if the user code was about to observe the task's exception),
// which can otherwise lead to spurious crashes during shutdown.
if (m_faultExceptions != null && !m_isHandled
&& !Environment.HasShutdownStarted /*&& !AppDomain.CurrentDomain.IsFinalizingForUnload() && !s_domainUnloadStarted*/)
{
// We will only propagate if this is truly unhandled. The reason this could
// ever occur is somewhat subtle: if a Task's exceptions are observed in some
// other finalizer, and the Task was finalized before the holder, the holder
// will have been marked as handled before even getting here.
// Give users a chance to keep this exception from crashing the process
// First, publish the unobserved exception and allow users to observe it
AggregateException exceptionToThrow = new AggregateException(
SR.TaskExceptionHolder_UnhandledException,
m_faultExceptions);
UnobservedTaskExceptionEventArgs ueea = new UnobservedTaskExceptionEventArgs(exceptionToThrow);
TaskScheduler.PublishUnobservedTaskException(m_task, ueea);
// Now, if we are still unobserved and we're configured to crash on unobserved, throw the exception.
// We need to publish the event above even if we're not going to crash, hence
// why this check doesn't come at the beginning of the method.
if (s_failFastOnUnobservedException && !ueea.m_observed)
{
throw exceptionToThrow;
}
}
}
/// <summary>Gets whether the exception holder is currently storing any exceptions for faults.</summary>
internal bool ContainsFaultList { get { return m_faultExceptions != null; } }
/// <summary>
/// Add an exception to the holder. This will ensure the holder is
/// in the proper state (handled/unhandled) depending on the list's contents.
/// </summary>
/// <param name="exceptionObject">
/// An exception object (either an Exception, an ExceptionDispatchInfo,
/// an IEnumerable{Exception}, or an IEnumerable{ExceptionDispatchInfo})
/// to add to the list.
/// </param>
/// <remarks>
/// Must be called under lock.
/// </remarks>
internal void Add(object exceptionObject)
{
Add(exceptionObject, representsCancellation: false);
}
/// <summary>
/// Add an exception to the holder. This will ensure the holder is
/// in the proper state (handled/unhandled) depending on the list's contents.
/// </summary>
/// <param name="representsCancellation">
/// Whether the exception represents a cancellation request (true) or a fault (false).
/// </param>
/// <param name="exceptionObject">
/// An exception object (either an Exception, an ExceptionDispatchInfo,
/// an IEnumerable{Exception}, or an IEnumerable{ExceptionDispatchInfo})
/// to add to the list.
/// </param>
/// <remarks>
/// Must be called under lock.
/// </remarks>
internal void Add(object exceptionObject, bool representsCancellation)
{
Debug.Assert(exceptionObject != null, "TaskExceptionHolder.Add(): Expected a non-null exceptionObject");
Debug.Assert(
exceptionObject is Exception || exceptionObject is IEnumerable<Exception> ||
exceptionObject is ExceptionDispatchInfo || exceptionObject is IEnumerable<ExceptionDispatchInfo>,
"TaskExceptionHolder.Add(): Expected Exception, IEnumerable<Exception>, ExceptionDispatchInfo, or IEnumerable<ExceptionDispatchInfo>");
if (representsCancellation) SetCancellationException(exceptionObject);
else AddFaultException(exceptionObject);
}
/// <summary>Sets the cancellation exception.</summary>
/// <param name="exceptionObject">The cancellation exception.</param>
/// <remarks>
/// Must be called under lock.
/// </remarks>
private void SetCancellationException(object exceptionObject)
{
Debug.Assert(exceptionObject != null, "Expected exceptionObject to be non-null.");
Debug.Assert(m_cancellationException == null,
"Expected SetCancellationException to be called only once.");
// Breaking this assumption will overwrite a previously OCE,
// and implies something may be wrong elsewhere, since there should only ever be one.
Debug.Assert(m_faultExceptions == null,
"Expected SetCancellationException to be called before any faults were added.");
// Breaking this assumption shouldn't hurt anything here, but it implies something may be wrong elsewhere.
// If this changes, make sure to only conditionally mark as handled below.
// Store the cancellation exception
var oce = exceptionObject as OperationCanceledException;
if (oce != null)
{
m_cancellationException = ExceptionDispatchInfo.Capture(oce);
}
else
{
var edi = exceptionObject as ExceptionDispatchInfo;
Debug.Assert(edi != null && edi.SourceException is OperationCanceledException,
"Expected an OCE or an EDI that contained an OCE");
m_cancellationException = edi;
}
// This is just cancellation, and there are no faults, so mark the holder as handled.
MarkAsHandled(false);
}
/// <summary>Adds the exception to the fault list.</summary>
/// <param name="exceptionObject">The exception to store.</param>
/// <remarks>
/// Must be called under lock.
/// </remarks>
private void AddFaultException(object exceptionObject)
{
Debug.Assert(exceptionObject != null, "AddFaultException(): Expected a non-null exceptionObject");
// Initialize the exceptions list if necessary. The list should be non-null iff it contains exceptions.
var exceptions = m_faultExceptions;
if (exceptions == null) m_faultExceptions = exceptions = new LowLevelListWithIList<ExceptionDispatchInfo>(1);
else Debug.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions.");
// Handle Exception by capturing it into an ExceptionDispatchInfo and storing that
var exception = exceptionObject as Exception;
if (exception != null)
{
exceptions.Add(ExceptionDispatchInfo.Capture(exception));
}
else
{
// Handle ExceptionDispatchInfo by storing it into the list
var edi = exceptionObject as ExceptionDispatchInfo;
if (edi != null)
{
exceptions.Add(edi);
}
else
{
// Handle enumerables of exceptions by capturing each of the contained exceptions into an EDI and storing it
var exColl = exceptionObject as IEnumerable<Exception>;
if (exColl != null)
{
#if DEBUG
int numExceptions = 0;
#endif
foreach (var exc in exColl)
{
#if DEBUG
Debug.Assert(exc != null, "No exceptions should be null");
numExceptions++;
#endif
exceptions.Add(ExceptionDispatchInfo.Capture(exc));
}
#if DEBUG
Debug.Assert(numExceptions > 0, "Collection should contain at least one exception.");
#endif
}
else
{
// Handle enumerables of EDIs by storing them directly
var ediColl = exceptionObject as IEnumerable<ExceptionDispatchInfo>;
if (ediColl != null)
{
exceptions.AddRange(ediColl);
#if DEBUG
Debug.Assert(exceptions.Count > 0, "There should be at least one dispatch info.");
foreach (var tmp in exceptions)
{
Debug.Assert(tmp != null, "No dispatch infos should be null");
}
#endif
}
// Anything else is a programming error
else
{
throw new ArgumentException(SR.TaskExceptionHolder_UnknownExceptionType, nameof(exceptionObject));
}
}
}
}
if (exceptions.Count > 0)
MarkAsUnhandled();
}
/// <summary>
/// A private helper method that ensures the holder is considered
/// unhandled, i.e. it is registered for finalization.
/// </summary>
private void MarkAsUnhandled()
{
// If a thread partially observed this thread's exceptions, we
// should revert back to "not handled" so that subsequent exceptions
// must also be seen. Otherwise, some could go missing. We also need
// to reregister for finalization.
if (m_isHandled)
{
GC.ReRegisterForFinalize(this);
m_isHandled = false;
}
}
/// <summary>
/// A private helper method that ensures the holder is considered
/// handled, i.e. it is not registered for finalization.
/// </summary>
/// <param name="calledFromFinalizer">Whether this is called from the finalizer thread.</param>
internal void MarkAsHandled(bool calledFromFinalizer)
{
if (!m_isHandled)
{
if (!calledFromFinalizer)
{
GC.SuppressFinalize(this);
}
m_isHandled = true;
}
}
/// <summary>
/// Allocates a new aggregate exception and adds the contents of the list to
/// it. By calling this method, the holder assumes exceptions to have been
/// "observed", such that the finalization check will be subsequently skipped.
/// </summary>
/// <param name="calledFromFinalizer">Whether this is being called from a finalizer.</param>
/// <param name="includeThisException">An extra exception to be included (optionally).</param>
/// <returns>The aggregate exception to throw.</returns>
internal AggregateException CreateExceptionObject(bool calledFromFinalizer, Exception includeThisException)
{
var exceptions = m_faultExceptions;
Debug.Assert(exceptions != null, "Expected an initialized list.");
Debug.Assert(exceptions.Count > 0, "Expected at least one exception.");
// Mark as handled and aggregate the exceptions.
MarkAsHandled(calledFromFinalizer);
// If we're only including the previously captured exceptions,
// return them immediately in an aggregate.
if (includeThisException == null)
return new AggregateException(exceptions);
// Otherwise, the caller wants a specific exception to be included,
// so return an aggregate containing that exception and the rest.
Exception[] combinedExceptions = new Exception[exceptions.Count + 1];
for (int i = 0; i < combinedExceptions.Length - 1; i++)
{
combinedExceptions[i] = exceptions[i].SourceException;
}
combinedExceptions[combinedExceptions.Length - 1] = includeThisException;
return new AggregateException(combinedExceptions);
}
/// <summary>
/// Wraps the exception dispatch infos into a new read-only collection. By calling this method,
/// the holder assumes exceptions to have been "observed", such that the finalization
/// check will be subsequently skipped.
/// </summary>
internal ReadOnlyCollection<ExceptionDispatchInfo> GetExceptionDispatchInfos()
{
var exceptions = m_faultExceptions;
Debug.Assert(exceptions != null, "Expected an initialized list.");
Debug.Assert(exceptions.Count > 0, "Expected at least one exception.");
MarkAsHandled(false);
return new ReadOnlyCollection<ExceptionDispatchInfo>(exceptions);
}
/// <summary>
/// Gets the ExceptionDispatchInfo representing the singular exception
/// that was the cause of the task's cancellation.
/// </summary>
/// <returns>
/// The ExceptionDispatchInfo for the cancellation exception. May be null.
/// </returns>
internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo()
{
var edi = m_cancellationException;
Debug.Assert(edi == null || edi.SourceException is OperationCanceledException,
"Expected the EDI to be for an OperationCanceledException");
return edi;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using OpenADK.Library.Common;
using OpenADK.Library.Infra;
using OpenADK.Library.Learner;
using OpenADK.Library.School;
using NUnit.Framework;
using Library.UnitTesting.Framework;
using OpenADK.Library;
namespace OpenADK.Library.Nunit.UK
{
[TestFixture]
public class SifWriterTests : AdkTest
{
[Test]
public void TestxsiNill_SIFMessagePayload()
{
LearnerPersonal lp = new LearnerPersonal();
// Add a null UPN
SifString str= new SifString( null );
lp.SetField( LearnerDTD.LEARNERPERSONAL_UPN, str );
// Add a null AlertMsg
AlertMsg msg = new AlertMsg( AlertMsgType.DISCIPLINE, null );
lp.AlertMsgList = new AlertMsgList( msg );
msg.SetField( CommonDTD.ALERTMSG, new SifString( null ) );
SIF_Response sifMessage = new SIF_Response();
sifMessage.AddChild( lp );
// Write the object to a file
Console.WriteLine("Writing to file...");
using (Stream fos = File.Open("SifWriterTest.Temp.xml", FileMode.Create, FileAccess.Write))
{
SifWriter writer = new SifWriter(fos);
sifMessage.SetChanged(true);
writer.Write( sifMessage );
writer.Flush();
fos.Close();
}
// Parse the object from the file
Console.WriteLine("Parsing from file...");
SifParser p = SifParser.NewInstance();
using (Stream fis = File.OpenRead("SifWriterTest.Temp.xml"))
{
sifMessage = (SIF_Response)p.Parse(fis, null);
}
lp = (LearnerPersonal) sifMessage.GetChildList()[0];
SimpleField upn = lp.GetField( LearnerDTD.LEARNERPERSONAL_UPN );
Assert.IsNotNull( upn );
SifString rawValue = (SifString)upn.SifValue;
Assert.IsNotNull( rawValue );
Assert.IsNull( rawValue.Value );
Assert.IsNull( upn.Value );
AlertMsgList alertMsgs = lp.AlertMsgList;
Assert.IsNotNull( alertMsgs );
Assert.IsTrue( alertMsgs.Count == 1 );
msg = (AlertMsg)alertMsgs.GetChildList()[0];
Assert.IsNull( msg.Value );
SifSimpleType msgValue = msg.SifValue;
Assert.IsNotNull( msgValue );
Assert.IsNull( msgValue.RawValue );
}
[Test]
public void testmeth()
{
String c = GetColumnName( 1, 1 );
Assert.AreEqual( "A1", c );
c = GetColumnName(27, 1);
Assert.AreEqual("AA1", c);
c = GetColumnName(28, 1);
Assert.AreEqual("AB1", c);
}
private String GetColumnName(int ordinal, int Row)
{
if (ordinal < 27)
{
return ((char)(ordinal + 'A' - 1)).ToString() + Row.ToString();
}
int charIndex = ordinal % 26;
char c1 = (char)( charIndex + 'A' - 1);
char c2 = (char)(ordinal - (charIndex * 26) + 'A' - 1);
return c1.ToString() + c2.ToString() + Row.ToString();
}
[Test]
public void TestxsiNill_SDOObjectXML()
{
LearnerPersonal lp = new LearnerPersonal();
// Add a null UPN
SifString str = new SifString(null);
lp.SetField(LearnerDTD.LEARNERPERSONAL_UPN, str);
// Add a null AlertMsg
AlertMsg msg = new AlertMsg(AlertMsgType.DISCIPLINE, null);
lp.AlertMsgList = new AlertMsgList(msg);
msg.SetField(CommonDTD.ALERTMSG, new SifString(null));
// Write the object to a file
Console.WriteLine("Writing to file...");
using (Stream fos = File.Open("SifWriterTest.Temp.xml", FileMode.Create, FileAccess.Write))
{
SifWriter writer = new SifWriter(fos);
lp.SetChanged(true);
writer.Write(lp);
writer.Flush();
fos.Close();
}
// Parse the object from the file
Console.WriteLine("Parsing from file...");
SifParser p = SifParser.NewInstance();
using (Stream fis = File.OpenRead("SifWriterTest.Temp.xml"))
{
lp = (LearnerPersonal)p.Parse(fis, null);
}
SimpleField upn = lp.GetField(LearnerDTD.LEARNERPERSONAL_UPN);
Assert.IsNotNull(upn);
SifString rawValue = (SifString)upn.SifValue;
Assert.IsNotNull(rawValue);
Assert.IsNull(rawValue.Value);
Assert.IsNull(upn.Value);
AlertMsgList alertMsgs = lp.AlertMsgList;
Assert.IsNotNull(alertMsgs);
Assert.IsTrue(alertMsgs.Count == 1);
msg = (AlertMsg)alertMsgs.GetChildList()[0];
Assert.IsNull(msg.Value);
SifSimpleType msgValue = msg.SifValue;
Assert.IsNotNull(msgValue);
Assert.IsNull(msgValue.RawValue);
}
public void TestXsiNill_AllChildrenNil()
{
SchoolInfo si = new SchoolInfo();
AddressableObjectName paon = new AddressableObjectName( );
paon.Description = "The little white school house";
paon.StartNumber = "321";
Address addr = new Address( AddressType.CURRENT, paon );
GridLocation gl = new GridLocation();
gl.SetField( CommonDTD.GRIDLOCATION_PROPERTYEASTING, new SifDecimal( null ) );
gl.SetField( CommonDTD.GRIDLOCATION_PROPERTYNORTHING, new SifDecimal( null ) );
addr.GridLocation = gl;
si.AddressList = new AddressList( addr );
// Write the object to a file
Console.WriteLine("Writing to file...");
using (Stream fos = File.Open("SifWriterTest.Temp.xml", FileMode.Create, FileAccess.Write))
{
SifWriter writer = new SifWriter(fos);
si.SetChanged(true);
writer.Write(si);
writer.Flush();
fos.Close();
}
// Parse the object from the file
Console.WriteLine("Parsing from file...");
SifParser p = SifParser.NewInstance();
using (Stream fis = File.OpenRead("SifWriterTest.Temp.xml"))
{
si = (SchoolInfo)p.Parse(fis, null);
}
AddressList al = si.AddressList;
Assert.IsNotNull( al );
addr = al.ItemAt( 0 );
Assert.IsNotNull( addr );
gl = addr.GridLocation;
Assert.IsNotNull( gl );
Assert.IsNull( gl.PropertyEasting );
Assert.IsNull(gl.PropertyNorthing );
SimpleField sf = gl.GetField( CommonDTD.GRIDLOCATION_PROPERTYEASTING );
Assert.IsNotNull( sf );
Assert.IsNull( sf.Value );
sf = gl.GetField(CommonDTD.GRIDLOCATION_PROPERTYNORTHING );
Assert.IsNotNull(sf);
Assert.IsNull(sf.Value);
}
public void TestXsiNill_AllChildrenNilMultiple()
{
SIF_Data data = new SIF_Data();
for (int a = 0; a < 3; a++)
{
SchoolInfo si = new SchoolInfo();
AddressableObjectName paon = new AddressableObjectName();
paon.Description = "The little white school house";
paon.StartNumber = "321";
Address addr = new Address( AddressType.CURRENT, paon );
GridLocation gl = new GridLocation();
gl.SetField( CommonDTD.GRIDLOCATION_PROPERTYEASTING, new SifDecimal( null ) );
gl.SetField( CommonDTD.GRIDLOCATION_PROPERTYNORTHING, new SifDecimal( null ) );
addr.GridLocation = gl;
si.AddressList = new AddressList( addr );
data.AddChild( si );
}
// Write the object to a file
Console.WriteLine("Writing to file...");
using (Stream fos = File.Open("SifWriterTest.Temp.xml", FileMode.Create, FileAccess.Write))
{
SifWriter writer = new SifWriter(fos);
data.SetChanged(true);
writer.Write(data);
writer.Flush();
fos.Close();
}
// Parse the object from the file
Console.WriteLine("Parsing from file...");
SifParser p = SifParser.NewInstance();
using (Stream fis = File.OpenRead("SifWriterTest.Temp.xml"))
{
data = (SIF_Data)p.Parse(fis, null);
}
foreach ( SchoolInfo si in data.GetChildList() )
{
AddressList al = si.AddressList;
Assert.IsNotNull(al);
Address addr = al.ItemAt(0);
Assert.IsNotNull(addr);
GridLocation gl = addr.GridLocation;
Assert.IsNotNull(gl);
Assert.IsNull(gl.PropertyEasting);
Assert.IsNull(gl.PropertyNorthing);
SimpleField sf = gl.GetField(CommonDTD.GRIDLOCATION_PROPERTYEASTING);
Assert.IsNotNull(sf);
Assert.IsNull(sf.Value);
sf = gl.GetField(CommonDTD.GRIDLOCATION_PROPERTYNORTHING);
Assert.IsNotNull(sf);
Assert.IsNull(sf.Value);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.IndicesGetSettings1
{
public partial class IndicesGetSettings1YamlTests
{
public class IndicesGetSettings110BasicYamlBase : YamlTestsBase
{
public IndicesGetSettings110BasicYamlBase() : base()
{
//do indices.create
this.Do(()=> _client.IndicesCreate("test_1", null));
//do indices.create
this.Do(()=> _client.IndicesCreate("test_2", null));
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetSettings2Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetSettings2Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettingsForAll());
//match _response.test_1.settings.index.number_of_shards:
this.IsMatch(_response.test_1.settings.index.number_of_shards, 5);
//match _response.test_1.settings.index.number_of_replicas:
this.IsMatch(_response.test_1.settings.index.number_of_replicas, 1);
//match _response.test_2.settings.index.number_of_shards:
this.IsMatch(_response.test_2.settings.index.number_of_shards, 5);
//match _response.test_2.settings.index.number_of_replicas:
this.IsMatch(_response.test_2.settings.index.number_of_replicas, 1);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetIndexSettings3Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetIndexSettings3Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettings("test_1"));
//match _response.test_1.settings.index.number_of_shards:
this.IsMatch(_response.test_1.settings.index.number_of_shards, 5);
//match _response.test_1.settings.index.number_of_replicas:
this.IsMatch(_response.test_1.settings.index.number_of_replicas, 1);
//is_false _response.test_2;
this.IsFalse(_response.test_2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetIndexSettingsAll4Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetIndexSettingsAll4Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettings("test_1", "_all"));
//match _response.test_1.settings.index.number_of_shards:
this.IsMatch(_response.test_1.settings.index.number_of_shards, 5);
//match _response.test_1.settings.index.number_of_replicas:
this.IsMatch(_response.test_1.settings.index.number_of_replicas, 1);
//is_false _response.test_2;
this.IsFalse(_response.test_2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetIndexSettings5Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetIndexSettings5Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettings("test_1", "*"));
//match _response.test_1.settings.index.number_of_shards:
this.IsMatch(_response.test_1.settings.index.number_of_shards, 5);
//match _response.test_1.settings.index.number_of_replicas:
this.IsMatch(_response.test_1.settings.index.number_of_replicas, 1);
//is_false _response.test_2;
this.IsFalse(_response.test_2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetIndexSettingsName6Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetIndexSettingsName6Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettings("test_1", "index.number_of_shards"));
//match _response.test_1.settings.index.number_of_shards:
this.IsMatch(_response.test_1.settings.index.number_of_shards, 5);
//is_false _response.test_1.settings.index.number_of_replicas;
this.IsFalse(_response.test_1.settings.index.number_of_replicas);
//is_false _response.test_2;
this.IsFalse(_response.test_2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetIndexSettingsNameName7Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetIndexSettingsNameName7Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettings("test_1", "index.number_of_shards,index.number_of_replicas"));
//match _response.test_1.settings.index.number_of_shards:
this.IsMatch(_response.test_1.settings.index.number_of_shards, 5);
//match _response.test_1.settings.index.number_of_replicas:
this.IsMatch(_response.test_1.settings.index.number_of_replicas, 1);
//is_false _response.test_2;
this.IsFalse(_response.test_2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetIndexSettingsName8Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetIndexSettingsName8Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettings("test_1", "index.number_of_s*"));
//match _response.test_1.settings.index.number_of_shards:
this.IsMatch(_response.test_1.settings.index.number_of_shards, 5);
//is_false _response.test_1.settings.index.number_of_replicas;
this.IsFalse(_response.test_1.settings.index.number_of_replicas);
//is_false _response.test_2;
this.IsFalse(_response.test_2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetSettingsName9Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetSettingsName9Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettingsForAll("index.number_of_shards"));
//match _response.test_1.settings.index.number_of_shards:
this.IsMatch(_response.test_1.settings.index.number_of_shards, 5);
//match _response.test_2.settings.index.number_of_shards:
this.IsMatch(_response.test_2.settings.index.number_of_shards, 5);
//is_false _response.test_1.settings.index.number_of_replicas;
this.IsFalse(_response.test_1.settings.index.number_of_replicas);
//is_false _response.test_2.settings.index.number_of_replicas;
this.IsFalse(_response.test_2.settings.index.number_of_replicas);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAllSettingsName10Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetAllSettingsName10Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettings("_all", "index.number_of_shards"));
//match _response.test_1.settings.index.number_of_shards:
this.IsMatch(_response.test_1.settings.index.number_of_shards, 5);
//match _response.test_2.settings.index.number_of_shards:
this.IsMatch(_response.test_2.settings.index.number_of_shards, 5);
//is_false _response.test_1.settings.index.number_of_replicas;
this.IsFalse(_response.test_1.settings.index.number_of_replicas);
//is_false _response.test_2.settings.index.number_of_replicas;
this.IsFalse(_response.test_2.settings.index.number_of_replicas);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetSettingsName11Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetSettingsName11Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettings("*", "index.number_of_shards"));
//match _response.test_1.settings.index.number_of_shards:
this.IsMatch(_response.test_1.settings.index.number_of_shards, 5);
//match _response.test_2.settings.index.number_of_shards:
this.IsMatch(_response.test_2.settings.index.number_of_shards, 5);
//is_false _response.test_1.settings.index.number_of_replicas;
this.IsFalse(_response.test_1.settings.index.number_of_replicas);
//is_false _response.test_2.settings.index.number_of_replicas;
this.IsFalse(_response.test_2.settings.index.number_of_replicas);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetIndexIndexSettingsName12Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetIndexIndexSettingsName12Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettings("test_1,test_2", "index.number_of_shards"));
//match _response.test_1.settings.index.number_of_shards:
this.IsMatch(_response.test_1.settings.index.number_of_shards, 5);
//match _response.test_2.settings.index.number_of_shards:
this.IsMatch(_response.test_2.settings.index.number_of_shards, 5);
//is_false _response.test_1.settings.index.number_of_replicas;
this.IsFalse(_response.test_1.settings.index.number_of_replicas);
//is_false _response.test_2.settings.index.number_of_replicas;
this.IsFalse(_response.test_2.settings.index.number_of_replicas);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetIndexSettingsName13Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetIndexSettingsName13Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettings("*2", "index.number_of_shards"));
//match _response.test_2.settings.index.number_of_shards:
this.IsMatch(_response.test_2.settings.index.number_of_shards, 5);
//is_false _response.test_1;
this.IsFalse(_response.test_1);
//is_false _response.test_2.settings.index.number_of_replicas;
this.IsFalse(_response.test_2.settings.index.number_of_replicas);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetSettingsWithLocalFlag14Tests : IndicesGetSettings110BasicYamlBase
{
[Test]
public void GetSettingsWithLocalFlag14Test()
{
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettingsForAll(nv=>nv
.AddQueryString("local", @"true")
));
//is_true _response.test_1;
this.IsTrue(_response.test_1);
//is_true _response.test_2;
this.IsTrue(_response.test_2);
}
}
}
}
| |
//
// WebOSDevice.cs
//
// Author:
// Aaron Bockover <[email protected]>
// Jeff Wheeler <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
// Copyright (C) 2009 Jeff Wheeler
//
// 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 Mono.Unix;
using Banshee.Base;
using Banshee.Hardware;
using Banshee.Library;
using Banshee.Collection;
using Banshee.Collection.Database;
namespace Banshee.Dap.MassStorage
{
public class WebOSDevice : CustomMassStorageDevice
{
private static string [] playback_mime_types = new string [] {
// Video
"video/mp4-generic",
"video/quicktime",
"video/mp4",
"video/mpeg4",
"video/3gp",
"video/3gpp2",
"application/sdp",
// Audio
"audio/3gpp",
"audio/3ga",
"audio/3gpp2",
"audio/amr",
"audio/x-amr",
"audio/mpa",
"audio/mp3",
"audio/x-mp3",
"audio/x-mpg",
"audio/mpeg",
"audio/mpeg3",
"audio/mpg3",
"audio/mpg",
"audio/mp4",
"audio/m4a",
"audio/aac",
"audio/x-aac",
"audio/mp4a-latm",
"audio/wav"
};
// The Pre theoretically supports these formats, but it does not
// recognize them within the media player.
private static string [] playlist_formats = new string [] {
// "audio/x-scpls",
"audio/mpegurl",
"audio/x-mpegurl"
};
private static string playlists_path = "Music/";
private static string [] audio_folders = new string [] {
"Music/",
"Videos/",
//"ringtones/",
"AmazonMP3/"
};
private static string [] video_folders = new string [] {
"Videos/"
};
private static string [] icon_names = new string [] {
"phone-palm-pre", DapSource.FallbackIcon
};
private AmazonMp3GroupSource amazon_source;
private string amazon_base_dir;
private RingtonesGroupSource ringtones_source;
public override void SourceInitialize ()
{
amazon_base_dir = System.IO.Path.Combine (Source.Volume.MountPoint, audio_folders[2]);
amazon_source = new AmazonMp3GroupSource (Source, "AmazonMP3", amazon_base_dir);
amazon_source.AutoHide = true;
ringtones_source = new RingtonesGroupSource (Source);
ringtones_source.AutoHide = true;
}
public override bool LoadDeviceConfiguration ()
{
LoadConfig ();
return true;
}
protected override string DefaultName {
get { return VendorProductInfo.ProductName; }
}
protected override string [] DefaultAudioFolders {
get { return audio_folders; }
}
protected override string [] DefaultVideoFolders {
get { return video_folders; }
}
protected override string [] DefaultPlaybackMimeTypes {
get { return playback_mime_types; }
}
protected override int DefaultFolderDepth {
get { return 2; }
}
protected override string DefaultCoverArtFileType {
get { return "jpeg"; }
}
protected override int DefaultCoverArtSize {
get { return 320; }
}
protected override string [] DefaultPlaylistFormats {
get { return playlist_formats; }
}
protected override string DefaultPlaylistPath {
get { return playlists_path; }
}
public override string [] GetIconNames ()
{
return icon_names;
}
#region Amazon MP3 Store Purchased Tracks Management
public override bool DeleteTrackHook (DatabaseTrackInfo track)
{
// Do not allow removing purchased tracks if not in the
// Amazon Purchased Music source; this should prevent
// accidental deletion of purchased music that may not
// have been copied from the device yet.
//
// TODO: Provide some feedback when a purchased track is
// skipped from deletion
//
// FIXME: unfortunately this does not work due to
// the cache models being potentially different
// even though they will always reference the same tracks
// amazon_source.TrackModel.IndexOf (track) >= 0
if (!amazon_source.Active && amazon_source.Count > 0 && track.Uri.LocalPath.StartsWith (amazon_base_dir)) {
return false;
}
return true;
}
#endregion
#region Ringtones Support
private class RingtonesGroupSource : MediaGroupSource
{
// TODO: Support dropping files onto this playlist to copy into the ringtones directory
public RingtonesGroupSource (DapSource parent)
: base (parent, Catalog.GetString ("Ringtones"))
{
ConditionSql = String.Format ("({0} LIKE \"%ringtones/%\")", Banshee.Query.BansheeQuery.UriField.Column);
}
}
#endregion
}
}
| |
// BitWriter.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2011 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// Last Saved: <2011-July-25 18:57:31>
//
// ------------------------------------------------------------------
//
// This module defines the BitWriter class, which writes bits at a time
// to an output stream. It's used by the BZip2Compressor class, and by
// the BZip2OutputStream class and its parallel variant,
// ParallelBZip2OutputStream.
//
// ------------------------------------------------------------------
//
// Design notes:
//
// BZip2 employs byte-shredding in its data format - rather than
// aligning all data items in a compressed .bz2 file on byte barriers,
// the BZip2 format uses portions of bytes to represent independent
// pieces of information. This "shredding" starts with the first
// "randomised" bit - just 12 bytes or so into a bz2 file or stream. But
// the approach is used extensively in bzip2 files - sometimes 5 bits
// are used, sometimes 24 or 3 bits, sometimes just 1 bit, and so on.
// It's not possible to send this information directly to a stream in
// this form; Streams in .NET accept byte-oriented input. Therefore,
// when actually writing a bz2 file, the output data must be organized
// into a byte-aligned format before being written to the output stream.
//
// This BitWriter class provides the byte-shredding necessary for BZip2
// output. Think of this class as an Adapter that enables Bit-oriented
// output to a standard byte-oriented .NET stream. This class writes
// data out to the captive output stream only after the data bits have
// been accumulated and aligned. For example, suppose that during
// operation, the BZip2 compressor emits 5 bits, then 24 bits, then 32
// bits. When the first 5 bits are sent to the BitWriter, nothing is
// written to the output stream; instead these 5 bits are simply stored
// in the internal accumulator. When the next 24 bits are written, the
// first 3 bits are gathered with the accumulated bits. The resulting
// 5+3 constitutes an entire byte; the BitWriter then actually writes
// that byte to the output stream. This leaves 21 bits. BitWriter writes
// 2 more whole bytes (16 more bits), in 8-bit chunks, leaving 5 in the
// accumulator. BitWriter then follows the same procedure with the 32
// new bits. And so on.
//
// A quick tour of the implementation:
//
// The accumulator is a uint - so it can accumulate at most 4 bytes of
// information. In practice because of the design of this class, it
// never accumulates more than 3 bytes.
//
// The Flush() method emits all whole bytes available. After calling
// Flush(), there may be between 0-7 bits yet to be emitted into the
// output stream.
//
// FinishAndPad() emits all data, including the last partial byte and
// any necessary padding. In effect, it establishes a byte-alignment
// barrier. To support bzip2, FinishAndPad() should be called only once
// for a bz2 file, after the last bit of data has been written through
// this adapter. Other binary file formats may use byte-alignment at
// various points within the file, and FinishAndPad() would support that
// scenario.
//
// The internal fn Reset() is used to reset the state of the adapter;
// this class is used by BZip2Compressor, instances of which get re-used
// by multiple distinct threads, for different blocks of data.
//
using System;
using System.IO;
namespace Ionic.BZip2
{
internal class BitWriter
{
private uint accumulator;
private int nAccumulatedBits;
private Stream output;
private int totalBytesWrittenOut;
public BitWriter(Stream s)
{
this.output = s;
}
/// <summary>
/// Delivers the remaining bits, left-aligned, in a byte.
/// </summary>
/// <remarks>
/// <para>
/// This is valid only if NumRemainingBits is less than 8;
/// in other words it is valid only after a call to Flush().
/// </para>
/// </remarks>
public byte RemainingBits
{
get
{
return (byte) (this.accumulator >> (32 - this.nAccumulatedBits) & 0xff);
}
}
public int NumRemainingBits
{
get
{
return this.nAccumulatedBits;
}
}
public int TotalBytesWrittenOut
{
get
{
return this.totalBytesWrittenOut;
}
}
/// <summary>
/// Reset the BitWriter.
/// </summary>
/// <remarks>
/// <para>
/// This is useful when the BitWriter writes into a MemoryStream, and
/// is used by a BZip2Compressor, which itself is re-used for multiple
/// distinct data blocks.
/// </para>
/// </remarks>
public void Reset()
{
this.accumulator = 0;
this.nAccumulatedBits = 0;
this.totalBytesWrittenOut = 0;
this.output.Seek(0, SeekOrigin.Begin);
this.output.SetLength(0);
}
/// <summary>
/// Write some number of bits from the given value, into the output.
/// </summary>
/// <remarks>
/// <para>
/// The nbits value should be a max of 25, for safety. For performance
/// reasons, this method does not check!
/// </para>
/// </remarks>
public void WriteBits(int nbits, uint value)
{
int nAccumulated = this.nAccumulatedBits;
uint u = this.accumulator;
while (nAccumulated >= 8)
{
this.output.WriteByte ((byte)(u >> 24 & 0xff));
this.totalBytesWrittenOut++;
u <<= 8;
nAccumulated -= 8;
}
this.accumulator = u | (value << (32 - nAccumulated - nbits));
this.nAccumulatedBits = nAccumulated + nbits;
// Console.WriteLine("WriteBits({0}, 0x{1:X2}) => {2:X8} n({3})",
// nbits, value, accumulator, nAccumulatedBits);
// Console.ReadLine();
// At this point the accumulator may contain up to 31 bits waiting for
// output.
}
/// <summary>
/// Write a full 8-bit byte into the output.
/// </summary>
public void WriteByte(byte b)
{
WriteBits(8, b);
}
/// <summary>
/// Write four 8-bit bytes into the output.
/// </summary>
public void WriteInt(uint u)
{
WriteBits(8, (u >> 24) & 0xff);
WriteBits(8, (u >> 16) & 0xff);
WriteBits(8, (u >> 8) & 0xff);
WriteBits(8, u & 0xff);
}
/// <summary>
/// Write all available byte-aligned bytes.
/// </summary>
/// <remarks>
/// <para>
/// This method writes no new output, but flushes any accumulated
/// bits. At completion, the accumulator may contain up to 7
/// bits.
/// </para>
/// <para>
/// This is necessary when re-assembling output from N independent
/// compressors, one for each of N blocks. The output of any
/// particular compressor will in general have some fragment of a byte
/// remaining. This fragment needs to be accumulated into the
/// parent BZip2OutputStream.
/// </para>
/// </remarks>
public void Flush()
{
WriteBits(0,0);
}
/// <summary>
/// Writes all available bytes, and emits padding for the final byte as
/// necessary. This must be the last method invoked on an instance of
/// BitWriter.
/// </summary>
public void FinishAndPad()
{
Flush();
if (this.NumRemainingBits > 0)
{
byte b = (byte)((this.accumulator >> 24) & 0xff);
this.output.WriteByte(b);
this.totalBytesWrittenOut++;
}
}
}
}
| |
// 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.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal static class TypeManager
{
// The RuntimeBinder uses a global lock when Binding that keeps this dictionary safe.
private static readonly Dictionary<(Assembly, Assembly), bool> s_internalsVisibleToCache =
new Dictionary<(Assembly, Assembly), bool>();
private static readonly StdTypeVarColl s_stvcMethod = new StdTypeVarColl();
private sealed class StdTypeVarColl
{
private readonly List<TypeParameterType> prgptvs;
public StdTypeVarColl()
{
prgptvs = new List<TypeParameterType>();
}
////////////////////////////////////////////////////////////////////////////////
// Get the standard type variable (eg, !0, !1, or !!0, !!1).
//
// iv is the index.
// pbsm is the containing symbol manager
// fMeth designates whether this is a method type var or class type var
//
// The standard class type variables are useful during emit, but not for type
// comparison when binding. The standard method type variables are useful during
// binding for signature comparison.
public TypeParameterType GetTypeVarSym(int iv, bool fMeth)
{
Debug.Assert(iv >= 0);
TypeParameterType tpt;
if (iv >= prgptvs.Count)
{
TypeParameterSymbol pTypeParameter = new TypeParameterSymbol();
pTypeParameter.SetIsMethodTypeParameter(fMeth);
pTypeParameter.SetIndexInOwnParameters(iv);
pTypeParameter.SetIndexInTotalParameters(iv);
pTypeParameter.SetAccess(ACCESS.ACC_PRIVATE);
tpt = GetTypeParameter(pTypeParameter);
prgptvs.Add(tpt);
}
else
{
tpt = prgptvs[iv];
}
Debug.Assert(tpt != null);
return tpt;
}
}
public static ArrayType GetArray(CType elementType, int args, bool isSZArray)
{
Debug.Assert(args > 0 && args < 32767);
Debug.Assert(args == 1 || !isSZArray);
int rankNum = isSZArray ? 0 : args;
// See if we already have an array type of this element type and rank.
ArrayType pArray = TypeTable.LookupArray(elementType, rankNum);
if (pArray == null)
{
// No existing array symbol. Create a new one.
pArray = new ArrayType(elementType, args, isSZArray);
TypeTable.InsertArray(elementType, rankNum, pArray);
}
Debug.Assert(pArray.Rank == args);
Debug.Assert(pArray.ElementType == elementType);
return pArray;
}
public static AggregateType GetAggregate(AggregateSymbol agg, AggregateType atsOuter, TypeArray typeArgs)
{
Debug.Assert(atsOuter == null || atsOuter.OwningAggregate == agg.Parent, "");
if (typeArgs == null)
{
typeArgs = TypeArray.Empty;
}
Debug.Assert(agg.GetTypeVars().Count == typeArgs.Count);
AggregateType pAggregate = TypeTable.LookupAggregate(agg, atsOuter, typeArgs);
if (pAggregate == null)
{
pAggregate = new AggregateType(agg, typeArgs, atsOuter);
Debug.Assert(!pAggregate.ConstraintError.HasValue);
TypeTable.InsertAggregate(agg, atsOuter, typeArgs, pAggregate);
}
Debug.Assert(pAggregate.OwningAggregate == agg);
Debug.Assert(pAggregate.TypeArgsThis != null && pAggregate.TypeArgsAll != null);
Debug.Assert(pAggregate.TypeArgsThis == typeArgs);
return pAggregate;
}
public static AggregateType GetAggregate(AggregateSymbol agg, TypeArray typeArgsAll)
{
Debug.Assert(typeArgsAll != null && typeArgsAll.Count == agg.GetTypeVarsAll().Count);
if (typeArgsAll.Count == 0)
return agg.getThisType();
AggregateSymbol aggOuter = agg.GetOuterAgg();
if (aggOuter == null)
return GetAggregate(agg, null, typeArgsAll);
int cvarOuter = aggOuter.GetTypeVarsAll().Count;
Debug.Assert(cvarOuter <= typeArgsAll.Count);
TypeArray typeArgsOuter = TypeArray.Allocate(cvarOuter, typeArgsAll, 0);
TypeArray typeArgsInner = TypeArray.Allocate(agg.GetTypeVars().Count, typeArgsAll, cvarOuter);
AggregateType atsOuter = GetAggregate(aggOuter, typeArgsOuter);
return GetAggregate(agg, atsOuter, typeArgsInner);
}
public static PointerType GetPointer(CType baseType)
{
PointerType pPointer = TypeTable.LookupPointer(baseType);
if (pPointer == null)
{
// No existing type. Create a new one.
pPointer = new PointerType(baseType);
TypeTable.InsertPointer(baseType, pPointer);
}
Debug.Assert(pPointer.ReferentType == baseType);
return pPointer;
}
public static NullableType GetNullable(CType pUnderlyingType)
{
Debug.Assert(!(pUnderlyingType is NullableType), "Attempt to make nullable of nullable");
NullableType pNullableType = TypeTable.LookupNullable(pUnderlyingType);
if (pNullableType == null)
{
pNullableType = new NullableType(pUnderlyingType);
TypeTable.InsertNullable(pUnderlyingType, pNullableType);
}
return pNullableType;
}
public static ParameterModifierType GetParameterModifier(CType paramType, bool isOut)
{
ParameterModifierType pParamModifier = TypeTable.LookupParameterModifier(paramType, isOut);
if (pParamModifier == null)
{
// No existing parammod symbol. Create a new one.
pParamModifier = new ParameterModifierType(paramType, isOut);
TypeTable.InsertParameterModifier(paramType, isOut, pParamModifier);
}
Debug.Assert(pParamModifier.ParameterType == paramType);
return pParamModifier;
}
public static AggregateSymbol GetNullable() => GetPredefAgg(PredefinedType.PT_G_OPTIONAL);
private static CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, bool denormMeth)
{
Debug.Assert(typeSrc != null);
SubstContext ctx = new SubstContext(typeArgsCls, typeArgsMeth, denormMeth);
return ctx.IsNop ? typeSrc : SubstTypeCore(typeSrc, ctx);
}
public static AggregateType SubstType(AggregateType typeSrc, TypeArray typeArgsCls)
{
Debug.Assert(typeSrc != null);
SubstContext ctx = new SubstContext(typeArgsCls, null, false);
return ctx.IsNop ? typeSrc : SubstTypeCore(typeSrc, ctx);
}
private static CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth) =>
SubstType(typeSrc, typeArgsCls, typeArgsMeth, false);
public static TypeArray SubstTypeArray(TypeArray taSrc, SubstContext ctx)
{
if (taSrc != null && taSrc.Count != 0 && ctx != null && !ctx.IsNop)
{
CType[] srcs = taSrc.Items;
for (int i = 0; i < srcs.Length; i++)
{
CType src = srcs[i];
CType dst = SubstTypeCore(src, ctx);
if (src != dst)
{
CType[] dsts = new CType[srcs.Length];
Array.Copy(srcs, 0, dsts, 0, i);
dsts[i] = dst;
while (++i < srcs.Length)
{
dsts[i] = SubstTypeCore(srcs[i], ctx);
}
return TypeArray.Allocate(dsts);
}
}
}
return taSrc;
}
public static TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth)
=> taSrc == null || taSrc.Count == 0
? taSrc
: SubstTypeArray(taSrc, new SubstContext(typeArgsCls, typeArgsMeth, false));
public static TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls) => SubstTypeArray(taSrc, typeArgsCls, null);
private static AggregateType SubstTypeCore(AggregateType type, SubstContext ctx)
{
TypeArray args = type.TypeArgsAll;
if (args.Count > 0)
{
TypeArray typeArgs = SubstTypeArray(args, ctx);
if (args != typeArgs)
{
return GetAggregate(type.OwningAggregate, typeArgs);
}
}
return type;
}
private static CType SubstTypeCore(CType type, SubstContext pctx)
{
CType typeSrc;
CType typeDst;
switch (type.TypeKind)
{
default:
Debug.Fail("Unknown type kind");
return type;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_MethodGroupType:
case TypeKind.TK_ArgumentListType:
return type;
case TypeKind.TK_ParameterModifierType:
ParameterModifierType mod = (ParameterModifierType)type;
typeDst = SubstTypeCore(typeSrc = mod.ParameterType, pctx);
return (typeDst == typeSrc) ? type : GetParameterModifier(typeDst, mod.IsOut);
case TypeKind.TK_ArrayType:
var arr = (ArrayType)type;
typeDst = SubstTypeCore(typeSrc = arr.ElementType, pctx);
return (typeDst == typeSrc) ? type : GetArray(typeDst, arr.Rank, arr.IsSZArray);
case TypeKind.TK_PointerType:
typeDst = SubstTypeCore(typeSrc = ((PointerType)type).ReferentType, pctx);
return (typeDst == typeSrc) ? type : GetPointer(typeDst);
case TypeKind.TK_NullableType:
typeDst = SubstTypeCore(typeSrc = ((NullableType)type).UnderlyingType, pctx);
return (typeDst == typeSrc) ? type : GetNullable(typeDst);
case TypeKind.TK_AggregateType:
return SubstTypeCore((AggregateType)type, pctx);
case TypeKind.TK_TypeParameterType:
{
TypeParameterSymbol tvs = ((TypeParameterType)type).Symbol;
int index = tvs.GetIndexInTotalParameters();
if (tvs.IsMethodTypeParameter())
{
if (pctx.DenormMeth && tvs.parent != null)
{
return type;
}
Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters());
if (index < pctx.MethodTypes.Length)
{
Debug.Assert(pctx.MethodTypes != null);
return pctx.MethodTypes[index];
}
return type;
}
return index < pctx.ClassTypes.Length ? pctx.ClassTypes[index] : type;
}
}
}
public static bool SubstEqualTypes(CType typeDst, CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, bool denormMeth)
{
if (typeDst.Equals(typeSrc))
{
Debug.Assert(typeDst.Equals(SubstType(typeSrc, typeArgsCls, typeArgsMeth, denormMeth)));
return true;
}
SubstContext ctx = new SubstContext(typeArgsCls, typeArgsMeth, denormMeth);
return !ctx.IsNop && SubstEqualTypesCore(typeDst, typeSrc, ctx);
}
public static bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth)
{
// Handle the simple common cases first.
if (taDst == taSrc || (taDst != null && taDst.Equals(taSrc)))
{
// The following assertion is not always true and indicates a problem where
// the signature of override method does not match the one inherited from
// the base class. The method match we have found does not take the type
// arguments of the base class into account. So actually we are not overriding
// the method that we "intend" to.
// Debug.Assert(taDst == SubstTypeArray(taSrc, typeArgsCls, typeArgsMeth, grfst));
return true;
}
if (taDst.Count != taSrc.Count)
return false;
if (taDst.Count == 0)
return true;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, true);
if (ctx.IsNop)
{
return false;
}
for (int i = 0; i < taDst.Count; i++)
{
if (!SubstEqualTypesCore(taDst[i], taSrc[i], ctx))
return false;
}
return true;
}
private static bool SubstEqualTypesCore(CType typeDst, CType typeSrc, SubstContext pctx)
{
LRecurse: // Label used for "tail" recursion.
if (typeDst == typeSrc || typeDst.Equals(typeSrc))
{
return true;
}
switch (typeSrc.TypeKind)
{
default:
Debug.Fail("Bad Symbol kind in SubstEqualTypesCore");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
// There should only be a single instance of these.
Debug.Assert(typeDst.TypeKind != typeSrc.TypeKind);
return false;
case TypeKind.TK_ArrayType:
ArrayType arrSrc = (ArrayType)typeSrc;
if (!(typeDst is ArrayType arrDst) || arrDst.Rank != arrSrc.Rank || arrDst.IsSZArray != arrSrc.IsSZArray)
return false;
goto LCheckBases;
case TypeKind.TK_ParameterModifierType:
if (!(typeDst is ParameterModifierType modDest) || modDest.IsOut != ((ParameterModifierType)typeSrc).IsOut)
{
return false;
}
goto LCheckBases;
case TypeKind.TK_PointerType:
case TypeKind.TK_NullableType:
if (typeDst.TypeKind != typeSrc.TypeKind)
return false;
LCheckBases:
typeSrc = typeSrc.BaseOrParameterOrElementType;
typeDst = typeDst.BaseOrParameterOrElementType;
goto LRecurse;
case TypeKind.TK_AggregateType:
if (!(typeDst is AggregateType atsDst))
return false;
{ // BLOCK
AggregateType atsSrc = (AggregateType)typeSrc;
if (atsSrc.OwningAggregate != atsDst.OwningAggregate)
return false;
Debug.Assert(atsSrc.TypeArgsAll.Count == atsDst.TypeArgsAll.Count);
// All the args must unify.
for (int i = 0; i < atsSrc.TypeArgsAll.Count; i++)
{
if (!SubstEqualTypesCore(atsDst.TypeArgsAll[i], atsSrc.TypeArgsAll[i], pctx))
return false;
}
}
return true;
case TypeKind.TK_TypeParameterType:
{ // BLOCK
TypeParameterSymbol tvs = ((TypeParameterType)typeSrc).Symbol;
int index = tvs.GetIndexInTotalParameters();
if (tvs.IsMethodTypeParameter())
{
if (pctx.DenormMeth && tvs.parent != null)
{
// typeDst == typeSrc was handled above.
Debug.Assert(typeDst != typeSrc);
return false;
}
Debug.Assert(tvs.GetIndexInOwnParameters() == index);
Debug.Assert(tvs.GetIndexInTotalParameters() < pctx.MethodTypes.Length);
if (index < pctx.MethodTypes.Length)
{
return typeDst == pctx.MethodTypes[index];
}
}
else
{
Debug.Assert(index < pctx.ClassTypes.Length);
if (index < pctx.ClassTypes.Length)
{
return typeDst == pctx.ClassTypes[index];
}
}
}
return false;
}
}
public static bool TypeContainsType(CType type, CType typeFind)
{
LRecurse: // Label used for "tail" recursion.
if (type == typeFind || type.Equals(typeFind))
return true;
switch (type.TypeKind)
{
default:
Debug.Fail("Bad Symbol kind in TypeContainsType");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
// There should only be a single instance of these.
Debug.Assert(typeFind.TypeKind != type.TypeKind);
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.BaseOrParameterOrElementType;
goto LRecurse;
case TypeKind.TK_AggregateType:
{ // BLOCK
AggregateType ats = (AggregateType)type;
for (int i = 0; i < ats.TypeArgsAll.Count; i++)
{
if (TypeContainsType(ats.TypeArgsAll[i], typeFind))
return true;
}
}
return false;
case TypeKind.TK_TypeParameterType:
return false;
}
}
public static bool TypeContainsTyVars(CType type, TypeArray typeVars)
{
LRecurse: // Label used for "tail" recursion.
switch (type.TypeKind)
{
default:
Debug.Fail("Bad Symbol kind in TypeContainsTyVars");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_MethodGroupType:
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.BaseOrParameterOrElementType;
goto LRecurse;
case TypeKind.TK_AggregateType:
{ // BLOCK
AggregateType ats = (AggregateType)type;
for (int i = 0; i < ats.TypeArgsAll.Count; i++)
{
if (TypeContainsTyVars(ats.TypeArgsAll[i], typeVars))
{
return true;
}
}
}
return false;
case TypeKind.TK_TypeParameterType:
if (typeVars != null && typeVars.Count > 0)
{
int ivar = ((TypeParameterType)type).IndexInTotalParameters;
return ivar < typeVars.Count && type == typeVars[ivar];
}
return true;
}
}
public static AggregateSymbol GetPredefAgg(PredefinedType pt) => PredefinedTypes.GetPredefinedAggregate(pt);
public static AggregateType SubstType(AggregateType typeSrc, SubstContext ctx) =>
ctx == null || ctx.IsNop ? typeSrc : SubstTypeCore(typeSrc, ctx);
public static CType SubstType(CType typeSrc, SubstContext pctx) =>
pctx == null || pctx.IsNop ? typeSrc : SubstTypeCore(typeSrc, pctx);
public static CType SubstType(CType typeSrc, AggregateType atsCls) => SubstType(typeSrc, atsCls, null);
public static CType SubstType(CType typeSrc, AggregateType atsCls, TypeArray typeArgsMeth) =>
SubstType(typeSrc, atsCls?.TypeArgsAll, typeArgsMeth);
public static CType SubstType(CType typeSrc, CType typeCls, TypeArray typeArgsMeth) =>
SubstType(typeSrc, (typeCls as AggregateType)?.TypeArgsAll, typeArgsMeth);
public static TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth) =>
SubstTypeArray(taSrc, atsCls?.TypeArgsAll, typeArgsMeth);
public static TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls) => SubstTypeArray(taSrc, atsCls, null);
private static bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls, TypeArray typeArgsMeth) =>
SubstEqualTypes(typeDst, typeSrc, (typeCls as AggregateType)?.TypeArgsAll, typeArgsMeth, false);
public static bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls) => SubstEqualTypes(typeDst, typeSrc, typeCls, null);
public static TypeParameterType GetStdMethTypeVar(int iv) => s_stvcMethod.GetTypeVarSym(iv, true);
// These are singletons for each.
public static TypeParameterType GetTypeParameter(TypeParameterSymbol pSymbol)
{
Debug.Assert(pSymbol.GetTypeParameterType() == null); // Should have been checked first before creating
return new TypeParameterType(pSymbol);
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal static CType GetBestAccessibleType(AggregateSymbol context, CType typeSrc)
{
// This method implements the "best accessible type" algorithm for determining the type
// of untyped arguments in the runtime binder. It is also used in method type inference
// to fix type arguments to types that are accessible.
// The new type is returned in an out parameter. The result will be true (and the out param
// non-null) only when the algorithm could find a suitable accessible type.
Debug.Assert(typeSrc != null);
Debug.Assert(!(typeSrc is ParameterModifierType));
Debug.Assert(!(typeSrc is PointerType));
if (CSemanticChecker.CheckTypeAccess(typeSrc, context))
{
// If we already have an accessible type, then use it.
return typeSrc;
}
// These guys have no accessibility concerns.
Debug.Assert(!(typeSrc is VoidType) && !(typeSrc is TypeParameterType));
if (typeSrc is AggregateType aggSrc)
{
for (;;)
{
if ((aggSrc.IsInterfaceType || aggSrc.IsDelegateType) && TryVarianceAdjustmentToGetAccessibleType(context, aggSrc, out CType typeDst))
{
// If we have an interface or delegate type, then it can potentially be varied by its type arguments
// to produce an accessible type, and if that's the case, then return that.
// Example: IEnumerable<PrivateConcreteFoo> --> IEnumerable<PublicAbstractFoo>
Debug.Assert(CSemanticChecker.CheckTypeAccess(typeDst, context));
return typeDst;
}
// We have an AggregateType, so recurse on its base class.
AggregateType baseType = aggSrc.BaseClass;
if (baseType == null)
{
// This happens with interfaces, for instance. But in that case, the
// conversion to object does exist, is an implicit reference conversion,
// and is guaranteed to be accessible, so we will use it.
return GetPredefAgg(PredefinedType.PT_OBJECT).getThisType();
}
if (CSemanticChecker.CheckTypeAccess(baseType, context))
{
return baseType;
}
// baseType is always an AggregateType, so no need for logic of other types.
aggSrc = baseType;
}
}
if (typeSrc is ArrayType arrSrc)
{
if (TryArrayVarianceAdjustmentToGetAccessibleType(context, arrSrc, out CType typeDst))
{
// Similarly to the interface and delegate case, arrays are covariant in their element type and
// so we can potentially produce an array type that is accessible.
// Example: PrivateConcreteFoo[] --> PublicAbstractFoo[]
Debug.Assert(CSemanticChecker.CheckTypeAccess(typeDst, context));
return typeDst;
}
// We have an inaccessible array type for which we could not earlier find a better array type
// with a covariant conversion, so the best we can do is System.Array.
return GetPredefAgg(PredefinedType.PT_ARRAY).getThisType();
}
Debug.Assert(typeSrc is NullableType);
// We have an inaccessible nullable type, which means that the best we can do is System.ValueType.
return GetPredefAgg(PredefinedType.PT_VALUE).getThisType();
}
private static bool TryVarianceAdjustmentToGetAccessibleType(AggregateSymbol context, AggregateType typeSrc, out CType typeDst)
{
Debug.Assert(typeSrc != null);
Debug.Assert(typeSrc.IsInterfaceType || typeSrc.IsDelegateType);
typeDst = null;
AggregateSymbol aggSym = typeSrc.OwningAggregate;
AggregateType aggOpenType = aggSym.getThisType();
if (!CSemanticChecker.CheckTypeAccess(aggOpenType, context))
{
// if the aggregate symbol itself is not accessible, then forget it, there is no
// variance that will help us arrive at an accessible type.
return false;
}
TypeArray typeArgs = typeSrc.TypeArgsThis;
TypeArray typeParams = aggOpenType.TypeArgsThis;
CType[] newTypeArgsTemp = new CType[typeArgs.Count];
for (int i = 0; i < newTypeArgsTemp.Length; i++)
{
CType typeArg = typeArgs[i];
if (CSemanticChecker.CheckTypeAccess(typeArg, context))
{
// we have an accessible argument, this position is not a problem.
newTypeArgsTemp[i] = typeArg;
continue;
}
if (!typeArg.IsReferenceType || !((TypeParameterType)typeParams[i]).Covariant)
{
// This guy is inaccessible, and we are not going to be able to vary him, so we need to fail.
return false;
}
newTypeArgsTemp[i] = GetBestAccessibleType(context, typeArg);
// now we either have a value type (which must be accessible due to the above
// check, OR we have an inaccessible type (which must be a ref type). In either
// case, the recursion worked out and we are OK to vary this argument.
}
TypeArray newTypeArgs = TypeArray.Allocate(newTypeArgsTemp);
CType intermediateType = GetAggregate(aggSym, typeSrc.OuterType, newTypeArgs);
// All type arguments were varied successfully, which means now we must be accessible. But we could
// have violated constraints. Let's check that out.
if (!TypeBind.CheckConstraints(intermediateType, CheckConstraintsFlags.NoErrors))
{
return false;
}
typeDst = intermediateType;
Debug.Assert(CSemanticChecker.CheckTypeAccess(typeDst, context));
return true;
}
private static bool TryArrayVarianceAdjustmentToGetAccessibleType(AggregateSymbol context, ArrayType typeSrc, out CType typeDst)
{
Debug.Assert(typeSrc != null);
// We are here because we have an array type with an inaccessible element type. If possible,
// we should create a new array type that has an accessible element type for which a
// conversion exists.
CType elementType = typeSrc.ElementType;
// Covariant array conversions exist for reference types only.
if (elementType.IsReferenceType)
{
CType destElement = GetBestAccessibleType(context, elementType);
typeDst = GetArray(destElement, typeSrc.Rank, typeSrc.IsSZArray);
Debug.Assert(CSemanticChecker.CheckTypeAccess(typeDst, context));
return true;
}
typeDst = null;
return false;
}
internal static bool InternalsVisibleTo(Assembly assemblyThatDefinesAttribute, Assembly assemblyToCheck)
{
RuntimeBinder.EnsureLockIsTaken();
(Assembly, Assembly) key = (assemblyThatDefinesAttribute, assemblyToCheck);
if (!s_internalsVisibleToCache.TryGetValue(key, out bool result))
{
AssemblyName assyName;
// Assembly.GetName() requires FileIOPermission to FileIOPermissionAccess.PathDiscovery.
// If we don't have that (we're in low trust), then we are going to effectively turn off
// InternalsVisibleTo. The alternative is to crash when this happens.
try
{
assyName = assemblyToCheck.GetName();
result = assemblyThatDefinesAttribute.GetCustomAttributes()
.OfType<InternalsVisibleToAttribute>()
.Select(ivta => new AssemblyName(ivta.AssemblyName))
.Any(an => AssemblyName.ReferenceMatchesDefinition(an, assyName));
}
catch (SecurityException)
{
result = false;
}
s_internalsVisibleToCache[key] = result;
}
return result;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// END RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Versioning;
using System.Collections.Generic;
namespace System.Data.Common
{
internal class DbConnectionOptions
{
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is easier to verify correctness
// without the risk of the objects of the class being modified during execution.
#if DEBUG
private const string ConnectionStringPattern = // may not contain embedded null except trailing last value
"([\\s;]*" // leading whitespace and extra semicolons
+ "(?![\\s;])" // key does not start with space or semicolon
+ "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)" // allow any visible character for keyname except '=' which must quoted as '=='
+ "\\s*=(?!=)\\s*" // the equal sign divides the key and value parts
+ "(?<value>"
+ "(\"([^\"\u0000]|\"\")*\")" // double quoted string, " must be quoted as ""
+ "|"
+ "('([^'\u0000]|'')*')" // single quoted string, ' must be quoted as ''
+ "|"
+ "((?![\"'\\s])" // unquoted value must not start with " or ' or space, would also like = but too late to change
+ "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
+ "(?<![\"']))" // unquoted value must not stop with " or '
+ ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
+ ")*" // repeat the key-value pair
+ "[\\s;]*[\u0000\\s]*" // traling whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
;
private static readonly Regex s_connectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture);
#endif
private const string ConnectionStringValidKeyPattern = "^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$"; // key not allowed to start with semi-colon or space or contain non-visible characters or end with space
private const string ConnectionStringValidValuePattern = "^[^\u0000]*$"; // value not allowed to contain embedded null
private const string ConnectionStringQuoteValuePattern = "^[^\"'=;\\s\\p{Cc}]*$"; // generally do not quote the value if it matches the pattern
internal const string DataDirectory = "|datadirectory|";
private static readonly Regex s_connectionStringValidKeyRegex = new Regex(ConnectionStringValidKeyPattern);
private static readonly Regex s_connectionStringValidValueRegex = new Regex(ConnectionStringValidValuePattern);
private static readonly Regex s_connectionStringQuoteValueRegex = new Regex(ConnectionStringQuoteValuePattern);
// connection string common keywords
private static class KEY
{
internal const string Integrated_Security = "integrated security";
internal const string Password = "password";
internal const string Persist_Security_Info = "persist security info";
internal const string User_ID = "user id";
};
// known connection string common synonyms
private static class SYNONYM
{
internal const string Pwd = "pwd";
internal const string UID = "uid";
};
private readonly string _usersConnectionString;
private readonly Dictionary<string, string> _parsetable;
internal readonly NameValuePair KeyChain;
internal readonly bool HasPasswordKeyword;
// synonyms Dictionary is meant to be read-only translation of parsed string
// keywords/synonyms to a known keyword string
public DbConnectionOptions(string connectionString, Dictionary<string, string> synonyms)
{
_parsetable = new Dictionary<string, string>();
_usersConnectionString = ((null != connectionString) ? connectionString : "");
// first pass on parsing, initial syntax check
if (0 < _usersConnectionString.Length)
{
KeyChain = ParseInternal(_parsetable, _usersConnectionString, true, synonyms, false);
HasPasswordKeyword = (_parsetable.ContainsKey(KEY.Password) || _parsetable.ContainsKey(SYNONYM.Pwd));
}
}
protected DbConnectionOptions(DbConnectionOptions connectionOptions)
{ // Clone used by SqlConnectionString
_usersConnectionString = connectionOptions._usersConnectionString;
HasPasswordKeyword = connectionOptions.HasPasswordKeyword;
_parsetable = connectionOptions._parsetable;
KeyChain = connectionOptions.KeyChain;
}
internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string keyValue, bool useOdbcRules)
{
ADP.CheckArgumentNull(builder, "builder");
ADP.CheckArgumentLength(keyName, "keyName");
if ((null == keyName) || !s_connectionStringValidKeyRegex.IsMatch(keyName))
{
throw ADP.InvalidKeyname(keyName);
}
if ((null != keyValue) && !IsValueValidInternal(keyValue))
{
throw ADP.InvalidValue(keyName);
}
if ((0 < builder.Length) && (';' != builder[builder.Length - 1]))
{
builder.Append(";");
}
if (useOdbcRules)
{
builder.Append(keyName);
}
else
{
builder.Append(keyName.Replace("=", "=="));
}
builder.Append("=");
if (null != keyValue)
{ // else <keyword>=;
if (s_connectionStringQuoteValueRegex.IsMatch(keyValue))
{
// <value> -> <value>
builder.Append(keyValue);
}
else if ((-1 != keyValue.IndexOf('\"')) && (-1 == keyValue.IndexOf('\'')))
{
// <val"ue> -> <'val"ue'>
builder.Append('\'');
builder.Append(keyValue);
builder.Append('\'');
}
else
{
// <val'ue> -> <"val'ue">
// <=value> -> <"=value">
// <;value> -> <";value">
// < value> -> <" value">
// <va lue> -> <"va lue">
// <va'"lue> -> <"va'""lue">
builder.Append('\"');
builder.Append(keyValue.Replace("\"", "\"\""));
builder.Append('\"');
}
}
}
static private string GetKeyName(StringBuilder buffer)
{
int count = buffer.Length;
while ((0 < count) && Char.IsWhiteSpace(buffer[count - 1]))
{
count--; // trailing whitespace
}
return buffer.ToString(0, count).ToLowerInvariant();
}
static private string GetKeyValue(StringBuilder buffer, bool trimWhitespace)
{
int count = buffer.Length;
int index = 0;
if (trimWhitespace)
{
while ((index < count) && Char.IsWhiteSpace(buffer[index]))
{
index++; // leading whitespace
}
while ((0 < count) && Char.IsWhiteSpace(buffer[count - 1]))
{
count--; // trailing whitespace
}
}
return buffer.ToString(index, count - index);
}
// transistion states used for parsing
private enum ParserState
{
NothingYet = 1, //start point
Key,
KeyEqual,
KeyEnd,
UnquotedValue,
DoubleQuoteValue,
DoubleQuoteValueQuote,
SingleQuoteValue,
SingleQuoteValueQuote,
BraceQuoteValue,
BraceQuoteValueQuote,
QuotedValueEnd,
NullTermination,
};
static internal int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string keyname, out string keyvalue)
{
int startposition = currentPosition;
buffer.Length = 0;
keyname = null;
keyvalue = null;
char currentChar = '\0';
ParserState parserState = ParserState.NothingYet;
int length = connectionString.Length;
for (; currentPosition < length; ++currentPosition)
{
currentChar = connectionString[currentPosition];
switch (parserState)
{
case ParserState.NothingYet: // [\\s;]*
if ((';' == currentChar) || Char.IsWhiteSpace(currentChar))
{
continue;
}
if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; }
if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
startposition = currentPosition;
if ('=' != currentChar)
{
parserState = ParserState.Key;
break;
}
else
{
parserState = ParserState.KeyEqual;
continue;
}
case ParserState.Key: // (?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)
if ('=' == currentChar) { parserState = ParserState.KeyEqual; continue; }
if (Char.IsWhiteSpace(currentChar)) { break; }
if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.KeyEqual: // \\s*=(?!=)\\s*
if (!useOdbcRules && '=' == currentChar) { parserState = ParserState.Key; break; }
keyname = GetKeyName(buffer);
if (ADP.IsEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); }
buffer.Length = 0;
parserState = ParserState.KeyEnd;
goto case ParserState.KeyEnd;
case ParserState.KeyEnd:
if (Char.IsWhiteSpace(currentChar)) { continue; }
if (useOdbcRules)
{
if ('{' == currentChar) { parserState = ParserState.BraceQuoteValue; break; }
}
else
{
if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; continue; }
if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; continue; }
}
if (';' == currentChar) { goto ParserExit; }
if ('\0' == currentChar) { goto ParserExit; }
if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
parserState = ParserState.UnquotedValue;
break;
case ParserState.UnquotedValue: // "((?![\"'\\s])" + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" + "(?<![\"']))"
if (Char.IsWhiteSpace(currentChar)) { break; }
if (Char.IsControl(currentChar) || ';' == currentChar) { goto ParserExit; }
break;
case ParserState.DoubleQuoteValue: // "(\"([^\"\u0000]|\"\")*\")"
if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValueQuote; continue; }
if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.DoubleQuoteValueQuote:
if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.SingleQuoteValue: // "('([^'\u0000]|'')*')"
if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValueQuote; continue; }
if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.SingleQuoteValueQuote:
if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.BraceQuoteValue: // "(\\{([^\\}\u0000]|\\}\\})*\\})"
if ('}' == currentChar) { parserState = ParserState.BraceQuoteValueQuote; break; }
if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.BraceQuoteValueQuote:
if ('}' == currentChar) { parserState = ParserState.BraceQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.QuotedValueEnd:
if (Char.IsWhiteSpace(currentChar)) { continue; }
if (';' == currentChar) { goto ParserExit; }
if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; }
throw ADP.ConnectionStringSyntax(startposition); // unbalanced single quote
case ParserState.NullTermination: // [\\s;\u0000]*
if ('\0' == currentChar) { continue; }
if (Char.IsWhiteSpace(currentChar)) { continue; }
throw ADP.ConnectionStringSyntax(currentPosition);
default:
throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState1);
}
buffer.Append(currentChar);
}
ParserExit:
switch (parserState)
{
case ParserState.Key:
case ParserState.DoubleQuoteValue:
case ParserState.SingleQuoteValue:
case ParserState.BraceQuoteValue:
// keyword not found/unbalanced double/single quote
throw ADP.ConnectionStringSyntax(startposition);
case ParserState.KeyEqual:
// equal sign at end of line
keyname = GetKeyName(buffer);
if (ADP.IsEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.UnquotedValue:
// unquoted value at end of line
keyvalue = GetKeyValue(buffer, true);
char tmpChar = keyvalue[keyvalue.Length - 1];
if (!useOdbcRules && (('\'' == tmpChar) || ('"' == tmpChar)))
{
throw ADP.ConnectionStringSyntax(startposition); // unquoted value must not end in quote, except for odbc
}
break;
case ParserState.DoubleQuoteValueQuote:
case ParserState.SingleQuoteValueQuote:
case ParserState.BraceQuoteValueQuote:
case ParserState.QuotedValueEnd:
// quoted value at end of line
keyvalue = GetKeyValue(buffer, false);
break;
case ParserState.NothingYet:
case ParserState.KeyEnd:
case ParserState.NullTermination:
// do nothing
break;
default:
throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState2);
}
if ((';' == currentChar) && (currentPosition < connectionString.Length))
{
currentPosition++;
}
return currentPosition;
}
static private bool IsValueValidInternal(string keyvalue)
{
if (null != keyvalue)
{
#if DEBUG
bool compValue = s_connectionStringValidValueRegex.IsMatch(keyvalue);
Debug.Assert((-1 == keyvalue.IndexOf('\u0000')) == compValue, "IsValueValid mismatch with regex");
#endif
return (-1 == keyvalue.IndexOf('\u0000'));
}
return true;
}
static private bool IsKeyNameValid(string keyname)
{
if (null != keyname)
{
#if DEBUG
bool compValue = s_connectionStringValidKeyRegex.IsMatch(keyname);
Debug.Assert(((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000'))) == compValue, "IsValueValid mismatch with regex");
#endif
return ((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000')));
}
return false;
}
#if DEBUG
private static Dictionary<string, string> SplitConnectionString(string connectionString, Dictionary<string, string> synonyms, bool firstKey)
{
Dictionary<string, string> parsetable = new Dictionary<string, string>();
Debug.Assert(!firstKey, "ODBC rules are not supported in CoreCLR");
Regex parser = s_connectionStringRegex;
const int KeyIndex = 1, ValueIndex = 2;
Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index");
Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index");
if (null != connectionString)
{
Match match = parser.Match(connectionString);
if (!match.Success || (match.Length != connectionString.Length))
{
throw ADP.ConnectionStringSyntax(match.Length);
}
int indexValue = 0;
CaptureCollection keyvalues = match.Groups[ValueIndex].Captures;
foreach (Capture keypair in match.Groups[KeyIndex].Captures)
{
string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLowerInvariant();
string keyvalue = keyvalues[indexValue++].Value;
if (0 < keyvalue.Length)
{
if (!firstKey)
{
switch (keyvalue[0])
{
case '\"':
keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\"\"", "\"");
break;
case '\'':
keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\'\'", "\'");
break;
default:
break;
}
}
}
else
{
keyvalue = null;
}
string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
if (!IsKeyNameValid(realkeyname))
{
throw ADP.KeywordNotSupported(keyname);
}
if (!firstKey || !parsetable.ContainsKey(realkeyname))
{
parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
}
}
}
return parsetable;
}
private static void ParseComparison(Dictionary<string, string> parsetable, string connectionString, Dictionary<string, string> synonyms, bool firstKey, Exception e)
{
try
{
Dictionary<string, string> parsedvalues = SplitConnectionString(connectionString, synonyms, firstKey);
foreach (var entry in parsedvalues)
{
string keyname = (string)entry.Key;
string value1 = (string)entry.Value;
string value2 = (string)parsetable[keyname];
Debug.Assert(parsetable.ContainsKey(keyname), "ParseInternal code vs. regex mismatch keyname <" + keyname + ">");
Debug.Assert(value1 == value2, "ParseInternal code vs. regex mismatch keyvalue <" + value1 + "> <" + value2 + ">");
}
}
catch (ArgumentException f)
{
if (null != e)
{
string msg1 = e.Message;
string msg2 = f.Message;
const string KeywordNotSupportedMessagePrefix = "Keyword not supported:";
const string WrongFormatMessagePrefix = "Format of the initialization string";
bool isEquivalent = (msg1 == msg2);
if (!isEquivalent)
{
// We also accept cases were Regex parser (debug only) reports "wrong format" and
// retail parsing code reports format exception in different location or "keyword not supported"
if (msg2.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal))
{
if (msg1.StartsWith(KeywordNotSupportedMessagePrefix, StringComparison.Ordinal) || msg1.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal))
{
isEquivalent = true;
}
}
}
Debug.Assert(isEquivalent, "ParseInternal code vs regex message mismatch: <" + msg1 + "> <" + msg2 + ">");
}
else
{
Debug.Assert(false, "ParseInternal code vs regex throw mismatch " + f.Message);
}
e = null;
}
if (null != e)
{
Debug.Assert(false, "ParseInternal code threw exception vs regex mismatch");
}
}
#endif
private static NameValuePair ParseInternal(Dictionary<string, string> parsetable, string connectionString, bool buildChain, Dictionary<string, string> synonyms, bool firstKey)
{
Debug.Assert(null != connectionString, "null connectionstring");
StringBuilder buffer = new StringBuilder();
NameValuePair localKeychain = null, keychain = null;
#if DEBUG
try
{
#endif
int nextStartPosition = 0;
int endPosition = connectionString.Length;
while (nextStartPosition < endPosition)
{
int startPosition = nextStartPosition;
string keyname, keyvalue;
nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue);
if (ADP.IsEmpty(keyname))
{
break;
}
#if DEBUG
Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname");
Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue");
#endif
string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
if (!IsKeyNameValid(realkeyname))
{
throw ADP.KeywordNotSupported(keyname);
}
if (!firstKey || !parsetable.ContainsKey(realkeyname))
{
parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
}
if (null != localKeychain)
{
localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
}
else if (buildChain)
{ // first time only - don't contain modified chain from UDL file
keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
}
}
#if DEBUG
}
catch (ArgumentException e)
{
ParseComparison(parsetable, connectionString, synonyms, firstKey, e);
throw;
}
ParseComparison(parsetable, connectionString, synonyms, firstKey, null);
#endif
return keychain;
}
internal static void ValidateKeyValuePair(string keyword, string value)
{
if ((null == keyword) || !s_connectionStringValidKeyRegex.IsMatch(keyword))
{
throw ADP.InvalidKeyname(keyword);
}
if ((null != value) && !s_connectionStringValidValueRegex.IsMatch(value))
{
throw ADP.InvalidValue(keyword);
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT
#define DEBUG
namespace NLog.UnitTests
{
using System.Diagnostics;
using Xunit;
public class NLogTraceListenerTests : NLogTestBase
{
[Fact]
public void TraceWriteTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Debug.Write("Hello");
AssertDebugLastMessage("debug", "Logger1 Debug Hello");
Debug.Write("Hello", "Cat1");
AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello");
Debug.Write(3.1415);
AssertDebugLastMessage("debug", string.Format("Logger1 Debug {0}", 3.1415));
Debug.Write(3.1415, "Cat2");
AssertDebugLastMessage("debug", string.Format("Logger1 Debug Cat2: {0}", 3.1415));
}
[Fact]
public void TraceWriteLineTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Debug.WriteLine("Hello");
AssertDebugLastMessage("debug", "Logger1 Debug Hello");
Debug.WriteLine("Hello", "Cat1");
AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello");
Debug.WriteLine(3.1415);
AssertDebugLastMessage("debug", string.Format("Logger1 Debug {0}", 3.1415));
Debug.WriteLine(3.1415, "Cat2");
AssertDebugLastMessage("debug", string.Format("Logger1 Debug Cat2: {0}", 3.1415));
}
[Fact]
public void TraceWriteNonDefaultLevelTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
Debug.Write("Hello");
AssertDebugLastMessage("debug", "Logger1 Trace Hello");
}
[Fact]
public void TraceConfiguration()
{
var listener = new NLogTraceListener();
listener.Attributes.Add("defaultLogLevel", "Warn");
listener.Attributes.Add("forceLogLevel", "Error");
listener.Attributes.Add("autoLoggerName", "1");
Assert.Equal(LogLevel.Warn, listener.DefaultLogLevel);
Assert.Equal(LogLevel.Error, listener.ForceLogLevel);
Assert.True(listener.AutoLoggerName);
}
[Fact]
public void TraceFailTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Debug.Fail("Message");
AssertDebugLastMessage("debug", "Logger1 Error Message");
Debug.Fail("Message", "Detailed Message");
AssertDebugLastMessage("debug", "Logger1 Error Message Detailed Message");
}
[Fact]
public void AutoLoggerNameTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1", AutoLoggerName = true });
Debug.Write("Hello");
AssertDebugLastMessage("debug", this.GetType().FullName + " Debug Hello");
}
[Fact]
public void TraceDataTests()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceData(TraceEventType.Critical, 123, 42);
AssertDebugLastMessage("debug", "MySource1 Fatal 42 123");
ts.TraceData(TraceEventType.Critical, 145, 42, 3.14, "foo");
AssertDebugLastMessage("debug", string.Format("MySource1 Fatal 42, {0}, foo 145", 3.14));
}
[Fact]
public void LogInformationTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceInformation("Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Info Mary had a little lamb 0");
}
[Fact]
public void TraceEventTests()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceEvent(TraceEventType.Information, 123, "Quick brown {0} jumps over the lazy {1}.", "fox", "dog");
AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox jumps over the lazy dog. 123");
ts.TraceEvent(TraceEventType.Information, 123);
AssertDebugLastMessage("debug", "MySource1 Info 123");
ts.TraceEvent(TraceEventType.Verbose, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Trace Bar 145");
ts.TraceEvent(TraceEventType.Error, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Error Foo 145");
ts.TraceEvent(TraceEventType.Suspend, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Debug Bar 145");
ts.TraceEvent(TraceEventType.Resume, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Debug Foo 145");
ts.TraceEvent(TraceEventType.Warning, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Warn Bar 145");
ts.TraceEvent(TraceEventType.Critical, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Fatal Foo 145");
}
[Fact]
public void ForceLogLevelTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn });
// force all logs to be Warn, DefaultLogLevel has no effect on TraceSource
ts.TraceInformation("Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Warn Mary had a little lamb 0");
}
private static TraceSource CreateTraceSource()
{
var ts = new TraceSource("MySource1", SourceLevels.All);
#if MONO
// for some reason needed on Mono
ts.Switch = new SourceSwitch("MySource1", "Verbose");
ts.Switch.Level = SourceLevels.All;
#endif
return ts;
}
}
}
#endif
| |
/*
* CP1146.cs - IBM EBCDIC (United Kingdom with Euro) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ibm-1146.ucm".
namespace I18N.Rare
{
using System;
using I18N.Common;
public class CP1146 : ByteEncoding
{
public CP1146()
: base(1146, ToChars, "IBM EBCDIC (United Kingdom with Euro)",
"ibm1146", "ibm1146", "ibm1146",
false, false, false, false, 1252)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009',
'\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087',
'\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083',
'\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089',
'\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007',
'\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095',
'\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B',
'\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0',
'\u00E2', '\u00E4', '\u00E0', '\u00E1', '\u00E3', '\u00E5',
'\u00E7', '\u00F1', '\u0024', '\u002E', '\u003C', '\u0028',
'\u002B', '\u007C', '\u0026', '\u00E9', '\u00EA', '\u00EB',
'\u00E8', '\u00ED', '\u00EE', '\u00EF', '\u00EC', '\u00DF',
'\u0021', '\u00A3', '\u002A', '\u0029', '\u003B', '\u00AC',
'\u002D', '\u002F', '\u00C2', '\u00C4', '\u00C0', '\u00C1',
'\u00C3', '\u00C5', '\u00C7', '\u00D1', '\u00A6', '\u002C',
'\u0025', '\u005F', '\u003E', '\u003F', '\u00F8', '\u00C9',
'\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF',
'\u00CC', '\u0060', '\u003A', '\u0023', '\u0040', '\u0027',
'\u003D', '\u0022', '\u00D8', '\u0061', '\u0062', '\u0063',
'\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069',
'\u00AB', '\u00BB', '\u00F0', '\u00FD', '\u00FE', '\u00B1',
'\u00B0', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E',
'\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA',
'\u00E6', '\u00B8', '\u00C6', '\u20AC', '\u00B5', '\u00AF',
'\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078',
'\u0079', '\u007A', '\u00A1', '\u00BF', '\u00D0', '\u00DD',
'\u00DE', '\u00AE', '\u00A2', '\u005B', '\u00A5', '\u00B7',
'\u00A9', '\u00A7', '\u00B6', '\u00BC', '\u00BD', '\u00BE',
'\u005E', '\u005D', '\u007E', '\u00A8', '\u00B4', '\u00D7',
'\u007B', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045',
'\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4',
'\u00F6', '\u00F2', '\u00F3', '\u00F5', '\u007D', '\u004A',
'\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050',
'\u0051', '\u0052', '\u00B9', '\u00FB', '\u00FC', '\u00F9',
'\u00FA', '\u00FF', '\u005C', '\u00F7', '\u0053', '\u0054',
'\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A',
'\u00B2', '\u00D4', '\u00D6', '\u00D2', '\u00D3', '\u00D5',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB',
'\u00DC', '\u00D9', '\u00DA', '\u009F',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0x5A; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x7B; break;
case 0x0024: ch = 0x4A; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0x7C; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0xB1; break;
case 0x005C: ch = 0xE0; break;
case 0x005D: ch = 0xBB; break;
case 0x005E: ch = 0xBA; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x79; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0xC0; break;
case 0x007C: ch = 0x4F; break;
case 0x007D: ch = 0xD0; break;
case 0x007E: ch = 0xBC; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0x5B; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0x6A; break;
case 0x00A7: ch = 0xB5; break;
case 0x00A8: ch = 0xBD; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0x5F; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xA1; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x63; break;
case 0x00C5: ch = 0x67; break;
case 0x00C6: ch = 0x9E; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0x71; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x69; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0xEC; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x80; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0x43; break;
case 0x00E5: ch = 0x47; break;
case 0x00E6: ch = 0x9C; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x51; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x49; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0xCC; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x70; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xDC; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x203E: ch = 0xA1; break;
case 0x20AC: ch = 0x9F; break;
case 0xFF01: ch = 0x5A; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x7B; break;
case 0xFF04: ch = 0x4A; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0x7C; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0xB1; break;
case 0xFF3C: ch = 0xE0; break;
case 0xFF3D: ch = 0xBB; break;
case 0xFF3E: ch = 0xBA; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x79; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0xC0; break;
case 0xFF5C: ch = 0x4F; break;
case 0xFF5D: ch = 0xD0; break;
case 0xFF5E: ch = 0xBC; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0x5A; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x7B; break;
case 0x0024: ch = 0x4A; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0x7C; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0xB1; break;
case 0x005C: ch = 0xE0; break;
case 0x005D: ch = 0xBB; break;
case 0x005E: ch = 0xBA; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x79; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0xC0; break;
case 0x007C: ch = 0x4F; break;
case 0x007D: ch = 0xD0; break;
case 0x007E: ch = 0xBC; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0x5B; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0x6A; break;
case 0x00A7: ch = 0xB5; break;
case 0x00A8: ch = 0xBD; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0x5F; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xA1; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x63; break;
case 0x00C5: ch = 0x67; break;
case 0x00C6: ch = 0x9E; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0x71; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x69; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0xEC; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x80; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0x43; break;
case 0x00E5: ch = 0x47; break;
case 0x00E6: ch = 0x9C; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x51; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x49; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0xCC; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x70; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xDC; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x203E: ch = 0xA1; break;
case 0x20AC: ch = 0x9F; break;
case 0xFF01: ch = 0x5A; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x7B; break;
case 0xFF04: ch = 0x4A; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0x7C; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0xB1; break;
case 0xFF3C: ch = 0xE0; break;
case 0xFF3D: ch = 0xBB; break;
case 0xFF3E: ch = 0xBA; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x79; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0xC0; break;
case 0xFF5C: ch = 0x4F; break;
case 0xFF5D: ch = 0xD0; break;
case 0xFF5E: ch = 0xBC; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP1146
public class ENCibm1146 : CP1146
{
public ENCibm1146() : base() {}
}; // class ENCibm1146
}; // namespace I18N.Rare
| |
using EpisodeInformer.Core.Browsing;
using EpisodeInformer.Core.Net;
using EpisodeInformer.Core.Threading;
using EpisodeInformer.Data;
using EpisodeInformer.Data.Basics;
using EpisodeInformer.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using TvdbLib.Data;
namespace EpisodeInformer
{
public partial class frmBrowserMain : Form
{
private IContainer components = (IContainer)null;
private Label label1;
private ComboBox cmbSearchT;
private Button btnSearch;
private Button btnClear;
private Button btnClose;
private Button btnNext;
private PictureBox pibBanner;
private Label label8;
private Label label7;
private Label label2;
private LinkLabel lilEpisodes;
private Label label6;
private Label label3;
private TextBox txtOv;
private TextBox txtNet;
private Label label5;
private TextBox txtAct;
private TextBox txtFA;
private TextBox txtStat;
private TextBox txtID;
private TextBox txtTitle;
private Label label4;
private PictureBox pibcover;
private Panel panel1;
private Panel panel2;
private Panel panel3;
private ToolTip tltTxtTitle;
private LinkLabel lblGuidLine;
protected override void Dispose(bool disposing)
{
if (disposing && this.components != null)
this.components.Dispose();
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = (IContainer)new Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutBox));
this.label1 = new Label();
this.cmbSearchT = new ComboBox();
this.btnSearch = new Button();
this.pibcover = new PictureBox();
this.label8 = new Label();
this.label7 = new Label();
this.label2 = new Label();
this.lilEpisodes = new LinkLabel();
this.label6 = new Label();
this.label3 = new Label();
this.txtOv = new TextBox();
this.txtNet = new TextBox();
this.label5 = new Label();
this.txtAct = new TextBox();
this.txtFA = new TextBox();
this.txtStat = new TextBox();
this.txtID = new TextBox();
this.txtTitle = new TextBox();
this.label4 = new Label();
this.pibBanner = new PictureBox();
this.btnClear = new Button();
this.btnClose = new Button();
this.btnNext = new Button();
this.panel1 = new Panel();
this.panel2 = new Panel();
this.lblGuidLine = new LinkLabel();
this.panel3 = new Panel();
this.tltTxtTitle = new ToolTip(this.components);
((ISupportInitialize)this.pibcover).BeginInit();
((ISupportInitialize)this.pibBanner).BeginInit();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.panel3.SuspendLayout();
this.SuspendLayout();
this.label1.AutoSize = true;
this.label1.BackColor = Color.Transparent;
this.label1.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.label1.Location = new Point(14, 10);
this.label1.Name = "label1";
this.label1.Size = new Size(30, 15);
this.label1.TabIndex = 2;
this.label1.Text = "Title";
this.cmbSearchT.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.cmbSearchT.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.cmbSearchT.Font = new Font("Calibri", 9.75f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.cmbSearchT.FormattingEnabled = true;
this.cmbSearchT.Location = new Point(52, 7);
this.cmbSearchT.Name = "cmbSearchT";
this.cmbSearchT.Size = new Size(459, 23);
this.cmbSearchT.TabIndex = 1;
this.cmbSearchT.KeyDown += new KeyEventHandler(this.cmbSearchT_KeyDown);
this.btnSearch.FlatStyle = FlatStyle.System;
this.btnSearch.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.btnSearch.Location = new Point(517, 6);
this.btnSearch.Name = "btnSearch";
this.btnSearch.Size = new Size(75, 23);
this.btnSearch.TabIndex = 0;
this.btnSearch.Text = "&Search";
this.btnSearch.UseVisualStyleBackColor = true;
this.btnSearch.Click += new EventHandler(this.btnSearch_Click);
this.pibcover.BackColor = SystemColors.ActiveCaptionText;
this.pibcover.BackgroundImageLayout = ImageLayout.Center;
this.pibcover.BorderStyle = BorderStyle.Fixed3D;
this.pibcover.Image = (Image)Resources.coverx;
this.pibcover.Location = new Point(17, 14);
this.pibcover.Name = "pibcover";
this.pibcover.Size = new Size(163, 240);
this.pibcover.SizeMode = PictureBoxSizeMode.Zoom;
this.pibcover.TabIndex = 23;
this.pibcover.TabStop = false;
this.label8.AutoSize = true;
this.label8.BackColor = Color.Transparent;
this.label8.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.label8.Location = new Point(185, 189);
this.label8.Name = "label8";
this.label8.Size = new Size(60, 15);
this.label8.TabIndex = 10;
this.label8.Text = "First Aired";
this.label7.AutoSize = true;
this.label7.BackColor = Color.Transparent;
this.label7.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.label7.Location = new Point(189, 241);
this.label7.Name = "label7";
this.label7.Size = new Size(52, 15);
this.label7.TabIndex = 19;
this.label7.Text = "Network";
this.label2.AutoSize = true;
this.label2.BackColor = Color.Transparent;
this.label2.Font = new Font("Segoe UI", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.label2.Location = new Point(192, 8);
this.label2.Name = "label2";
this.label2.Size = new Size(30, 15);
this.label2.TabIndex = 8;
this.label2.Text = "Title";
this.lilEpisodes.AutoSize = true;
this.lilEpisodes.BackColor = Color.Transparent;
this.lilEpisodes.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.lilEpisodes.Location = new Point(514, 34);
this.lilEpisodes.Name = "lilEpisodes";
this.lilEpisodes.Size = new Size(74, 15);
this.lilEpisodes.TabIndex = 22;
this.lilEpisodes.TabStop = true;
this.lilEpisodes.Text = "Episodes List";
this.lilEpisodes.LinkClicked += new LinkLabelLinkClickedEventHandler(this.lilEpisodes_LinkClicked);
this.label6.AutoSize = true;
this.label6.BackColor = Color.Transparent;
this.label6.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.label6.Location = new Point(189, 215);
this.label6.Name = "label6";
this.label6.Size = new Size(39, 15);
this.label6.TabIndex = 18;
this.label6.Text = "Status";
this.label3.AutoSize = true;
this.label3.BackColor = Color.Transparent;
this.label3.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.label3.Location = new Point(192, 34);
this.label3.Name = "label3";
this.label3.Size = new Size(49, 15);
this.label3.TabIndex = 11;
this.label3.Text = "TvDB ID";
this.txtOv.BackColor = SystemColors.Window;
this.txtOv.Font = new Font("Calibri", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.txtOv.Location = new Point(249, 58);
this.txtOv.Multiline = true;
this.txtOv.Name = "txtOv";
this.txtOv.ReadOnly = true;
this.txtOv.ScrollBars = ScrollBars.Vertical;
this.txtOv.Size = new Size(339, 66);
this.txtOv.TabIndex = 14;
this.txtNet.BackColor = SystemColors.Window;
this.txtNet.Font = new Font("Calibri", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.txtNet.Location = new Point(249, 239);
this.txtNet.Name = "txtNet";
this.txtNet.ReadOnly = true;
this.txtNet.Size = new Size(129, 22);
this.txtNet.TabIndex = 21;
this.label5.AutoSize = true;
this.label5.BackColor = Color.Transparent;
this.label5.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.label5.Location = new Point(189, 132);
this.label5.Name = "label5";
this.label5.Size = new Size(41, 15);
this.label5.TabIndex = 15;
this.label5.Text = "Actors";
this.txtAct.BackColor = SystemColors.Window;
this.txtAct.Font = new Font("Calibri", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.txtAct.Location = new Point(249, 130);
this.txtAct.Multiline = true;
this.txtAct.Name = "txtAct";
this.txtAct.ReadOnly = true;
this.txtAct.ScrollBars = ScrollBars.Vertical;
this.txtAct.Size = new Size(339, 51);
this.txtAct.TabIndex = 16;
this.txtFA.BackColor = SystemColors.Window;
this.txtFA.Font = new Font("Calibri", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.txtFA.Location = new Point(249, 187);
this.txtFA.Name = "txtFA";
this.txtFA.ReadOnly = true;
this.txtFA.Size = new Size(129, 22);
this.txtFA.TabIndex = 20;
this.txtStat.BackColor = SystemColors.Window;
this.txtStat.Font = new Font("Calibri", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.txtStat.Location = new Point(249, 213);
this.txtStat.Name = "txtStat";
this.txtStat.ReadOnly = true;
this.txtStat.Size = new Size(129, 22);
this.txtStat.TabIndex = 17;
this.txtID.BackColor = SystemColors.Window;
this.txtID.Font = new Font("Calibri", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.txtID.Location = new Point(249, 32);
this.txtID.Name = "txtID";
this.txtID.ReadOnly = true;
this.txtID.Size = new Size(129, 22);
this.txtID.TabIndex = 12;
this.txtTitle.BackColor = SystemColors.Window;
this.txtTitle.Font = new Font("Calibri", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.txtTitle.Location = new Point(249, 6);
this.txtTitle.Name = "txtTitle";
this.txtTitle.Size = new Size(262, 22);
this.txtTitle.TabIndex = 9;
this.tltTxtTitle.SetToolTip((Control)this.txtTitle, "Please refer the guidlines before adding a series");
this.txtTitle.TextChanged += new EventHandler(this.txtTitle_TextChanged);
this.label4.AutoSize = true;
this.label4.BackColor = Color.Transparent;
this.label4.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
this.label4.Location = new Point(189, 60);
this.label4.Name = "label4";
this.label4.Size = new Size(56, 15);
this.label4.TabIndex = 13;
this.label4.Text = "Overview";
this.pibBanner.BackColor = SystemColors.ControlText;
this.pibBanner.BorderStyle = BorderStyle.FixedSingle;
this.pibBanner.Image = (Image)resources.GetObject("pibBanner.Image");
this.pibBanner.Location = new Point(7, 6);
this.pibBanner.Name = "pibBanner";
this.pibBanner.Size = new Size(603, 114);
this.pibBanner.TabIndex = 1;
this.pibBanner.TabStop = false;
this.btnClear.Font = new Font("Segoe UI Symbol", 9f);
this.btnClear.Location = new Point(11, 5);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new Size(75, 23);
this.btnClear.TabIndex = 2;
this.btnClear.Text = "C&lear";
this.btnClear.UseVisualStyleBackColor = true;
this.btnClear.Click += new EventHandler(this.btnClear_Click);
this.btnClose.Font = new Font("Segoe UI Symbol", 9f);
this.btnClose.Location = new Point(433, 5);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new Size(75, 23);
this.btnClose.TabIndex = 1;
this.btnClose.Text = "&Close";
this.btnClose.UseVisualStyleBackColor = true;
this.btnClose.Click += new EventHandler(this.btnClose_Click);
this.btnNext.Enabled = false;
this.btnNext.Font = new Font("Segoe UI Symbol", 9f);
this.btnNext.Location = new Point(514, 5);
this.btnNext.Name = "btnNext";
this.btnNext.Size = new Size(75, 23);
this.btnNext.TabIndex = 0;
this.btnNext.Text = "&Next";
this.btnNext.UseVisualStyleBackColor = true;
this.btnNext.Click += new EventHandler(this.btnNext_Click);
this.panel1.BackColor = SystemColors.ButtonFace;
this.panel1.BackgroundImage = (Image)Resources.last;
this.panel1.BorderStyle = BorderStyle.FixedSingle;
this.panel1.Controls.Add((Control)this.btnClear);
this.panel1.Controls.Add((Control)this.btnClose);
this.panel1.Controls.Add((Control)this.btnNext);
this.panel1.Location = new Point(7, 478);
this.panel1.Name = "panel1";
this.panel1.Size = new Size(603, 35);
this.panel1.TabIndex = 2;
this.panel2.BackColor = SystemColors.ButtonFace;
this.panel2.BackgroundImage = (Image)Resources.middle;
this.panel2.BorderStyle = BorderStyle.FixedSingle;
this.panel2.Controls.Add((Control)this.lblGuidLine);
this.panel2.Controls.Add((Control)this.pibcover);
this.panel2.Controls.Add((Control)this.label8);
this.panel2.Controls.Add((Control)this.label4);
this.panel2.Controls.Add((Control)this.label7);
this.panel2.Controls.Add((Control)this.txtTitle);
this.panel2.Controls.Add((Control)this.label2);
this.panel2.Controls.Add((Control)this.txtID);
this.panel2.Controls.Add((Control)this.lilEpisodes);
this.panel2.Controls.Add((Control)this.txtStat);
this.panel2.Controls.Add((Control)this.label6);
this.panel2.Controls.Add((Control)this.txtFA);
this.panel2.Controls.Add((Control)this.label3);
this.panel2.Controls.Add((Control)this.txtAct);
this.panel2.Controls.Add((Control)this.txtOv);
this.panel2.Controls.Add((Control)this.label5);
this.panel2.Controls.Add((Control)this.txtNet);
this.panel2.Location = new Point(8, 183);
this.panel2.Name = "panel2";
this.panel2.Size = new Size(603, 289);
this.panel2.TabIndex = 3;
this.lblGuidLine.AutoSize = true;
this.lblGuidLine.BackColor = Color.Transparent;
this.lblGuidLine.Font = new Font("Segoe UI Symbol", 9f);
this.lblGuidLine.Location = new Point(526, 8);
this.lblGuidLine.Name = "lblGuidLine";
this.lblGuidLine.Size = new Size(62, 15);
this.lblGuidLine.TabIndex = 24;
this.lblGuidLine.TabStop = true;
this.lblGuidLine.Text = "Guidelines";
this.lblGuidLine.LinkClicked += new LinkLabelLinkClickedEventHandler(this.lblGuidLine_LinkClicked);
this.panel3.BackColor = SystemColors.ButtonFace;
this.panel3.BackgroundImage = (Image)Resources.head;
this.panel3.BorderStyle = BorderStyle.FixedSingle;
this.panel3.Controls.Add((Control)this.label1);
this.panel3.Controls.Add((Control)this.cmbSearchT);
this.panel3.Controls.Add((Control)this.btnSearch);
this.panel3.Location = new Point(8, 136);
this.panel3.Name = "panel3";
this.panel3.Size = new Size(603, 38);
this.panel3.TabIndex = 4;
this.tltTxtTitle.ToolTipIcon = ToolTipIcon.Info;
this.tltTxtTitle.ToolTipTitle = "Important";
this.AutoScaleDimensions = new SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = SystemColors.ButtonHighlight;
this.BackgroundImage = (Image)Resources.back;
this.ClientSize = new Size(618, 524);
this.Controls.Add((Control)this.panel3);
this.Controls.Add((Control)this.panel2);
this.Controls.Add((Control)this.panel1);
this.Controls.Add((Control)this.pibBanner);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = (Icon)resources.GetObject("$this.Icon");
this.MaximizeBox = false;
this.Name = "frmBrowserMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "TvDB.com : Browser";
this.FormClosed += new FormClosedEventHandler(this.frmBrowserMain_FormClosed);
this.Load += new EventHandler(this.frmBrowserMain_Load);
this.Shown += new EventHandler(this.frmBrowserMain_Shown);
((ISupportInitialize)this.pibcover).EndInit();
((ISupportInitialize)this.pibBanner).EndInit();
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.panel3.ResumeLayout(false);
this.panel3.PerformLayout();
this.ResumeLayout(false);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
public class DockContent : Form, IDockContent
{
public DockContent()
{
m_dockHandler = new DockContentHandler(this, new GetPersistStringCallback(GetPersistString));
m_dockHandler.DockStateChanged += new EventHandler(DockHandler_DockStateChanged);
//Suggested as a fix by bensty regarding form resize
this.ParentChanged += new EventHandler(DockContent_ParentChanged);
}
//Suggested as a fix by bensty regarding form resize
private void DockContent_ParentChanged(object Sender, EventArgs e)
{
if (this.Parent != null)
this.Font = this.Parent.Font;
}
private DockContentHandler m_dockHandler = null;
[Browsable(false)]
public DockContentHandler DockHandler
{
get { return m_dockHandler; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_AllowEndUserDocking_Description")]
[DefaultValue(true)]
public bool AllowEndUserDocking
{
get { return DockHandler.AllowEndUserDocking; }
set { DockHandler.AllowEndUserDocking = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_DockAreas_Description")]
[DefaultValue(DockAreas.DockLeft|DockAreas.DockRight|DockAreas.DockTop|DockAreas.DockBottom|DockAreas.Document|DockAreas.Float)]
public DockAreas DockAreas
{
get { return DockHandler.DockAreas; }
set { DockHandler.DockAreas = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_AutoHidePortion_Description")]
[DefaultValue(0.25)]
public double AutoHidePortion
{
get { return DockHandler.AutoHidePortion; }
set { DockHandler.AutoHidePortion = value; }
}
private string m_tabText = null;
[Localizable(true)]
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_TabText_Description")]
[DefaultValue(null)]
public string TabText
{
get { return m_tabText; }
set { DockHandler.TabText = m_tabText = value; }
}
private bool ShouldSerializeTabText()
{
return (m_tabText != null);
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_CloseButton_Description")]
[DefaultValue(true)]
public bool CloseButton
{
get { return DockHandler.CloseButton; }
set { DockHandler.CloseButton = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_CloseButtonVisible_Description")]
[DefaultValue(true)]
public bool CloseButtonVisible
{
get { return DockHandler.CloseButtonVisible; }
set { DockHandler.CloseButtonVisible = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockPanel DockPanel
{
get { return DockHandler.DockPanel; }
set { DockHandler.DockPanel = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockState DockState
{
get { return DockHandler.DockState; }
set { DockHandler.DockState = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockPane Pane
{
get { return DockHandler.Pane; }
set { DockHandler.Pane = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsHidden
{
get { return DockHandler.IsHidden; }
set { DockHandler.IsHidden = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockState VisibleState
{
get { return DockHandler.VisibleState; }
set { DockHandler.VisibleState = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsFloat
{
get { return DockHandler.IsFloat; }
set { DockHandler.IsFloat = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockPane PanelPane
{
get { return DockHandler.PanelPane; }
set { DockHandler.PanelPane = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockPane FloatPane
{
get { return DockHandler.FloatPane; }
set { DockHandler.FloatPane = value; }
}
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public virtual string GetPersistString()
{
return GetType().ToString();
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_HideOnClose_Description")]
[DefaultValue(false)]
public bool HideOnClose
{
get { return DockHandler.HideOnClose; }
set { DockHandler.HideOnClose = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_ShowHint_Description")]
[DefaultValue(DockState.Unknown)]
public DockState ShowHint
{
get { return DockHandler.ShowHint; }
set { DockHandler.ShowHint = value; }
}
[Browsable(false)]
public bool IsActivated
{
get { return DockHandler.IsActivated; }
}
public bool IsDockStateValid(DockState dockState)
{
return DockHandler.IsDockStateValid(dockState);
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_TabPageContextMenu_Description")]
[DefaultValue(null)]
public ContextMenu TabPageContextMenu
{
get { return DockHandler.TabPageContextMenu; }
set { DockHandler.TabPageContextMenu = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_TabPageContextMenuStrip_Description")]
[DefaultValue(null)]
public ContextMenuStrip TabPageContextMenuStrip
{
get { return DockHandler.TabPageContextMenuStrip; }
set { DockHandler.TabPageContextMenuStrip = value; }
}
[Localizable(true)]
[Category("Appearance")]
[LocalizedDescription("DockContent_ToolTipText_Description")]
[DefaultValue(null)]
public string ToolTipText
{
get { return DockHandler.ToolTipText; }
set { DockHandler.ToolTipText = value; }
}
public new void Activate()
{
DockHandler.Activate();
}
public new void Hide()
{
DockHandler.Hide();
}
public new void Show()
{
DockHandler.Show();
}
public void Show(DockPanel dockPanel)
{
DockHandler.Show(dockPanel);
}
public void Show(DockPanel dockPanel, DockState dockState)
{
DockHandler.Show(dockPanel, dockState);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")]
public void Show(DockPanel dockPanel, Rectangle floatWindowBounds)
{
DockHandler.Show(dockPanel, floatWindowBounds);
}
public void Show(DockPane pane, IDockContent beforeContent)
{
DockHandler.Show(pane, beforeContent);
}
public void Show(DockPane previousPane, DockAlignment alignment, double proportion)
{
DockHandler.Show(previousPane, alignment, proportion);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")]
public void FloatAt(Rectangle floatWindowBounds)
{
DockHandler.FloatAt(floatWindowBounds);
}
public void DockTo(DockPane paneTo, DockStyle dockStyle, int contentIndex)
{
DockHandler.DockTo(paneTo, dockStyle, contentIndex);
}
public void DockTo(DockPanel panel, DockStyle dockStyle)
{
DockHandler.DockTo(panel, dockStyle);
}
#region IDockContent Members
void IDockContent.OnActivated(EventArgs e)
{
this.OnActivated(e);
}
void IDockContent.OnDeactivate(EventArgs e)
{
this.OnDeactivate(e);
}
#endregion
#region Events
private void DockHandler_DockStateChanged(object sender, EventArgs e)
{
OnDockStateChanged(e);
}
private static readonly object DockStateChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("Pane_DockStateChanged_Description")]
public event EventHandler DockStateChanged
{
add { Events.AddHandler(DockStateChangedEvent, value); }
remove { Events.RemoveHandler(DockStateChangedEvent, value); }
}
protected virtual void OnDockStateChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[DockStateChangedEvent];
if (handler != null)
handler(this, e);
}
#endregion
/// <summary>
/// Overridden to avoid resize issues with nested controls
/// </summary>
/// <remarks>
/// http://blogs.msdn.com/b/alejacma/archive/2008/11/20/controls-won-t-get-resized-once-the-nesting-hierarchy-of-windows-exceeds-a-certain-depth-x64.aspx
/// http://support.microsoft.com/kb/953934
/// </remarks>
protected override void OnSizeChanged(EventArgs e)
{
if (DockPanel != null && DockPanel.SupportDeeplyNestedContent && IsHandleCreated)
{
BeginInvoke((MethodInvoker)delegate
{
base.OnSizeChanged(e);
});
}
else
{
base.OnSizeChanged(e);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using AsmResolver.DotNet.Signatures.Types;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
namespace AsmResolver.DotNet.Signatures
{
public partial class SignatureComparer :
IEqualityComparer<TypeSignature>,
IEqualityComparer<CorLibTypeSignature>,
IEqualityComparer<ByReferenceTypeSignature>,
IEqualityComparer<PointerTypeSignature>,
IEqualityComparer<SzArrayTypeSignature>,
IEqualityComparer<PinnedTypeSignature>,
IEqualityComparer<BoxedTypeSignature>,
IEqualityComparer<TypeDefOrRefSignature>,
IEqualityComparer<CustomModifierTypeSignature>,
IEqualityComparer<GenericInstanceTypeSignature>,
IEqualityComparer<GenericParameterSignature>,
IEqualityComparer<ArrayTypeSignature>,
IEqualityComparer<SentinelTypeSignature>,
IEqualityComparer<IList<TypeSignature>>,
IEqualityComparer<IEnumerable<TypeSignature>>
{
/// <inheritdoc />
public bool Equals(TypeSignature? x, TypeSignature? y)
{
if (ReferenceEquals(x, y))
return true;
if (x is null || y is null)
return false;
switch (x.ElementType)
{
case ElementType.ValueType:
case ElementType.Class:
return Equals(x as TypeDefOrRefSignature, y as TypeDefOrRefSignature);
case ElementType.CModReqD:
case ElementType.CModOpt:
return Equals(x as CustomModifierTypeSignature, y as CustomModifierTypeSignature);
case ElementType.GenericInst:
return Equals(x as GenericInstanceTypeSignature, y as GenericInstanceTypeSignature);
case ElementType.Var:
case ElementType.MVar:
return Equals(x as GenericParameterSignature, y as GenericParameterSignature);
case ElementType.Ptr:
return Equals(x as PointerTypeSignature, y as PointerTypeSignature);
case ElementType.ByRef:
return Equals(x as ByReferenceTypeSignature, y as ByReferenceTypeSignature);
case ElementType.Array:
return Equals(x as ArrayTypeSignature, y as ArrayTypeSignature);
case ElementType.SzArray:
return Equals(x as SzArrayTypeSignature, y as SzArrayTypeSignature);
case ElementType.Sentinel:
return Equals(x as SentinelTypeSignature, y as SentinelTypeSignature);
case ElementType.Pinned:
return Equals(x as PinnedTypeSignature, y as PinnedTypeSignature);
case ElementType.Boxed:
return Equals(x as BoxedTypeSignature, y as BoxedTypeSignature);
case ElementType.FnPtr:
case ElementType.Internal:
case ElementType.Modifier:
throw new NotSupportedException();
default:
return Equals(x as CorLibTypeSignature, y as CorLibTypeSignature);
}
}
/// <inheritdoc />
public int GetHashCode(TypeSignature obj)
{
switch (obj.ElementType)
{
case ElementType.ValueType:
case ElementType.Class:
return GetHashCode((TypeDefOrRefSignature) obj);
case ElementType.CModReqD:
case ElementType.CModOpt:
return GetHashCode((CustomModifierTypeSignature) obj);
case ElementType.GenericInst:
return GetHashCode((GenericInstanceTypeSignature) obj);
case ElementType.Var:
case ElementType.MVar:
return GetHashCode((GenericParameterSignature) obj);
case ElementType.Ptr:
return GetHashCode((PointerTypeSignature) obj);
case ElementType.ByRef:
return GetHashCode((ByReferenceTypeSignature) obj);
case ElementType.Array:
return GetHashCode((ArrayTypeSignature) obj);
case ElementType.SzArray:
return GetHashCode((SzArrayTypeSignature) obj);
case ElementType.Sentinel:
return GetHashCode((SentinelTypeSignature) obj);
case ElementType.Pinned:
return GetHashCode((PinnedTypeSignature) obj);
case ElementType.Boxed:
return GetHashCode((BoxedTypeSignature) obj);
case ElementType.FnPtr:
case ElementType.Internal:
case ElementType.Modifier:
throw new NotSupportedException();
default:
return GetHashCode((CorLibTypeSignature) obj);
}
}
/// <inheritdoc />
public bool Equals(CorLibTypeSignature? x, CorLibTypeSignature? y)
{
if (ReferenceEquals(x, y))
return true;
if (x is null || y is null)
return false;
return x.ElementType == y.ElementType;
}
/// <inheritdoc />
public int GetHashCode(CorLibTypeSignature obj) =>
(int) obj.ElementType << ElementTypeOffset;
/// <inheritdoc />
public bool Equals(SentinelTypeSignature? x, SentinelTypeSignature? y)
{
if (ReferenceEquals(x, y))
return true;
if (x is null || y is null)
return false;
return x.ElementType == y.ElementType;
}
/// <inheritdoc />
public int GetHashCode(SentinelTypeSignature obj) =>
(int) obj.ElementType << ElementTypeOffset;
/// <inheritdoc />
public bool Equals(ByReferenceTypeSignature? x, ByReferenceTypeSignature? y) =>
Equals(x as TypeSpecificationSignature, y);
/// <inheritdoc />
public int GetHashCode(ByReferenceTypeSignature obj) =>
GetHashCode(obj as TypeSpecificationSignature);
/// <inheritdoc />
public bool Equals(PointerTypeSignature? x, PointerTypeSignature? y) =>
Equals(x as TypeSpecificationSignature, y);
/// <inheritdoc />
public int GetHashCode(PointerTypeSignature obj) =>
GetHashCode(obj as TypeSpecificationSignature);
/// <inheritdoc />
public bool Equals(SzArrayTypeSignature? x, SzArrayTypeSignature? y) =>
Equals(x as TypeSpecificationSignature, y);
/// <inheritdoc />
public int GetHashCode(SzArrayTypeSignature obj) =>
GetHashCode(obj as TypeSpecificationSignature);
/// <inheritdoc />
public bool Equals(PinnedTypeSignature? x, PinnedTypeSignature? y) =>
Equals(x as TypeSpecificationSignature, y);
/// <inheritdoc />
public int GetHashCode(PinnedTypeSignature obj) =>
GetHashCode(obj as TypeSpecificationSignature);
/// <inheritdoc />
public bool Equals(BoxedTypeSignature? x, BoxedTypeSignature? y) =>
Equals(x as TypeSpecificationSignature, y);
/// <inheritdoc />
public int GetHashCode(BoxedTypeSignature obj) =>
GetHashCode(obj as TypeSpecificationSignature);
/// <inheritdoc />
public bool Equals(TypeDefOrRefSignature? x, TypeDefOrRefSignature? y)
{
if (ReferenceEquals(x, y))
return true;
if (x is null || y is null)
return false;
return SimpleTypeEquals(x.Type, y.Type);
}
/// <inheritdoc />
public int GetHashCode(TypeDefOrRefSignature obj)
{
unchecked
{
int hashCode = (int) obj.ElementType << ElementTypeOffset;
hashCode = (hashCode * 397) ^ obj.Name.GetHashCode();
hashCode = (hashCode * 397) ^ (obj.Namespace is null ? 0 : obj.Namespace.GetHashCode());
hashCode = (hashCode * 397) ^ (obj.Scope is null ? 0 : GetHashCode(obj.Scope));
return hashCode;
}
}
/// <inheritdoc />
public bool Equals(CustomModifierTypeSignature? x, CustomModifierTypeSignature? y)
{
if (ReferenceEquals(x, y))
return true;
if (x is null || y is null)
return false;
return x.IsRequired == y.IsRequired
&& Equals(x.ModifierType, y.ModifierType)
&& Equals(x.BaseType, y.BaseType);
}
/// <inheritdoc />
public int GetHashCode(CustomModifierTypeSignature obj)
{
unchecked
{
int hashCode = (int) obj.ElementType << ElementTypeOffset;
hashCode = (hashCode * 397) ^ obj.ModifierType.GetHashCode();
hashCode = (hashCode * 397) ^ obj.BaseType.GetHashCode();
return hashCode;
}
}
/// <inheritdoc />
public bool Equals(GenericInstanceTypeSignature? x, GenericInstanceTypeSignature? y)
{
if (ReferenceEquals(x, y))
return true;
if (x is null || y is null)
return false;
return x.IsValueType == y.IsValueType
&& Equals(x.GenericType, y.GenericType)
&& Equals(x.TypeArguments, y.TypeArguments);
}
/// <inheritdoc />
public int GetHashCode(GenericInstanceTypeSignature obj)
{
unchecked
{
int hashCode = (int) obj.ElementType << ElementTypeOffset;
hashCode = (hashCode * 397) ^ obj.GenericType.GetHashCode();
hashCode = (hashCode * 397) ^ GetHashCode(obj.TypeArguments);
return hashCode;
}
}
/// <inheritdoc />
public bool Equals(GenericParameterSignature? x, GenericParameterSignature? y)
{
if (ReferenceEquals(x, y))
return true;
if (x is null || y is null)
return false;
return x.Index == y.Index
&& x.ParameterType == y.ParameterType;
}
/// <inheritdoc />
public int GetHashCode(GenericParameterSignature obj) =>
(int) obj.ElementType << ElementTypeOffset | obj.Index;
private bool Equals(TypeSpecificationSignature? x, TypeSpecificationSignature? y)
{
if (ReferenceEquals(x, y))
return true;
if (x is null || y is null || x.ElementType != y.ElementType)
return false;
return Equals(x.BaseType, y.BaseType);
}
private int GetHashCode(TypeSpecificationSignature obj) =>
(int) obj.ElementType << ElementTypeOffset ^ GetHashCode(obj.BaseType);
/// <inheritdoc />
public bool Equals(ArrayTypeSignature? x, ArrayTypeSignature? y)
{
if (ReferenceEquals(x, y))
return true;
if (x is null || y is null || x.Dimensions.Count != y.Dimensions.Count)
return false;
for (int i = 0; i < x.Dimensions.Count; i++)
{
if (x.Dimensions[i].Size != y.Dimensions[i].Size
|| x.Dimensions[i].LowerBound != y.Dimensions[i].LowerBound)
{
return false;
}
}
return Equals(x.BaseType, y.BaseType);
}
/// <inheritdoc />
public int GetHashCode(ArrayTypeSignature obj)
{
unchecked
{
int hashCode = (int) obj.ElementType << ElementTypeOffset;
hashCode = (hashCode * 397) ^ GetHashCode(obj.BaseType);
for (int i = 0; i < obj.Dimensions.Count; i++)
hashCode = (hashCode * 397) ^ obj.Dimensions[i].GetHashCode();
return hashCode;
}
}
/// <inheritdoc />
public bool Equals(IList<TypeSignature>? x, IList<TypeSignature>? y)
{
if (ReferenceEquals(x, y))
return true;
if (x is null || y is null || x.Count != y.Count)
return false;
for (int i = 0; i < x.Count; i++)
{
if (!Equals(x[i], y[i]))
return false;
}
return true;
}
/// <inheritdoc />
public int GetHashCode(IList<TypeSignature> obj)
{
int checksum = 0;
for (int i = 0; i < obj.Count; i++)
checksum ^= GetHashCode(obj[i]);
return checksum;
}
/// <inheritdoc />
public bool Equals(IEnumerable<TypeSignature>? x, IEnumerable<TypeSignature>? y)
{
if (ReferenceEquals(x, y))
return true;
if (x is null || y is null)
return false;
return x.SequenceEqual(y, this);
}
/// <inheritdoc />
public int GetHashCode(IEnumerable<TypeSignature> obj)
{
int checksum = 0;
foreach (var type in obj)
checksum ^= GetHashCode(type);
return checksum;
}
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <[email protected]>
*/
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Reflection;
using HLA40 = Net.Pkcs11Interop.HighLevelAPI40;
using HLA41 = Net.Pkcs11Interop.HighLevelAPI41;
using HLA80 = Net.Pkcs11Interop.HighLevelAPI80;
using HLA81 = Net.Pkcs11Interop.HighLevelAPI81;
using LLA40 = Net.Pkcs11Interop.LowLevelAPI40;
using LLA41 = Net.Pkcs11Interop.LowLevelAPI41;
using LLA80 = Net.Pkcs11Interop.LowLevelAPI80;
using LLA81 = Net.Pkcs11Interop.LowLevelAPI81;
namespace Net.Pkcs11Interop.Tests.HighLevelAPI
{
/// <summary>
/// Object attributes tests.
/// </summary>
[TestFixture()]
public class _13_ObjectAttributeTest
{
/// <summary>
/// Attribute dispose test.
/// </summary>
[Test()]
public void _01_DisposeAttributeTest()
{
// Unmanaged memory for attribute value stored in low level CK_ATTRIBUTE struct
// is allocated by constructor of ObjectAttribute class.
ObjectAttribute attr1 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
// Do something interesting with attribute
// This unmanaged memory is freed by Dispose() method.
attr1.Dispose();
// ObjectAttribute class can be used in using statement which defines a scope
// at the end of which an object will be disposed (and unmanaged memory freed).
using (ObjectAttribute attr2 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA))
{
// Do something interesting with attribute
}
#pragma warning disable 0219
// Explicit calling of Dispose() method can also be ommitted.
ObjectAttribute attr3 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
// Do something interesting with attribute
// Dispose() method will be called (and unmanaged memory freed) by GC eventually
// but we cannot be sure when will this occur.
#pragma warning restore 0219
}
/// <summary>
/// Attribute with empty value test.
/// </summary>
[Test()]
public void _02_EmptyAttributeTest()
{
// Create attribute without the value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_CLASS))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_CLASS);
Assert.IsTrue(attr.GetValueAsByteArray() == null);
}
}
/// <summary>
/// Attribute with ulong value test.
/// </summary>
[Test()]
public void _03_UintAttributeTest()
{
ulong value = (ulong)CKO.CKO_DATA;
// Create attribute with ulong value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_CLASS, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_CLASS);
Assert.IsTrue(attr.GetValueAsUlong() == value);
}
}
/// <summary>
/// Attribute with bool value test.
/// </summary>
[Test()]
public void _04_BoolAttributeTest()
{
bool value = true;
// Create attribute with bool value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_TOKEN, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_TOKEN);
Assert.IsTrue(attr.GetValueAsBool() == value);
}
}
/// <summary>
/// Attribute with string value test.
/// </summary>
[Test()]
public void _05_StringAttributeTest()
{
string value = "Hello world";
// Create attribute with string value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_LABEL, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_LABEL);
Assert.IsTrue(attr.GetValueAsString() == value);
}
value = null;
// Create attribute with null string value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_LABEL, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_LABEL);
Assert.IsTrue(attr.GetValueAsString() == value);
}
}
/// <summary>
/// Attribute with byte array value test.
/// </summary>
[Test()]
public void _06_ByteArrayAttributeTest()
{
byte[] value = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
// Create attribute with byte array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ID, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ID);
Assert.IsTrue(Convert.ToBase64String(attr.GetValueAsByteArray()) == Convert.ToBase64String(value));
}
value = null;
// Create attribute with null byte array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ID, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ID);
Assert.IsTrue(attr.GetValueAsByteArray() == value);
}
}
/// <summary>
/// Attribute with DateTime (CKA_DATE) value test.
/// </summary>
[Test()]
public void _07_DateTimeAttributeTest()
{
DateTime value = new DateTime(2012, 1, 30, 0, 0, 0, DateTimeKind.Utc);
// Create attribute with DateTime value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_START_DATE, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_START_DATE);
Assert.IsTrue(attr.GetValueAsDateTime() == value);
}
}
/// <summary>
/// Attribute with attribute array value test.
/// </summary>
[Test()]
public void _08_AttributeArrayAttributeTest()
{
ObjectAttribute nestedAttribute1 = new ObjectAttribute(CKA.CKA_TOKEN, true);
ObjectAttribute nestedAttribute2 = new ObjectAttribute(CKA.CKA_PRIVATE, true);
List<ObjectAttribute> originalValue = new List<ObjectAttribute>();
originalValue.Add(nestedAttribute1);
originalValue.Add(nestedAttribute2);
// Create attribute with attribute array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_WRAP_TEMPLATE);
List<ObjectAttribute> recoveredValue = attr.GetValueAsObjectAttributeList();
Assert.IsTrue(recoveredValue.Count == 2);
Assert.IsTrue(recoveredValue[0].Type == (ulong)CKA.CKA_TOKEN);
Assert.IsTrue(recoveredValue[0].GetValueAsBool() == true);
Assert.IsTrue(recoveredValue[1].Type == (ulong)CKA.CKA_PRIVATE);
Assert.IsTrue(recoveredValue[1].GetValueAsBool() == true);
}
if (Platform.UnmanagedLongSize == 4)
{
if (Platform.StructPackingSize == 0)
{
// There is the same pointer to unmanaged memory in both nestedAttribute1 and recoveredValue[0] instances
// therefore private low level attribute structure needs to be modified to prevent double free.
// This special handling is needed only in this synthetic test and should be avoided in real world application.
HLA40.ObjectAttribute objectAttribute40a = (HLA40.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute40", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute1);
LLA40.CK_ATTRIBUTE ckAttribute40a = (LLA40.CK_ATTRIBUTE)typeof(HLA40.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute40a);
ckAttribute40a.value = IntPtr.Zero;
ckAttribute40a.valueLen = 0;
typeof(HLA40.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute40a, ckAttribute40a);
// There is the same pointer to unmanaged memory in both nestedAttribute2 and recoveredValue[1] instances
// therefore private low level attribute structure needs to be modified to prevent double free.
// This special handling is needed only in this synthetic test and should be avoided in real world application.
HLA40.ObjectAttribute objectAttribute40b = (HLA40.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute40", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute2);
LLA40.CK_ATTRIBUTE ckAttribute40b = (LLA40.CK_ATTRIBUTE)typeof(HLA40.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute40b);
ckAttribute40b.value = IntPtr.Zero;
ckAttribute40b.valueLen = 0;
typeof(HLA40.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute40b, ckAttribute40b);
}
else
{
// There is the same pointer to unmanaged memory in both nestedAttribute1 and recoveredValue[0] instances
// therefore private low level attribute structure needs to be modified to prevent double free.
// This special handling is needed only in this synthetic test and should be avoided in real world application.
HLA41.ObjectAttribute objectAttribute41a = (HLA41.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute41", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute1);
LLA41.CK_ATTRIBUTE ckAttribute41a = (LLA41.CK_ATTRIBUTE)typeof(HLA41.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute41a);
ckAttribute41a.value = IntPtr.Zero;
ckAttribute41a.valueLen = 0;
typeof(HLA41.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute41a, ckAttribute41a);
// There is the same pointer to unmanaged memory in both nestedAttribute2 and recoveredValue[1] instances
// therefore private low level attribute structure needs to be modified to prevent double free.
// This special handling is needed only in this synthetic test and should be avoided in real world application.
HLA41.ObjectAttribute objectAttribute41b = (HLA41.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute41", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute2);
LLA41.CK_ATTRIBUTE ckAttribute41b = (LLA41.CK_ATTRIBUTE)typeof(HLA41.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute41b);
ckAttribute41b.value = IntPtr.Zero;
ckAttribute41b.valueLen = 0;
typeof(HLA41.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute41b, ckAttribute41b);
}
}
else
{
if (Platform.StructPackingSize == 0)
{
// There is the same pointer to unmanaged memory in both nestedAttribute1 and recoveredValue[0] instances
// therefore private low level attribute structure needs to be modified to prevent double free.
// This special handling is needed only in this synthetic test and should be avoided in real world application.
HLA80.ObjectAttribute objectAttribute80a = (HLA80.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute80", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute1);
LLA80.CK_ATTRIBUTE ckAttribute80a = (LLA80.CK_ATTRIBUTE)typeof(HLA80.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute80a);
ckAttribute80a.value = IntPtr.Zero;
ckAttribute80a.valueLen = 0;
typeof(HLA80.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute80a, ckAttribute80a);
// There is the same pointer to unmanaged memory in both nestedAttribute2 and recoveredValue[1] instances
// therefore private low level attribute structure needs to be modified to prevent double free.
// This special handling is needed only in this synthetic test and should be avoided in real world application.
HLA80.ObjectAttribute objectAttribute80b = (HLA80.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute80", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute2);
LLA80.CK_ATTRIBUTE ckAttribute80b = (LLA80.CK_ATTRIBUTE)typeof(HLA80.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute80b);
ckAttribute80b.value = IntPtr.Zero;
ckAttribute80b.valueLen = 0;
typeof(HLA80.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute80b, ckAttribute80b);
}
else
{
// There is the same pointer to unmanaged memory in both nestedAttribute1 and recoveredValue[0] instances
// therefore private low level attribute structure needs to be modified to prevent double free.
// This special handling is needed only in this synthetic test and should be avoided in real world application.
HLA81.ObjectAttribute objectAttribute81a = (HLA81.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute81", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute1);
LLA81.CK_ATTRIBUTE ckAttribute81a = (LLA81.CK_ATTRIBUTE)typeof(HLA81.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute81a);
ckAttribute81a.value = IntPtr.Zero;
ckAttribute81a.valueLen = 0;
typeof(HLA81.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute81a, ckAttribute81a);
// There is the same pointer to unmanaged memory in both nestedAttribute2 and recoveredValue[1] instances
// therefore private low level attribute structure needs to be modified to prevent double free.
// This special handling is needed only in this synthetic test and should be avoided in real world application.
HLA81.ObjectAttribute objectAttribute81b = (HLA81.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute81", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute2);
LLA81.CK_ATTRIBUTE ckAttribute81b = (LLA81.CK_ATTRIBUTE)typeof(HLA81.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute81b);
ckAttribute81b.value = IntPtr.Zero;
ckAttribute81b.valueLen = 0;
typeof(HLA81.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute81b, ckAttribute81b);
}
}
originalValue = null;
// Create attribute with null attribute array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_WRAP_TEMPLATE);
Assert.IsTrue(attr.GetValueAsObjectAttributeList() == originalValue);
}
originalValue = new List<ObjectAttribute>();
// Create attribute with empty attribute array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_WRAP_TEMPLATE);
Assert.IsTrue(attr.GetValueAsObjectAttributeList() == null);
}
}
/// <summary>
/// Attribute with ulong array value test.
/// </summary>
[Test()]
public void _09_UintArrayAttributeTest()
{
List<ulong> originalValue = new List<ulong>();
originalValue.Add(333333);
originalValue.Add(666666);
// Create attribute with ulong array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS);
List<ulong> recoveredValue = attr.GetValueAsUlongList();
for (int i = 0; i < recoveredValue.Count; i++)
Assert.IsTrue(originalValue[i] == recoveredValue[i]);
}
originalValue = null;
// Create attribute with null ulong array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS);
Assert.IsTrue(attr.GetValueAsUlongList() == originalValue);
}
originalValue = new List<ulong>();
// Create attribute with empty ulong array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS);
Assert.IsTrue(attr.GetValueAsUlongList() == null);
}
}
/// <summary>
/// Attribute with mechanism array value test.
/// </summary>
[Test()]
public void _10_MechanismArrayAttributeTest()
{
List<CKM> originalValue = new List<CKM>();
originalValue.Add(CKM.CKM_RSA_PKCS);
originalValue.Add(CKM.CKM_AES_CBC);
// Create attribute with mechanism array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS);
List<CKM> recoveredValue = attr.GetValueAsCkmList();
for (int i = 0; i < recoveredValue.Count; i++)
Assert.IsTrue(originalValue[i] == recoveredValue[i]);
}
originalValue = null;
// Create attribute with null mechanism array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS);
Assert.IsTrue(attr.GetValueAsCkmList() == originalValue);
}
originalValue = new List<CKM>();
// Create attribute with empty mechanism array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS);
Assert.IsTrue(attr.GetValueAsCkmList() == null);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using NuGet.VisualStudio.Resources;
using VSLangProj;
using MsBuildProject = Microsoft.Build.Evaluation.Project;
using MsBuildProjectItem = Microsoft.Build.Evaluation.ProjectItem;
using Project = EnvDTE.Project;
namespace NuGet.VisualStudio
{
public class VsProjectSystem : IProjectSystem, IVsProjectSystem, IComparer<IPackageFile>
{
private const string BinDir = "bin";
private static readonly string[] AssemblyReferencesExtensions = new[] { ".dll", ".exe", ".winmd" };
private readonly IFileSystem _baseFileSystem;
private FrameworkName _targetFramework;
public VsProjectSystem(Project project, IFileSystemProvider fileSystemProvider)
{
Project = project;
_baseFileSystem = fileSystemProvider.GetFileSystem(project.GetFullPath());
Debug.Assert(_baseFileSystem != null);
}
public ILogger Logger
{
get { return _baseFileSystem.Logger; }
set { _baseFileSystem.Logger = value; }
}
public string Root
{
get { return _baseFileSystem.Root; }
}
protected Project Project
{
get;
private set;
}
public virtual string ProjectName
{
get
{
return Project.Name;
}
}
public string UniqueName
{
get
{
return Project.UniqueName;
}
}
public FrameworkName TargetFramework
{
get
{
if (_targetFramework == null)
{
_targetFramework = Project.GetTargetFrameworkName() ?? VersionUtility.DefaultTargetFramework;
}
return _targetFramework;
}
}
public virtual void AddFile(string path, Stream stream)
{
bool fileExistsInProject = FileExistsInProject(path);
// If the file exists on disk but not in the project then skip it
if (_baseFileSystem.FileExists(path) && !fileExistsInProject)
{
Logger.Log(MessageLevel.Warning, VsResources.Warning_FileAlreadyExists, path);
}
else
{
EnsureCheckedOutIfExists(path);
_baseFileSystem.AddFile(path, stream);
if (!fileExistsInProject)
{
AddFileToProject(path);
}
}
}
public void DeleteDirectory(string path, bool recursive = false)
{
// Only delete this folder if it is empty and we didn't specify that we want to recurse
if (!recursive && (_baseFileSystem.GetFiles(path, "*.*").Any() || _baseFileSystem.GetDirectories(path).Any()))
{
Logger.Log(MessageLevel.Warning, VsResources.Warning_DirectoryNotEmpty, path);
return;
}
if (Project.DeleteProjectItem(path))
{
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFolder, path);
}
}
public void DeleteFile(string path)
{
if (Project.DeleteProjectItem(path))
{
string folderPath = Path.GetDirectoryName(path);
if (!String.IsNullOrEmpty(folderPath))
{
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFileFromFolder, Path.GetFileName(path), folderPath);
}
else
{
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFile, Path.GetFileName(path));
}
}
}
public void AddFrameworkReference(string name)
{
try
{
// Add a reference to the project
AddGacReference(name);
Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName);
}
catch (Exception e)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddGacReference, name), e);
}
}
protected virtual void AddGacReference(string name)
{
Project.Object.References.Add(name);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to catch all exceptions")]
public virtual void AddReference(string referencePath, Stream stream)
{
string name = Path.GetFileNameWithoutExtension(referencePath);
try
{
// Get the full path to the reference
string fullPath = PathUtility.GetAbsolutePath(Root, referencePath);
string assemblyPath = fullPath;
bool usedTempFile = false;
// There is a bug in Visual Studio whereby if the fullPath contains a comma,
// then calling Project.Object.References.Add() on it will throw a COM exception.
// To work around it, we copy the assembly into temp folder and add reference to the copied assembly
if (fullPath.Contains(","))
{
string tempFile = Path.Combine(Path.GetTempPath(), Path.GetFileName(fullPath));
File.Copy(fullPath, tempFile, true);
assemblyPath = tempFile;
usedTempFile = true;
}
// Add a reference to the project
Reference reference = Project.Object.References.Add(assemblyPath);
// if we copied the assembly to temp folder earlier, delete it now since we no longer need it.
if (usedTempFile)
{
try
{
File.Delete(assemblyPath);
}
catch
{
// don't care if we fail to delete a temp file
}
}
// Always set copy local to true for references that we add
try
{
reference.CopyLocal = true;
}
catch (NotSupportedException)
{
}
catch (NotImplementedException)
{
}
// This happens if the assembly appears in any of the search paths that VS uses to locate assembly references.
// Most commonly, it happens if this assembly is in the GAC or in the output path.
if (!reference.Path.Equals(fullPath, StringComparison.OrdinalIgnoreCase))
{
// Get the msbuild project for this project
MsBuildProject buildProject = Project.AsMSBuildProject();
if (buildProject != null)
{
// Get the assembly name of the reference we are trying to add
AssemblyName assemblyName = AssemblyName.GetAssemblyName(fullPath);
// Try to find the item for the assembly name
MsBuildProjectItem item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences()
where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2)
select assemblyReferenceNode.Item1).FirstOrDefault();
if (item != null)
{
// Add the <HintPath> metadata item as a relative path
item.SetMetadataValue("HintPath", referencePath);
// Save the project after we've modified it.
Project.Save();
}
}
}
Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName);
}
catch (Exception e)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddReference, name), e);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to catch all exceptions")]
public virtual void RemoveReference(string name)
{
try
{
// Get the reference name without extension
string referenceName = Path.GetFileNameWithoutExtension(name);
// Remove the reference from the project
var reference = Project.Object.References.Item(referenceName);
if (reference != null)
{
reference.Remove();
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemoveReference, name, ProjectName);
}
}
catch (Exception e)
{
Logger.Log(MessageLevel.Warning, e.Message);
}
}
public bool FileExists(string path)
{
// Only check the project system if the file is on disk to begin with
return _baseFileSystem.FileExists(path) || FileExistsInProject(path);
}
private bool FileExistsInProject(string path)
{
return Project.GetProjectItem(path) != null;
}
protected virtual bool ExcludeFile(string path)
{
// Exclude files from the bin directory.
return BinDir.Equals(Path.GetDirectoryName(path), StringComparison.OrdinalIgnoreCase);
}
protected virtual void AddFileToProject(string path)
{
if (ExcludeFile(path))
{
return;
}
// Get the project items for the folder path
string folderPath = Path.GetDirectoryName(path);
string fullPath = GetFullPath(path);
ThreadHelper.Generic.Invoke(() =>
{
ProjectItems container = Project.GetProjectItems(folderPath, createIfNotExists: true);
// Add the file to project or folder
AddFileToContainer(fullPath, container);
});
Logger.Log(MessageLevel.Debug, VsResources.Debug_AddedFileToProject, path, ProjectName);
}
protected virtual void AddFileToContainer(string fullPath, ProjectItems container)
{
container.AddFromFileCopy(fullPath);
}
public virtual string ResolvePath(string path)
{
return path;
}
public IEnumerable<string> GetFiles(string path, string filter)
{
// Get all physical files
return from p in Project.GetChildItems(path, filter, VsConstants.VsProjectItemKindPhysicalFile)
select p.Name;
}
public virtual IEnumerable<string> GetDirectories(string path)
{
// Get all physical folders
return from p in Project.GetChildItems(path, "*.*", VsConstants.VsProjectItemKindPhysicalFolder)
select p.Name;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We never want to fail when checking for existance")]
public virtual bool ReferenceExists(string name)
{
try
{
string referenceName = name;
if (AssemblyReferencesExtensions.Contains(Path.GetExtension(name), StringComparer.OrdinalIgnoreCase))
{
// Get the reference name without extension
referenceName = Path.GetFileNameWithoutExtension(name);
}
return Project.Object.References.Item(referenceName) != null;
}
catch
{
}
return false;
}
public virtual dynamic GetPropertyValue(string propertyName)
{
try
{
Property property = Project.Properties.Item(propertyName);
if (property != null)
{
return property.Value;
}
}
catch (ArgumentException)
{
// If the property doesn't exist this will throw an argument exception
}
return null;
}
public virtual bool IsSupportedFile(string path)
{
return !("web.config".Equals(Path.GetFileName(path), StringComparison.OrdinalIgnoreCase));
}
private void EnsureCheckedOutIfExists(string path)
{
string fullPath = GetFullPath(path);
if (FileExists(path) &&
Project.DTE.SourceControl != null &&
Project.DTE.SourceControl.IsItemUnderSCC(fullPath) &&
!Project.DTE.SourceControl.IsItemCheckedOut(fullPath))
{
// Check out the item
Project.DTE.SourceControl.CheckOutItem(fullPath);
}
}
private static bool AssemblyNamesMatch(AssemblyName name1, AssemblyName name2)
{
return name1.Name.Equals(name2.Name, StringComparison.OrdinalIgnoreCase) &&
EqualsIfNotNull(name1.Version, name2.Version) &&
EqualsIfNotNull(name1.CultureInfo, name2.CultureInfo) &&
EqualsIfNotNull(name1.GetPublicKeyToken(), name2.GetPublicKeyToken(), Enumerable.SequenceEqual);
}
private static bool EqualsIfNotNull<T>(T obj1, T obj2)
{
return EqualsIfNotNull(obj1, obj2, (a, b) => a.Equals(b));
}
private static bool EqualsIfNotNull<T>(T obj1, T obj2, Func<T, T, bool> equals)
{
// If both objects are non null do the equals
if (obj1 != null && obj2 != null)
{
return equals(obj1, obj2);
}
// Otherwise consider them equal if either of the values are null
return true;
}
public string GetFullPath(string path)
{
return _baseFileSystem.GetFullPath(path);
}
public virtual bool DirectoryExists(string path)
{
return _baseFileSystem.DirectoryExists(path);
}
public Stream OpenFile(string path)
{
return _baseFileSystem.OpenFile(path);
}
public DateTimeOffset GetLastModified(string path)
{
return _baseFileSystem.GetLastModified(path);
}
public DateTimeOffset GetCreated(string path)
{
return _baseFileSystem.GetCreated(path);
}
public int Compare(IPackageFile x, IPackageFile y)
{
// BUG 636: We sort files so that they are added in the correct order
// e.g aspx before aspx.cs
if (x.Path.Equals(y.Path, StringComparison.OrdinalIgnoreCase))
{
return 0;
}
// Add files that are prefixes of other files first
if (x.Path.StartsWith(y.Path, StringComparison.OrdinalIgnoreCase))
{
return -1;
}
if (y.Path.StartsWith(x.Path, StringComparison.OrdinalIgnoreCase))
{
return 1;
}
return y.Path.CompareTo(x.Path);
}
}
}
| |
// 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.Collections.Generic;
using System.Text;
using System.Reflection;
using stress.execution;
namespace stress.codegen
{
public class ExecutionFileGeneratorLinux : ISourceFileGenerator
{
/*
* scriptName - name of the script to be generated, this should include the path
* testName - the name of the test executable
* arguments - arguments to be passed to the test executable
* envVars - dictionary of environment variables and their values
* host (optional) - needed for hosted runtimes
*/
public void GenerateSourceFile(LoadTestInfo loadTestInfo)
{
string lldbInspectionFileName = "inspectCoreWithLLDB.py";
string shellScriptPath = Path.Combine(loadTestInfo.SourceDirectory, "stress.sh");
using (TextWriter stressScript = new StreamWriter(shellScriptPath, false))
{
// set the line ending for shell scripts
stressScript.NewLine = "\n";
stressScript.WriteLine("!# /bin/sh");
stressScript.WriteLine();
stressScript.WriteLine();
stressScript.WriteLine("# stress script for {0}", loadTestInfo.TestName);
stressScript.WriteLine();
stressScript.WriteLine();
stressScript.WriteLine("# environment section");
// first take care of the environment variables
foreach (KeyValuePair<string, string> kvp in loadTestInfo.EnvironmentVariables)
{
stressScript.WriteLine("export {0}={1}", kvp.Key, kvp.Value);
}
stressScript.WriteLine();
stressScript.WriteLine();
// The default limit for coredumps on Linux and Mac is 0 and needs to be reset to allow core dumps to be created
stressScript.WriteLine("# The default limit for coredumps on Linux and Mac is 0 and this needs to be reset to allow core dumps to be created");
stressScript.WriteLine("echo calling [ulimit -c unlimited]");
stressScript.WriteLine("ulimit -c unlimited");
// report the current limits (in theory this should get into the test log)
stressScript.WriteLine("echo calling [ulimit -a]");
stressScript.WriteLine("ulimit -a");
stressScript.WriteLine();
stressScript.WriteLine();
// Prepare the test execution line
string testCommandLine = loadTestInfo.TestName + ".exe";
// If there is a host then prepend it to the test command line
if (!String.IsNullOrEmpty(loadTestInfo.SuiteConfig.Host))
{
testCommandLine = loadTestInfo.SuiteConfig.Host + " " + testCommandLine;
// If the command line isn't a full path or ./ for current directory then add it to ensure we're using the host in the current directory
if ((!loadTestInfo.SuiteConfig.Host.StartsWith("/")) && (!loadTestInfo.SuiteConfig.Host.StartsWith("./")))
{
testCommandLine = "./" + testCommandLine;
}
}
stressScript.WriteLine("# test execution");
stressScript.WriteLine("echo calling [{0}]", testCommandLine);
stressScript.WriteLine(testCommandLine);
// Save off the exit code
stressScript.WriteLine("export _EXITCODE=$?");
stressScript.WriteLine("echo test exited with ExitCode: $_EXITCODE");
// Check the return code
stressScript.WriteLine("if [ $_EXITCODE != 0 ]");
stressScript.WriteLine("then");
//This is a temporary hack workaround for the fact that the process exits before the coredump file is completely written
//We need to replace this with a more hardened way to guaruntee that we don't zip and upload before the coredump is available
stressScript.WriteLine(" echo Work item failed waiting for coredump...");
stressScript.WriteLine(" sleep 2m");
stressScript.WriteLine(" echo zipping work item data for coredump analysis");
stressScript.WriteLine($" echo EXEC: $HELIX_PYTHONPATH $HELIX_SCRIPT_ROOT/zip_script.py $HELIX_WORKITEM_ROOT/../{loadTestInfo.TestName}.zip $HELIX_WORKITEM_ROOT $HELIX_WORKITEM_ROOT/execution $HELIX_WORKITEM_ROOT/core_root");
stressScript.WriteLine($" $HELIX_PYTHONPATH $HELIX_SCRIPT_ROOT/zip_script.py -zipFile $HELIX_WORKITEM_ROOT/../{loadTestInfo.TestName}.zip $HELIX_WORKITEM_ROOT $HELIX_WORKITEM_ROOT/execution $HELIX_WORKITEM_ROOT/core_root");
stressScript.WriteLine($" echo uploading coredump zip to $HELIX_RESULTS_CONTAINER_URI{loadTestInfo.TestName}.zip analysis");
stressScript.WriteLine($" echo EXEC: $HELIX_PYTHONPATH $HELIX_SCRIPT_ROOT/upload_result.py -result $HELIX_WORKITEM_ROOT/../{loadTestInfo.TestName}.zip -result_name {loadTestInfo.TestName}.zip -upload_client_type Blob");
stressScript.WriteLine($" $HELIX_PYTHONPATH $HELIX_SCRIPT_ROOT/upload_result.py -result $HELIX_WORKITEM_ROOT/../{loadTestInfo.TestName}.zip -result_name {loadTestInfo.TestName}.zip -upload_client_type Blob");
stressScript.WriteLine("fi");
//// stressScript.WriteLine("zip -r {0}.zip .", testName);
//// stressScript.WriteLine("else");
//// stressScript.WriteLine(" echo JRS - Test Passed. Report the pass.");
//stressScript.WriteLine("fi");
//stressScript.WriteLine();
//stressScript.WriteLine();
// exit the script with the return code
stressScript.WriteLine("exit $_EXITCODE");
}
// Add the shell script to the source files
loadTestInfo.SourceFiles.Add(new SourceFileInfo(shellScriptPath, SourceFileAction.Binplace));
var shimAssmPath = Assembly.GetAssembly(typeof(StressTestShim)).Location;
var shimAssm = Path.GetFileName(shimAssmPath);
string shimRefPath = Path.Combine(loadTestInfo.SourceDirectory, shimAssm);
File.Copy(shimAssmPath, shimRefPath);
loadTestInfo.SourceFiles.Add(new SourceFileInfo(shimAssmPath, SourceFileAction.Binplace));
// Generate the python script, figure out if the run script is being generated into
// a specific directory, if so then generate the LLDB python script there as well
GenerateLLDBPythonScript(lldbInspectionFileName, loadTestInfo);
}
// The reason for the spacing and begin/end blocks is that python relies on whitespace instead of things
// like being/ends each nested block increases the spaces by 2
public void GenerateLLDBPythonScript(string scriptName, LoadTestInfo loadTestInfo)
{
// If the application is hosted then the debuggee is the host, otherwise it is the test exe
string debuggee = String.IsNullOrEmpty(loadTestInfo.SuiteConfig.Host) ? loadTestInfo.TestName + ".exe" : loadTestInfo.SuiteConfig.Host;
// the name of the core file (should be in the current directory)
string coreFileName = "core";
// LastEvent.txt will contain the ClrStack, native callstack and last exception (if I can get it)
string lastEventFile = "LastEvent.txt";
// LLDBError.txt will contain any error messages from failures to LLDB
string lldbErrorFile = "LLDBError.txt";
// Threads.txt will contain full native callstacks for each threads (equivalent of bt all)
string threadsFile = "Threads.txt";
string scriptNameWithPath = Path.Combine(loadTestInfo.SourceDirectory, scriptName);
using (TextWriter lldbScript = new StreamWriter(scriptNameWithPath, false))
{
// set the line ending for linux/mac
lldbScript.NewLine = "\n";
lldbScript.WriteLine("import lldb");
// Create the debugger object
lldbScript.WriteLine("debugger = lldb.SBDebugger.Create()");
// Create the return object. This contains the return informaton (success/failure, output or error text etc) from the debugger call
lldbScript.WriteLine("retobj = lldb.SBCommandReturnObject()");
// Load the SOS plugin
lldbScript.WriteLine("debugger.GetCommandInterpreter().HandleCommand(\"plugin load libsosplugin.so\", retobj)");
// Create the target
lldbScript.WriteLine("target = debugger.CreateTarget('{0}')", debuggee);
// If the target was created successfully
lldbScript.WriteLine("if target:");
{
// Load the core
lldbScript.WriteLine(" process = target.LoadCore('{0}')", coreFileName);
{
//
lldbScript.WriteLine(" debugger.GetCommandInterpreter().HandleCommand(\"sos ClrStack\", retobj)");
lldbScript.WriteLine(" if retobj.Succeeded():");
{
lldbScript.WriteLine(" LastEventFile = open('{0}', 'w')", lastEventFile);
lldbScript.WriteLine(" LastEventFile.write(retobj.GetOutput())");
lldbScript.WriteLine(" thread = process.GetSelectedThread()");
lldbScript.WriteLine(@" LastEventFile.write('\n'.join(str(frame) for frame in thread))");
lldbScript.WriteLine(" LastEventFile.close()");
}
lldbScript.WriteLine(" else:");
{
lldbScript.WriteLine(" LLDBErrorFile = open('{0}', 'w')", lldbErrorFile);
lldbScript.WriteLine(" LLDBErrorFile.write(retobj.GetError())");
lldbScript.WriteLine(" LLDBErrorFile.close()");
}
lldbScript.WriteLine(" ThreadsFile = open('{0}', 'w')", threadsFile);
lldbScript.WriteLine(" for thread in process:");
{
lldbScript.WriteLine(@" ThreadsFile.write('Thread %s:\n' % str(thread.GetThreadID()))");
lldbScript.WriteLine(" for frame in thread:");
{
lldbScript.WriteLine(@" ThreadsFile.write(str(frame)+'\n')");
}
}
lldbScript.WriteLine(" ThreadsFile.close()");
}
}
}
// Add the python script to the source files
loadTestInfo.SourceFiles.Add(new SourceFileInfo(scriptNameWithPath, SourceFileAction.Binplace));
}
}
public class ExecutionFileGeneratorWindows : ISourceFileGenerator
{
public void GenerateSourceFile(LoadTestInfo loadTestInfo)// (string scriptName, string testName, Dictionary<string, string> envVars, string host = null)
{
string batchScriptPath = Path.Combine(loadTestInfo.SourceDirectory, "stress.bat");
using (TextWriter stressScript = new StreamWriter(batchScriptPath, false))
{
stressScript.WriteLine("@echo off");
stressScript.WriteLine("REM stress script for " + loadTestInfo.TestName);
stressScript.WriteLine();
stressScript.WriteLine();
stressScript.WriteLine("REM environment section");
// first take care of the environment variables
foreach (KeyValuePair<string, string> kvp in loadTestInfo.EnvironmentVariables)
{
stressScript.WriteLine("set {0}={1}", kvp.Key, kvp.Value);
}
stressScript.WriteLine();
stressScript.WriteLine();
// Prepare the test execution line
string testCommandLine = loadTestInfo.TestName + ".exe";
// If there is a host then prepend it to the test command line
if (!String.IsNullOrEmpty(loadTestInfo.SuiteConfig.Host))
{
testCommandLine = loadTestInfo.SuiteConfig.Host + " " + testCommandLine;
}
stressScript.WriteLine("REM test execution");
stressScript.WriteLine("echo calling [{0}]", testCommandLine);
stressScript.WriteLine(testCommandLine);
// Save off the exit code
stressScript.WriteLine("set _EXITCODE=%ERRORLEVEL%");
stressScript.WriteLine("echo test exited with ExitCode: %_EXITCODE%");
stressScript.WriteLine();
stressScript.WriteLine();
// // Check the return code
// stressScript.WriteLine("if %_EXITCODE% EQU 0 goto :REPORT_PASS");
// stressScript.WriteLine("REM error processing");
// stressScript.WriteLine("echo JRS - Test Failed. Report the failure, call to do the initial dump analysis, zip up the directory and return that along with an event");
// stressScript.WriteLine("goto :END");
// stressScript.WriteLine();
// stressScript.WriteLine();
//
// stressScript.WriteLine(":REPORT_PASS");
// stressScript.WriteLine("echo JRS - Test Passed. Report the pass.");
// stressScript.WriteLine();
// stressScript.WriteLine();
// exit the script with the exit code from the process
stressScript.WriteLine(":END");
stressScript.WriteLine("exit /b %_EXITCODE%");
}
// Add the batch script to the source files
loadTestInfo.SourceFiles.Add(new SourceFileInfo(batchScriptPath, SourceFileAction.Binplace));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;
using NUnit.Framework;
using MvcContrib.TestHelper;
using Assert=NUnit.Framework.Assert;
namespace MvcContrib.UnitTests.TestHelper
{
[TestFixture]
public class ActionResultHelperTester
{
public class SampleObject
{
public string Name { get; set; }
}
public class SampleController : Controller
{
public RedirectToRouteResult TestMethod()
{
return
this.RedirectToAction(c => c.SomeOtherMethod(1, new SampleObject {Name = "name"}));
}
public ActionResult SomeOtherMethod(int number, SampleObject obj)
{
return View();
}
}
[Test]
public void Should_convert()
{
ActionResult result = new EmptyResult();
var converted = result.AssertResultIs<EmptyResult>();
Assert.IsNotNull(converted);
}
[Test, ExpectedException(typeof(ActionResultAssertionException), ExpectedMessage = "Expected result to be of type EmptyResult. It is actually of type RedirectResult.")]
public void Should_throw_when_conversiontype_is_incorrect()
{
ActionResult result = new RedirectResult("http://mvccontrib.org");
result.AssertResultIs<EmptyResult>();
}
[Test]
public void Should_convert_to_ViewResult()
{
ActionResult result = new ViewResult();
ViewResult converted = result.AssertViewRendered();
Assert.IsNotNull(converted);
}
[Test]
public void Should_convert_to_RedirectToRouteResult()
{
ActionResult result = new RedirectToRouteResult(new RouteValueDictionary());
RedirectToRouteResult converted = result.AssertActionRedirect();
Assert.IsNotNull(converted);
}
[Test]
public void Should_convert_to_HttpRedirectResult()
{
ActionResult result = new RedirectResult("http://mvccontrib.org");
RedirectResult converted = result.AssertHttpRedirect();
Assert.IsNotNull(converted);
}
[Test]
public void WithParameter_should_return_source_result()
{
var result = new RedirectToRouteResult(new RouteValueDictionary(new { foo = "bar" }));
var final = result.WithParameter("foo", "bar");
Assert.That(final, Is.EqualTo(result));
}
[Test]
public void GetParameter_should_return_value_type_parameters()
{
var controller = new SampleController();
var result = controller.TestMethod();
var parameter = result.GetStronglyTypedParameter(controller, "number");
Assert.That(parameter, Is.EqualTo(1));
}
[Test]
public void GetParameter_should_return_reference_type_parameters()
{
var controller = new SampleController();
var result = controller.TestMethod();
var parameter = (SampleObject)result.GetStronglyTypedParameter(controller, "obj");
Assert.That(parameter.Name, Is.EqualTo("name"));
}
[Test, ExpectedException(typeof(ActionResultAssertionException), ExpectedMessage = "Could not find a parameter named 'foo' in the result's Values collection.")]
public void WithParameter_should_throw_if_key_not_in_dictionary()
{
var result = new RedirectToRouteResult(new RouteValueDictionary());
result.WithParameter("foo", "bar");
}
[Test, ExpectedException(typeof(ActionResultAssertionException), ExpectedMessage = "When looking for a parameter named 'foo', expected 'bar' but was 'baz'.")]
public void WithParameter_should_throw_if_values_are_different()
{
var result = new RedirectToRouteResult(new RouteValueDictionary(new { foo = "baz" }));
result.WithParameter("foo", "bar");
}
[Test]
public void ForView_should_return_source_result()
{
var result = new ViewResult { ViewName = "Index" };
var final = result.ForView("Index");
Assert.That(final, Is.EqualTo(result));
}
[Test, ExpectedException(typeof(ActionResultAssertionException), ExpectedMessage = "Expected view name 'Index', actual was 'About'")]
public void ForView_should_throw_if_view_names_do_not_match()
{
var result = new ViewResult {ViewName = "About"};
result.ForView("Index");
}
[Test]
public void ForUrl_should_return_source_Result()
{
var result = new RedirectResult("http://mvccontrib.org");
var final = result.ToUrl("http://mvccontrib.org");
Assert.That(final, Is.EqualTo(result));
}
[Test, ExpectedException(typeof(ActionResultAssertionException), ExpectedMessage = "Expected redirect to 'http://mvccontrib.org', actual was 'http://www.asp.net'")]
public void ForUrl_should_throw_if_urls_do_not_match()
{
var result = new RedirectResult("http://www.asp.net");
result.ToUrl("http://mvccontrib.org");
}
[Test]
public void Should_chain()
{
ActionResult result = new RedirectToRouteResult(new RouteValueDictionary(new {controller = "Home", action = "Index", id = 1}));
var final = result.AssertActionRedirect().ToController("Home").ToAction("Index").WithParameter("id", 1);
Assert.That(final, Is.EqualTo(result));
}
[Test]
public void ToAction_should_support_strongly_typed_controller_and_action()
{
ActionResult result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "PageHandler", action = "About" }));
var final = result.AssertActionRedirect().ToAction<PageHandler>(c => c.About());
Assert.That(final, Is.EqualTo(result));
}
[Test]
public void ToAction_with_strongly_typed_controller_can_ignore_the_controller_suffix()
{
ActionResult result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Fake", action = "About" }));
var final = result.AssertActionRedirect().ToAction<FakeController>(c => c.About());
Assert.That(final, Is.EqualTo(result));
}
[Test, ExpectedException(typeof(ActionResultAssertionException), ExpectedMessage = "Expected view data of type 'CustomReferenceTypeViewData', actual was 'String'")]
public void WithViewData_should_throw_if_view_data_type_does_not_match()
{
const string wrongViewDataType = "WrongType";
var result = new ViewResult { ViewData = new ViewDataDictionary(wrongViewDataType)};
result.WithViewData<CustomReferenceTypeViewData>();
}
[Test]
public void WithViewData_should_return_view_data_if_view_data_type_matches()
{
var expectedData = new CustomReferenceTypeViewData {ID = 2, Name = "Foo"};
var renderResult = new ViewResult {ViewData = new ViewDataDictionary(expectedData)};
var result = renderResult.WithViewData<CustomReferenceTypeViewData>();
Assert.That(result, Is.EqualTo(expectedData));
}
[Test]
public void WithViewData_should_return_view_data_if_view_data_type_is_subclass_of_expected_type()
{
var expectedData = new DerivedCustomViewData {ID = 2, Name = "Foo"};
var renderResult = new ViewResult {ViewData = new ViewDataDictionary(expectedData)};
var result = renderResult.WithViewData<CustomReferenceTypeViewData>();
Assert.That(result, Is.EqualTo(expectedData));
}
[Test]
[ExpectedException(typeof(ActionResultAssertionException), ExpectedMessage = "Expected view data of type 'CustomValueTypeViewData', actual was NULL")]
public void WithViewData_should_throw_exception_if_view_data_is_null()
{
var renderResult = new ViewResult {ViewData = new ViewDataDictionary<CustomReferenceTypeViewData>() };
renderResult.WithViewData<CustomValueTypeViewData>();
}
[Test]
public void WithViewData_should_return_view_data_if_view_data_type_is_implementation_of_generic_interface()
{
var expectedData = new List<string> { "a", "b", "c" };
var renderResult = new ViewResult { ViewData = new ViewDataDictionary(expectedData) };
var result = renderResult.WithViewData<IList<string>>();
Assert.That(result, Is.EqualTo(expectedData));
}
[Test]
public void Should_convert_to_PartialViewResult()
{
ActionResult result = new PartialViewResult();
result.AssertPartialViewRendered().ShouldNotBeNull();
}
class DerivedCustomViewData : CustomReferenceTypeViewData
{
}
class CustomReferenceTypeViewData
{
public int ID { get; set; }
public string Name { get; set; }
}
struct CustomValueTypeViewData
{
public int ID { get; set; }
public string Name { get; set; }
}
class PageHandler : Controller
{
public ActionResult About()
{
return null;
}
}
class FakeController : Controller
{
public ActionResult About()
{
return null;
}
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 374175 $
* $LastChangedDate: 2006-04-26 14:12:57 -0600 (Wed, 26 Apr 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using IBatisNet.Common;
using IBatisNet.DataMapper.Exceptions;
namespace IBatisNet.DataMapper.Commands
{
/// <summary>
/// An implementation of <see cref="IDataReader"/> that will copy the contents
/// of the an open <see cref="IDataReader"/> to an in-memory <see cref="InMemoryDataReader"/> if the
/// session <see cref="IDbProvider"/> doesn't allow multiple open <see cref="IDataReader"/> with
/// the same <see cref="IDbConnection"/>.
/// </summary>
public class InMemoryDataReader : IDataReader
{
private int _currentRowIndex = 0;
private int _currentResultIndex = 0;
private bool _isClosed = false;
private InMemoryResultSet[ ] _results = null;
/// <summary>
/// Creates an InMemoryDataReader from a <see cref="IDataReader" />
/// </summary>
/// <param name="reader">The <see cref="IDataReader" /> which holds the records from the Database.</param>
public InMemoryDataReader(IDataReader reader)
{
ArrayList resultList = new ArrayList();
try
{
_currentResultIndex = 0;
_currentRowIndex = 0;
resultList.Add( new InMemoryResultSet( reader, true ) );
while( reader.NextResult() )
{
resultList.Add( new InMemoryResultSet( reader, false ) );
}
_results = ( InMemoryResultSet[ ] ) resultList.ToArray( typeof( InMemoryResultSet ) );
}
catch( Exception e )
{
throw new DataMapperException( "There was a problem converting an IDataReader to an InMemoryDataReader", e );
}
finally
{
reader.Close();
reader.Dispose();
}
}
#region IDataReader Members
/// <summary>
/// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement.
/// </summary>
public int RecordsAffected
{
get { throw new NotImplementedException( "InMemoryDataReader only used for select IList statements !" ); }
}
/// <summary>
/// Gets a value indicating whether the data reader is closed.
/// </summary>
public bool IsClosed
{
get { return _isClosed; }
}
/// <summary>
/// Advances the data reader to the next result, when reading the results of batch SQL statements.
/// </summary>
/// <returns></returns>
public bool NextResult()
{
_currentResultIndex++;
if( _currentResultIndex >= _results.Length )
{
_currentResultIndex--;
return false;
}
return true;
}
/// <summary>
/// Closes the IDataReader 0bject.
/// </summary>
public void Close()
{
_isClosed = true;
}
/// <summary>
/// Advances the IDataReader to the next record.
/// </summary>
/// <returns>true if there are more rows; otherwise, false.</returns>
public bool Read()
{
_currentRowIndex++;
if( _currentRowIndex >= _results[ _currentResultIndex ].RecordCount )
{
_currentRowIndex--;
return false;
}
return true;
}
/// <summary>
/// Gets a value indicating the depth of nesting for the current row.
/// </summary>
public int Depth
{
get { return _currentResultIndex; }
}
/// <summary>
/// Returns a DataTable that describes the column metadata of the IDataReader.
/// </summary>
/// <returns></returns>
public DataTable GetSchemaTable()
{
throw new NotImplementedException( "GetSchemaTable() is not implemented, cause not use." );
}
#endregion
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
_isClosed = true;
_results = null;
}
#endregion
#region IDataRecord Members
/// <summary>
/// Gets the 32-bit signed integer value of the specified field.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public int GetInt32(int fieldIndex)
{
return (int) GetValue(fieldIndex);
}
/// <summary>
/// Gets the column with the specified name.
/// </summary>
public object this[string name]
{
get { return this [GetOrdinal(name)]; }
}
/// <summary>
/// Gets the column located at the specified index.
/// </summary>
public object this[int fieldIndex]
{
get { return GetValue( fieldIndex ); }
}
/// <summary>
/// Return the value of the specified field.
/// </summary>
/// <param name="fieldIndex">The index of the field to find. </param>
/// <returns>The object which will contain the field value upon return.</returns>
public object GetValue(int fieldIndex)
{
return this.CurrentResultSet.GetValue( _currentRowIndex, fieldIndex );
}
/// <summary>
/// Return whether the specified field is set to null.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public bool IsDBNull(int fieldIndex)
{
return (GetValue(fieldIndex) == DBNull.Value);
}
/// <summary>
/// Reads a stream of bytes from the specified column offset into the buffer as an array,
/// starting at the given buffer offset.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <param name="dataIndex">The index within the field from which to begin the read operation. </param>
/// <param name="buffer">The buffer into which to read the stream of bytes. </param>
/// <param name="bufferIndex">The index for buffer to begin the read operation.</param>
/// <param name="length">The number of bytes to read. </param>
/// <returns>The actual number of bytes read.</returns>
public long GetBytes(int fieldIndex, long dataIndex, byte[] buffer, int bufferIndex, int length)
{
object value = GetValue(fieldIndex);
if (!(value is byte []))
{
throw new InvalidCastException ("Type is " + value.GetType ().ToString ());
}
if ( buffer == null )
{
// Return length of data
return ((byte []) value).Length;
}
else
{
// Copy data into buffer
int availableLength = (int) ( ( (byte []) value).Length - dataIndex);
if (availableLength < length)
{
length = availableLength;
}
Array.Copy ((byte []) value, (int) dataIndex, buffer, bufferIndex, length);
return length;
}
}
/// <summary>
/// Gets the 8-bit unsigned integer value of the specified column.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public byte GetByte(int fieldIndex)
{
return (byte) GetValue(fieldIndex);
}
/// <summary>
/// Gets the Type information corresponding to the type of Object that would be returned from GetValue.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public Type GetFieldType(int fieldIndex)
{
return this.CurrentResultSet.GetFieldType(fieldIndex);
}
/// <summary>
/// Gets the fixed-position numeric value of the specified field.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public decimal GetDecimal(int fieldIndex)
{
return (decimal) GetValue(fieldIndex);
}
/// <summary>
/// Gets all the attribute fields in the collection for the current record.
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public int GetValues(object[] values)
{
return this.CurrentResultSet.GetValues( _currentRowIndex, values );
}
/// <summary>
/// Gets the name for the field to find.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public string GetName(int fieldIndex)
{
return this.CurrentResultSet.GetName( fieldIndex );
}
/// <summary>
/// Indicates the number of fields within the current record. This property is read-only.
/// </summary>
public int FieldCount
{
get { return this.CurrentResultSet.FieldCount; }
}
/// <summary>
///
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public long GetInt64(int fieldIndex)
{
return (long) GetValue(fieldIndex);
}
/// <summary>
///
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public double GetDouble(int fieldIndex)
{
return (double) GetValue(fieldIndex);
}
/// <summary>
/// Gets the value of the specified column as a Boolean.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public bool GetBoolean(int fieldIndex)
{
return (bool) GetValue(fieldIndex);
}
/// <summary>
/// Returns the GUID value of the specified field.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public Guid GetGuid(int fieldIndex)
{
return (Guid) GetValue(fieldIndex);
}
/// <summary>
/// Returns the value of the specified column as a DateTime object.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public DateTime GetDateTime(int fieldIndex)
{
return (DateTime) GetValue(fieldIndex);
}
/// <summary>
/// Returns the column ordinal, given the name of the column.
/// </summary>
/// <param name="colName">The name of the column. </param>
/// <returns>The value of the column.</returns>
public int GetOrdinal(string colName)
{
return this.CurrentResultSet.GetOrdinal(colName);
}
/// <summary>
/// Gets the database type information for the specified field.
/// </summary>
/// <param name="fieldIndex">The index of the field to find.</param>
/// <returns>The database type information for the specified field.</returns>
public string GetDataTypeName(int fieldIndex)
{
return this.CurrentResultSet.GetDataTypeName(fieldIndex);
}
/// <summary>
/// Returns the value of the specified column as a single-precision floating point number.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public float GetFloat(int fieldIndex)
{
return (float) GetValue(fieldIndex);
}
/// <summary>
/// Gets an IDataReader to be used when the field points to more remote structured data.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public IDataReader GetData(int fieldIndex)
{
throw new NotImplementedException( "GetData(int) is not implemented, cause not use." );
}
/// <summary>
/// Reads a stream of characters from the specified column offset into the buffer as an array,
/// starting at the given buffer offset.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <param name="dataIndex">The index within the row from which to begin the read operation.</param>
/// <param name="buffer">The buffer into which to read the stream of bytes.</param>
/// <param name="bufferIndex">The index for buffer to begin the read operation. </param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>The actual number of characters read.</returns>
public long GetChars(int fieldIndex, long dataIndex, char[] buffer, int bufferIndex, int length)
{
object value = GetValue(fieldIndex);
char [] valueBuffer = null;
if (value is char[])
{
valueBuffer = (char[])value;
}
else if (value is string)
{
valueBuffer = ((string)value).ToCharArray();
}
else
{
throw new InvalidCastException ("Type is " + value.GetType ().ToString ());
}
if ( buffer == null )
{
// Return length of data
return valueBuffer.Length;
}
else
{
// Copy data into buffer
Array.Copy (valueBuffer, (int) dataIndex, buffer, bufferIndex, length);
return valueBuffer.Length - dataIndex;
}
}
/// <summary>
/// Gets the string value of the specified field.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public string GetString(int fieldIndex)
{
return (string) GetValue(fieldIndex);
}
/// <summary>
/// Gets the character value of the specified column.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public char GetChar(int fieldIndex)
{
return (char) GetValue(fieldIndex);
}
/// <summary>
/// Gets the 16-bit signed integer value of the specified field.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public short GetInt16(int fieldIndex)
{
return (short)GetValue (fieldIndex);
}
#endregion
/// <summary>
/// Gets the current result set.
/// </summary>
/// <value>The current result set.</value>
private InMemoryResultSet CurrentResultSet
{
get {return _results[ _currentResultIndex ];}
}
/// <summary>
/// Represent an in-memory result set
/// </summary>
private class InMemoryResultSet
{
// [row][column]
private readonly object[ ][ ] _records = null;
private int _fieldCount = 0;
private string[] _fieldsName = null;
private Type[] _fieldsType = null;
StringDictionary _fieldsNameLookup = new StringDictionary();
private string[] _dataTypeName = null;
/// <summary>
/// Creates an in-memory ResultSet from a <see cref="IDataReader" />
/// </summary>
/// <param name="isMidstream">
/// <c>true</c> if the <see cref="IDataReader"/> is already positioned on the record
/// to start reading from.
/// </param>
/// <param name="reader">The <see cref="IDataReader" /> which holds the records from the Database.</param>
public InMemoryResultSet(IDataReader reader, bool isMidstream )
{
// [record index][ columns values=object[ ] ]
ArrayList recordsList = new ArrayList();
_fieldCount = reader.FieldCount;
_fieldsName = new string[_fieldCount];
_fieldsType = new Type[_fieldCount];
_dataTypeName = new string[_fieldCount];
bool firstRow = true;
// if we are in the middle of processing the reader then don't bother
// to move to the next record - just use the current one.
// Copy the records in memory
while( isMidstream || reader.Read())
{
if( firstRow )
{
for( int fieldIndex = 0; fieldIndex < reader.FieldCount; fieldIndex++ )
{
string fieldName = reader.GetName( fieldIndex );
_fieldsName[ fieldIndex ] = fieldName;
if (!_fieldsNameLookup.ContainsKey(fieldName))
{
_fieldsNameLookup.Add(fieldName, fieldIndex.ToString() );
}
_fieldsType[fieldIndex] = reader.GetFieldType( fieldIndex ) ;
_dataTypeName[ fieldIndex ] = reader.GetDataTypeName( fieldIndex );
}
}
firstRow = false;
object[ ] columnsValues = new object[_fieldCount];
reader.GetValues( columnsValues );
recordsList.Add( columnsValues );
isMidstream = false;
}
_records = ( object[ ][ ] ) recordsList.ToArray( typeof( object[ ] ) );
}
/// <summary>
/// Gets the number of columns in the current row.
/// </summary>
/// <value>The number of columns in the current row.</value>
public int FieldCount
{
get {return _fieldCount;}
}
/// <summary>
/// Get a column value in a row
/// </summary>
/// <param name="rowIndex">The row index</param>
/// <param name="colIndex">The column index</param>
/// <returns>The column value</returns>
public object GetValue( int rowIndex, int colIndex )
{
return _records[ rowIndex ][ colIndex ];
}
/// <summary>
/// The number of record contained in the ResultSet.
/// </summary>
public int RecordCount
{
get { return _records.Length; }
}
/// <summary>
/// Gets the type of the field.
/// </summary>
/// <param name="colIndex">Index of the col.</param>
/// <returns>The type of the field.</returns>
public Type GetFieldType( int colIndex )
{
return _fieldsType[ colIndex ];
}
/// <summary>
/// Gets the name of the field.
/// </summary>
/// <param name="colIndex">Index of the col.</param>
/// <returns>The name of the field.</returns>
public string GetName( int colIndex )
{
return _fieldsName[ colIndex ];
}
/// <summary>
/// Gets the ordinal.
/// </summary>
/// <param name="colName">Name of the column.</param>
/// <returns>The ordinal of the column</returns>
public int GetOrdinal( string colName )
{
if( _fieldsNameLookup.ContainsKey(colName) )
{
return Convert.ToInt32(_fieldsNameLookup[ colName ]);
}
else
{
throw new IndexOutOfRangeException( String.Format( "No column with the specified name was found: {0}.", colName ) );
}
}
/// <summary>
/// Gets the name of the database type.
/// </summary>
/// <param name="colIndex">Index of the col.</param>
/// <returns>The name of the database type</returns>
public string GetDataTypeName( int colIndex )
{
return _dataTypeName[ colIndex ];
}
/// <summary>
/// Gets the values.
/// </summary>
/// <param name="rowIndex">Index of the row.</param>
/// <param name="values">The values.</param>
/// <returns></returns>
public int GetValues( int rowIndex, object[ ] values )
{
Array.Copy( _records[ rowIndex ], 0, values, 0, _fieldCount );
return _fieldCount;
}
}
}
}
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Serialization;
using Leap.Unity.Attributes;
using System.Collections.Generic;
using System;
namespace Leap.Unity.Interaction {
///<summary>
/// A physics-enabled slider. Sliding is triggered by physically pushing the slider to its compressed position.
/// Increasing the horizontal and vertical slide limits allows it to act as either a 1D or 2D slider.
///</summary>
public class InteractionSlider : InteractionButton {
public enum SliderType {
Vertical,
Horizontal,
TwoDimensional
}
[Header("Slider Settings")]
public SliderType sliderType = SliderType.Horizontal;
public bool dispatchSlideValueOnStart = true;
[Tooltip("Manually specify slider limits even if the slider's parent has a RectTransform.")]
[DisableIf("_parentHasRectTransform", isEqualTo: false)]
public bool overrideRectLimits = false;
[SerializeField, HideInInspector]
#pragma warning disable 0414
private bool _parentHasRectTransform = false;
#pragma warning restore 0414
[Header("Horizontal Axis")]
public float defaultHorizontalValue;
[Tooltip("The minimum and maximum values that the slider reports on the horizontal axis.")]
public Vector2 horizontalValueRange = new Vector2(0f, 1f);
[Tooltip("The minimum and maximum horizontal extents that the slider can slide to in world space.")]
[MinMax(-0.5f, 0.5f)]
public Vector2 horizontalSlideLimits = new Vector2(-0.05f, 0.05f);
[Tooltip("The number of discrete quantized notches **beyond the first** that this "
+ "slider can occupy on the horizontal axis. A value of zero indicates a "
+ "continuous (non-quantized) slider for this axis.")]
[MinValue(0)]
public int horizontalSteps = 0;
[System.Serializable]
public class FloatEvent : UnityEvent<float> { }
///<summary> Triggered while this slider is depressed. </summary>
[SerializeField]
[FormerlySerializedAs("horizontalSlideEvent")]
private FloatEvent _horizontalSlideEvent = new FloatEvent();
[Header("Vertical Axis")]
public float defaultVerticalValue;
[Tooltip("The minimum and maximum values that the slider reports on the horizontal axis.")]
public Vector2 verticalValueRange = new Vector2(0f, 1f);
[MinMax(-0.5f, 0.5f)]
[Tooltip("The minimum and maximum vertical extents that the slider can slide to in world space.")]
public Vector2 verticalSlideLimits = new Vector2(0f, 0f);
[Tooltip("The number of discrete quantized notches **beyond the first** that this "
+ "slider can occupy on the vertical axis. A value of zero indicates a "
+ "continuous (non-quantized) slider for this axis.")]
[MinValue(0)]
public int verticalSteps = 0;
///<summary> Triggered while this slider is depressed. </summary>
[SerializeField]
[FormerlySerializedAs("verticalSlideEvent")]
private FloatEvent _verticalSlideEvent = new FloatEvent();
public Action<float> HorizontalSlideEvent = (f) => { };
public Action<float> VerticalSlideEvent = (f) => { };
public float HorizontalSliderPercent {
get {
return _horizontalSliderPercent;
}
set {
if (!_started) {
Debug.LogWarning("An object is attempting to access this slider's value before it has been initialized! Initializing now; this could yield unexpected behaviour...", this);
Start();
}
_horizontalSliderPercent = value;
localPhysicsPosition.x = Mathf.Lerp(initialLocalPosition.x + horizontalSlideLimits.x, initialLocalPosition.x + horizontalSlideLimits.y, _horizontalSliderPercent);
physicsPosition = transform.parent.TransformPoint(localPhysicsPosition);
rigidbody.position = physicsPosition;
}
}
public float VerticalSliderPercent {
get {
return _verticalSliderPercent;
}
set {
if (!_started) {
Debug.LogWarning("An object is attempting to access this slider's value before it has been initialized! Initializing now; this could yield unpected behaviour...", this);
Start();
}
_verticalSliderPercent = value;
localPhysicsPosition.y = Mathf.Lerp(initialLocalPosition.y + verticalSlideLimits.x, initialLocalPosition.y + verticalSlideLimits.y, _verticalSliderPercent);
physicsPosition = transform.parent.TransformPoint(localPhysicsPosition);
rigidbody.position = physicsPosition;
}
}
///<summary> This slider's horizontal slider value, mapped between the values in the HorizontalValueRange. </summary>
public float HorizontalSliderValue {
get {
return Mathf.Lerp(horizontalValueRange.x, horizontalValueRange.y, _horizontalSliderPercent);
}
set {
HorizontalSliderPercent = Mathf.InverseLerp(horizontalValueRange.x, horizontalValueRange.y, value);
}
}
///<summary> This slider's current vertical slider value, mapped between the values in the VerticalValueRange. </summary>
public float VerticalSliderValue {
get {
return Mathf.Lerp(verticalValueRange.x, verticalValueRange.y, _verticalSliderPercent);
}
set {
VerticalSliderPercent = Mathf.InverseLerp(verticalValueRange.x, verticalValueRange.y, value);
}
}
//Internal Slider Values
protected float _horizontalSliderPercent;
protected float _verticalSliderPercent;
protected RectTransform parent;
private bool _started = false;
protected override void OnValidate() {
base.OnValidate();
if (this.transform.parent != null && this.transform.parent.GetComponent<RectTransform>() != null) {
_parentHasRectTransform = true;
}
else {
_parentHasRectTransform = false;
}
}
protected override void Start() {
if (_started) return;
_started = true;
calculateSliderLimits();
switch (sliderType) {
case SliderType.Horizontal:
verticalSlideLimits = new Vector2(0, 0);
break;
case SliderType.Vertical:
horizontalSlideLimits = new Vector2(0, 0);
break;
}
base.Start();
HorizontalSlideEvent += _horizontalSlideEvent.Invoke;
VerticalSlideEvent += _verticalSlideEvent.Invoke;
HorizontalSliderValue = defaultHorizontalValue;
VerticalSliderValue = defaultVerticalValue;
if (dispatchSlideValueOnStart) {
HorizontalSlideEvent(HorizontalSliderValue);
VerticalSlideEvent(VerticalSliderValue);
}
}
public void RecalculateSliderLimits() {
calculateSliderLimits();
}
private void calculateSliderLimits() {
if (transform.parent != null) {
parent = transform.parent.GetComponent<RectTransform>();
if (overrideRectLimits) return;
if (parent != null) {
if (parent.rect.width < 0f || parent.rect.height < 0f) {
Debug.LogError("Parent Rectangle dimensions negative; can't set slider boundaries!", parent.gameObject);
enabled = false;
} else {
var self = transform.GetComponent<RectTransform>();
if (self != null) {
horizontalSlideLimits = new Vector2(parent.rect.xMin - transform.localPosition.x + self.rect.width / 2F, parent.rect.xMax - transform.localPosition.x - self.rect.width / 2F);
if (horizontalSlideLimits.x > horizontalSlideLimits.y) {
horizontalSlideLimits = new Vector2(0F, 0F);
}
if (Mathf.Abs(horizontalSlideLimits.x) < 0.0001F) {
horizontalSlideLimits.x = 0F;
}
if (Mathf.Abs(horizontalSlideLimits.y) < 0.0001F) {
horizontalSlideLimits.y = 0F;
}
verticalSlideLimits = new Vector2(parent.rect.yMin - transform.localPosition.y + self.rect.height / 2F, parent.rect.yMax - transform.localPosition.y - self.rect.height / 2F);
if (verticalSlideLimits.x > verticalSlideLimits.y) {
verticalSlideLimits = new Vector2(0F, 0F);
}
if (Mathf.Abs(verticalSlideLimits.x) < 0.0001F) {
verticalSlideLimits.x = 0F;
}
if (Mathf.Abs(verticalSlideLimits.y) < 0.0001F) {
verticalSlideLimits.y = 0F;
}
} else {
horizontalSlideLimits = new Vector2(parent.rect.xMin - transform.localPosition.x, parent.rect.xMax - transform.localPosition.x);
verticalSlideLimits = new Vector2(parent.rect.yMin - transform.localPosition.y, parent.rect.yMax - transform.localPosition.y);
}
}
}
}
}
protected override void Update() {
base.Update();
if (!Application.isPlaying) { return; }
if (isDepressed || isGrasped) {
calculateSliderValues();
}
}
protected override void OnEnable() {
base.OnEnable();
OnContactStay += calculateSliderValues;
}
protected override void OnDisable() {
OnContactStay -= calculateSliderValues;
base.OnDisable();
}
private void calculateSliderValues() {
// Calculate renormalized slider values.
if (horizontalSlideLimits.x != horizontalSlideLimits.y) {
_horizontalSliderPercent = Mathf.InverseLerp(initialLocalPosition.x + horizontalSlideLimits.x, initialLocalPosition.x + horizontalSlideLimits.y, localPhysicsPosition.x);
HorizontalSlideEvent(HorizontalSliderValue);
}
if (verticalSlideLimits.x != verticalSlideLimits.y) {
_verticalSliderPercent = Mathf.InverseLerp(initialLocalPosition.y + verticalSlideLimits.x, initialLocalPosition.y + verticalSlideLimits.y, localPhysicsPosition.y);
VerticalSlideEvent(VerticalSliderValue);
}
}
public float normalizedHorizontalValue {
get {
return _horizontalSliderPercent;
}
}
public float normalizedVerticalValue {
get {
return _verticalSliderPercent;
}
}
/// <summary>
/// Returns the number of horizontal steps past the minimum value of the slider, for
/// sliders with a non-zero number of horizontal steps. This value is independent of
/// the horizontal value range of the slider. For example a slider with a
/// horizontalSteps value of 9 could have horizontalStepValues of 0-9.
/// </summary>
public int horizontalStepValue {
get {
float range = horizontalValueRange.y - horizontalValueRange.x;
if (range == 0F) return 0;
else {
return (int)(_horizontalSliderPercent * horizontalSteps * 1.001F);
}
}
}
protected override Vector3 getDepressedConstrainedLocalPosition(Vector3 desiredOffset) {
Vector3 unSnappedPosition =
new Vector3(Mathf.Clamp((localPhysicsPosition.x + desiredOffset.x), initialLocalPosition.x + horizontalSlideLimits.x, initialLocalPosition.x + horizontalSlideLimits.y),
Mathf.Clamp((localPhysicsPosition.y + desiredOffset.y), initialLocalPosition.y + verticalSlideLimits.x, initialLocalPosition.y + verticalSlideLimits.y),
(localPhysicsPosition.z + desiredOffset.z));
float hSliderPercent = Mathf.InverseLerp(initialLocalPosition.x + horizontalSlideLimits.x, initialLocalPosition.x + horizontalSlideLimits.y, unSnappedPosition.x);
if (horizontalSteps > 0) {
hSliderPercent = Mathf.Round(hSliderPercent * (horizontalSteps)) / (horizontalSteps);
}
float vSliderPercent = Mathf.InverseLerp(initialLocalPosition.y + verticalSlideLimits.x, initialLocalPosition.y + verticalSlideLimits.y, unSnappedPosition.y);
if (verticalSteps > 0) {
vSliderPercent = Mathf.Round(vSliderPercent * (verticalSteps)) / (verticalSteps);
}
return new Vector3(Mathf.Lerp(initialLocalPosition.x + horizontalSlideLimits.x, initialLocalPosition.x + horizontalSlideLimits.y, hSliderPercent),
Mathf.Lerp(initialLocalPosition.y + verticalSlideLimits.x, initialLocalPosition.y + verticalSlideLimits.y, vSliderPercent),
(localPhysicsPosition.z + desiredOffset.z));
}
protected override void OnDrawGizmosSelected() {
base.OnDrawGizmosSelected();
if (transform.parent != null) {
Vector3 originPosition = Application.isPlaying ? initialLocalPosition : transform.localPosition;
if (Application.isPlaying && startingPositionMode == StartingPositionMode.Relaxed) {
originPosition = originPosition + Vector3.back * Mathf.Lerp(minMaxHeight.x, minMaxHeight.y, restingHeight);
}
// Actual slider slide limits
Gizmos.color = Color.blue;
Gizmos.DrawWireCube(originPosition +
new Vector3((sliderType == SliderType.Vertical ? 0F : (horizontalSlideLimits.x + horizontalSlideLimits.y) * 0.5f),
(sliderType == SliderType.Horizontal ? 0F : (verticalSlideLimits.x + verticalSlideLimits.y) * 0.5f),
0f),
new Vector3((sliderType == SliderType.Vertical ? 0F : horizontalSlideLimits.y - horizontalSlideLimits.x),
(sliderType == SliderType.Horizontal ? 0F : verticalSlideLimits.y - verticalSlideLimits.x),
0f));
var self = GetComponent<RectTransform>();
if (self != null) {
// Apparent slide limits (against own rect limits)
parent = transform.parent.GetComponent<RectTransform>();
if (parent != null) {
var parentRectHorizontal = new Vector2(parent.rect.xMin - originPosition.x, parent.rect.xMax - originPosition.x);
var parentRectVertical = new Vector2(parent.rect.yMin - originPosition.y, parent.rect.yMax - originPosition.y);
Gizmos.color = Color.Lerp(Color.blue, Color.cyan, 0.5F);
Gizmos.DrawWireCube(originPosition +
new Vector3((parentRectHorizontal.x + parentRectHorizontal.y) * 0.5f,
(parentRectVertical.x + parentRectVertical.y) * 0.5f,
(startingPositionMode == StartingPositionMode.Relaxed ?
Mathf.Lerp(minMaxHeight.x, minMaxHeight.y, 0.5F) - Mathf.Lerp(minMaxHeight.x, minMaxHeight.y, 1 - restingHeight)
: -1F * Mathf.Lerp(minMaxHeight.x, minMaxHeight.y, 0.5F))),
new Vector3(parentRectHorizontal.y - parentRectHorizontal.x, parentRectVertical.y - parentRectVertical.x, (minMaxHeight.y - minMaxHeight.x)));
// Own rect width/height
Gizmos.color = Color.cyan;
Gizmos.DrawWireCube(originPosition,
self.rect.width * Vector3.right
+ self.rect.height * Vector3.up);
}
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
namespace Microsoft.Tools.ServiceModel.WsatConfig
{
using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;
using System.Security.Permissions;
using System.Text;
using Microsoft.Win32;
abstract class SafeClusterHandle : SafeHandle
{
[SecurityCritical]
internal SafeClusterHandle()
:
base(IntPtr.Zero, true)
{
}
public override bool IsInvalid
{
get { return IsClosed || handle == IntPtr.Zero; }
}
}
class SafeHCluster : SafeClusterHandle
{
// MSDN remarks: This function always returns TRUE.
[DllImport(SafeNativeMethods.ClusApi)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
static extern bool CloseCluster([In] IntPtr hCluster);
protected override bool ReleaseHandle()
{
return CloseCluster(handle);
}
}
class SafeHResource : SafeClusterHandle
{
[DllImport(SafeNativeMethods.ClusApi)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
static extern bool CloseClusterResource([In] IntPtr hResource);
protected override bool ReleaseHandle()
{
return CloseClusterResource(handle);
}
}
class SafeHClusEnum : SafeClusterHandle
{
[DllImport(SafeNativeMethods.ClusApi)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
static extern uint ClusterCloseEnum([In] IntPtr hEnum);
protected override bool ReleaseHandle()
{
return ClusterCloseEnum(handle) == SafeNativeMethods.ERROR_SUCCESS;
}
}
class SafeHKey : SafeClusterHandle
{
[DllImport(SafeNativeMethods.ClusApi)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
static extern int ClusterRegCloseKey([In] IntPtr hEnum);
protected override bool ReleaseHandle()
{
return ClusterRegCloseKey(handle) == SafeNativeMethods.ERROR_SUCCESS;
}
}
[Flags]
enum ClusterEnum : uint
{
Node = 0x00000001,
ResType = 0x00000002,
Resource = 0x00000004,
Group = 0x00000008,
Network = 0x00000010,
NetInterface = 0x00000020,
InternalNetwork = 0x80000000
}
enum ClusterResourceControlCode : uint
{
GetResourceType = 0x0100002d,
//GetId = 0x01000039
}
static partial class SafeNativeMethods
{
internal const string ClusApi = "clusapi.dll";
internal const uint ERROR_SUCCESS = 0;
internal const uint ERROR_FILE_NOT_FOUND = 2;
internal const uint ERROR_INSUFFICIENT_BUFFER = 122;
internal const uint ERROR_MORE_DATA = 234;
internal const uint ERROR_NO_MORE_ITEMS = 259;
internal const uint REG_OPTION_NON_VOLATILE = 0;
[DllImport(ClusApi, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafeHCluster OpenCluster(
[MarshalAs(UnmanagedType.LPWStr)] [In] string lpszClusterName);
[DllImport(ClusApi, SetLastError = false, CharSet = CharSet.Unicode)]
internal static extern int GetClusterInformation(
[In] SafeHCluster hCluster,
[Out] StringBuilder lpszClusterName,
[In, Out] ref uint lpcchClusterName,
[In, Out] IntPtr lpClusterInfo
);
[DllImport(ClusApi, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafeHClusEnum ClusterOpenEnum(
[In] SafeHCluster hCluster,
[In] ClusterEnum dwType);
[DllImport(ClusApi, CharSet = CharSet.Unicode)]
internal static extern uint ClusterEnum(
[In] SafeHClusEnum hEnum,
[In] uint dwIndex,
[Out] out uint lpdwType,
[Out] StringBuilder lpszName,
[In, Out] ref uint lpcchName);
[DllImport(ClusApi, CharSet = CharSet.Unicode)]
internal static extern uint ClusterResourceControl(
[In] SafeHResource hResource,
[In] IntPtr hHostNode, //HNODE hHostNode, never used
[In] ClusterResourceControlCode dwControlCode,
[In] IntPtr lpInBuffer, // LPVOID lpInBuffer, never used
[In] uint cbInBufferSize,
[In, Out, MarshalAs(UnmanagedType.LPArray)] byte[] buffer,
[In] uint cbOutBufferSize,
[In, Out] ref uint lpcbBytesReturned);
[DllImport(ClusApi, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafeHResource OpenClusterResource(
[In] SafeHCluster hCluster,
[In, MarshalAs(UnmanagedType.LPWStr)] string lpszResourceName);
[DllImport(ClusApi, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool GetClusterResourceNetworkName(
[In] SafeHResource hResource,
[Out] StringBuilder lpBuffer,
[In, Out] ref uint nSize);
[DllImport(ClusApi, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafeHKey GetClusterResourceKey(
[In] SafeHResource hResource,
[In] RegistryRights samDesired);
[DllImport(ClusApi, SetLastError = false, CharSet = CharSet.Unicode)]
internal static extern int ClusterRegCreateKey(
[In] SafeHKey hKey,
[In, MarshalAs(UnmanagedType.LPWStr)] string lpszSubKey,
[In] uint dwOption,
[In] RegistryRights samDesired,
[In] IntPtr lpSecurityAttributes,
[Out] out SafeHKey phkResult,
[Out] out int lpdwDisposition);
[DllImport(ClusApi, CharSet = CharSet.Unicode)]
internal static extern int ClusterRegQueryValue(
[In] SafeHKey hKey,
[In, MarshalAs(UnmanagedType.LPWStr)] string lpszValueName,
[Out] out RegistryValueKind lpdwValueType,
[Out, MarshalAs(UnmanagedType.LPArray)] byte[] lpbData,
[In, Out] ref uint lpcbData);
[DllImport(ClusApi, CharSet = CharSet.Unicode)]
internal static extern int ClusterRegSetValue(
[In] SafeHKey hKey,
[In, MarshalAs(UnmanagedType.LPWStr)] string lpszValueName,
[In] RegistryValueKind lpdwValueType,
[In, MarshalAs(UnmanagedType.LPArray)] byte[] lpbData,
[In] uint lpcbData);
[DllImport(ClusApi, CharSet = CharSet.Unicode)]
internal static extern int ClusterRegGetKeySecurity(
[In] SafeHKey hKey,
[In] SecurityInfos securityInformation,
[In, Out] byte[] securityDescriptor,
[In, Out] ref uint lpcbSecurityDescriptor);
[DllImport(ClusApi, CharSet = CharSet.Unicode)]
internal static extern int ClusterRegSetKeySecurity(
[In] SafeHKey hKey,
[In] SecurityInfos securityInformation,
[In] byte[] securityDescriptor);
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/metric_service.proto
// Original file comments:
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace Google.Cloud.Monitoring.V3 {
/// <summary>
/// Manages metric descriptors, monitored resource descriptors, and
/// time series data.
/// </summary>
public static class MetricService
{
static readonly string __ServiceName = "google.monitoring.v3.MetricService";
static readonly Marshaller<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest> __Marshaller_ListMonitoredResourceDescriptorsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> __Marshaller_ListMonitoredResourceDescriptorsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest> __Marshaller_GetMonitoredResourceDescriptorRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Api.MonitoredResourceDescriptor> __Marshaller_MonitoredResourceDescriptor = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Api.MonitoredResourceDescriptor.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest> __Marshaller_ListMetricDescriptorsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse> __Marshaller_ListMetricDescriptorsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest> __Marshaller_GetMetricDescriptorRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Api.MetricDescriptor> __Marshaller_MetricDescriptor = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Api.MetricDescriptor.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest> __Marshaller_CreateMetricDescriptorRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest> __Marshaller_DeleteMetricDescriptorRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest> __Marshaller_ListTimeSeriesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse> __Marshaller_ListTimeSeriesResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest> __Marshaller_CreateTimeSeriesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest.Parser.ParseFrom);
static readonly Method<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest, global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> __Method_ListMonitoredResourceDescriptors = new Method<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest, global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse>(
MethodType.Unary,
__ServiceName,
"ListMonitoredResourceDescriptors",
__Marshaller_ListMonitoredResourceDescriptorsRequest,
__Marshaller_ListMonitoredResourceDescriptorsResponse);
static readonly Method<global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest, global::Google.Api.MonitoredResourceDescriptor> __Method_GetMonitoredResourceDescriptor = new Method<global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest, global::Google.Api.MonitoredResourceDescriptor>(
MethodType.Unary,
__ServiceName,
"GetMonitoredResourceDescriptor",
__Marshaller_GetMonitoredResourceDescriptorRequest,
__Marshaller_MonitoredResourceDescriptor);
static readonly Method<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest, global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse> __Method_ListMetricDescriptors = new Method<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest, global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse>(
MethodType.Unary,
__ServiceName,
"ListMetricDescriptors",
__Marshaller_ListMetricDescriptorsRequest,
__Marshaller_ListMetricDescriptorsResponse);
static readonly Method<global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest, global::Google.Api.MetricDescriptor> __Method_GetMetricDescriptor = new Method<global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest, global::Google.Api.MetricDescriptor>(
MethodType.Unary,
__ServiceName,
"GetMetricDescriptor",
__Marshaller_GetMetricDescriptorRequest,
__Marshaller_MetricDescriptor);
static readonly Method<global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest, global::Google.Api.MetricDescriptor> __Method_CreateMetricDescriptor = new Method<global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest, global::Google.Api.MetricDescriptor>(
MethodType.Unary,
__ServiceName,
"CreateMetricDescriptor",
__Marshaller_CreateMetricDescriptorRequest,
__Marshaller_MetricDescriptor);
static readonly Method<global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteMetricDescriptor = new Method<global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
MethodType.Unary,
__ServiceName,
"DeleteMetricDescriptor",
__Marshaller_DeleteMetricDescriptorRequest,
__Marshaller_Empty);
static readonly Method<global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest, global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse> __Method_ListTimeSeries = new Method<global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest, global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse>(
MethodType.Unary,
__ServiceName,
"ListTimeSeries",
__Marshaller_ListTimeSeriesRequest,
__Marshaller_ListTimeSeriesResponse);
static readonly Method<global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_CreateTimeSeries = new Method<global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
MethodType.Unary,
__ServiceName,
"CreateTimeSeries",
__Marshaller_CreateTimeSeriesRequest,
__Marshaller_Empty);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.Monitoring.V3.MetricServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of MetricService</summary>
public abstract class MetricServiceBase
{
/// <summary>
/// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptors(global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Gets a single monitored resource descriptor. This method does not require a Stackdriver account.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Api.MonitoredResourceDescriptor> GetMonitoredResourceDescriptor(global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Lists metric descriptors that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse> ListMetricDescriptors(global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Gets a single metric descriptor. This method does not require a Stackdriver account.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Api.MetricDescriptor> GetMetricDescriptor(global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Creates a new metric descriptor.
/// User-created metric descriptors define
/// [custom metrics](/monitoring/custom-metrics).
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Api.MetricDescriptor> CreateMetricDescriptor(global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Deletes a metric descriptor. Only user-created
/// [custom metrics](/monitoring/custom-metrics) can be deleted.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteMetricDescriptor(global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Lists time series that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse> ListTimeSeries(global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Creates or adds data to one or more time series.
/// The response is empty if all time series in the request were written.
/// If any time series could not be written, a corresponding failure message is
/// included in the error response.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> CreateTimeSeries(global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for MetricService</summary>
public class MetricServiceClient : ClientBase<MetricServiceClient>
{
/// <summary>Creates a new client for MetricService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public MetricServiceClient(Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for MetricService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public MetricServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected MetricServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected MetricServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse ListMonitoredResourceDescriptors(global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListMonitoredResourceDescriptors(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse ListMonitoredResourceDescriptors(global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListMonitoredResourceDescriptors, null, options, request);
}
/// <summary>
/// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptorsAsync(global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListMonitoredResourceDescriptorsAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptorsAsync(global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListMonitoredResourceDescriptors, null, options, request);
}
/// <summary>
/// Gets a single monitored resource descriptor. This method does not require a Stackdriver account.
/// </summary>
public virtual global::Google.Api.MonitoredResourceDescriptor GetMonitoredResourceDescriptor(global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetMonitoredResourceDescriptor(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets a single monitored resource descriptor. This method does not require a Stackdriver account.
/// </summary>
public virtual global::Google.Api.MonitoredResourceDescriptor GetMonitoredResourceDescriptor(global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetMonitoredResourceDescriptor, null, options, request);
}
/// <summary>
/// Gets a single monitored resource descriptor. This method does not require a Stackdriver account.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Api.MonitoredResourceDescriptor> GetMonitoredResourceDescriptorAsync(global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetMonitoredResourceDescriptorAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets a single monitored resource descriptor. This method does not require a Stackdriver account.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Api.MonitoredResourceDescriptor> GetMonitoredResourceDescriptorAsync(global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetMonitoredResourceDescriptor, null, options, request);
}
/// <summary>
/// Lists metric descriptors that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse ListMetricDescriptors(global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListMetricDescriptors(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists metric descriptors that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse ListMetricDescriptors(global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListMetricDescriptors, null, options, request);
}
/// <summary>
/// Lists metric descriptors that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse> ListMetricDescriptorsAsync(global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListMetricDescriptorsAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists metric descriptors that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse> ListMetricDescriptorsAsync(global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListMetricDescriptors, null, options, request);
}
/// <summary>
/// Gets a single metric descriptor. This method does not require a Stackdriver account.
/// </summary>
public virtual global::Google.Api.MetricDescriptor GetMetricDescriptor(global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetMetricDescriptor(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets a single metric descriptor. This method does not require a Stackdriver account.
/// </summary>
public virtual global::Google.Api.MetricDescriptor GetMetricDescriptor(global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetMetricDescriptor, null, options, request);
}
/// <summary>
/// Gets a single metric descriptor. This method does not require a Stackdriver account.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Api.MetricDescriptor> GetMetricDescriptorAsync(global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetMetricDescriptorAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets a single metric descriptor. This method does not require a Stackdriver account.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Api.MetricDescriptor> GetMetricDescriptorAsync(global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetMetricDescriptor, null, options, request);
}
/// <summary>
/// Creates a new metric descriptor.
/// User-created metric descriptors define
/// [custom metrics](/monitoring/custom-metrics).
/// </summary>
public virtual global::Google.Api.MetricDescriptor CreateMetricDescriptor(global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateMetricDescriptor(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates a new metric descriptor.
/// User-created metric descriptors define
/// [custom metrics](/monitoring/custom-metrics).
/// </summary>
public virtual global::Google.Api.MetricDescriptor CreateMetricDescriptor(global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CreateMetricDescriptor, null, options, request);
}
/// <summary>
/// Creates a new metric descriptor.
/// User-created metric descriptors define
/// [custom metrics](/monitoring/custom-metrics).
/// </summary>
public virtual AsyncUnaryCall<global::Google.Api.MetricDescriptor> CreateMetricDescriptorAsync(global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateMetricDescriptorAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates a new metric descriptor.
/// User-created metric descriptors define
/// [custom metrics](/monitoring/custom-metrics).
/// </summary>
public virtual AsyncUnaryCall<global::Google.Api.MetricDescriptor> CreateMetricDescriptorAsync(global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CreateMetricDescriptor, null, options, request);
}
/// <summary>
/// Deletes a metric descriptor. Only user-created
/// [custom metrics](/monitoring/custom-metrics) can be deleted.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteMetricDescriptor(global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteMetricDescriptor(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Deletes a metric descriptor. Only user-created
/// [custom metrics](/monitoring/custom-metrics) can be deleted.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteMetricDescriptor(global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_DeleteMetricDescriptor, null, options, request);
}
/// <summary>
/// Deletes a metric descriptor. Only user-created
/// [custom metrics](/monitoring/custom-metrics) can be deleted.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteMetricDescriptorAsync(global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteMetricDescriptorAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Deletes a metric descriptor. Only user-created
/// [custom metrics](/monitoring/custom-metrics) can be deleted.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteMetricDescriptorAsync(global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_DeleteMetricDescriptor, null, options, request);
}
/// <summary>
/// Lists time series that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse ListTimeSeries(global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListTimeSeries(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists time series that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse ListTimeSeries(global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListTimeSeries, null, options, request);
}
/// <summary>
/// Lists time series that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse> ListTimeSeriesAsync(global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListTimeSeriesAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists time series that match a filter. This method does not require a Stackdriver account.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse> ListTimeSeriesAsync(global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListTimeSeries, null, options, request);
}
/// <summary>
/// Creates or adds data to one or more time series.
/// The response is empty if all time series in the request were written.
/// If any time series could not be written, a corresponding failure message is
/// included in the error response.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty CreateTimeSeries(global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateTimeSeries(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates or adds data to one or more time series.
/// The response is empty if all time series in the request were written.
/// If any time series could not be written, a corresponding failure message is
/// included in the error response.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty CreateTimeSeries(global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CreateTimeSeries, null, options, request);
}
/// <summary>
/// Creates or adds data to one or more time series.
/// The response is empty if all time series in the request were written.
/// If any time series could not be written, a corresponding failure message is
/// included in the error response.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CreateTimeSeriesAsync(global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateTimeSeriesAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates or adds data to one or more time series.
/// The response is empty if all time series in the request were written.
/// If any time series could not be written, a corresponding failure message is
/// included in the error response.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CreateTimeSeriesAsync(global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CreateTimeSeries, null, options, request);
}
protected override MetricServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new MetricServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(MetricServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_ListMonitoredResourceDescriptors, serviceImpl.ListMonitoredResourceDescriptors)
.AddMethod(__Method_GetMonitoredResourceDescriptor, serviceImpl.GetMonitoredResourceDescriptor)
.AddMethod(__Method_ListMetricDescriptors, serviceImpl.ListMetricDescriptors)
.AddMethod(__Method_GetMetricDescriptor, serviceImpl.GetMetricDescriptor)
.AddMethod(__Method_CreateMetricDescriptor, serviceImpl.CreateMetricDescriptor)
.AddMethod(__Method_DeleteMetricDescriptor, serviceImpl.DeleteMetricDescriptor)
.AddMethod(__Method_ListTimeSeries, serviceImpl.ListTimeSeries)
.AddMethod(__Method_CreateTimeSeries, serviceImpl.CreateTimeSeries).Build();
}
}
}
#endregion
| |
using System;
using System.Collections.Generic;
using System.Linq;
using TimedText;
using TimedText.Styling;
#if SILVERLIGHT
using System.Windows;
using System.Windows.Media;
#else
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Windows.UI;
using Windows.UI.Text;
#endif
using Style = Microsoft.Media.TimedText.TimedTextStyle;
using TimedTextExtent = TimedText.Styling.Extent;
using TimedTextOrigin = TimedText.Styling.Origin;
namespace Microsoft.Media.TimedText
{
/// <summary>
/// Parses style information about a timed text marker.
/// </summary>
/// <remarks>
/// Style information determines the appearance of the marker text.
/// This class uses the style information defined in XML and creates corresponding
/// Style objects.
/// Styles are defined in the W3C TTAF 1.0 specification.
/// </remarks>
internal static class TimedTextStyleParser
{
private static readonly Style DefaultStyle = new Style();
internal static bool IsValidAnimationPropertyName(string name)
{
bool ret = false;
switch (name)
{
case "backgroundColor":
ret = true;
break;
case "color":
ret = true;
break;
case "displayAlign":
ret = true;
break;
case "display":
ret = true;
break;
case "extent":
ret = true;
break;
case "fontFamily":
ret = true;
break;
case "fontSize":
ret = true;
break;
case "fontStyle":
ret = true;
break;
case "fontWeight":
ret = true;
break;
case "lineHeight":
ret = true;
break;
case "opacity":
ret = true;
break;
case "origin":
ret = true;
break;
case "overflow":
ret = true;
break;
case "padding":
ret = true;
break;
case "showBackground":
ret = true;
break;
case "textAlign":
ret = true;
break;
case "visibility":
ret = true;
break;
case "wrapOption":
ret = true;
break;
case "zIndex":
ret = true;
break;
}
return ret;
}
static LengthUnit FromUnit(Unit unit)
{
switch (unit)
{
case Unit.Cell:
return LengthUnit.Cell;
case Unit.Em:
return LengthUnit.Em;
case Unit.Percent:
return LengthUnit.Percent;
case Unit.Pixel:
return LengthUnit.Pixel;
case Unit.PixelProportional:
return LengthUnit.PixelProportional;
default:
throw new ArgumentException("Unexpected unit type");
}
}
static Dictionary<string, NumberPair> numberPairXref = new Dictionary<string, NumberPair>();
static NumberPair GetNumberPair(string value)
{
if (numberPairXref.ContainsKey(value))
{
return new NumberPair(numberPairXref[value]);
}
else
{
NumberPair pair = new NumberPair(value);
numberPairXref.Add(value, new NumberPair(pair));
return pair;
}
}
internal static Style MapStyle(TimedTextElementBase styleElement, RegionElement region)
{
var style = new Style();
if (styleElement.Id != null)
{
style.Id = styleElement.Id;
}
var backgroundImage =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.BackgroundImage.LocalName, region)
as string;
style.BackgroundImage = backgroundImage;
var backgroundImageHorizontal =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.BackgroundImageHorizontal.LocalName, region)
as PositionLength;
style.BackgroundImageHorizontal = backgroundImageHorizontal;
var backgroundImageVertical =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.BackgroundImageVertical.LocalName, region)
as PositionLength;
style.BackgroundImageVertical = backgroundImageVertical;
var backgroundColor =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.BackgroundColor.LocalName, region)
as Color?;
style.BackgroundColor = backgroundColor.GetValueOrDefault(DefaultStyle.BackgroundColor);
var color =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.Color.LocalName, region) as Color?;
style.Color = color.GetValueOrDefault(DefaultStyle.Color);
bool isExtentInherited;
var extent = styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.Extent.LocalName, region, out isExtentInherited) as TimedTextExtent;
if (extent != null)
{
Length height = new Length { Value = extent.Height, Unit = FromUnit(extent.UnitMeasureVertical) };
Length width = new Length { Value = extent.Width, Unit = FromUnit(extent.UnitMeasureHorizontal) };
style.Extent = new Extent { Height = height, Width = width };
style.IsExtentSpecified = !isExtentInherited;
}
else
{
style.Extent = DefaultStyle.Extent;
}
var fontFamily =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.FontFamily.LocalName, region) as
string;
style.FontFamily = !fontFamily.IsNullOrWhiteSpace()
? new FontFamily(fontFamily)
: DefaultStyle.FontFamily;
object oFontSize = styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.FontSize.LocalName,
region);
var fontSize = oFontSize as string;
if (!fontSize.IsNullOrWhiteSpace())
{
var parsedFontSize = GetNumberPair(fontSize);
style.FontSize = new Length
{
Unit = FromUnit(parsedFontSize.UnitMeasureHorizontal),
Value = parsedFontSize.First
};
}
var fontStyle =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.FontStyle.LocalName, region) as
FontStyleAttributeValue?;
style.FontStyle = fontStyle.HasValue &&
(fontStyle.Value == FontStyleAttributeValue.Italic ||
fontStyle.Value == FontStyleAttributeValue.Oblique ||
fontStyle.Value == FontStyleAttributeValue.ReverseOblique)
? FontStyles.Italic
: DefaultStyle.FontStyle;
var fontWeight =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.FontWeight.LocalName, region) as
FontWeightAttributeValue?;
style.FontWeight = fontWeight.HasValue && fontWeight.Value == FontWeightAttributeValue.Bold
? Weight.Bold
: DefaultStyle.FontWeight;
var lineHeight =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.LineHeight.LocalName, region) as
LineHeight;
style.LineHeight = lineHeight != null && !(lineHeight is NormalHeight)
? new Length
{
Unit = FromUnit(lineHeight.UnitMeasureVertical),
Value = lineHeight.Height
}
: null;
var textOutline = styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.TextOutline.LocalName, region) as TextOutline;
style.OutlineBlur = new Length
{
Unit = FromUnit(textOutline.UnitMeasureBlur),
Value = textOutline.Blur
};
style.OutlineWidth = new Length
{
Unit = FromUnit(textOutline.UnitMeasureWidth),
Value = textOutline.Width
};
style.OutlineColor = textOutline.StrokeColor;
var opacity =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.Opacity.LocalName, region) as
double?;
style.Opacity = opacity.HasValue
? opacity.Value
: DefaultStyle.Opacity;
bool isOriginInherited;
var origin = styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.Origin.LocalName, region, out isOriginInherited) as TimedTextOrigin;
if (origin != null)
{
style.Origin = new Origin
{
Left = new Length
{
Unit = FromUnit(origin.UnitMeasureHorizontal),
Value = origin.X
},
Top = new Length
{
Unit = FromUnit(origin.UnitMeasureVertical),
Value = origin.Y
}
};
style.IsOriginSpecified = !isOriginInherited;
}
else
{
style.Origin = DefaultStyle.Origin;
}
var overflow =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.Overflow.LocalName, region) as
string;
Overflow parsedOverflow;
style.Overflow = overflow.EnumTryParse(true, out parsedOverflow)
? parsedOverflow
: DefaultStyle.Overflow;
var padding =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.Padding.LocalName, region) as
PaddingThickness;
style.Padding = padding != null
? new Padding
{
Left = new Length
{
Unit = FromUnit(padding.WidthStartUnit),
Value = padding.WidthStart
},
Right = new Length
{
Unit = FromUnit(padding.WidthEndUnit),
Value = padding.WidthEnd
},
Top = new Length
{
Unit = FromUnit(padding.WidthBeforeUnit),
Value = padding.WidthBefore
},
Bottom = new Length
{
Unit = FromUnit(padding.WidthAfterUnit),
Value = padding.WidthAfter
}
}
: DefaultStyle.Padding;
var textAlign =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.TextAlign.LocalName, region) as
string;
TextAlignment parsedTextAlign;
if (textAlign == "start") textAlign = "left";
else if (textAlign == "end") textAlign = "right";
style.TextAlign = textAlign.EnumTryParse(true, out parsedTextAlign)
? parsedTextAlign
: DefaultStyle.TextAlign;
var direction =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.Direction.LocalName, region) as
string;
style.Direction = direction == "rtl" ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
var displayAlign =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.DisplayAlign.LocalName, region) as
string;
DisplayAlign parsedDisplayAlign;
style.DisplayAlign = displayAlign.EnumTryParse(true, out parsedDisplayAlign)
? parsedDisplayAlign
: DefaultStyle.DisplayAlign;
var visibility =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.Visibility.LocalName, region) as
string;
style.Visibility = !visibility.IsNullOrWhiteSpace() &&
visibility.Equals("hidden", StringComparison.CurrentCultureIgnoreCase)
? Visibility.Collapsed
: DefaultStyle.Visibility;
var display =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.Display.LocalName, region) as
string;
style.Display = !display.IsNullOrWhiteSpace() &&
display.Equals("none", StringComparison.CurrentCultureIgnoreCase)
? Visibility.Collapsed
: DefaultStyle.Display;
var wrapOption =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.WrapOption.LocalName, region) as
string;
TextWrapping parsedWrapOption;
style.WrapOption = wrapOption.EnumTryParse(true, out parsedWrapOption)
? parsedWrapOption
: DefaultStyle.WrapOption;
var showBackground =
styleElement.GetComputedStyle(TimedTextVocabulary.Attributes.Styling.ShowBackground.LocalName, region)
as string;
ShowBackground parsedShowBackground;
style.ShowBackground = showBackground.EnumTryParse(true, out parsedShowBackground)
? parsedShowBackground
: DefaultStyle.ShowBackground;
object zindex = styleElement.GetComputedStyle("zIndex", null);
try
{
if (zindex is string == false)
{
var tmp = (double)zindex;
style.ZIndex = (int)tmp;
}
else
{
style.ZIndex = 0;
}
}
catch
{
style.ZIndex = 0;
}
return style;
}
private static TResult ConvertEnum<TSource, TResult>(TSource source)
where TSource : struct
where TResult : struct
{
TResult result;
return source.ToString().EnumTryParse(true, out result)
? result
: default(TResult);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using ApprovalTests;
using ApprovalTests.Reporters;
using ApprovalUtilities.Utilities;
using ConsoleToolkit.ConsoleIO;
using ConsoleToolkit.ConsoleIO.Internal;
using ConsoleToolkitTests.ConsoleIO.UnitTestUtilities;
using ConsoleToolkitTests.TestingUtilities;
using NUnit.Framework;
namespace ConsoleToolkitTests.ConsoleIO.Internal
{
[TestFixture]
[UseReporter(typeof (CustomReporter))]
public class TestColumnWidthNegotiator
{
private List<PropertyColumnFormat> _formats;
private class TestType
{
public string ShortString { get; set; }
public int Integer { get; set; }
public string LongString { get; set; }
public TestType(string shortString, string longString)
{
ShortString = shortString;
LongString = longString;
Integer = shortString.Length + longString.Length;
}
}
[SetUp]
public void TestFixtureSetUp()
{
_formats = FormatAnalyser.Analyse(typeof (TestType), null, true);
}
[Test]
public void ColumnsArePreciselySizedWhenDataFits()
{
var cwn = new ColumnWidthNegotiator(_formats, 1);
var items = Enumerable.Range(0, 5)
.Select(i => new TestType("AAAA" + i, "AAAAAAA AAAAAAAA AAAAAAAA"))
.ToList();
cwn.AddHeadings();
foreach (var item in items)
{
cwn.AddRow(item);
}
cwn.CalculateWidths(80);
var output = TabularReportRenderTool.Report(cwn, items);
Approvals.Verify(output);
}
[Test]
public void RowDataCanBeLoadedFromCachedRow()
{
var cwn = new ColumnWidthNegotiator(_formats, 1);
var items = Enumerable.Range(0, 5)
.Select(i => new TestType("AAAA" + i, "AAAAAAA AAAAAAAA AAAAAAAA"))
.ToList();
var cachedData = new CachedRows<TestType>(items);
cwn.AddHeadings();
foreach (var row in cachedData.GetRows())
{
cwn.AddRow(row);
}
cwn.CalculateWidths(80);
var output = TabularReportRenderTool.Report(cwn, items);
Approvals.Verify(output);
}
[Test]
public void ColumnsAreShrunkInOrderToFitData()
{
var cwn = new ColumnWidthNegotiator(_formats, 1);
var items = Enumerable.Range(0, 5)
.Select(i => new TestType("AAAA" + i, "AAAAAAA AAAAAAAA AAAAAAAA"))
.ToList();
cwn.AddHeadings();
foreach (var item in items)
{
cwn.AddRow(item);
}
cwn.CalculateWidths(40);
var output = TabularReportRenderTool.Report(cwn, items);
Approvals.Verify(output);
}
[Test]
public void IfTheReportCannotBeShrunkTheRightmostColumnsAreStacked()
{
var cwn = new ColumnWidthNegotiator(_formats, 1);
var items = Enumerable.Range(0, 5)
.Select(i => new TestType("AAAA" + i, "AAAAAAA AAAAAAAA AAAAAAAA"))
.ToList();
cwn.AddHeadings();
foreach (var item in items)
{
cwn.AddRow(item);
}
cwn.CalculateWidths(20);
var output = TabularReportRenderTool.Report(cwn, items);
Approvals.Verify(output);
}
[Test]
public void SizingDataCanBeRetrievedFromSizedColumns()
{
var cwn = new ColumnWidthNegotiator(_formats, 1);
var items = Enumerable.Range(0, 5)
.Select(i => new TestType("AAAA" + i, "AAAAAAA AAAAAAAA AAAAAAAA"))
.ToList();
cwn.AddHeadings();
foreach (var item in items)
{
cwn.AddRow(item);
}
cwn.CalculateWidths(80);
var output = TabularReportRenderTool.ReportSizingData(cwn);
Approvals.Verify(output);
}
[Test]
public void SizingDataIncludesStackedProperties()
{
var cwn = new ColumnWidthNegotiator(_formats, 1);
var items = Enumerable.Range(0, 5)
.Select(i => new TestType("AAAA" + i, "AAAAAAA AAAAAAAA AAAAAAAA"))
.ToList();
cwn.AddHeadings();
foreach (var item in items)
{
cwn.AddRow(item);
}
cwn.CalculateWidths(20);
var output = TabularReportRenderTool.ReportSizingData(cwn);
Console.WriteLine(output);
Approvals.Verify(output);
}
[Test]
public void FixedWidthColumnsAreNeverStretched()
{
var longStringColFormat = _formats.First(f => f.Property.Name == "LongString").Format;
longStringColFormat.FixedWidth = 4;
longStringColFormat.SetActualWidth(4);
var cwn = new ColumnWidthNegotiator(_formats, 1);
var items = Enumerable.Range(0, 5)
.Select(i => new TestType("AAAA" + i, "AAAAAAA AAAAAAAA AAAAAAAA"))
.ToList();
cwn.AddHeadings();
foreach (var item in items)
{
cwn.AddRow(item);
}
cwn.CalculateWidths(40);
var output = TabularReportRenderTool.Report(cwn, items);
Approvals.Verify(output);
}
[Test]
public void FixedWidthColumnsAreNeverShrunk()
{
var longStringColFormat = _formats.First(f => f.Property.Name == "LongString").Format;
longStringColFormat.FixedWidth = 25;
var cwn = new ColumnWidthNegotiator(_formats, 1);
var items = Enumerable.Range(0, 5)
.Select(i => new TestType("AAAA" + i, "AAAAAAA AAAAAAAA AAAA"))
.ToList();
cwn.AddHeadings();
foreach (var item in items)
{
cwn.AddRow(item);
}
cwn.CalculateWidths(40);
var output = TabularReportRenderTool.Report(cwn, items);
Approvals.Verify(output);
}
[Test]
public void FixedWidthColumnsCanBeStacked()
{
var longStringColFormat = _formats.Last().Format;
longStringColFormat.FixedWidth = 35;
var cwn = new ColumnWidthNegotiator(_formats, 1);
var items = Enumerable.Range(0, 5)
.Select(i => new TestType("AAAA" + i, "AAAAAAA AAAAAAAA AAAA"))
.ToList();
cwn.AddHeadings();
foreach (var item in items)
{
cwn.AddRow(item);
}
cwn.CalculateWidths(40);
var output = cwn.StackedColumns.Select(sc => sc.Property.Name).JoinWith(", ");
Assert.That(output, Is.EqualTo("LongString"));
}
[Test]
public void MinWidthColumnsAreNotShrunkPastMinimum()
{
var longStringColFormat = _formats.First(f => f.Property.Name == "Integer").Format;
longStringColFormat.MinWidth = 9;
var cwn = new ColumnWidthNegotiator(_formats, 1);
var items = Enumerable.Range(0, 5)
.Select(i => new TestType("AAAA" + i, "AAAAAAA AAAAAAAA AAAA"))
.ToList();
cwn.AddHeadings();
foreach (var item in items)
{
cwn.AddRow(item);
}
cwn.CalculateWidths(30);
var output = TabularReportRenderTool.Report(cwn, items);
Approvals.Verify(output);
}
[Test]
public void MinWidthColumnsCanBeWiderThanMinimum()
{
var longStringColFormat = _formats.First(f => f.Property.Name == "LongString").Format;
longStringColFormat.MinWidth = 9;
var cwn = new ColumnWidthNegotiator(_formats, 1);
var items = Enumerable.Range(0, 5)
.Select(i => new TestType("AAAA" + i, "AAAAAAA AAAAAAAA AAAA"))
.ToList();
cwn.AddHeadings();
foreach (var item in items)
{
cwn.AddRow(item);
}
cwn.CalculateWidths(30);
var output = TabularReportRenderTool.Report(cwn, items);
Approvals.Verify(output);
}
[Test]
public void ProportionalColumnsShareTheAvailableSpace()
{
var longStringColFormat = _formats.First(f => f.Property.Name == "LongString").Format;
var shortStringColFormat = _formats.First(f => f.Property.Name == "ShortString").Format;
longStringColFormat.ProportionalWidth = 1;
shortStringColFormat.ProportionalWidth = 1;
var cwn = new ColumnWidthNegotiator(_formats, 1);
var items = Enumerable.Range(0, 5)
.Select(i => new TestType("AAAA" + i, "AAAAAAA AAAAAAAA AAAA"))
.ToList();
cwn.AddHeadings();
foreach (var item in items)
{
cwn.AddRow(item);
}
cwn.CalculateWidths(29);
var output = TabularReportRenderTool.Report(cwn, items);
Approvals.Verify(output);
}
}
}
| |
/*
* 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 QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
namespace QuantConnect.Securities
{
/// <summary>
/// SecurityHolding is a base class for purchasing and holding a market item which manages the asset portfolio
/// </summary>
public class SecurityHolding
{
/// <summary>
/// Event raised each time the holdings quantity is changed.
/// </summary>
public event EventHandler<SecurityHoldingQuantityChangedEventArgs> QuantityChanged;
//Working Variables
private decimal _averagePrice;
private decimal _quantity;
private decimal _price;
private decimal _totalSaleVolume;
private decimal _profit;
private decimal _lastTradeProfit;
private decimal _totalFees;
private readonly Security _security;
private readonly ICurrencyConverter _currencyConverter;
/// <summary>
/// Create a new holding class instance setting the initial properties to $0.
/// </summary>
/// <param name="security">The security being held</param>
/// <param name="currencyConverter">A currency converter instance</param>
public SecurityHolding(Security security, ICurrencyConverter currencyConverter)
{
_security = security;
//Total Sales Volume for the day
_totalSaleVolume = 0;
_lastTradeProfit = 0;
_currencyConverter = currencyConverter;
}
/// <summary>
/// Create a new holding class instance copying the initial properties
/// </summary>
/// <param name="holding">The security being held</param>
protected SecurityHolding(SecurityHolding holding)
{
_security = holding._security;
_averagePrice = holding._averagePrice;
_quantity = holding._quantity;
_price = holding._price;
_totalSaleVolume = holding._totalSaleVolume;
_profit = holding._profit;
_lastTradeProfit = holding._lastTradeProfit;
_totalFees = holding._totalFees;
_currencyConverter = holding._currencyConverter;
}
/// <summary>
/// The security being held
/// </summary>
protected Security Security
{
get
{
return _security;
}
}
/// <summary>
/// Gets the current target holdings for this security
/// </summary>
public IPortfolioTarget Target
{
get; set;
}
/// <summary>
/// Average price of the security holdings.
/// </summary>
public decimal AveragePrice
{
get
{
return _averagePrice;
}
protected set
{
_averagePrice = value;
}
}
/// <summary>
/// Quantity of the security held.
/// </summary>
/// <remarks>Positive indicates long holdings, negative quantity indicates a short holding</remarks>
/// <seealso cref="AbsoluteQuantity"/>
public decimal Quantity
{
get
{
return _quantity;
}
protected set
{
_quantity = value;
}
}
/// <summary>
/// Symbol identifier of the underlying security.
/// </summary>
public Symbol Symbol
{
get
{
return _security.Symbol;
}
}
/// <summary>
/// The security type of the symbol
/// </summary>
public SecurityType Type
{
get
{
return _security.Type;
}
}
/// <summary>
/// Leverage of the underlying security.
/// </summary>
public virtual decimal Leverage
{
get
{
return _security.BuyingPowerModel.GetLeverage(_security);
}
}
/// <summary>
/// Acquisition cost of the security total holdings in units of the account's currency.
/// </summary>
public virtual decimal HoldingsCost
{
get
{
if (Quantity == 0)
{
return 0;
}
return AveragePrice * Quantity * _security.QuoteCurrency.ConversionRate * _security.SymbolProperties.ContractMultiplier;
}
}
/// <summary>
/// Unlevered Acquisition cost of the security total holdings in units of the account's currency.
/// </summary>
public virtual decimal UnleveredHoldingsCost
{
get { return HoldingsCost/Leverage; }
}
/// <summary>
/// Current market price of the security.
/// </summary>
public virtual decimal Price
{
get
{
return _price;
}
protected set
{
_price = value;
}
}
/// <summary>
/// Absolute holdings cost for current holdings in units of the account's currency.
/// </summary>
/// <seealso cref="HoldingsCost"/>
public virtual decimal AbsoluteHoldingsCost
{
get
{
return Math.Abs(HoldingsCost);
}
}
/// <summary>
/// Unlevered absolute acquisition cost of the security total holdings in units of the account's currency.
/// </summary>
public virtual decimal UnleveredAbsoluteHoldingsCost
{
get
{
return Math.Abs(UnleveredHoldingsCost);
}
}
/// <summary>
/// Market value of our holdings in units of the account's currency.
/// </summary>
public virtual decimal HoldingsValue
{
get
{
if (Quantity == 0)
{
return 0;
}
return GetQuantityValue(Quantity);
}
}
/// <summary>
/// Absolute of the market value of our holdings in units of the account's currency.
/// </summary>
/// <seealso cref="HoldingsValue"/>
public virtual decimal AbsoluteHoldingsValue
{
get { return Math.Abs(HoldingsValue); }
}
/// <summary>
/// Boolean flat indicating if we hold any of the security
/// </summary>
public virtual bool HoldStock
{
get
{
return (AbsoluteQuantity > 0);
}
}
/// <summary>
/// Boolean flat indicating if we hold any of the security
/// </summary>
/// <remarks>Alias of HoldStock</remarks>
/// <seealso cref="HoldStock"/>
public virtual bool Invested
{
get
{
return HoldStock;
}
}
/// <summary>
/// The total transaction volume for this security since the algorithm started in units of the account's currency.
/// </summary>
public virtual decimal TotalSaleVolume
{
get { return _totalSaleVolume; }
}
/// <summary>
/// Total fees for this company since the algorithm started in units of the account's currency.
/// </summary>
public virtual decimal TotalFees
{
get { return _totalFees; }
}
/// <summary>
/// Boolean flag indicating we have a net positive holding of the security.
/// </summary>
/// <seealso cref="IsShort"/>
public virtual bool IsLong
{
get
{
return Quantity > 0;
}
}
/// <summary>
/// BBoolean flag indicating we have a net negative holding of the security.
/// </summary>
/// <seealso cref="IsLong"/>
public virtual bool IsShort
{
get
{
return Quantity < 0;
}
}
/// <summary>
/// Absolute quantity of holdings of this security
/// </summary>
/// <seealso cref="Quantity"/>
public virtual decimal AbsoluteQuantity
{
get
{
return Math.Abs(Quantity);
}
}
/// <summary>
/// Record of the closing profit from the last trade conducted in units of the account's currency.
/// </summary>
public virtual decimal LastTradeProfit
{
get
{
return _lastTradeProfit;
}
}
/// <summary>
/// Calculate the total profit for this security in units of the account's currency.
/// </summary>
/// <seealso cref="NetProfit"/>
public virtual decimal Profit
{
get { return _profit; }
}
/// <summary>
/// Return the net for this company measured by the profit less fees in units of the account's currency.
/// </summary>
/// <seealso cref="Profit"/>
/// <seealso cref="TotalFees"/>
public virtual decimal NetProfit
{
get
{
return Profit - TotalFees;
}
}
/// <summary>
/// Gets the unrealized profit as a percenage of holdings cost
/// </summary>
public decimal UnrealizedProfitPercent
{
get
{
if (AbsoluteHoldingsCost == 0) return 0m;
return UnrealizedProfit/AbsoluteHoldingsCost;
}
}
/// <summary>
/// Unrealized profit of this security when absolute quantity held is more than zero in units of the account's currency.
/// </summary>
public virtual decimal UnrealizedProfit
{
get { return TotalCloseProfit(); }
}
/// <summary>
/// Adds a fee to the running total of total fees in units of the account's currency.
/// </summary>
/// <param name="newFee"></param>
public void AddNewFee(decimal newFee)
{
_totalFees += newFee;
}
/// <summary>
/// Adds a profit record to the running total of profit in units of the account's currency.
/// </summary>
/// <param name="profitLoss">The cash change in portfolio from closing a position</param>
public void AddNewProfit(decimal profitLoss)
{
_profit += profitLoss;
}
/// <summary>
/// Adds a new sale value to the running total trading volume in units of the account's currency.
/// </summary>
/// <param name="saleValue"></param>
public void AddNewSale(decimal saleValue)
{
_totalSaleVolume += saleValue;
}
/// <summary>
/// Set the last trade profit for this security from a Portfolio.ProcessFill call in units of the account's currency.
/// </summary>
/// <param name="lastTradeProfit">Value of the last trade profit</param>
public void SetLastTradeProfit(decimal lastTradeProfit)
{
_lastTradeProfit = lastTradeProfit;
}
/// <summary>
/// Set the quantity of holdings and their average price after processing a portfolio fill.
/// </summary>
public virtual void SetHoldings(decimal averagePrice, int quantity)
{
SetHoldings(averagePrice, (decimal) quantity);
}
/// <summary>
/// Set the quantity of holdings and their average price after processing a portfolio fill.
/// </summary>
public virtual void SetHoldings(decimal averagePrice, decimal quantity)
{
var previousQuantity = _quantity;
var previousAveragePrice = _averagePrice;
_quantity = quantity;
_averagePrice = averagePrice;
OnQuantityChanged(previousAveragePrice, previousQuantity);
}
/// <summary>
/// Update local copy of closing price value.
/// </summary>
/// <param name="closingPrice">Price of the underlying asset to be used for calculating market price / portfolio value</param>
public virtual void UpdateMarketPrice(decimal closingPrice)
{
_price = closingPrice;
}
/// <summary>
/// Gets the total value of the specified <paramref name="quantity"/> of shares of this security
/// in the account currency
/// </summary>
/// <param name="quantity">The quantity of shares</param>
/// <returns>The value of the quantity of shares in the account currency</returns>
public virtual decimal GetQuantityValue(decimal quantity)
{
return GetQuantityValue(quantity, _price);
}
/// <summary>
/// Gets the total value of the specified <paramref name="quantity"/> of shares of this security
/// in the account currency
/// </summary>
/// <param name="quantity">The quantity of shares</param>
/// <param name="price">The current price</param>
/// <returns>The value of the quantity of shares in the account currency</returns>
public virtual decimal GetQuantityValue(decimal quantity, decimal price)
{
return price * quantity * _security.QuoteCurrency.ConversionRate * _security.SymbolProperties.ContractMultiplier;
}
/// <summary>
/// Profit if we closed the holdings right now including the approximate fees in units of the account's currency.
/// </summary>
/// <remarks>Does not use the transaction model for market fills but should.</remarks>
public virtual decimal TotalCloseProfit()
{
if (Quantity == 0)
{
return 0;
}
// this is in the account currency
var marketOrder = new MarketOrder(_security.Symbol, -Quantity, _security.LocalTime.ConvertToUtc(_security.Exchange.TimeZone));
var orderFee = _security.FeeModel.GetOrderFee(
new OrderFeeParameters(_security, marketOrder)).Value;
var feesInAccountCurrency = _currencyConverter.
ConvertToAccountCurrency(orderFee).Amount;
var price = marketOrder.Direction == OrderDirection.Sell ? _security.BidPrice : _security.AskPrice;
if (price == 0)
{
// Bid/Ask prices can both be equal to 0. This usually happens when we request our holdings from
// the brokerage, but only the last trade price was provided.
price = _security.Price;
}
return (price - AveragePrice) * Quantity * _security.QuoteCurrency.ConversionRate
* _security.SymbolProperties.ContractMultiplier - feesInAccountCurrency;
}
/// <summary>
/// Event invocator for the <see cref="QuantityChanged"/> event
/// </summary>
protected virtual void OnQuantityChanged(decimal previousAveragePrice, decimal previousQuantity)
{
QuantityChanged?.Invoke(this, new SecurityHoldingQuantityChangedEventArgs(
_security, previousAveragePrice, previousQuantity
));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extensions for configuring MVC using an <see cref="IMvcBuilder"/>.
/// </summary>
public static class MvcCoreMvcBuilderExtensions
{
/// <summary>
/// Registers an action to configure <see cref="MvcOptions"/>.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="setupAction">An <see cref="Action{MvcOptions}"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddMvcOptions(
this IMvcBuilder builder,
Action<MvcOptions> setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
builder.Services.Configure(setupAction);
return builder;
}
/// <summary>
/// Configures <see cref="JsonOptions"/> for the specified <paramref name="builder"/>.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="configure">An <see cref="Action"/> to configure the <see cref="JsonOptions"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddJsonOptions(
this IMvcBuilder builder,
Action<JsonOptions> configure)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
builder.Services.Configure(configure);
return builder;
}
/// <summary>
/// Configures <see cref="FormatterMappings"/> for the specified <paramref name="builder"/>.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="setupAction">An <see cref="Action"/> to configure the <see cref="FormatterMappings"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddFormatterMappings(
this IMvcBuilder builder,
Action<FormatterMappings> setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
builder.Services.Configure<MvcOptions>((options) => setupAction(options.FormatterMappings));
return builder;
}
/// <summary>
/// Adds an <see cref="ApplicationPart"/> to the list of <see cref="ApplicationPartManager.ApplicationParts"/> on the
/// <see cref="IMvcBuilder.PartManager"/>.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="assembly">The <see cref="Assembly"/> of the <see cref="ApplicationPart"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddApplicationPart(this IMvcBuilder builder, Assembly assembly)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
builder.ConfigureApplicationPartManager(manager =>
{
var partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly);
foreach (var applicationPart in partFactory.GetApplicationParts(assembly))
{
manager.ApplicationParts.Add(applicationPart);
}
});
return builder;
}
/// <summary>
/// Configures the <see cref="ApplicationPartManager"/> of the <see cref="IMvcBuilder.PartManager"/> using
/// the given <see cref="Action{ApplicationPartManager}"/>.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="setupAction">The <see cref="Action{ApplicationPartManager}"/></param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder ConfigureApplicationPartManager(
this IMvcBuilder builder,
Action<ApplicationPartManager> setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
setupAction(builder.PartManager);
return builder;
}
/// <summary>
/// Registers discovered controllers as services in the <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddControllersAsServices(this IMvcBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
var feature = new ControllerFeature();
builder.PartManager.PopulateFeature(feature);
foreach (var controller in feature.Controllers.Select(c => c.AsType()))
{
builder.Services.TryAddTransient(controller, controller);
}
builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
return builder;
}
/// <summary>
/// Sets the <see cref="CompatibilityVersion"/> for ASP.NET Core MVC for the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="version">The <see cref="CompatibilityVersion"/> value to configure.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
[Obsolete("This API is obsolete and will be removed in a future version. Consider removing usages.",
DiagnosticId = "ASP5001",
UrlFormat = "https://aka.ms/aspnetcore-warnings/{0}")]
public static IMvcBuilder SetCompatibilityVersion(this IMvcBuilder builder, CompatibilityVersion version)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Services.Configure<MvcCompatibilityOptions>(o => o.CompatibilityVersion = version);
return builder;
}
/// <summary>
/// Configures <see cref="ApiBehaviorOptions"/>.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="setupAction">The configure action.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder ConfigureApiBehaviorOptions(
this IMvcBuilder builder,
Action<ApiBehaviorOptions> setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
builder.Services.Configure(setupAction);
return builder;
}
}
}
| |
using System;
namespace EncompassRest.Loans
{
/// <summary>
/// SchedulePaymentTransaction
/// </summary>
public sealed partial class SchedulePaymentTransaction : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<decimal?>? _additionalEscrow;
private DirtyValue<decimal?>? _additionalPrincipal;
private DirtyValue<decimal?>? _buydownSubsidyAmount;
private DirtyValue<decimal?>? _buydownSubsidyAmountDue;
private DirtyValue<decimal?>? _cityPropertyTax;
private DirtyValue<string?>? _comments;
private DirtyValue<string?>? _createdById;
private DirtyValue<string?>? _createdByName;
private DirtyValue<DateTime?>? _createdDateTimeUtc;
private DirtyValue<decimal?>? _escrow;
private DirtyValue<decimal?>? _escrowCityPropertyTaxDue;
private DirtyValue<decimal?>? _escrowDue;
private DirtyValue<decimal?>? _escrowFloodInsuranceDue;
private DirtyValue<decimal?>? _escrowHazardInsuranceDue;
private DirtyValue<decimal?>? _escrowMortgageInsuranceDue;
private DirtyValue<decimal?>? _escrowOther1Due;
private DirtyValue<decimal?>? _escrowOther2Due;
private DirtyValue<decimal?>? _escrowOther3Due;
private DirtyValue<decimal?>? _escrowTaxDue;
private DirtyValue<decimal?>? _escrowUSDAMonthlyPremiumDue;
private DirtyValue<decimal?>? _floodInsurance;
private DirtyValue<string?>? _guid;
private DirtyValue<decimal?>? _hazardInsurance;
private DirtyValue<string?>? _id;
private DirtyValue<decimal?>? _indexRate;
private DirtyValue<decimal?>? _interest;
private DirtyValue<decimal?>? _interestDue;
private DirtyValue<decimal?>? _interestRate;
private DirtyValue<decimal?>? _lateFee;
private DirtyValue<DateTime?>? _latePaymentDate;
private DirtyValue<decimal?>? _miscFee;
private DirtyValue<decimal?>? _miscFeeDue;
private DirtyValue<string?>? _modifiedById;
private DirtyValue<string?>? _modifiedByName;
private DirtyValue<DateTime?>? _modifiedDateTimeUtc;
private DirtyValue<decimal?>? _mortgageInsurance;
private DirtyValue<decimal?>? _other1Escrow;
private DirtyValue<decimal?>? _other2Escrow;
private DirtyValue<decimal?>? _other3Escrow;
private DirtyValue<int?>? _paymentNumber;
private DirtyValue<DateTime?>? _paymentReceiveDate;
private DirtyValue<decimal?>? _principal;
private DirtyValue<decimal?>? _principalDue;
private DirtyValue<string?>? _servicingPaymentMethod;
private DirtyValue<string?>? _servicingTransactionType;
private DirtyValue<decimal?>? _taxes;
private DirtyValue<decimal?>? _totalPastDue;
private DirtyValue<decimal?>? _transactionAmount;
private DirtyValue<DateTime?>? _transactionDate;
private DirtyValue<decimal?>? _unpaidLateFeeDue;
private DirtyValue<decimal?>? _uSDAMonthlyPremium;
/// <summary>
/// SchedulePaymentTransaction AdditionalEscrow
/// </summary>
public decimal? AdditionalEscrow { get => _additionalEscrow; set => SetField(ref _additionalEscrow, value); }
/// <summary>
/// SchedulePaymentTransaction AdditionalPrincipal
/// </summary>
public decimal? AdditionalPrincipal { get => _additionalPrincipal; set => SetField(ref _additionalPrincipal, value); }
/// <summary>
/// SchedulePaymentTransaction BuydownSubsidyAmount
/// </summary>
public decimal? BuydownSubsidyAmount { get => _buydownSubsidyAmount; set => SetField(ref _buydownSubsidyAmount, value); }
/// <summary>
/// SchedulePaymentTransaction BuydownSubsidyAmountDue
/// </summary>
public decimal? BuydownSubsidyAmountDue { get => _buydownSubsidyAmountDue; set => SetField(ref _buydownSubsidyAmountDue, value); }
/// <summary>
/// SchedulePaymentTransaction CityPropertyTax
/// </summary>
public decimal? CityPropertyTax { get => _cityPropertyTax; set => SetField(ref _cityPropertyTax, value); }
/// <summary>
/// SchedulePaymentTransaction Comments
/// </summary>
public string? Comments { get => _comments; set => SetField(ref _comments, value); }
/// <summary>
/// SchedulePaymentTransaction CreatedById
/// </summary>
public string? CreatedById { get => _createdById; set => SetField(ref _createdById, value); }
/// <summary>
/// SchedulePaymentTransaction CreatedByName
/// </summary>
public string? CreatedByName { get => _createdByName; set => SetField(ref _createdByName, value); }
/// <summary>
/// SchedulePaymentTransaction CreatedDateTimeUtc
/// </summary>
public DateTime? CreatedDateTimeUtc { get => _createdDateTimeUtc; set => SetField(ref _createdDateTimeUtc, value); }
/// <summary>
/// SchedulePaymentTransaction Escrow
/// </summary>
public decimal? Escrow { get => _escrow; set => SetField(ref _escrow, value); }
/// <summary>
/// SchedulePaymentTransaction EscrowCityPropertyTaxDue
/// </summary>
public decimal? EscrowCityPropertyTaxDue { get => _escrowCityPropertyTaxDue; set => SetField(ref _escrowCityPropertyTaxDue, value); }
/// <summary>
/// SchedulePaymentTransaction EscrowDue
/// </summary>
public decimal? EscrowDue { get => _escrowDue; set => SetField(ref _escrowDue, value); }
/// <summary>
/// SchedulePaymentTransaction EscrowFloodInsuranceDue
/// </summary>
public decimal? EscrowFloodInsuranceDue { get => _escrowFloodInsuranceDue; set => SetField(ref _escrowFloodInsuranceDue, value); }
/// <summary>
/// SchedulePaymentTransaction EscrowHazardInsuranceDue
/// </summary>
public decimal? EscrowHazardInsuranceDue { get => _escrowHazardInsuranceDue; set => SetField(ref _escrowHazardInsuranceDue, value); }
/// <summary>
/// SchedulePaymentTransaction EscrowMortgageInsuranceDue
/// </summary>
public decimal? EscrowMortgageInsuranceDue { get => _escrowMortgageInsuranceDue; set => SetField(ref _escrowMortgageInsuranceDue, value); }
/// <summary>
/// SchedulePaymentTransaction EscrowOther1Due
/// </summary>
public decimal? EscrowOther1Due { get => _escrowOther1Due; set => SetField(ref _escrowOther1Due, value); }
/// <summary>
/// SchedulePaymentTransaction EscrowOther2Due
/// </summary>
public decimal? EscrowOther2Due { get => _escrowOther2Due; set => SetField(ref _escrowOther2Due, value); }
/// <summary>
/// SchedulePaymentTransaction EscrowOther3Due
/// </summary>
public decimal? EscrowOther3Due { get => _escrowOther3Due; set => SetField(ref _escrowOther3Due, value); }
/// <summary>
/// SchedulePaymentTransaction EscrowTaxDue
/// </summary>
public decimal? EscrowTaxDue { get => _escrowTaxDue; set => SetField(ref _escrowTaxDue, value); }
/// <summary>
/// SchedulePaymentTransaction EscrowUSDAMonthlyPremiumDue
/// </summary>
public decimal? EscrowUSDAMonthlyPremiumDue { get => _escrowUSDAMonthlyPremiumDue; set => SetField(ref _escrowUSDAMonthlyPremiumDue, value); }
/// <summary>
/// SchedulePaymentTransaction FloodInsurance
/// </summary>
public decimal? FloodInsurance { get => _floodInsurance; set => SetField(ref _floodInsurance, value); }
/// <summary>
/// SchedulePaymentTransaction Guid
/// </summary>
public string? Guid { get => _guid; set => SetField(ref _guid, value); }
/// <summary>
/// SchedulePaymentTransaction HazardInsurance
/// </summary>
public decimal? HazardInsurance { get => _hazardInsurance; set => SetField(ref _hazardInsurance, value); }
/// <summary>
/// SchedulePaymentTransaction Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// SchedulePaymentTransaction IndexRate
/// </summary>
public decimal? IndexRate { get => _indexRate; set => SetField(ref _indexRate, value); }
/// <summary>
/// SchedulePaymentTransaction Interest
/// </summary>
public decimal? Interest { get => _interest; set => SetField(ref _interest, value); }
/// <summary>
/// SchedulePaymentTransaction InterestDue
/// </summary>
public decimal? InterestDue { get => _interestDue; set => SetField(ref _interestDue, value); }
/// <summary>
/// SchedulePaymentTransaction InterestRate
/// </summary>
public decimal? InterestRate { get => _interestRate; set => SetField(ref _interestRate, value); }
/// <summary>
/// SchedulePaymentTransaction LateFee
/// </summary>
public decimal? LateFee { get => _lateFee; set => SetField(ref _lateFee, value); }
/// <summary>
/// SchedulePaymentTransaction LatePaymentDate
/// </summary>
public DateTime? LatePaymentDate { get => _latePaymentDate; set => SetField(ref _latePaymentDate, value); }
/// <summary>
/// SchedulePaymentTransaction MiscFee
/// </summary>
public decimal? MiscFee { get => _miscFee; set => SetField(ref _miscFee, value); }
/// <summary>
/// SchedulePaymentTransaction MiscFeeDue
/// </summary>
public decimal? MiscFeeDue { get => _miscFeeDue; set => SetField(ref _miscFeeDue, value); }
/// <summary>
/// SchedulePaymentTransaction ModifiedById
/// </summary>
public string? ModifiedById { get => _modifiedById; set => SetField(ref _modifiedById, value); }
/// <summary>
/// SchedulePaymentTransaction ModifiedByName
/// </summary>
public string? ModifiedByName { get => _modifiedByName; set => SetField(ref _modifiedByName, value); }
/// <summary>
/// SchedulePaymentTransaction ModifiedDateTimeUtc
/// </summary>
public DateTime? ModifiedDateTimeUtc { get => _modifiedDateTimeUtc; set => SetField(ref _modifiedDateTimeUtc, value); }
/// <summary>
/// SchedulePaymentTransaction MortgageInsurance
/// </summary>
public decimal? MortgageInsurance { get => _mortgageInsurance; set => SetField(ref _mortgageInsurance, value); }
/// <summary>
/// SchedulePaymentTransaction Other1Escrow
/// </summary>
public decimal? Other1Escrow { get => _other1Escrow; set => SetField(ref _other1Escrow, value); }
/// <summary>
/// SchedulePaymentTransaction Other2Escrow
/// </summary>
public decimal? Other2Escrow { get => _other2Escrow; set => SetField(ref _other2Escrow, value); }
/// <summary>
/// SchedulePaymentTransaction Other3Escrow
/// </summary>
public decimal? Other3Escrow { get => _other3Escrow; set => SetField(ref _other3Escrow, value); }
/// <summary>
/// SchedulePaymentTransaction PaymentNumber
/// </summary>
public int? PaymentNumber { get => _paymentNumber; set => SetField(ref _paymentNumber, value); }
/// <summary>
/// SchedulePaymentTransaction PaymentReceiveDate
/// </summary>
public DateTime? PaymentReceiveDate { get => _paymentReceiveDate; set => SetField(ref _paymentReceiveDate, value); }
/// <summary>
/// SchedulePaymentTransaction Principal
/// </summary>
public decimal? Principal { get => _principal; set => SetField(ref _principal, value); }
/// <summary>
/// SchedulePaymentTransaction PrincipalDue
/// </summary>
public decimal? PrincipalDue { get => _principalDue; set => SetField(ref _principalDue, value); }
/// <summary>
/// SchedulePaymentTransaction ServicingPaymentMethod
/// </summary>
public string? ServicingPaymentMethod { get => _servicingPaymentMethod; set => SetField(ref _servicingPaymentMethod, value); }
/// <summary>
/// SchedulePaymentTransaction ServicingTransactionType
/// </summary>
public string? ServicingTransactionType { get => _servicingTransactionType; set => SetField(ref _servicingTransactionType, value); }
/// <summary>
/// SchedulePaymentTransaction Taxes
/// </summary>
public decimal? Taxes { get => _taxes; set => SetField(ref _taxes, value); }
/// <summary>
/// SchedulePaymentTransaction TotalPastDue
/// </summary>
public decimal? TotalPastDue { get => _totalPastDue; set => SetField(ref _totalPastDue, value); }
/// <summary>
/// SchedulePaymentTransaction TransactionAmount
/// </summary>
public decimal? TransactionAmount { get => _transactionAmount; set => SetField(ref _transactionAmount, value); }
/// <summary>
/// SchedulePaymentTransaction TransactionDate
/// </summary>
public DateTime? TransactionDate { get => _transactionDate; set => SetField(ref _transactionDate, value); }
/// <summary>
/// SchedulePaymentTransaction UnpaidLateFeeDue
/// </summary>
public decimal? UnpaidLateFeeDue { get => _unpaidLateFeeDue; set => SetField(ref _unpaidLateFeeDue, value); }
/// <summary>
/// SchedulePaymentTransaction USDAMonthlyPremium
/// </summary>
public decimal? USDAMonthlyPremium { get => _uSDAMonthlyPremium; set => SetField(ref _uSDAMonthlyPremium, value); }
}
}
| |
// 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.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Xunit;
namespace Microsoft.AspNetCore.Authentication
{
public class PolicyTests
{
[Fact]
public async Task CanDispatch()
{
using var server = await CreateServer(services =>
{
services.AddLogging().AddAuthentication(o =>
{
o.AddScheme<TestHandler>("auth1", "auth1");
o.AddScheme<TestHandler>("auth2", "auth2");
o.AddScheme<TestHandler>("auth3", "auth3");
})
.AddPolicyScheme("policy1", "policy1", p =>
{
p.ForwardDefault = "auth1";
})
.AddPolicyScheme("policy2", "policy2", p =>
{
p.ForwardAuthenticate = "auth2";
});
});
var transaction = await server.SendAsync("http://example.com/auth/policy1");
Assert.Equal("auth1", transaction.FindClaimValue(ClaimTypes.NameIdentifier, "auth1"));
transaction = await server.SendAsync("http://example.com/auth/auth1");
Assert.Equal("auth1", transaction.FindClaimValue(ClaimTypes.NameIdentifier, "auth1"));
transaction = await server.SendAsync("http://example.com/auth/auth2");
Assert.Equal("auth2", transaction.FindClaimValue(ClaimTypes.NameIdentifier, "auth2"));
transaction = await server.SendAsync("http://example.com/auth/auth3");
Assert.Equal("auth3", transaction.FindClaimValue(ClaimTypes.NameIdentifier, "auth3"));
transaction = await server.SendAsync("http://example.com/auth/policy2");
Assert.Equal("auth2", transaction.FindClaimValue(ClaimTypes.NameIdentifier, "auth2"));
}
[Fact]
public async Task DefaultTargetSelectorWinsOverDefaultTarget()
{
var services = new ServiceCollection().AddOptions().AddLogging();
services.AddAuthentication(o =>
{
o.AddScheme<TestHandler>("auth1", "auth1");
o.AddScheme<TestHandler2>("auth2", "auth2");
})
.AddPolicyScheme("forward", "forward", p => {
p.ForwardDefault= "auth2";
p.ForwardDefaultSelector = ctx => "auth1";
});
var handler1 = new TestHandler();
services.AddSingleton(handler1);
var handler2 = new TestHandler2();
services.AddSingleton(handler2);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
Assert.Equal(0, handler1.AuthenticateCount);
Assert.Equal(0, handler1.ForbidCount);
Assert.Equal(0, handler1.ChallengeCount);
Assert.Equal(0, handler1.SignInCount);
Assert.Equal(0, handler1.SignOutCount);
Assert.Equal(0, handler2.AuthenticateCount);
Assert.Equal(0, handler2.ForbidCount);
Assert.Equal(0, handler2.ChallengeCount);
Assert.Equal(0, handler2.SignInCount);
Assert.Equal(0, handler2.SignOutCount);
await context.AuthenticateAsync("forward");
Assert.Equal(1, handler1.AuthenticateCount);
Assert.Equal(0, handler2.AuthenticateCount);
await context.ForbidAsync("forward");
Assert.Equal(1, handler1.ForbidCount);
Assert.Equal(0, handler2.ForbidCount);
await context.ChallengeAsync("forward");
Assert.Equal(1, handler1.ChallengeCount);
Assert.Equal(0, handler2.ChallengeCount);
await context.SignOutAsync("forward");
Assert.Equal(1, handler1.SignOutCount);
Assert.Equal(0, handler2.SignOutCount);
await context.SignInAsync("forward", new ClaimsPrincipal(new ClaimsIdentity("whatever")));
Assert.Equal(1, handler1.SignInCount);
Assert.Equal(0, handler2.SignInCount);
}
[Fact]
public async Task NullDefaultTargetSelectorFallsBacktoDefaultTarget()
{
var services = new ServiceCollection().AddOptions().AddLogging();
services.AddAuthentication(o =>
{
o.AddScheme<TestHandler>("auth1", "auth1");
o.AddScheme<TestHandler2>("auth2", "auth2");
})
.AddPolicyScheme("forward", "forward", p => {
p.ForwardDefault= "auth1";
p.ForwardDefaultSelector = ctx => null;
});
var handler1 = new TestHandler();
services.AddSingleton(handler1);
var handler2 = new TestHandler2();
services.AddSingleton(handler2);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
Assert.Equal(0, handler1.AuthenticateCount);
Assert.Equal(0, handler1.ForbidCount);
Assert.Equal(0, handler1.ChallengeCount);
Assert.Equal(0, handler1.SignInCount);
Assert.Equal(0, handler1.SignOutCount);
Assert.Equal(0, handler2.AuthenticateCount);
Assert.Equal(0, handler2.ForbidCount);
Assert.Equal(0, handler2.ChallengeCount);
Assert.Equal(0, handler2.SignInCount);
Assert.Equal(0, handler2.SignOutCount);
await context.AuthenticateAsync("forward");
Assert.Equal(1, handler1.AuthenticateCount);
Assert.Equal(0, handler2.AuthenticateCount);
await context.ForbidAsync("forward");
Assert.Equal(1, handler1.ForbidCount);
Assert.Equal(0, handler2.ForbidCount);
await context.ChallengeAsync("forward");
Assert.Equal(1, handler1.ChallengeCount);
Assert.Equal(0, handler2.ChallengeCount);
await context.SignOutAsync("forward");
Assert.Equal(1, handler1.SignOutCount);
Assert.Equal(0, handler2.SignOutCount);
await context.SignInAsync("forward", new ClaimsPrincipal(new ClaimsIdentity("whatever")));
Assert.Equal(1, handler1.SignInCount);
Assert.Equal(0, handler2.SignInCount);
}
[Fact]
public async Task SpecificTargetAlwaysWinsOverDefaultTarget()
{
var services = new ServiceCollection().AddOptions().AddLogging();
services.AddAuthentication(o =>
{
o.AddScheme<TestHandler>("auth1", "auth1");
o.AddScheme<TestHandler2>("auth2", "auth2");
})
.AddPolicyScheme("forward", "forward", p => {
p.ForwardDefault= "auth2";
p.ForwardDefaultSelector = ctx => "auth2";
p.ForwardAuthenticate = "auth1";
p.ForwardSignIn = "auth1";
p.ForwardSignOut = "auth1";
p.ForwardForbid = "auth1";
p.ForwardChallenge = "auth1";
});
var handler1 = new TestHandler();
services.AddSingleton(handler1);
var handler2 = new TestHandler2();
services.AddSingleton(handler2);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
Assert.Equal(0, handler1.AuthenticateCount);
Assert.Equal(0, handler1.ForbidCount);
Assert.Equal(0, handler1.ChallengeCount);
Assert.Equal(0, handler1.SignInCount);
Assert.Equal(0, handler1.SignOutCount);
Assert.Equal(0, handler2.AuthenticateCount);
Assert.Equal(0, handler2.ForbidCount);
Assert.Equal(0, handler2.ChallengeCount);
Assert.Equal(0, handler2.SignInCount);
Assert.Equal(0, handler2.SignOutCount);
await context.AuthenticateAsync("forward");
Assert.Equal(1, handler1.AuthenticateCount);
Assert.Equal(0, handler2.AuthenticateCount);
await context.ForbidAsync("forward");
Assert.Equal(1, handler1.ForbidCount);
Assert.Equal(0, handler2.ForbidCount);
await context.ChallengeAsync("forward");
Assert.Equal(1, handler1.ChallengeCount);
Assert.Equal(0, handler2.ChallengeCount);
await context.SignOutAsync("forward");
Assert.Equal(1, handler1.SignOutCount);
Assert.Equal(0, handler2.SignOutCount);
await context.SignInAsync("forward", new ClaimsPrincipal(new ClaimsIdentity("whatever")));
Assert.Equal(1, handler1.SignInCount);
Assert.Equal(0, handler2.SignInCount);
}
[Fact]
public async Task VirtualSchemeTargetsForwardWithDefaultTarget()
{
var services = new ServiceCollection().AddOptions().AddLogging();
services.AddAuthentication(o =>
{
o.AddScheme<TestHandler>("auth1", "auth1");
o.AddScheme<TestHandler2>("auth2", "auth2");
})
.AddPolicyScheme("forward", "forward", p => p.ForwardDefault= "auth1");
var handler1 = new TestHandler();
services.AddSingleton(handler1);
var handler2 = new TestHandler2();
services.AddSingleton(handler2);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
Assert.Equal(0, handler1.AuthenticateCount);
Assert.Equal(0, handler1.ForbidCount);
Assert.Equal(0, handler1.ChallengeCount);
Assert.Equal(0, handler1.SignInCount);
Assert.Equal(0, handler1.SignOutCount);
Assert.Equal(0, handler2.AuthenticateCount);
Assert.Equal(0, handler2.ForbidCount);
Assert.Equal(0, handler2.ChallengeCount);
Assert.Equal(0, handler2.SignInCount);
Assert.Equal(0, handler2.SignOutCount);
await context.AuthenticateAsync("forward");
Assert.Equal(1, handler1.AuthenticateCount);
Assert.Equal(0, handler2.AuthenticateCount);
await context.ForbidAsync("forward");
Assert.Equal(1, handler1.ForbidCount);
Assert.Equal(0, handler2.ForbidCount);
await context.ChallengeAsync("forward");
Assert.Equal(1, handler1.ChallengeCount);
Assert.Equal(0, handler2.ChallengeCount);
await context.SignOutAsync("forward");
Assert.Equal(1, handler1.SignOutCount);
Assert.Equal(0, handler2.SignOutCount);
await context.SignInAsync("forward", new ClaimsPrincipal(new ClaimsIdentity("whatever")));
Assert.Equal(1, handler1.SignInCount);
Assert.Equal(0, handler2.SignInCount);
}
[Fact]
public async Task VirtualSchemeTargetsOverrideDefaultTarget()
{
var services = new ServiceCollection().AddOptions().AddLogging();
services.AddAuthentication(o =>
{
o.AddScheme<TestHandler>("auth1", "auth1");
o.AddScheme<TestHandler2>("auth2", "auth2");
})
.AddPolicyScheme("forward", "forward", p =>
{
p.ForwardDefault= "auth1";
p.ForwardChallenge = "auth2";
p.ForwardSignIn = "auth2";
});
var handler1 = new TestHandler();
services.AddSingleton(handler1);
var handler2 = new TestHandler2();
services.AddSingleton(handler2);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
Assert.Equal(0, handler1.AuthenticateCount);
Assert.Equal(0, handler1.ForbidCount);
Assert.Equal(0, handler1.ChallengeCount);
Assert.Equal(0, handler1.SignInCount);
Assert.Equal(0, handler1.SignOutCount);
Assert.Equal(0, handler2.AuthenticateCount);
Assert.Equal(0, handler2.ForbidCount);
Assert.Equal(0, handler2.ChallengeCount);
Assert.Equal(0, handler2.SignInCount);
Assert.Equal(0, handler2.SignOutCount);
await context.AuthenticateAsync("forward");
Assert.Equal(1, handler1.AuthenticateCount);
Assert.Equal(0, handler2.AuthenticateCount);
await context.ForbidAsync("forward");
Assert.Equal(1, handler1.ForbidCount);
Assert.Equal(0, handler2.ForbidCount);
await context.ChallengeAsync("forward");
Assert.Equal(0, handler1.ChallengeCount);
Assert.Equal(1, handler2.ChallengeCount);
await context.SignOutAsync("forward");
Assert.Equal(1, handler1.SignOutCount);
Assert.Equal(0, handler2.SignOutCount);
await context.SignInAsync("forward", new ClaimsPrincipal(new ClaimsIdentity("whatever")));
Assert.Equal(0, handler1.SignInCount);
Assert.Equal(1, handler2.SignInCount);
}
[Fact]
public async Task CanDynamicTargetBasedOnQueryString()
{
using var server = await CreateServer(services =>
{
services.AddAuthentication(o =>
{
o.AddScheme<TestHandler>("auth1", "auth1");
o.AddScheme<TestHandler>("auth2", "auth2");
o.AddScheme<TestHandler>("auth3", "auth3");
})
.AddPolicyScheme("dynamic", "dynamic", p =>
{
p.ForwardDefaultSelector = c => c.Request.QueryString.Value.Substring(1);
});
});
var transaction = await server.SendAsync("http://example.com/auth/dynamic?auth1");
Assert.Equal("auth1", transaction.FindClaimValue(ClaimTypes.NameIdentifier, "auth1"));
transaction = await server.SendAsync("http://example.com/auth/dynamic?auth2");
Assert.Equal("auth2", transaction.FindClaimValue(ClaimTypes.NameIdentifier, "auth2"));
transaction = await server.SendAsync("http://example.com/auth/dynamic?auth3");
Assert.Equal("auth3", transaction.FindClaimValue(ClaimTypes.NameIdentifier, "auth3"));
}
private class TestHandler : IAuthenticationSignInHandler
{
public AuthenticationScheme Scheme { get; set; }
public int SignInCount { get; set; }
public int SignOutCount { get; set; }
public int ForbidCount { get; set; }
public int ChallengeCount { get; set; }
public int AuthenticateCount { get; set; }
public Task<AuthenticateResult> AuthenticateAsync()
{
AuthenticateCount++;
var principal = new ClaimsPrincipal();
var id = new ClaimsIdentity();
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, Scheme.Name, ClaimValueTypes.String, Scheme.Name));
principal.AddIdentity(id);
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, new AuthenticationProperties(), Scheme.Name)));
}
public Task ChallengeAsync(AuthenticationProperties properties)
{
ChallengeCount++;
return Task.CompletedTask;
}
public Task ForbidAsync(AuthenticationProperties properties)
{
ForbidCount++;
return Task.CompletedTask;
}
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
Scheme = scheme;
return Task.CompletedTask;
}
public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
SignInCount++;
return Task.CompletedTask;
}
public Task SignOutAsync(AuthenticationProperties properties)
{
SignOutCount++;
return Task.CompletedTask;
}
}
private class TestHandler2 : IAuthenticationSignInHandler
{
public AuthenticationScheme Scheme { get; set; }
public int SignInCount { get; set; }
public int SignOutCount { get; set; }
public int ForbidCount { get; set; }
public int ChallengeCount { get; set; }
public int AuthenticateCount { get; set; }
public Task<AuthenticateResult> AuthenticateAsync()
{
AuthenticateCount++;
var principal = new ClaimsPrincipal();
var id = new ClaimsIdentity();
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, Scheme.Name, ClaimValueTypes.String, Scheme.Name));
principal.AddIdentity(id);
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, new AuthenticationProperties(), Scheme.Name)));
}
public Task ChallengeAsync(AuthenticationProperties properties)
{
ChallengeCount++;
return Task.CompletedTask;
}
public Task ForbidAsync(AuthenticationProperties properties)
{
ForbidCount++;
return Task.CompletedTask;
}
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
Scheme = scheme;
return Task.CompletedTask;
}
public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
SignInCount++;
return Task.CompletedTask;
}
public Task SignOutAsync(AuthenticationProperties properties)
{
SignOutCount++;
return Task.CompletedTask;
}
}
private static async Task<TestServer> CreateServer(Action<IServiceCollection> configure = null, string defaultScheme = null)
{
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.Configure(app =>
{
app.UseAuthentication();
app.Use(async (context, next) =>
{
var req = context.Request;
var res = context.Response;
if (req.Path.StartsWithSegments(new PathString("/auth"), out var remainder))
{
var name = (remainder.Value.Length > 0) ? remainder.Value.Substring(1) : null;
var result = await context.AuthenticateAsync(name);
await res.DescribeAsync(result?.Ticket?.Principal);
}
else
{
await next(context);
}
});
})
.UseTestServer();
})
.ConfigureServices(services =>
{
configure?.Invoke(services);
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
return server;
}
}
}
| |
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using k8s.Autorest;
namespace k8s.LeaderElection
{
public class LeaderElector : IDisposable
{
private const double JitterFactor = 1.2;
private readonly LeaderElectionConfig config;
/// <summary>
/// OnStartedLeading is called when a LeaderElector client starts leading
/// </summary>
public event Action OnStartedLeading;
/// <summary>
/// OnStoppedLeading is called when a LeaderElector client stops leading
/// </summary>
public event Action OnStoppedLeading;
/// <summary>
/// OnNewLeader is called when the client observes a leader that is
/// not the previously observed leader. This includes the first observed
/// leader when the client starts.
/// </summary>
public event Action<string> OnNewLeader;
private volatile LeaderElectionRecord observedRecord;
private DateTimeOffset observedTime = DateTimeOffset.MinValue;
private string reportedLeader;
public LeaderElector(LeaderElectionConfig config)
{
this.config = config;
}
public bool IsLeader()
{
return observedRecord?.HolderIdentity != null && observedRecord?.HolderIdentity == config.Lock.Identity;
}
public string GetLeader()
{
return observedRecord?.HolderIdentity;
}
public async Task RunAsync(CancellationToken cancellationToken = default)
{
await AcquireAsync(cancellationToken).ConfigureAwait(false);
try
{
OnStartedLeading?.Invoke();
// renew loop
for (; ; )
{
cancellationToken.ThrowIfCancellationRequested();
var acq = Task.Run(async () =>
{
try
{
while (!await TryAcquireOrRenew(cancellationToken).ConfigureAwait(false))
{
await Task.Delay(config.RetryPeriod, cancellationToken).ConfigureAwait(false);
MaybeReportTransition();
}
}
catch
{
// ignore
return false;
}
return true;
});
if (await Task.WhenAny(acq, Task.Delay(config.RenewDeadline, cancellationToken))
.ConfigureAwait(false) == acq)
{
var succ = await acq.ConfigureAwait(false);
if (succ)
{
await Task.Delay(config.RetryPeriod, cancellationToken).ConfigureAwait(false);
// retry
continue;
}
// renew failed
}
// timeout
break;
}
}
finally
{
OnStoppedLeading?.Invoke();
}
}
private async Task<bool> TryAcquireOrRenew(CancellationToken cancellationToken)
{
var l = config.Lock;
var leaderElectionRecord = new LeaderElectionRecord()
{
HolderIdentity = l.Identity,
LeaseDurationSeconds = (int)config.LeaseDuration.TotalSeconds,
AcquireTime = DateTime.UtcNow,
RenewTime = DateTime.UtcNow,
LeaderTransitions = 0,
};
// 1. obtain or create the ElectionRecord
LeaderElectionRecord oldLeaderElectionRecord = null;
try
{
oldLeaderElectionRecord = await l.GetAsync(cancellationToken).ConfigureAwait(false);
}
catch (HttpOperationException e)
{
if (e.Response.StatusCode != HttpStatusCode.NotFound)
{
return false;
}
}
if (oldLeaderElectionRecord?.AcquireTime == null ||
oldLeaderElectionRecord?.RenewTime == null ||
oldLeaderElectionRecord?.HolderIdentity == null)
{
var created = await l.CreateAsync(leaderElectionRecord, cancellationToken).ConfigureAwait(false);
if (created)
{
observedRecord = leaderElectionRecord;
observedTime = DateTimeOffset.Now;
return true;
}
return false;
}
// 2. Record obtained, check the Identity & Time
if (!Equals(observedRecord, oldLeaderElectionRecord))
{
observedRecord = oldLeaderElectionRecord;
observedTime = DateTimeOffset.Now;
}
if (!string.IsNullOrEmpty(oldLeaderElectionRecord.HolderIdentity)
&& observedTime + config.LeaseDuration > DateTimeOffset.Now
&& !IsLeader())
{
// lock is held by %v and has not yet expired", oldLeaderElectionRecord.HolderIdentity
return false;
}
// 3. We're going to try to update. The leaderElectionRecord is set to it's default
// here. Let's correct it before updating.
if (IsLeader())
{
leaderElectionRecord.AcquireTime = oldLeaderElectionRecord.AcquireTime;
leaderElectionRecord.LeaderTransitions = oldLeaderElectionRecord.LeaderTransitions;
}
else
{
leaderElectionRecord.LeaderTransitions = oldLeaderElectionRecord.LeaderTransitions + 1;
}
var updated = await l.UpdateAsync(leaderElectionRecord, cancellationToken).ConfigureAwait(false);
if (!updated)
{
return false;
}
observedRecord = leaderElectionRecord;
observedTime = DateTimeOffset.Now;
return true;
}
private async Task AcquireAsync(CancellationToken cancellationToken)
{
var delay = (int)config.RetryPeriod.TotalMilliseconds;
for (; ; )
{
try
{
var acq = TryAcquireOrRenew(cancellationToken);
if (await Task.WhenAny(acq, Task.Delay(delay, cancellationToken))
.ConfigureAwait(false) == acq)
{
if (await acq.ConfigureAwait(false))
{
return;
}
// wait RetryPeriod since acq return immediately
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
// else timeout
delay = (int)(delay * JitterFactor);
}
finally
{
MaybeReportTransition();
}
}
}
private void MaybeReportTransition()
{
if (observedRecord == null)
{
return;
}
if (observedRecord.HolderIdentity == reportedLeader)
{
return;
}
reportedLeader = observedRecord.HolderIdentity;
OnNewLeader?.Invoke(reportedLeader);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
}
}
/// <inheritdoc/>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| |
using ICSharpCode.SharpZipLib.Checksum;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using System;
using System.IO;
namespace ICSharpCode.SharpZipLib.GZip
{
/// <summary>
/// This filter stream is used to compress a stream into a "GZIP" stream.
/// The "GZIP" format is described in RFC 1952.
///
/// author of the original java version : John Leuner
/// </summary>
/// <example> This sample shows how to gzip a file
/// <code>
/// using System;
/// using System.IO;
///
/// using ICSharpCode.SharpZipLib.GZip;
/// using ICSharpCode.SharpZipLib.Core;
///
/// class MainClass
/// {
/// public static void Main(string[] args)
/// {
/// using (Stream s = new GZipOutputStream(File.Create(args[0] + ".gz")))
/// using (FileStream fs = File.OpenRead(args[0])) {
/// byte[] writeData = new byte[4096];
/// Streamutils.Copy(s, fs, writeData);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public class GZipOutputStream : DeflaterOutputStream
{
private enum OutputState
{
Header,
Footer,
Finished,
Closed,
};
#region Instance Fields
/// <summary>
/// CRC-32 value for uncompressed data
/// </summary>
protected Crc32 crc = new Crc32();
private OutputState state_ = OutputState.Header;
#endregion Instance Fields
#region Constructors
/// <summary>
/// Creates a GzipOutputStream with the default buffer size
/// </summary>
/// <param name="baseOutputStream">
/// The stream to read data (to be compressed) from
/// </param>
public GZipOutputStream(Stream baseOutputStream)
: this(baseOutputStream, 4096)
{
}
/// <summary>
/// Creates a GZipOutputStream with the specified buffer size
/// </summary>
/// <param name="baseOutputStream">
/// The stream to read data (to be compressed) from
/// </param>
/// <param name="size">
/// Size of the buffer to use
/// </param>
public GZipOutputStream(Stream baseOutputStream, int size) : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true), size)
{
}
#endregion Constructors
#region Public API
/// <summary>
/// Sets the active compression level (0-9). The new level will be activated
/// immediately.
/// </summary>
/// <param name="level">The compression level to set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Level specified is not supported.
/// </exception>
/// <see cref="Deflater"/>
public void SetLevel(int level)
{
if (level < Deflater.NO_COMPRESSION || level > Deflater.BEST_COMPRESSION)
throw new ArgumentOutOfRangeException(nameof(level), "Compression level must be 0-9");
deflater_.SetLevel(level);
}
/// <summary>
/// Get the current compression level.
/// </summary>
/// <returns>The current compression level.</returns>
public int GetLevel()
{
return deflater_.GetLevel();
}
#endregion Public API
#region Stream overrides
/// <summary>
/// Write given buffer to output updating crc
/// </summary>
/// <param name="buffer">Buffer to write</param>
/// <param name="offset">Offset of first byte in buf to write</param>
/// <param name="count">Number of bytes to write</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (state_ == OutputState.Header)
{
WriteHeader();
}
if (state_ != OutputState.Footer)
{
throw new InvalidOperationException("Write not permitted in current state");
}
crc.Update(new ArraySegment<byte>(buffer, offset, count));
base.Write(buffer, offset, count);
}
/// <summary>
/// Writes remaining compressed output data to the output stream
/// and closes it.
/// </summary>
protected override void Dispose(bool disposing)
{
try
{
Finish();
}
finally
{
if (state_ != OutputState.Closed)
{
state_ = OutputState.Closed;
if (IsStreamOwner)
{
baseOutputStream_.Dispose();
}
}
}
}
#endregion Stream overrides
#region DeflaterOutputStream overrides
/// <summary>
/// Finish compression and write any footer information required to stream
/// </summary>
public override void Finish()
{
// If no data has been written a header should be added.
if (state_ == OutputState.Header)
{
WriteHeader();
}
if (state_ == OutputState.Footer)
{
state_ = OutputState.Finished;
base.Finish();
var totalin = (uint)(deflater_.TotalIn & 0xffffffff);
var crcval = (uint)(crc.Value & 0xffffffff);
byte[] gzipFooter;
unchecked
{
gzipFooter = new byte[] {
(byte) crcval, (byte) (crcval >> 8),
(byte) (crcval >> 16), (byte) (crcval >> 24),
(byte) totalin, (byte) (totalin >> 8),
(byte) (totalin >> 16), (byte) (totalin >> 24)
};
}
baseOutputStream_.Write(gzipFooter, 0, gzipFooter.Length);
}
}
#endregion DeflaterOutputStream overrides
#region Support Routines
private void WriteHeader()
{
if (state_ == OutputState.Header)
{
state_ = OutputState.Footer;
var mod_time = (int)((DateTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000L); // Ticks give back 100ns intervals
byte[] gzipHeader = {
// The two magic bytes
(byte) (GZipConstants.GZIP_MAGIC >> 8), (byte) (GZipConstants.GZIP_MAGIC & 0xff),
// The compression type
(byte) Deflater.DEFLATED,
// The flags (not set)
0,
// The modification time
(byte) mod_time, (byte) (mod_time >> 8),
(byte) (mod_time >> 16), (byte) (mod_time >> 24),
// The extra flags
0,
// The OS type (unknown)
(byte) 255
};
baseOutputStream_.Write(gzipHeader, 0, gzipHeader.Length);
}
}
#endregion Support Routines
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS;
namespace ColorRamps
{
public class Form1 : System.Windows.Forms.Form
{
private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1;
private ESRI.ArcGIS.Controls.AxPageLayoutControl axPageLayoutControl1;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Button button1;
private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1;
private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
//Release COM objects
ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown();
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl();
this.axPageLayoutControl1 = new ESRI.ArcGIS.Controls.AxPageLayoutControl();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.button1 = new System.Windows.Forms.Button();
this.axTOCControl1 = new ESRI.ArcGIS.Controls.AxTOCControl();
this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axPageLayoutControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit();
this.SuspendLayout();
//
// axToolbarControl1
//
this.axToolbarControl1.Location = new System.Drawing.Point(8, 8);
this.axToolbarControl1.Name = "axToolbarControl1";
this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState")));
this.axToolbarControl1.Size = new System.Drawing.Size(392, 28);
this.axToolbarControl1.TabIndex = 0;
//
// axPageLayoutControl1
//
this.axPageLayoutControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.axPageLayoutControl1.Location = new System.Drawing.Point(192, 40);
this.axPageLayoutControl1.Name = "axPageLayoutControl1";
this.axPageLayoutControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axPageLayoutControl1.OcxState")));
this.axPageLayoutControl1.Size = new System.Drawing.Size(464, 384);
this.axPageLayoutControl1.TabIndex = 1;
this.axPageLayoutControl1.OnPageLayoutReplaced += new ESRI.ArcGIS.Controls.IPageLayoutControlEvents_Ax_OnPageLayoutReplacedEventHandler(this.axPageLayoutControl1_OnPageLayoutReplaced);
//
// comboBox1
//
this.comboBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.comboBox1.Location = new System.Drawing.Point(408, 8);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 21);
this.comboBox1.TabIndex = 3;
this.comboBox1.Text = "comboBox1";
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(536, 8);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(120, 23);
this.button1.TabIndex = 4;
this.button1.Text = "Change Color Ramp";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// axTOCControl1
//
this.axTOCControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.axTOCControl1.Location = new System.Drawing.Point(8, 40);
this.axTOCControl1.Name = "axTOCControl1";
this.axTOCControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axTOCControl1.OcxState")));
this.axTOCControl1.Size = new System.Drawing.Size(176, 384);
this.axTOCControl1.TabIndex = 5;
//
// axLicenseControl1
//
this.axLicenseControl1.Enabled = true;
this.axLicenseControl1.Location = new System.Drawing.Point(176, 216);
this.axLicenseControl1.Name = "axLicenseControl1";
this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState")));
this.axLicenseControl1.Size = new System.Drawing.Size(32, 32);
this.axLicenseControl1.TabIndex = 6;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(664, 430);
this.Controls.Add(this.axLicenseControl1);
this.Controls.Add(this.axTOCControl1);
this.Controls.Add(this.button1);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.axPageLayoutControl1);
this.Controls.Add(this.axToolbarControl1);
this.Name = "Form1";
this.Text = "Color Ramps";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axPageLayoutControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit();
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
if (!RuntimeManager.Bind(ProductCode.Engine))
{
if (!RuntimeManager.Bind(ProductCode.Desktop))
{
MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down.");
return;
}
}
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
//Set buddy control
axToolbarControl1.SetBuddyControl(axPageLayoutControl1);
axTOCControl1.SetBuddyControl(axPageLayoutControl1);
//Add ToolbarControl items
axToolbarControl1.AddItem("esriControls.ControlsOpenDocCommand");
axToolbarControl1.AddItem("esriControls.ControlsSaveAsDocCommand");
axToolbarControl1.AddItem("esriControls.ControlsPageZoomInTool");
axToolbarControl1.AddItem("esriControls.ControlsPageZoomOutTool");
axToolbarControl1.AddItem("esriControls.ControlsPageZoomWholePageCommand");
axToolbarControl1.AddItem("esriControls.ControlsMapZoomInTool");
axToolbarControl1.AddItem("esriControls.ControlsMapZoomOutTool");
axToolbarControl1.AddItem("esriControls.ControlsMapPanTool");
axToolbarControl1.AddItem("esriControls.ControlsMapFullExtentCommand");
axToolbarControl1.AddItem("esriControls.ControlsMapIdentifyTool");
//Disable controls
button1.Enabled = false;
comboBox1.Enabled = false;
}
private void axPageLayoutControl1_OnPageLayoutReplaced(object sender, ESRI.ArcGIS.Controls.IPageLayoutControlEvents_OnPageLayoutReplacedEvent e)
{
//Clear the combo box
comboBox1.Items.Clear();
//Get IGeoFeatureLayers CLSID
UID uid = new UIDClass();
uid.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
//Get IGeoFeatureLayers from the focus map
IEnumLayer layers = axPageLayoutControl1.ActiveView.FocusMap.get_Layers(uid, true);
if (layers == null) return;
//Reset enumeration and loop through layers
layers.Reset();
IGeoFeatureLayer geoFeatureLayer = (IGeoFeatureLayer) layers.Next();
while (geoFeatureLayer != null)
{
//If layer contains polygon features add to combo box
if (geoFeatureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
{
if ((geoFeatureLayer is IGroupLayer) == false) comboBox1.Items.Add(geoFeatureLayer.Name);
}
geoFeatureLayer = (IGeoFeatureLayer) layers.Next();
}
comboBox1.SelectedIndex = 0;
//Enable controls
button1.Enabled = true;
comboBox1.Enabled = true;
}
private void button1_Click(object sender, System.EventArgs e)
{
//Get the layer selected in the combo box
IGeoFeatureLayer geofeaturelayer = null;
IMap map = axPageLayoutControl1.ActiveView.FocusMap;
for (int i=0; i<= map.LayerCount-1; i++)
{
if (map.get_Layer(i).Name == comboBox1.SelectedItem.ToString())
{
geofeaturelayer = (IGeoFeatureLayer) map.get_Layer(i);
break;
}
}
if (geofeaturelayer == null) return;
//Create ClassBreaks form
Form2 classBreaksForm = new Form2();
//Get a ClassBreakRenderer that uses the selected ColorRamp
IClassBreaksRenderer classBreaksRenderer = classBreaksForm.GetClassBreaksRenderer(geofeaturelayer);
if (classBreaksRenderer == null) return;
//Set the new renderer
geofeaturelayer.Renderer = (IFeatureRenderer) classBreaksRenderer;
//Trigger contents changed event for TOCControl
axPageLayoutControl1.ActiveView.ContentsChanged();
//Refresh the display
axPageLayoutControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, geofeaturelayer, null);
//Dispose of the form
classBreaksForm.Dispose();
}
}
}
| |
using System.ComponentModel;
using System.Data;
using System.Xml;
using Epi.Data;
namespace Epi.Fields
{
/// <summary>
/// Phone Number Field.
/// </summary>
public class PhoneNumberField : InputTextBoxField, IPatternable
{
#region Private Members
private XmlElement viewElement;
private XmlNode fieldNode;
private string pattern = string.Empty;
private BackgroundWorker _updater;
private BackgroundWorker _inserter;
#endregion
#region Constructors
/// <summary>
/// Constructor for the class
/// </summary>
/// <param name="page">The page this field belongs to</param>
public PhoneNumberField(Page page) : base(page)
{
Construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">View</param>
public PhoneNumberField(View view) : base(view)
{
Construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="page">Page</param>
/// <param name="viewElement">Xml view element</param>
public PhoneNumberField(Page page, XmlElement viewElement)
: base(page)
{
this.viewElement = viewElement;
this.Page = page;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">View</param>
/// <param name="fieldNode">Xml field node</param>
public PhoneNumberField(View view, XmlNode fieldNode) : base(view)
{
this.fieldNode = fieldNode;
this.view.Project.Metadata.GetFieldData(this, this.fieldNode);
}
private void Construct()
{
genericDbColumnType = GenericDbColumnType.String;
this.dbColumnType = DbType.String;
}
/// <summary>
/// Load from row
/// </summary>
/// <param name="row">Row</param>
public override void LoadFromRow(DataRow row)
{
base.LoadFromRow(row);
pattern = row[ColumnNames.PATTERN].ToString();
}
public PhoneNumberField Clone()
{
PhoneNumberField clone = (PhoneNumberField)this.MemberwiseClone();
base.AssignMembers(clone);
return clone;
}
#endregion Constructors
#region Public Events
#endregion
#region Public Properties
/// <summary>
/// Returns field type
/// </summary>
public override MetaFieldType FieldType
{
get
{
return MetaFieldType.PhoneNumber;
}
}
/// <summary>
/// Returns a fully-typed current record value
/// </summary>
public string CurrentRecordValue
{
get
{
if (base.CurrentRecordValueObject == null) return string.Empty;
else return CurrentRecordValueObject.ToString();
}
set
{
base.CurrentRecordValueObject = value;
}
}
/// <summary>
/// The view element of the field
/// </summary>
public XmlElement ViewElement
{
get
{
return viewElement;
}
set
{
viewElement = value;
}
}
#endregion Public Properties
#region IPatternableField Members
/// <summary>
/// Gets and sets Pattern for field
/// </summary>
public string Pattern
{
get
{
return (pattern);
}
set
{
pattern = value;
}
}
#endregion
#region Public Methods
/// <summary>
/// Returns specific data type for the target DB.
/// </summary>
/// <returns></returns>
public override string GetDbSpecificColumnType()
{
return base.GetDbSpecificColumnType() + "(20)";
}
#endregion Public Methods
#region Private Methods
/// <summary>
/// Inserts the field to the database
/// </summary>
protected override void InsertField()
{
this.Id = GetMetadata().CreateField(this);
base.OnFieldAdded();
}
/// <summary>
/// Update the field to the database
/// </summary>
protected override void UpdateField()
{
GetMetadata().UpdateField(this);
}
///// <summary>
///// Inserts the field to the database
///// </summary>
//protected override void InsertField()
//{
// insertStarted = true;
// _inserter = new BackgroundWorker();
// _inserter.DoWork += new DoWorkEventHandler(inserter_DoWork);
// _inserter.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_inserter_RunWorkerCompleted);
// _inserter.RunWorkerAsync();
//}
//void _inserter_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// OnFieldInserted(this);
//}
//void inserter_DoWork(object sender, DoWorkEventArgs e)
//{
// fieldsWaitingToUpdate++;
// lock (view.FieldLockToken)
// {
// this.Id = GetMetadata().CreateField(this);
// base.OnFieldAdded();
// fieldsWaitingToUpdate--;
// }
//}
///// <summary>
///// Update the field to the database
///// </summary>
//protected override void UpdateField()
//{
// _updater = new BackgroundWorker();
// _updater.DoWork += new DoWorkEventHandler(DoWork);
// _updater.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_updater_RunWorkerCompleted);
// _updater.RunWorkerAsync();
//}
//void _updater_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// OnFieldUpdated(this);
//}
//private void DoWork(object sender, DoWorkEventArgs e)
//{
// fieldsWaitingToUpdate++;
// lock (view.FieldLockToken)
// {
// GetMetadata().UpdateField(this);
// fieldsWaitingToUpdate--;
// }
//}
#endregion Private Methods
#region Event Handlers
#endregion Event Handler
}
}
| |
// 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;
namespace System.Xml
{
enum DocumentXmlWriterType
{
InsertSiblingAfter,
InsertSiblingBefore,
PrependChild,
AppendChild,
AppendAttribute,
ReplaceToFollowingSibling,
}
// Implements a XmlWriter that augments a XmlDocument.
sealed class DocumentXmlWriter : XmlRawWriter, IXmlNamespaceResolver
{
enum State
{
Error,
Attribute,
Prolog,
Fragment,
Content,
Last, // always last
}
enum Method
{
WriteXmlDeclaration,
WriteStartDocument,
WriteEndDocument,
WriteDocType,
WriteStartElement,
WriteEndElement,
WriteFullEndElement,
WriteStartAttribute,
WriteEndAttribute,
WriteStartNamespaceDeclaration,
WriteEndNamespaceDeclaration,
WriteCData,
WriteComment,
WriteProcessingInstruction,
WriteEntityRef,
WriteWhitespace,
WriteString,
}
DocumentXmlWriterType type; // writer type
XmlNode start; // context node
XmlDocument document; // context document
XmlNamespaceManager namespaceManager; // context namespace manager
State state; // current state
XmlNode write; // current node
List<XmlNode> fragment; // top level node cache
XmlWriterSettings settings; // wrapping writer settings
DocumentXPathNavigator navigator; // context for replace
XmlNode end; // context for replace
public DocumentXmlWriter(DocumentXmlWriterType type, XmlNode start, XmlDocument document)
{
this.type = type;
this.start = start;
this.document = document;
state = StartState();
fragment = new List<XmlNode>();
settings = new XmlWriterSettings();
settings.CheckCharacters = false;
settings.CloseOutput = false;
settings.ConformanceLevel = (state == State.Prolog ? ConformanceLevel.Document : ConformanceLevel.Fragment);
}
public XmlNamespaceManager NamespaceManager
{
set
{
namespaceManager = value;
}
}
public override XmlWriterSettings Settings
{
get
{
return settings;
}
}
internal void SetSettings(XmlWriterSettings value)
{
settings = value;
}
public DocumentXPathNavigator Navigator
{
set
{
navigator = value;
}
}
public XmlNode EndNode
{
set
{
end = value;
}
}
internal override void WriteXmlDeclaration(XmlStandalone standalone)
{
VerifyState(Method.WriteXmlDeclaration);
if (standalone != XmlStandalone.Omit)
{
XmlNode node = document.CreateXmlDeclaration("1.0", string.Empty, standalone == XmlStandalone.Yes ? "yes" : "no");
AddChild(node, write);
}
}
internal override void WriteXmlDeclaration(string xmldecl)
{
VerifyState(Method.WriteXmlDeclaration);
string version, encoding, standalone;
XmlParsingHelper.ParseXmlDeclarationValue(xmldecl, out version, out encoding, out standalone);
XmlNode node = document.CreateXmlDeclaration(version, encoding, standalone);
AddChild(node, write);
}
public override void WriteStartDocument()
{
VerifyState(Method.WriteStartDocument);
}
public override void WriteStartDocument(bool standalone)
{
VerifyState(Method.WriteStartDocument);
}
public override void WriteEndDocument()
{
VerifyState(Method.WriteEndDocument);
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
throw new NotSupportedException();
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
VerifyState(Method.WriteStartElement);
XmlNode node = document.CreateElement(prefix, localName, ns);
AddChild(node, write);
write = node;
}
public override void WriteEndElement()
{
VerifyState(Method.WriteEndElement);
if (write == null)
{
throw new InvalidOperationException();
}
write = write.ParentNode;
}
internal override void WriteEndElement(string prefix, string localName, string ns)
{
WriteEndElement();
}
public override void WriteFullEndElement()
{
VerifyState(Method.WriteFullEndElement);
XmlElement elem = write as XmlElement;
if (elem == null)
{
throw new InvalidOperationException();
}
elem.IsEmpty = false;
write = elem.ParentNode;
}
internal override void WriteFullEndElement(string prefix, string localName, string ns)
{
WriteFullEndElement();
}
internal override void StartElementContent()
{
// nop
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
VerifyState(Method.WriteStartAttribute);
XmlAttribute attr = document.CreateAttribute(prefix, localName, ns);
AddAttribute(attr, write);
write = attr;
}
public override void WriteEndAttribute()
{
VerifyState(Method.WriteEndAttribute);
XmlAttribute attr = write as XmlAttribute;
if (attr == null)
{
throw new InvalidOperationException();
}
if (!attr.HasChildNodes)
{
XmlNode node = document.CreateTextNode(string.Empty);
AddChild(node, attr);
}
write = attr.OwnerElement;
}
internal override void WriteNamespaceDeclaration(string prefix, string ns)
{
this.WriteStartNamespaceDeclaration(prefix);
this.WriteString(ns);
this.WriteEndNamespaceDeclaration();
}
internal override bool SupportsNamespaceDeclarationInChunks
{
get
{
return true;
}
}
internal override void WriteStartNamespaceDeclaration(string prefix)
{
VerifyState(Method.WriteStartNamespaceDeclaration);
XmlAttribute attr;
if (prefix.Length == 0)
{
attr = document.CreateAttribute(prefix, XmlConst.NsXmlNs, XmlConst.ReservedNsXmlNs);
}
else
{
attr = document.CreateAttribute(XmlConst.NsXmlNs, prefix, XmlConst.ReservedNsXmlNs);
}
AddAttribute(attr, write);
write = attr;
}
internal override void WriteEndNamespaceDeclaration()
{
VerifyState(Method.WriteEndNamespaceDeclaration);
XmlAttribute attr = write as XmlAttribute;
if (attr == null)
{
throw new InvalidOperationException();
}
if (!attr.HasChildNodes)
{
XmlNode node = document.CreateTextNode(string.Empty);
AddChild(node, attr);
}
write = attr.OwnerElement;
}
public override void WriteCData(string text)
{
VerifyState(Method.WriteCData);
XmlConvertEx.VerifyCharData(text, ExceptionType.ArgumentException);
XmlNode node = document.CreateCDataSection(text);
AddChild(node, write);
}
public override void WriteComment(string text)
{
VerifyState(Method.WriteComment);
XmlConvertEx.VerifyCharData(text, ExceptionType.ArgumentException);
XmlNode node = document.CreateComment(text);
AddChild(node, write);
}
public override void WriteProcessingInstruction(string name, string text)
{
VerifyState(Method.WriteProcessingInstruction);
XmlConvertEx.VerifyCharData(text, ExceptionType.ArgumentException);
XmlNode node = document.CreateProcessingInstruction(name, text);
AddChild(node, write);
}
public override void WriteEntityRef(string name)
{
throw new NotSupportedException();
}
public override void WriteCharEntity(char ch)
{
WriteString(new string(ch, 1));
}
public override void WriteWhitespace(string text)
{
VerifyState(Method.WriteWhitespace);
XmlConvertEx.VerifyCharData(text, ExceptionType.ArgumentException);
if (document.PreserveWhitespace)
{
XmlNode node = document.CreateWhitespace(text);
AddChild(node, write);
}
}
public override void WriteString(string text)
{
VerifyState(Method.WriteString);
XmlConvertEx.VerifyCharData(text, ExceptionType.ArgumentException);
XmlNode node = document.CreateTextNode(text);
AddChild(node, write);
}
public override void WriteSurrogateCharEntity(char lowCh, char highCh)
{
WriteString(new string(new char[] { highCh, lowCh }));
}
public override void WriteChars(char[] buffer, int index, int count)
{
WriteString(new string(buffer, index, count));
}
public override void WriteRaw(char[] buffer, int index, int count)
{
WriteString(new string(buffer, index, count));
}
public override void WriteRaw(string data)
{
WriteString(data);
}
internal override void Close(WriteState currentState)
{
if (currentState == WriteState.Error)
{
return;
}
try
{
switch (type)
{
case DocumentXmlWriterType.InsertSiblingAfter:
XmlNode parent = start.ParentNode;
if (parent == null)
{
throw new InvalidOperationException(SR.Xpn_MissingParent);
}
for (int i = fragment.Count - 1; i >= 0; i--)
{
parent.InsertAfter(fragment[i], start);
}
break;
case DocumentXmlWriterType.InsertSiblingBefore:
parent = start.ParentNode;
if (parent == null)
{
throw new InvalidOperationException(SR.Xpn_MissingParent);
}
for (int i = 0; i < fragment.Count; i++)
{
parent.InsertBefore(fragment[i], start);
}
break;
case DocumentXmlWriterType.PrependChild:
for (int i = fragment.Count - 1; i >= 0; i--)
{
start.PrependChild(fragment[i]);
}
break;
case DocumentXmlWriterType.AppendChild:
for (int i = 0; i < fragment.Count; i++)
{
start.AppendChild(fragment[i]);
}
break;
case DocumentXmlWriterType.AppendAttribute:
CloseWithAppendAttribute();
break;
case DocumentXmlWriterType.ReplaceToFollowingSibling:
if (fragment.Count == 0)
{
throw new InvalidOperationException(SR.Xpn_NoContent);
}
CloseWithReplaceToFollowingSibling();
break;
}
}
finally
{
fragment.Clear();
}
}
private void CloseWithAppendAttribute()
{
XmlElement elem = start as XmlElement;
Debug.Assert(elem != null);
XmlAttributeCollection attrs = elem.Attributes;
for (int i = 0; i < fragment.Count; i++)
{
XmlAttribute attr = fragment[i] as XmlAttribute;
Debug.Assert(attr != null);
int offset = attrs.FindNodeOffsetNS(attr);
if (offset != -1
&& (attrs[offset]).Specified)
{
throw new XmlException(SR.Format(SR.Xml_DupAttributeName, attr.Prefix.Length == 0 ? attr.LocalName : string.Concat(attr.Prefix, ":", attr.LocalName)));
}
}
for (int i = 0; i < fragment.Count; i++)
{
XmlAttribute attr = fragment[i] as XmlAttribute;
Debug.Assert(attr != null);
attrs.Append(attr);
}
}
private void CloseWithReplaceToFollowingSibling()
{
XmlNode parent = start.ParentNode;
if (parent == null)
{
throw new InvalidOperationException(SR.Xpn_MissingParent);
}
if (start != end)
{
if (!DocumentXPathNavigator.IsFollowingSibling(start, end))
{
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
if (start.IsReadOnly)
{
throw new InvalidOperationException(SR.Xdom_Node_Modify_ReadOnly);
}
DocumentXPathNavigator.DeleteToFollowingSibling(start.NextSibling, end);
}
XmlNode fragment0 = fragment[0];
parent.ReplaceChild(fragment0, start);
for (int i = fragment.Count - 1; i >= 1; i--)
{
parent.InsertAfter(fragment[i], fragment0);
}
navigator.ResetPosition(fragment0);
}
public override void Flush()
{
// nop
}
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return namespaceManager.GetNamespacesInScope(scope);
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return namespaceManager.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return namespaceManager.LookupPrefix(namespaceName);
}
void AddAttribute(XmlAttribute attr, XmlNode parent)
{
if (parent == null)
{
fragment.Add(attr);
}
else
{
XmlElement elem = parent as XmlElement;
if (elem == null)
{
throw new InvalidOperationException();
}
elem.Attributes.Append(attr);
}
}
void AddChild(XmlNode node, XmlNode parent)
{
if (parent == null)
{
fragment.Add(node);
}
else
{
parent.AppendChild(node);
}
}
State StartState()
{
XmlNodeType nodeType = XmlNodeType.None;
switch (type)
{
case DocumentXmlWriterType.InsertSiblingAfter:
case DocumentXmlWriterType.InsertSiblingBefore:
XmlNode parent = start.ParentNode;
if (parent != null)
{
nodeType = parent.NodeType;
}
if (nodeType == XmlNodeType.Document)
{
return State.Prolog;
}
else if (nodeType == XmlNodeType.DocumentFragment)
{
return State.Fragment;
}
break;
case DocumentXmlWriterType.PrependChild:
case DocumentXmlWriterType.AppendChild:
nodeType = start.NodeType;
if (nodeType == XmlNodeType.Document)
{
return State.Prolog;
}
else if (nodeType == XmlNodeType.DocumentFragment)
{
return State.Fragment;
}
break;
case DocumentXmlWriterType.AppendAttribute:
return State.Attribute;
case DocumentXmlWriterType.ReplaceToFollowingSibling:
break;
}
return State.Content;
}
static State[] changeState = {
// State.Error, State.Attribute,State.Prolog, State.Fragment, State.Content,
// Method.XmlDeclaration:
State.Error, State.Error, State.Prolog, State.Content, State.Error,
// Method.StartDocument:
State.Error, State.Error, State.Error, State.Error, State.Error,
// Method.EndDocument:
State.Error, State.Error, State.Error, State.Error, State.Error,
// Method.DocType:
State.Error, State.Error, State.Prolog, State.Error, State.Error,
// Method.StartElement:
State.Error, State.Error, State.Content, State.Content, State.Content,
// Method.EndElement:
State.Error, State.Error, State.Error, State.Error, State.Content,
// Method.FullEndElement:
State.Error, State.Error, State.Error, State.Error, State.Content,
// Method.StartAttribute:
State.Error, State.Content, State.Error, State.Error, State.Content,
// Method.EndAttribute:
State.Error, State.Error, State.Error, State.Error, State.Content,
// Method.StartNamespaceDeclaration:
State.Error, State.Content, State.Error, State.Error, State.Content,
// Method.EndNamespaceDeclaration:
State.Error, State.Error, State.Error, State.Error, State.Content,
// Method.CData:
State.Error, State.Error, State.Error, State.Content, State.Content,
// Method.Comment:
State.Error, State.Error, State.Prolog, State.Content, State.Content,
// Method.ProcessingInstruction:
State.Error, State.Error, State.Prolog, State.Content, State.Content,
// Method.EntityRef:
State.Error, State.Error, State.Error, State.Content, State.Content,
// Method.Whitespace:
State.Error, State.Error, State.Prolog, State.Content, State.Content,
// Method.String:
State.Error, State.Error, State.Error, State.Content, State.Content,
};
void VerifyState(Method method)
{
state = changeState[(int)method * (int)State.Last + (int)state];
if (state == State.Error)
{
throw new InvalidOperationException(SR.Xml_ClosedOrError);
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="Graph.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Data.Common.Utils;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Globalization;
using System.Linq;
namespace System.Data.Mapping.Update.Internal
{
/// <summary>
/// A directed graph class.
/// </summary>
/// <remarks>
/// Notes on language (in case you're familiar with one or the other convention):
///
/// node == vertex
/// arc == edge
/// predecessor == incoming
/// successor == outgoing
/// </remarks>
/// <typeparam name="TVertex">Type of nodes in the graph</typeparam>
internal class Graph<TVertex>
{
#region Constructors
/// <summary>
/// Initialize a new graph
/// </summary>
/// <param name="comparer">Comparer used to determine if two node references are
/// equivalent</param>
internal Graph(IEqualityComparer<TVertex> comparer)
{
EntityUtil.CheckArgumentNull(comparer, "comparer");
m_comparer = comparer;
m_successorMap = new Dictionary<TVertex, HashSet<TVertex>>(comparer);
m_predecessorCounts = new Dictionary<TVertex, int>(comparer);
m_vertices = new HashSet<TVertex>(comparer);
}
#endregion
#region Fields
/// <summary>
/// Gets successors of the node (outgoing edges).
/// </summary>
private readonly Dictionary<TVertex, HashSet<TVertex>> m_successorMap;
/// <summary>
/// Gets number of predecessors of the node.
/// </summary>
private readonly Dictionary<TVertex, int> m_predecessorCounts;
/// <summary>
/// Gets the vertices that exist in the graph.
/// </summary>
private readonly HashSet<TVertex> m_vertices;
private readonly IEqualityComparer<TVertex> m_comparer;
#endregion
#region Properties
/// <summary>
/// Returns the vertices of the graph.
/// </summary>
internal IEnumerable<TVertex> Vertices
{
get { return m_vertices; }
}
/// <summary>
/// Returns the edges of the graph in the form: [from, to]
/// </summary>
internal IEnumerable<KeyValuePair<TVertex, TVertex>> Edges
{
get
{
foreach (KeyValuePair<TVertex, HashSet<TVertex>> successors in m_successorMap)
{
foreach (TVertex vertex in successors.Value)
{
yield return new KeyValuePair<TVertex, TVertex>(successors.Key, vertex);
}
}
}
}
#endregion
#region Methods
/// <summary>
/// Adds a new node to the graph. Does nothing if the vertex already exists.
/// </summary>
/// <param name="vertex">New node</param>
internal void AddVertex(TVertex vertex)
{
m_vertices.Add(vertex);
}
/// <summary>
/// Adds a new edge to the graph. NOTE: only adds edges for existing vertices.
/// </summary>
/// <param name="from">Source node</param>
/// <param name="to">Target node</param>
internal void AddEdge(TVertex from, TVertex to)
{
// Add only edges relevant to the current graph vertices
if (m_vertices.Contains(from) && m_vertices.Contains(to))
{
HashSet<TVertex> successors;
if (!m_successorMap.TryGetValue(from, out successors))
{
successors = new HashSet<TVertex>(m_comparer);
m_successorMap.Add(from, successors);
}
if (successors.Add(to))
{
// If the edge does not already exist, increment the count of incoming edges (predecessors).
int predecessorCount;
if (!m_predecessorCounts.TryGetValue(to, out predecessorCount))
{
predecessorCount = 1;
}
else
{
++predecessorCount;
}
m_predecessorCounts[to] = predecessorCount;
}
}
}
/// <summary>
/// DESTRUCTIVE OPERATION: performing a sort modifies the graph
/// Performs topological sort on graph. Nodes with no remaining incoming edges are removed
/// in sort order (assumes elements implement IComparable(Of TVertex))
/// </summary>
/// <returns>true if the sort succeeds; false if it fails and there is a remainder</returns>
internal bool TryTopologicalSort(out IEnumerable<TVertex> orderedVertices, out IEnumerable<TVertex> remainder)
{
// populate all predecessor-less nodes to root queue
var rootsPriorityQueue = new SortedSet<TVertex>(Comparer<TVertex>.Default);
foreach (TVertex vertex in m_vertices)
{
int predecessorCount;
if (!m_predecessorCounts.TryGetValue(vertex, out predecessorCount) || 0 == predecessorCount)
{
rootsPriorityQueue.Add(vertex);
}
}
var result = new TVertex[m_vertices.Count];
int resultCount = 0;
// perform sort
while (0 < rootsPriorityQueue.Count)
{
// get the vertex that is next in line in the secondary ordering
TVertex from = rootsPriorityQueue.Min;
rootsPriorityQueue.Remove(from);
// remove all outgoing edges (free all vertices that depend on 'from')
HashSet<TVertex> toSet;
if (m_successorMap.TryGetValue(from, out toSet))
{
foreach (TVertex to in toSet)
{
int predecessorCount = m_predecessorCounts[to] - 1;
m_predecessorCounts[to] = predecessorCount;
if (predecessorCount == 0)
{
// 'to' contains no incoming edges, so it is now a root
rootsPriorityQueue.Add(to);
}
}
// remove the entire successor set since it has been emptied
m_successorMap.Remove(from);
}
// add the freed vertex to the result and remove it from the graph
result[resultCount++] = from;
m_vertices.Remove(from);
}
// check that all elements were yielded
if (m_vertices.Count == 0)
{
// all vertices were ordered
orderedVertices = result;
remainder = Enumerable.Empty<TVertex>();
return true;
}
else
{
orderedVertices = result.Take(resultCount);
remainder = m_vertices;
return false;
}
}
/// <summary>
/// For debugging purposes.
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<TVertex, HashSet<TVertex>> outgoingEdge in m_successorMap)
{
bool first = true;
sb.AppendFormat(CultureInfo.InvariantCulture, "[{0}] --> ", outgoingEdge.Key);
foreach (TVertex vertex in outgoingEdge.Value)
{
if (first) { first = false; }
else { sb.Append(", "); }
sb.AppendFormat(CultureInfo.InvariantCulture, "[{0}]", vertex);
}
sb.Append("; ");
}
return sb.ToString();
}
#endregion
}
}
| |
/*
* BmpReader.cs - Implementation of the "DotGNU.Images.BmpReader" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software, you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY, without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program, if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace DotGNU.Images
{
using System;
using System.IO;
internal sealed class BmpReader
{
// Load a BMP image from the specified stream. The first 4 bytes
// have already been read and discarded.
public static void Load(Stream stream, Image image)
{
byte[] buffer = new byte [1024];
int width, height, planes, bitCount;
int compression;
bool quads;
// Read the rest of the BITMAPFILEHEADER.
if(stream.Read(buffer, 0, 10) != 10)
{
throw new FormatException();
}
int bfOffBits = Utils.ReadInt32(buffer, 6);
// The current file offset at the end of the BITMAPFILEHEADER.
int offset = 14;
// Get the size of the BITMAPINFOHEADER structure that follows,
// and then read it into the buffer.
if(stream.Read(buffer, 0, 4) != 4)
{
throw new FormatException();
}
int size = Utils.ReadInt32(buffer, 0);
if(size <= 4 || size > 1024)
{
throw new FormatException();
}
if(stream.Read(buffer, 4, size - 4) != (size - 4))
{
throw new FormatException();
}
offset += size;
if(size >= 40)
{
// This is a BITMAPINFOHEADER structure (Windows bitmaps).
width = Utils.ReadInt32(buffer, 4);
height = Utils.ReadInt32(buffer, 8);
planes = Utils.ReadUInt16(buffer, 12);
bitCount = Utils.ReadUInt16(buffer, 14);
compression = Utils.ReadInt32(buffer, 16);
quads = true;
}
else if(size == 12)
{
// This is a BITMAPCOREHEADER structure (OS/2 bitmaps).
width = Utils.ReadUInt16(buffer, 4);
height = Utils.ReadUInt16(buffer, 6);
planes = Utils.ReadUInt16(buffer, 8);
bitCount = Utils.ReadUInt16(buffer, 10);
compression = 0; // BI_RGB
quads = false;
}
else
{
throw new FormatException();
}
// Perform a sanity check on the header values.
if(width <= 0 || planes != 1)
{
throw new FormatException();
}
if(bitCount != 1 && bitCount != 4 && bitCount != 16 &&
bitCount != 8 && bitCount != 24)
{
// TODO: non-traditional BMP formats.
throw new FormatException();
}
if(compression != 0 && compression != 3/*BI_BITFIELDS*/)
{
// TODO: RLE bitmaps
throw new FormatException();
}
// Set the basic image properties.
image.Width = width;
image.Height = height < 0 ? -height : height;
image.PixelFormat = Utils.BitCountToFormat(bitCount);
image.LoadFormat = Image.Bmp;
// Do the unusual 16 bit formats.
if (compression == 3)
{
if(stream.Read(buffer, 0, 3 * 4) != (3 * 4))
{
throw new FormatException();
}
int redMask = Utils.ReadInt32(buffer, 0);
int greenMask = Utils.ReadInt32(buffer, 4);
int blueMask = Utils.ReadInt32(buffer, 8);
if (blueMask == 0x001F && redMask == 0x7C00 && greenMask == 0x03E0)
image.PixelFormat = PixelFormat.Format16bppRgb555;
else if (blueMask == 0x001F && redMask == 0xF800 && greenMask == 0x07E0)
image.PixelFormat = PixelFormat.Format16bppRgb565;
else
throw new FormatException();
}
// Read the palette into memory and set it.
if(bitCount <= 8)
{
int colors = (1 << bitCount);
int index;
int[] palette = new int [colors];
if(quads)
{
// The RGB values are specified as RGBQUAD's.
if(stream.Read(buffer, 0, colors * 4) != (colors * 4))
{
throw new FormatException();
}
offset += colors * 4;
for(index = 0; index < colors; ++index)
{
palette[index] = Utils.ReadBGR(buffer, index * 4);
}
}
else
{
// The RGB values are specified as RGBTRIPLE's.
if(stream.Read(buffer, 0, colors * 3) != (colors * 3))
{
throw new FormatException();
}
offset += colors * 3;
for(index = 0; index < colors; ++index)
{
palette[index] = Utils.ReadBGR(buffer, index * 3);
}
}
image.Palette = palette;
}
// Seek to the start of the bitmap data.
Utils.Seek(stream, offset, bfOffBits);
// Add a frame to the image object.
Frame frame = image.AddFrame();
// Load the bitmap data from the stream into the frame.
LoadBitmapData(stream, frame, false, height > 0);
}
// Load bitmap data into a frame.
public static void LoadBitmapData(Stream stream, Frame frame, bool mask, bool reverse)
{
byte[] data;
int stride;
int line;
// Get the buffer and stride for the frame.
if(!mask)
{
data = frame.Data;
stride = frame.Stride;
}
else
{
frame.AddMask();
data = frame.Mask;
stride = frame.MaskStride;
}
// BMP images are usuallystored upside down in the stream.
if (reverse)
{
for(line = frame.Height - 1; line >= 0; --line)
{
stream.Read(data, line * stride, stride);
}
}
else
{
for(line = 0; line < frame.Height; line++)
{
stream.Read(data, line * stride, stride);
}
}
}
}; // class BmpReader
}; // namespace DotGNU.Images
| |
// 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.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata.Ecma335
{
internal class NamespaceCache
{
private readonly MetadataReader _metadataReader;
private readonly object _namespaceTableAndListLock = new object();
private Dictionary<NamespaceDefinitionHandle, NamespaceData> _namespaceTable;
private NamespaceData _rootNamespace;
private ImmutableArray<NamespaceDefinitionHandle> _namespaceList;
internal NamespaceCache(MetadataReader reader)
{
Debug.Assert(reader != null);
_metadataReader = reader;
}
/// <summary>
/// Returns whether the namespaceTable has been created. If it hasn't, calling a GetXXX method
/// on this will probably have a very high amount of overhead.
/// </summary>
internal bool CacheIsRealized
{
get { return _namespaceTable != null; }
}
internal string GetFullName(NamespaceDefinitionHandle handle)
{
Debug.Assert(!handle.HasFullName); // we should not hit the cache in this case.
NamespaceData data = GetNamespaceData(handle);
return data.FullName;
}
internal NamespaceData GetRootNamespace()
{
EnsureNamespaceTableIsPopulated();
Debug.Assert(_rootNamespace != null);
return _rootNamespace;
}
internal NamespaceData GetNamespaceData(NamespaceDefinitionHandle handle)
{
EnsureNamespaceTableIsPopulated();
NamespaceData result;
if (!_namespaceTable.TryGetValue(handle, out result))
{
ThrowInvalidHandle();
}
return result;
}
// TODO: move throw helpers to common place.
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void ThrowInvalidHandle()
{
throw new BadImageFormatException(MetadataResources.InvalidHandle);
}
/// <summary>
/// This will return a StringHandle for the simple name of a namespace name at the given segment index.
/// If no segment index is passed explicitly or the "segment" index is greater than or equal to the number
/// of segments, then the last segment is used. "Segment" in this context refers to part of a namespace
/// name between dots.
///
/// Example: Given a NamespaceDefinitionHandle to "System.Collections.Generic.Test" called 'handle':
///
/// reader.GetString(GetSimpleName(handle)) == "Test"
/// reader.GetString(GetSimpleName(handle, 0)) == "System"
/// reader.GetString(GetSimpleName(handle, 1)) == "Collections"
/// reader.GetString(GetSimpleName(handle, 2)) == "Generic"
/// reader.GetString(GetSimpleName(handle, 3)) == "Test"
/// reader.GetString(GetSimpleName(handle, 1000)) == "Test"
/// </summary>
private StringHandle GetSimpleName(NamespaceDefinitionHandle fullNamespaceHandle, int segmentIndex = Int32.MaxValue)
{
StringHandle handleContainingSegment = fullNamespaceHandle.GetFullName();
Debug.Assert(!handleContainingSegment.IsVirtual);
int lastFoundIndex = fullNamespaceHandle.Index - 1;
int currentSegment = 0;
while (currentSegment < segmentIndex)
{
int currentIndex = _metadataReader.StringStream.IndexOfRaw(lastFoundIndex + 1, '.');
if (currentIndex == -1)
{
break;
}
lastFoundIndex = currentIndex;
++currentSegment;
}
Debug.Assert(lastFoundIndex >= 0 || currentSegment == 0);
// + 1 because lastFoundIndex will either "point" to a '.', or will be -1. Either way,
// we want the next char.
uint resultIndex = (uint)(lastFoundIndex + 1);
return StringHandle.FromIndex(resultIndex).WithDotTermination();
}
/// <summary>
/// Two distinct namespace handles represent the same namespace if their full names are the same. This
/// method merges builders corresponding to such namespace handles.
/// </summary>
private void PopulateNamespaceTable()
{
lock (_namespaceTableAndListLock)
{
if (_namespaceTable != null)
{
return;
}
var namespaceBuilderTable = new Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder>();
// Make sure to add entry for root namespace. The root namespace is special in that even
// though it might not have types of its own it always has an equivalent representation
// as a nil handle and we don't want to handle it below as dot-terminated synthetic namespace.
// We use NamespaceDefinitionHandle.FromIndexOfFullName(0) instead of default(NamespaceDefinitionHandle) so
// that we never hand back a handle to the user that doesn't have a typeid as that prevents
// round-trip conversion to Handle and back. (We may discover other handle aliases for the
// root namespace (any nil/empty string will do), but we need this one to always be there.
NamespaceDefinitionHandle rootNamespace = NamespaceDefinitionHandle.FromIndexOfFullName(0);
namespaceBuilderTable.Add(
rootNamespace,
new NamespaceDataBuilder(
rootNamespace,
rootNamespace.GetFullName(),
String.Empty));
PopulateTableWithTypeDefinitions(namespaceBuilderTable);
PopulateTableWithExportedTypes(namespaceBuilderTable);
Dictionary<string, NamespaceDataBuilder> stringTable;
MergeDuplicateNamespaces(namespaceBuilderTable, out stringTable);
List<NamespaceDataBuilder> syntheticNamespaces;
ResolveParentChildRelationships(stringTable, out syntheticNamespaces);
var namespaceTable = new Dictionary<NamespaceDefinitionHandle, NamespaceData>();
foreach (var group in namespaceBuilderTable)
{
// Freeze() caches the result, so any many-to-one relationships
// between keys and values will be preserved and efficiently handled.
namespaceTable.Add(group.Key, group.Value.Freeze());
}
if (syntheticNamespaces != null)
{
foreach (var syntheticNamespace in syntheticNamespaces)
{
namespaceTable.Add(syntheticNamespace.Handle, syntheticNamespace.Freeze());
}
}
_namespaceTable = namespaceTable;
_rootNamespace = namespaceTable[rootNamespace];
}
}
/// <summary>
/// This will take 'table' and merge all of the NamespaceData instances that point to the same
/// namespace. It has to create 'stringTable' as an intermediate dictionary, so it will hand it
/// back to the caller should the caller want to use it.
/// </summary>
private void MergeDuplicateNamespaces(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table, out Dictionary<string, NamespaceDataBuilder> stringTable)
{
var namespaces = new Dictionary<string, NamespaceDataBuilder>();
List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>> remaps = null;
foreach (var group in table)
{
NamespaceDataBuilder data = group.Value;
NamespaceDataBuilder existingRecord;
if (namespaces.TryGetValue(data.FullName, out existingRecord))
{
// Children should not exist until the next step.
Debug.Assert(data.Namespaces.Count == 0);
data.MergeInto(existingRecord);
if (remaps == null)
{
remaps = new List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>>();
}
remaps.Add(new KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>(group.Key, existingRecord));
}
else
{
namespaces.Add(data.FullName, data);
}
}
// Needs to be done outside of foreach (var group in table) to avoid modifying the dictionary while foreach'ing over it.
if (remaps != null)
{
foreach (var tuple in remaps)
{
table[tuple.Key] = tuple.Value;
}
}
stringTable = namespaces;
}
/// <summary>
/// Creates a NamespaceDataBuilder instance that contains a synthesized NamespaceDefinitionHandle,
/// as well as the name provided.
/// </summary>
private NamespaceDataBuilder SynthesizeNamespaceData(string fullName, NamespaceDefinitionHandle realChild)
{
Debug.Assert(realChild.HasFullName);
int numberOfSegments = 0;
foreach (char c in fullName)
{
if (c == '.')
{
numberOfSegments++;
}
}
StringHandle simpleName = GetSimpleName(realChild, numberOfSegments);
var namespaceHandle = NamespaceDefinitionHandle.FromIndexOfSimpleName((uint)simpleName.Index);
return new NamespaceDataBuilder(namespaceHandle, simpleName, fullName);
}
/// <summary>
/// Quick convenience method that handles linking together child + parent
/// </summary>
private void LinkChildDataToParentData(NamespaceDataBuilder child, NamespaceDataBuilder parent)
{
Debug.Assert(child != null && parent != null);
Debug.Assert(!child.Handle.IsNil);
child.Parent = parent.Handle;
parent.Namespaces.Add(child.Handle);
}
/// <summary>
/// Links a child to its parent namespace. If the parent namespace doesn't exist, this will create a
/// synthetic one. This will automatically link any synthetic namespaces it creates up to its parents.
/// </summary>
private void LinkChildToParentNamespace(Dictionary<string, NamespaceDataBuilder> existingNamespaces,
NamespaceDataBuilder realChild,
ref List<NamespaceDataBuilder> syntheticNamespaces)
{
Debug.Assert(realChild.Handle.HasFullName);
string childName = realChild.FullName;
var child = realChild;
// The condition for this loop is very complex -- essentially, we keep going
// until we:
// A. Encounter the root namespace as 'child'
// B. Find a preexisting namespace as 'parent'
while (true)
{
int lastIndex = childName.LastIndexOf('.');
string parentName;
if (lastIndex == -1)
{
if (childName.Length == 0)
{
return;
}
else
{
parentName = String.Empty;
}
}
else
{
parentName = childName.Substring(0, lastIndex);
}
NamespaceDataBuilder parentData;
if (existingNamespaces.TryGetValue(parentName, out parentData))
{
LinkChildDataToParentData(child, parentData);
return;
}
if (syntheticNamespaces != null)
{
foreach (var data in syntheticNamespaces)
{
if (data.FullName == parentName)
{
LinkChildDataToParentData(child, data);
return;
}
}
}
else
{
syntheticNamespaces = new List<NamespaceDataBuilder>();
}
var syntheticParent = SynthesizeNamespaceData(parentName, realChild.Handle);
LinkChildDataToParentData(child, syntheticParent);
syntheticNamespaces.Add(syntheticParent);
childName = syntheticParent.FullName;
child = syntheticParent;
}
}
/// <summary>
/// This will link all parents/children in the given namespaces dictionary up to each other.
///
/// In some cases, we need to synthesize namespaces that do not have any type definitions or forwarders
/// of their own, but do have child namespaces. These are returned via the syntheticNamespaces out
/// parameter.
/// </summary>
private void ResolveParentChildRelationships(Dictionary<string, NamespaceDataBuilder> namespaces, out List<NamespaceDataBuilder> syntheticNamespaces)
{
syntheticNamespaces = null;
foreach (var namespaceData in namespaces.Values)
{
LinkChildToParentNamespace(namespaces, namespaceData, ref syntheticNamespaces);
}
}
/// <summary>
/// Loops through all type definitions in metadata, adding them to the given table
/// </summary>
private void PopulateTableWithTypeDefinitions(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table)
{
Debug.Assert(table != null);
foreach (var typeHandle in _metadataReader.TypeDefinitions)
{
TypeDefinition type = _metadataReader.GetTypeDefinition(typeHandle);
if (type.Attributes.IsNested())
{
continue;
}
NamespaceDefinitionHandle namespaceHandle = _metadataReader.TypeDefTable.GetNamespace(typeHandle);
NamespaceDataBuilder builder;
if (table.TryGetValue(namespaceHandle, out builder))
{
builder.TypeDefinitions.Add(typeHandle);
}
else
{
StringHandle name = GetSimpleName(namespaceHandle);
string fullName = _metadataReader.GetString(namespaceHandle);
var newData = new NamespaceDataBuilder(namespaceHandle, name, fullName);
newData.TypeDefinitions.Add(typeHandle);
table.Add(namespaceHandle, newData);
}
}
}
/// <summary>
/// Loops through all type forwarders in metadata, adding them to the given table
/// </summary>
private void PopulateTableWithExportedTypes(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table)
{
Debug.Assert(table != null);
foreach (var exportedTypeHandle in _metadataReader.ExportedTypes)
{
ExportedType exportedType = _metadataReader.GetExportedType(exportedTypeHandle);
if (exportedType.Implementation.Kind == HandleKind.ExportedType)
{
continue; // skip nested exported types.
}
NamespaceDefinitionHandle namespaceHandle = exportedType.Namespace;
NamespaceDataBuilder builder;
if (table.TryGetValue(namespaceHandle, out builder))
{
builder.ExportedTypes.Add(exportedTypeHandle);
}
else
{
Debug.Assert(namespaceHandle.HasFullName);
StringHandle simpleName = GetSimpleName(namespaceHandle);
string fullName = _metadataReader.GetString(namespaceHandle);
var newData = new NamespaceDataBuilder(namespaceHandle, simpleName, fullName);
newData.ExportedTypes.Add(exportedTypeHandle);
table.Add(namespaceHandle, newData);
}
}
}
/// <summary>
/// Populates namespaceList with distinct namespaces. No ordering is guaranteed.
/// </summary>
private void PopulateNamespaceList()
{
lock (_namespaceTableAndListLock)
{
if (_namespaceList != null)
{
return;
}
Debug.Assert(_namespaceTable != null);
var namespaceNameSet = new HashSet<string>();
var namespaceListBuilder = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>();
foreach (var group in _namespaceTable)
{
var data = group.Value;
if (namespaceNameSet.Add(data.FullName))
{
namespaceListBuilder.Add(group.Key);
}
}
_namespaceList = namespaceListBuilder.ToImmutable();
}
}
/// <summary>
/// If the namespace table doesn't exist, populates it!
/// </summary>
private void EnsureNamespaceTableIsPopulated()
{
// PERF: Branch will rarely be taken; do work in PopulateNamespaceList() so this can be inlined easily.
if (_namespaceTable == null)
{
PopulateNamespaceTable();
}
Debug.Assert(_namespaceTable != null);
}
/// <summary>
/// If the namespace list doesn't exist, populates it!
/// </summary>
private void EnsureNamespaceListIsPopulated()
{
if (_namespaceList == null)
{
PopulateNamespaceList();
}
Debug.Assert(_namespaceList != null);
}
/// <summary>
/// An intermediate class used to build NamespaceData instances. This was created because we wanted to
/// use ImmutableArrays in NamespaceData, but having ArrayBuilders and ImmutableArrays that served the
/// same purpose in NamespaceData got ugly. With the current design of how we create our Namespace
/// dictionary, this needs to be a class because we have a many-to-one mapping between NamespaceHandles
/// and NamespaceData. So, the pointer semantics must be preserved.
///
/// This class assumes that the builders will not be modified in any way after the first call to
/// Freeze().
/// </summary>
private class NamespaceDataBuilder
{
public readonly NamespaceDefinitionHandle Handle;
public readonly StringHandle Name;
public readonly string FullName;
public NamespaceDefinitionHandle Parent;
public ImmutableArray<NamespaceDefinitionHandle>.Builder Namespaces;
public ImmutableArray<TypeDefinitionHandle>.Builder TypeDefinitions;
public ImmutableArray<ExportedTypeHandle>.Builder ExportedTypes;
private NamespaceData _frozen;
public NamespaceDataBuilder(NamespaceDefinitionHandle handle, StringHandle name, string fullName)
{
Handle = handle;
Name = name;
FullName = fullName;
Namespaces = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>();
TypeDefinitions = ImmutableArray.CreateBuilder<TypeDefinitionHandle>();
ExportedTypes = ImmutableArray.CreateBuilder<ExportedTypeHandle>();
}
/// <summary>
/// Returns a NamespaceData that represents this NamespaceDataBuilder instance. After calling
/// this method, it is an error to use any methods or fields except Freeze() on the target
/// NamespaceDataBuilder.
/// </summary>
public NamespaceData Freeze()
{
// It is not an error to call this function multiple times. We cache the result
// because it's immutable.
if (_frozen == null)
{
var namespaces = Namespaces.ToImmutable();
Namespaces = null;
var typeDefinitions = TypeDefinitions.ToImmutable();
TypeDefinitions = null;
var exportedTypes = ExportedTypes.ToImmutable();
ExportedTypes = null;
_frozen = new NamespaceData(Name, FullName, Parent, namespaces, typeDefinitions, exportedTypes);
}
return _frozen;
}
public void MergeInto(NamespaceDataBuilder other)
{
Parent = default(NamespaceDefinitionHandle);
other.Namespaces.AddRange(this.Namespaces);
other.TypeDefinitions.AddRange(this.TypeDefinitions);
other.ExportedTypes.AddRange(this.ExportedTypes);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Timers;
using System.Text.RegularExpressions;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.World.AutoBackup
{
/// <summary>
/// Choose between ways of naming the backup files that are generated.
/// </summary>
/// <remarks>Time: OARs are named by a timestamp.
/// Sequential: OARs are named by counting (Region_1.oar, Region_2.oar, etc.)
/// Overwrite: Only one file per region is created; it's overwritten each time a backup is made.</remarks>
public enum NamingType
{
Time,
Sequential,
Overwrite
}
///<summary>
/// AutoBackupModule: save OAR region backups to disk periodically
/// </summary>
/// <remarks>
/// Config Settings Documentation.
/// At the TOP LEVEL, e.g. in OpenSim.ini, we have the following options:
/// EACH REGION, in OpenSim.ini, can have the following settings under the [AutoBackupModule] section.
/// IMPORTANT: You may optionally specify the key name as follows for a per-region key: [Region Name].[Key Name]
/// Example: My region is named Foo.
/// If I wanted to specify the "AutoBackupInterval" key just for this region, I would name my key "Foo.AutoBackupInterval", under the [AutoBackupModule] section of OpenSim.ini.
/// Instead of specifying them on a per-region basis, you can also omit the region name to specify the default setting for all regions.
/// Region-specific settings take precedence.
///
/// AutoBackupModuleEnabled: True/False. Default: False. If True, use the auto backup module. This setting does not support per-region basis.
/// All other settings under [AutoBackupModule] are ignored if AutoBackupModuleEnabled is false, even per-region settings!
/// AutoBackup: True/False. Default: False. If True, activate auto backup functionality.
/// This is the only required option for enabling auto-backup; the other options have sane defaults.
/// If False for a particular region, the auto-backup module becomes a no-op for the region, and all other AutoBackup* settings are ignored.
/// If False globally (the default), only regions that specifically override this with "FooRegion.AutoBackup = true" will get AutoBackup functionality.
/// AutoBackupInterval: Double, non-negative value. Default: 720 (12 hours).
/// The number of minutes between each backup attempt.
/// If a negative or zero value is given, it is equivalent to setting AutoBackup = False.
/// AutoBackupBusyCheck: True/False. Default: True.
/// If True, we will only take an auto-backup if a set of conditions are met.
/// These conditions are heuristics to try and avoid taking a backup when the sim is busy.
/// AutoBackupScript: String. Default: not specified (disabled).
/// File path to an executable script or binary to run when an automatic backup is taken.
/// The file should really be (Windows) an .exe or .bat, or (Linux/Mac) a shell script or binary.
/// Trying to "run" directories, or things with weird file associations on Win32, might cause unexpected results!
/// argv[1] of the executed file/script will be the file name of the generated OAR.
/// If the process can't be spawned for some reason (file not found, no execute permission, etc), write a warning to the console.
/// AutoBackupNaming: string. Default: Time.
/// One of three strings (case insensitive):
/// "Time": Current timestamp is appended to file name. An existing file will never be overwritten.
/// "Sequential": A number is appended to the file name. So if RegionName_x.oar exists, we'll save to RegionName_{x+1}.oar next. An existing file will never be overwritten.
/// "Overwrite": Always save to file named "${AutoBackupDir}/RegionName.oar", even if we have to overwrite an existing file.
/// AutoBackupDir: String. Default: "." (the current directory).
/// A directory (absolute or relative) where backups should be saved.
/// AutoBackupDilationThreshold: float. Default: 0.5. Lower bound on time dilation required for BusyCheck heuristics to pass.
/// If the time dilation is below this value, don't take a backup right now.
/// AutoBackupAgentThreshold: int. Default: 10. Upper bound on # of agents in region required for BusyCheck heuristics to pass.
/// If the number of agents is greater than this value, don't take a backup right now
/// Save memory by setting low initial capacities. Minimizes impact in common cases of all regions using same interval, and instances hosting 1 ~ 4 regions.
/// Also helps if you don't want AutoBackup at all.
/// </remarks>
public class AutoBackupModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Dictionary<Guid, IScene> m_pendingSaves = new Dictionary<Guid, IScene>(1);
private readonly AutoBackupModuleState m_defaultState = new AutoBackupModuleState();
private readonly Dictionary<IScene, AutoBackupModuleState> m_states =
new Dictionary<IScene, AutoBackupModuleState>(1);
private readonly Dictionary<Timer, List<IScene>> m_timerMap =
new Dictionary<Timer, List<IScene>>(1);
private readonly Dictionary<double, Timer> m_timers = new Dictionary<double, Timer>(1);
private delegate T DefaultGetter<T>(string settingName, T defaultValue);
private bool m_enabled;
/// <summary>
/// Whether the shared module should be enabled at all. NOT the same as m_Enabled in AutoBackupModuleState!
/// </summary>
private bool m_closed;
private IConfigSource m_configSource;
/// <summary>
/// Required by framework.
/// </summary>
public bool IsSharedModule
{
get { return true; }
}
#region ISharedRegionModule Members
/// <summary>
/// Identifies the module to the system.
/// </summary>
string IRegionModuleBase.Name
{
get { return "AutoBackupModule"; }
}
/// <summary>
/// We don't implement an interface, this is a single-use module.
/// </summary>
Type IRegionModuleBase.ReplaceableInterface
{
get { return null; }
}
/// <summary>
/// Called once in the lifetime of the module at startup.
/// </summary>
/// <param name="source">The input config source for OpenSim.ini.</param>
void IRegionModuleBase.Initialise(IConfigSource source)
{
// Determine if we have been enabled at all in OpenSim.ini -- this is part and parcel of being an optional module
this.m_configSource = source;
IConfig moduleConfig = source.Configs["AutoBackupModule"];
if (moduleConfig == null)
{
this.m_enabled = false;
return;
}
else
{
this.m_enabled = moduleConfig.GetBoolean("AutoBackupModuleEnabled", false);
if (this.m_enabled)
{
m_log.Info("[AUTO BACKUP]: AutoBackupModule enabled");
}
else
{
return;
}
}
Timer defTimer = new Timer(43200000);
this.m_defaultState.Timer = defTimer;
this.m_timers.Add(43200000, defTimer);
defTimer.Elapsed += this.HandleElapsed;
defTimer.AutoReset = true;
defTimer.Start();
AutoBackupModuleState abms = this.ParseConfig(null, true);
m_log.Debug("[AUTO BACKUP]: Here is the default config:");
m_log.Debug(abms.ToString());
}
/// <summary>
/// Called once at de-init (sim shutting down).
/// </summary>
void IRegionModuleBase.Close()
{
if (!this.m_enabled)
{
return;
}
// We don't want any timers firing while the sim's coming down; strange things may happen.
this.StopAllTimers();
}
/// <summary>
/// Currently a no-op for AutoBackup because we have to wait for region to be fully loaded.
/// </summary>
/// <param name="scene"></param>
void IRegionModuleBase.AddRegion(Scene scene)
{
}
/// <summary>
/// Here we just clean up some resources and stop the OAR backup (if any) for the given scene.
/// </summary>
/// <param name="scene">The scene (region) to stop performing AutoBackup on.</param>
void IRegionModuleBase.RemoveRegion(Scene scene)
{
if (!this.m_enabled)
{
return;
}
if (this.m_states.ContainsKey(scene))
{
AutoBackupModuleState abms = this.m_states[scene];
// Remove this scene out of the timer map list
Timer timer = abms.Timer;
List<IScene> list = this.m_timerMap[timer];
list.Remove(scene);
// Shut down the timer if this was the last scene for the timer
if (list.Count == 0)
{
this.m_timerMap.Remove(timer);
this.m_timers.Remove(timer.Interval);
timer.Close();
}
this.m_states.Remove(scene);
}
}
/// <summary>
/// Most interesting/complex code paths in AutoBackup begin here.
/// We read lots of Nini config, maybe set a timer, add members to state tracking Dictionaries, etc.
/// </summary>
/// <param name="scene">The scene to (possibly) perform AutoBackup on.</param>
void IRegionModuleBase.RegionLoaded(Scene scene)
{
if (!this.m_enabled)
{
return;
}
// This really ought not to happen, but just in case, let's pretend it didn't...
if (scene == null)
{
return;
}
AutoBackupModuleState abms = this.ParseConfig(scene, false);
m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
m_log.Debug((abms == null ? "DEFAULT" : abms.ToString()));
}
/// <summary>
/// Currently a no-op.
/// </summary>
void ISharedRegionModule.PostInitialise()
{
}
#endregion
/// <summary>
/// Set up internal state for a given scene. Fairly complex code.
/// When this method returns, we've started auto-backup timers, put members in Dictionaries, and created a State object for this scene.
/// </summary>
/// <param name="scene">The scene to look at.</param>
/// <param name="parseDefault">Whether this call is intended to figure out what we consider the "default" config (applied to all regions unless overridden by per-region settings).</param>
/// <returns>An AutoBackupModuleState contains most information you should need to know relevant to auto-backup, as applicable to a single region.</returns>
private AutoBackupModuleState ParseConfig(IScene scene, bool parseDefault)
{
string sRegionName;
string sRegionLabel;
string prepend;
AutoBackupModuleState state;
if (parseDefault)
{
sRegionName = null;
sRegionLabel = "DEFAULT";
prepend = "";
state = this.m_defaultState;
}
else
{
sRegionName = scene.RegionInfo.RegionName;
sRegionLabel = sRegionName;
prepend = sRegionName + ".";
state = null;
}
// Read the config settings and set variables.
IConfig regionConfig = (scene != null ? scene.Config.Configs[sRegionName] : null);
IConfig config = this.m_configSource.Configs["AutoBackupModule"];
if (config == null)
{
// defaultState would be disabled too if the section doesn't exist.
state = this.m_defaultState;
return state;
}
bool tmpEnabled = ResolveBoolean("AutoBackup", this.m_defaultState.Enabled, config, regionConfig);
if (state == null && tmpEnabled != this.m_defaultState.Enabled)
//Varies from default state
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.Enabled = tmpEnabled;
}
// If you don't want AutoBackup, we stop.
if ((state == null && !this.m_defaultState.Enabled) || (state != null && !state.Enabled))
{
return state;
}
else
{
m_log.Info("[AUTO BACKUP]: Region " + sRegionLabel + " is AutoBackup ENABLED.");
}
// Borrow an existing timer if one exists for the same interval; otherwise, make a new one.
double interval =
this.ResolveDouble("AutoBackupInterval", this.m_defaultState.IntervalMinutes,
config, regionConfig) * 60000.0;
if (state == null && interval != this.m_defaultState.IntervalMinutes*60000.0)
{
state = new AutoBackupModuleState();
}
if (this.m_timers.ContainsKey(interval))
{
if (state != null)
{
state.Timer = this.m_timers[interval];
}
m_log.Debug("[AUTO BACKUP]: Reusing timer for " + interval + " msec for region " +
sRegionLabel);
}
else
{
// 0 or negative interval == do nothing.
if (interval <= 0.0 && state != null)
{
state.Enabled = false;
return state;
}
if (state == null)
{
state = new AutoBackupModuleState();
}
Timer tim = new Timer(interval);
state.Timer = tim;
//Milliseconds -> minutes
this.m_timers.Add(interval, tim);
tim.Elapsed += this.HandleElapsed;
tim.AutoReset = true;
tim.Start();
}
// Add the current region to the list of regions tied to this timer.
if (scene != null)
{
if (state != null)
{
if (this.m_timerMap.ContainsKey(state.Timer))
{
this.m_timerMap[state.Timer].Add(scene);
}
else
{
List<IScene> scns = new List<IScene>(1);
scns.Add(scene);
this.m_timerMap.Add(state.Timer, scns);
}
}
else
{
if (this.m_timerMap.ContainsKey(this.m_defaultState.Timer))
{
this.m_timerMap[this.m_defaultState.Timer].Add(scene);
}
else
{
List<IScene> scns = new List<IScene>(1);
scns.Add(scene);
this.m_timerMap.Add(this.m_defaultState.Timer, scns);
}
}
}
bool tmpBusyCheck = ResolveBoolean("AutoBackupBusyCheck",
this.m_defaultState.BusyCheck, config, regionConfig);
if (state == null && tmpBusyCheck != this.m_defaultState.BusyCheck)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.BusyCheck = tmpBusyCheck;
}
// Set file naming algorithm
string stmpNamingType = ResolveString("AutoBackupNaming",
this.m_defaultState.NamingType.ToString(), config, regionConfig);
NamingType tmpNamingType;
if (stmpNamingType.Equals("Time", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Time;
}
else if (stmpNamingType.Equals("Sequential", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Sequential;
}
else if (stmpNamingType.Equals("Overwrite", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Overwrite;
}
else
{
m_log.Warn("Unknown naming type specified for region " + sRegionLabel + ": " +
stmpNamingType);
tmpNamingType = NamingType.Time;
}
if (state == null && tmpNamingType != this.m_defaultState.NamingType)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.NamingType = tmpNamingType;
}
string tmpScript = ResolveString("AutoBackupScript",
this.m_defaultState.Script, config, regionConfig);
if (state == null && tmpScript != this.m_defaultState.Script)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.Script = tmpScript;
}
string tmpBackupDir = ResolveString("AutoBackupDir", ".", config, regionConfig);
if (state == null && tmpBackupDir != this.m_defaultState.BackupDir)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.BackupDir = tmpBackupDir;
// Let's give the user some convenience and auto-mkdir
if (state.BackupDir != ".")
{
try
{
DirectoryInfo dirinfo = new DirectoryInfo(state.BackupDir);
if (!dirinfo.Exists)
{
dirinfo.Create();
}
}
catch (Exception e)
{
m_log.Warn(
"BAD NEWS. You won't be able to save backups to directory " +
state.BackupDir +
" because it doesn't exist or there's a permissions issue with it. Here's the exception.",
e);
}
}
}
return state;
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private bool ResolveBoolean(string settingName, bool defaultValue, IConfig global, IConfig local)
{
if(local != null)
{
return local.GetBoolean(settingName, global.GetBoolean(settingName, defaultValue));
}
else
{
return global.GetBoolean(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private double ResolveDouble(string settingName, double defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetDouble(settingName, global.GetDouble(settingName, defaultValue));
}
else
{
return global.GetDouble(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private int ResolveInt(string settingName, int defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetInt(settingName, global.GetInt(settingName, defaultValue));
}
else
{
return global.GetInt(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private string ResolveString(string settingName, string defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetString(settingName, global.GetString(settingName, defaultValue));
}
else
{
return global.GetString(settingName, defaultValue);
}
}
/// <summary>
/// Called when any auto-backup timer expires. This starts the code path for actually performing a backup.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void HandleElapsed(object sender, ElapsedEventArgs e)
{
// TODO: heuristic thresholds are per-region, so we should probably run heuristics once per region
// XXX: Running heuristics once per region could add undue performance penalty for something that's supposed to
// check whether the region is too busy! Especially on sims with LOTS of regions.
// Alternative: make heuristics thresholds global to the module rather than per-region. Less flexible,
// but would allow us to be semantically correct while being easier on perf.
// Alternative 2: Run heuristics once per unique set of heuristics threshold parameters! Ay yi yi...
// Alternative 3: Don't support per-region heuristics at all; just accept them as a global only parameter.
// Since this is pretty experimental, I haven't decided which alternative makes the most sense.
if (this.m_closed)
{
return;
}
bool heuristicsRun = false;
bool heuristicsPassed = false;
if (!this.m_timerMap.ContainsKey((Timer) sender))
{
m_log.Debug("Code-up error: timerMap doesn't contain timer " + sender);
}
List<IScene> tmap = this.m_timerMap[(Timer) sender];
if (tmap != null && tmap.Count > 0)
{
foreach (IScene scene in tmap)
{
AutoBackupModuleState state = this.m_states[scene];
bool heuristics = state.BusyCheck;
// Fast path: heuristics are on; already ran em; and sim is fine; OR, no heuristics for the region.
if ((heuristics && heuristicsRun && heuristicsPassed) || !heuristics)
{
this.DoRegionBackup(scene);
// Heuristics are on; ran but we're too busy -- keep going. Maybe another region will have heuristics off!
}
else if (heuristicsRun)
{
m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
scene.RegionInfo.RegionName + " right now.");
continue;
// Logical Deduction: heuristics are on but haven't been run
}
else
{
heuristicsPassed = this.RunHeuristics(scene);
heuristicsRun = true;
if (!heuristicsPassed)
{
m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
scene.RegionInfo.RegionName + " right now.");
continue;
}
this.DoRegionBackup(scene);
}
}
}
}
/// <summary>
/// Save an OAR, register for the callback for when it's done, then call the AutoBackupScript (if applicable).
/// </summary>
/// <param name="scene"></param>
private void DoRegionBackup(IScene scene)
{
if (scene.RegionStatus != RegionStatus.Up)
{
// We won't backup a region that isn't operating normally.
m_log.Warn("[AUTO BACKUP]: Not backing up region " + scene.RegionInfo.RegionName +
" because its status is " + scene.RegionStatus);
return;
}
AutoBackupModuleState state = this.m_states[scene];
IRegionArchiverModule iram = scene.RequestModuleInterface<IRegionArchiverModule>();
string savePath = BuildOarPath(scene.RegionInfo.RegionName,
state.BackupDir,
state.NamingType);
if (savePath == null)
{
m_log.Warn("[AUTO BACKUP]: savePath is null in HandleElapsed");
return;
}
Guid guid = Guid.NewGuid();
m_pendingSaves.Add(guid, scene);
state.LiveRequests.Add(guid, savePath);
((Scene) scene).EventManager.OnOarFileSaved += new EventManager.OarFileSaved(EventManager_OnOarFileSaved);
iram.ArchiveRegion(savePath, guid, null);
}
/// <summary>
/// Called by the Event Manager when the OnOarFileSaved event is fired.
/// </summary>
/// <param name="guid"></param>
/// <param name="message"></param>
void EventManager_OnOarFileSaved(Guid guid, string message)
{
// Ignore if the OAR save is being done by some other part of the system
if (m_pendingSaves.ContainsKey(guid))
{
AutoBackupModuleState abms = m_states[(m_pendingSaves[guid])];
ExecuteScript(abms.Script, abms.LiveRequests[guid]);
m_pendingSaves.Remove(guid);
abms.LiveRequests.Remove(guid);
}
}
/// <summary>This format may turn out to be too unwieldy to keep...
/// Besides, that's what ctimes are for. But then how do I name each file uniquely without using a GUID?
/// Sequential numbers, right? We support those, too!</summary>
private static string GetTimeString()
{
StringWriter sw = new StringWriter();
sw.Write("_");
DateTime now = DateTime.Now;
sw.Write(now.Year);
sw.Write("y_");
sw.Write(now.Month);
sw.Write("M_");
sw.Write(now.Day);
sw.Write("d_");
sw.Write(now.Hour);
sw.Write("h_");
sw.Write(now.Minute);
sw.Write("m_");
sw.Write(now.Second);
sw.Write("s");
sw.Flush();
string output = sw.ToString();
sw.Close();
return output;
}
/// <summary>Return value of true ==> not too busy; false ==> too busy to backup an OAR right now, or error.</summary>
private bool RunHeuristics(IScene region)
{
try
{
return this.RunTimeDilationHeuristic(region) && this.RunAgentLimitHeuristic(region);
}
catch (Exception e)
{
m_log.Warn("[AUTO BACKUP]: Exception in RunHeuristics", e);
return false;
}
}
/// <summary>
/// If the time dilation right at this instant is less than the threshold specified in AutoBackupDilationThreshold (default 0.5),
/// then we return false and trip the busy heuristic's "too busy" path (i.e. don't save an OAR).
/// AutoBackupDilationThreshold is a _LOWER BOUND_. Lower Time Dilation is bad, so if you go lower than our threshold, it's "too busy".
/// </summary>
/// <param name="region"></param>
/// <returns>Returns true if we're not too busy; false means we've got worse time dilation than the threshold.</returns>
private bool RunTimeDilationHeuristic(IScene region)
{
string regionName = region.RegionInfo.RegionName;
return region.TimeDilation >=
this.m_configSource.Configs["AutoBackupModule"].GetFloat(
regionName + ".AutoBackupDilationThreshold", 0.5f);
}
/// <summary>
/// If the root agent count right at this instant is less than the threshold specified in AutoBackupAgentThreshold (default 10),
/// then we return false and trip the busy heuristic's "too busy" path (i.e., don't save an OAR).
/// AutoBackupAgentThreshold is an _UPPER BOUND_. Higher Agent Count is bad, so if you go higher than our threshold, it's "too busy".
/// </summary>
/// <param name="region"></param>
/// <returns>Returns true if we're not too busy; false means we've got more agents on the sim than the threshold.</returns>
private bool RunAgentLimitHeuristic(IScene region)
{
string regionName = region.RegionInfo.RegionName;
try
{
Scene scene = (Scene) region;
// TODO: Why isn't GetRootAgentCount() a method in the IScene interface? Seems generally useful...
return scene.GetRootAgentCount() <=
this.m_configSource.Configs["AutoBackupModule"].GetInt(
regionName + ".AutoBackupAgentThreshold", 10);
}
catch (InvalidCastException ice)
{
m_log.Debug(
"[AUTO BACKUP]: I NEED MAINTENANCE: IScene is not a Scene; can't get root agent count!",
ice);
return true;
// Non-obstructionist safest answer...
}
}
/// <summary>
/// Run the script or executable specified by the "AutoBackupScript" config setting.
/// Of course this is a security risk if you let anyone modify OpenSim.ini and they want to run some nasty bash script.
/// But there are plenty of other nasty things that can be done with an untrusted OpenSim.ini, such as running high threat level scripting functions.
/// </summary>
/// <param name="scriptName"></param>
/// <param name="savePath"></param>
private static void ExecuteScript(string scriptName, string savePath)
{
// Do nothing if there's no script.
if (scriptName == null || scriptName.Length <= 0)
{
return;
}
try
{
FileInfo fi = new FileInfo(scriptName);
if (fi.Exists)
{
ProcessStartInfo psi = new ProcessStartInfo(scriptName);
psi.Arguments = savePath;
psi.CreateNoWindow = true;
Process proc = Process.Start(psi);
proc.ErrorDataReceived += HandleProcErrorDataReceived;
}
}
catch (Exception e)
{
m_log.Warn(
"Exception encountered when trying to run script for oar backup " + savePath, e);
}
}
/// <summary>
/// Called if a running script process writes to stderr.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void HandleProcErrorDataReceived(object sender, DataReceivedEventArgs e)
{
m_log.Warn("ExecuteScript hook " + ((Process) sender).ProcessName +
" is yacking on stderr: " + e.Data);
}
/// <summary>
/// Quickly stop all timers from firing.
/// </summary>
private void StopAllTimers()
{
foreach (Timer t in this.m_timerMap.Keys)
{
t.Close();
}
this.m_closed = true;
}
/// <summary>
/// Determine the next unique filename by number, for "Sequential" AutoBackupNamingType.
/// </summary>
/// <param name="dirName"></param>
/// <param name="regionName"></param>
/// <returns></returns>
private static string GetNextFile(string dirName, string regionName)
{
FileInfo uniqueFile = null;
long biggestExistingFile = GetNextOarFileNumber(dirName, regionName);
biggestExistingFile++;
// We don't want to overwrite the biggest existing file; we want to write to the NEXT biggest.
uniqueFile =
new FileInfo(dirName + Path.DirectorySeparatorChar + regionName + "_" +
biggestExistingFile + ".oar");
return uniqueFile.FullName;
}
/// <summary>
/// Top-level method for creating an absolute path to an OAR backup file based on what naming scheme the user wants.
/// </summary>
/// <param name="regionName">Name of the region to save.</param>
/// <param name="baseDir">Absolute or relative path to the directory where the file should reside.</param>
/// <param name="naming">The naming scheme for the file name.</param>
/// <returns></returns>
private static string BuildOarPath(string regionName, string baseDir, NamingType naming)
{
FileInfo path = null;
switch (naming)
{
case NamingType.Overwrite:
path = new FileInfo(baseDir + Path.DirectorySeparatorChar + regionName + ".oar");
return path.FullName;
case NamingType.Time:
path =
new FileInfo(baseDir + Path.DirectorySeparatorChar + regionName +
GetTimeString() + ".oar");
return path.FullName;
case NamingType.Sequential:
// All codepaths in GetNextFile should return a file name ending in .oar
path = new FileInfo(GetNextFile(baseDir, regionName));
return path.FullName;
default:
m_log.Warn("VERY BAD: Unhandled case element " + naming);
break;
}
return null;
}
/// <summary>
/// Helper function for Sequential file naming type (see BuildOarPath and GetNextFile).
/// </summary>
/// <param name="dirName"></param>
/// <param name="regionName"></param>
/// <returns></returns>
private static long GetNextOarFileNumber(string dirName, string regionName)
{
long retval = 1;
DirectoryInfo di = new DirectoryInfo(dirName);
FileInfo[] fi = di.GetFiles(regionName, SearchOption.TopDirectoryOnly);
Array.Sort(fi, (f1, f2) => StringComparer.CurrentCultureIgnoreCase.Compare(f1.Name, f2.Name));
if (fi.LongLength > 0)
{
long subtract = 1L;
bool worked = false;
Regex reg = new Regex(regionName + "_([0-9])+" + ".oar");
while (!worked && subtract <= fi.LongLength)
{
// Pick the file with the last natural ordering
string biggestFileName = fi[fi.LongLength - subtract].Name;
MatchCollection matches = reg.Matches(biggestFileName);
long l = 1;
if (matches.Count > 0 && matches[0].Groups.Count > 0)
{
try
{
long.TryParse(matches[0].Groups[1].Value, out l);
retval = l;
worked = true;
}
catch (FormatException fe)
{
m_log.Warn(
"[AUTO BACKUP]: Error: Can't parse long value from file name to determine next OAR backup file number!",
fe);
subtract++;
}
}
else
{
subtract++;
}
}
}
return retval;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using Internal.Cryptography;
using Internal.NativeCrypto;
using Microsoft.Win32.SafeHandles;
using static Internal.NativeCrypto.CapiHelper;
namespace System.Security.Cryptography
{
public sealed partial class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm
{
private int _keySize;
private readonly CspParameters _parameters;
private readonly bool _randomKeyContainer;
private SafeKeyHandle _safeKeyHandle;
private SafeProvHandle _safeProvHandle;
private static volatile CspProviderFlags s_useMachineKeyStore = 0;
private bool _disposed;
public RSACryptoServiceProvider()
: this(0, new CspParameters(CapiHelper.DefaultRsaProviderType,
null,
null,
s_useMachineKeyStore),
true)
{
}
public RSACryptoServiceProvider(int dwKeySize)
: this(dwKeySize,
new CspParameters(CapiHelper.DefaultRsaProviderType,
null,
null,
s_useMachineKeyStore), false)
{
}
public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters)
: this(dwKeySize, parameters, false)
{
}
public RSACryptoServiceProvider(CspParameters parameters)
: this(0, parameters, true)
{
}
private RSACryptoServiceProvider(int keySize, CspParameters parameters, bool useDefaultKeySize)
{
if (keySize < 0)
{
throw new ArgumentOutOfRangeException("dwKeySize", "ArgumentOutOfRange_NeedNonNegNum");
}
_parameters = CapiHelper.SaveCspParameters(
CapiHelper.CspAlgorithmType.Rsa,
parameters,
s_useMachineKeyStore,
out _randomKeyContainer);
_keySize = useDefaultKeySize ? 1024 : keySize;
// If this is not a random container we generate, create it eagerly
// in the constructor so we can report any errors now.
if (!_randomKeyContainer)
{
// Force-read the SafeKeyHandle property, which will summon it into existence.
SafeKeyHandle localHandle = SafeKeyHandle;
Debug.Assert(localHandle != null);
}
}
private SafeProvHandle SafeProvHandle
{
get
{
if (_safeProvHandle == null)
{
lock (_parameters)
{
if (_safeProvHandle == null)
{
SafeProvHandle hProv = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer);
Debug.Assert(hProv != null);
Debug.Assert(!hProv.IsInvalid);
Debug.Assert(!hProv.IsClosed);
_safeProvHandle = hProv;
}
}
return _safeProvHandle;
}
return _safeProvHandle;
}
set
{
lock (_parameters)
{
SafeProvHandle current = _safeProvHandle;
if (ReferenceEquals(value, current))
{
return;
}
if (current != null)
{
SafeKeyHandle keyHandle = _safeKeyHandle;
_safeKeyHandle = null;
keyHandle?.Dispose();
current.Dispose();
}
_safeProvHandle = value;
}
}
}
private SafeKeyHandle SafeKeyHandle
{
get
{
if (_safeKeyHandle == null)
{
lock (_parameters)
{
if (_safeKeyHandle == null)
{
SafeKeyHandle hKey = CapiHelper.GetKeyPairHelper(
CapiHelper.CspAlgorithmType.Rsa,
_parameters,
_keySize,
SafeProvHandle);
Debug.Assert(hKey != null);
Debug.Assert(!hKey.IsInvalid);
Debug.Assert(!hKey.IsClosed);
_safeKeyHandle = hKey;
}
}
}
return _safeKeyHandle;
}
set
{
lock (_parameters)
{
SafeKeyHandle current = _safeKeyHandle;
if (ReferenceEquals(value, current))
{
return;
}
_safeKeyHandle = value;
current?.Dispose();
}
}
}
/// <summary>
/// CspKeyContainerInfo property
/// </summary>
public CspKeyContainerInfo CspKeyContainerInfo
{
get
{
// Desktop compat: Read the SafeKeyHandle property to force the key to load,
// because it might throw here.
SafeKeyHandle localHandle = SafeKeyHandle;
Debug.Assert(localHandle != null);
return new CspKeyContainerInfo(_parameters, _randomKeyContainer);
}
}
/// <summary>
/// _keySize property
/// </summary>
public override int KeySize
{
get
{
byte[] keySize = CapiHelper.GetKeyParameter(SafeKeyHandle, Constants.CLR_KEYLEN);
_keySize = (keySize[0] | (keySize[1] << 8) | (keySize[2] << 16) | (keySize[3] << 24));
return _keySize;
}
}
public override KeySizes[] LegalKeySizes
{
get
{
return new[] { new KeySizes(384, 16384, 8) };
}
}
/// <summary>
/// get set Persisted key in CSP
/// </summary>
public bool PersistKeyInCsp
{
get
{
return CapiHelper.GetPersistKeyInCsp(SafeProvHandle);
}
set
{
bool oldPersistKeyInCsp = this.PersistKeyInCsp;
if (value == oldPersistKeyInCsp)
{
return; // Do nothing
}
CapiHelper.SetPersistKeyInCsp(SafeProvHandle, value);
}
}
/// <summary>
/// Gets the information of key if it is a public key
/// </summary>
public bool PublicOnly
{
get
{
byte[] publicKey = CapiHelper.GetKeyParameter(SafeKeyHandle, Constants.CLR_PUBLICKEYONLY);
return (publicKey[0] == 1);
}
}
/// <summary>
/// MachineKey store properties
/// </summary>
public static bool UseMachineKeyStore
{
get
{
return (s_useMachineKeyStore == CspProviderFlags.UseMachineKeyStore);
}
set
{
s_useMachineKeyStore = (value ? CspProviderFlags.UseMachineKeyStore : 0);
}
}
/// <summary>
/// Decrypt raw data, generally used for decrypting symmetric key material
/// </summary>
/// <param name="rgb">encrypted data</param>
/// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param>
/// <returns>decrypted data</returns>
public byte[] Decrypt(byte[] rgb, bool fOAEP)
{
if (rgb == null)
{
throw new ArgumentNullException(nameof(rgb));
}
// Save the KeySize value to a local because it has non-trivial cost.
int keySize = KeySize;
// size check -- must be exactly the modulus size
if (rgb.Length != (keySize / 8))
{
throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize);
}
byte[] decryptedKey;
CapiHelper.DecryptKey(SafeKeyHandle, rgb, rgb.Length, fOAEP, out decryptedKey);
return decryptedKey;
}
/// <summary>
/// This method is not supported. Use Decrypt(byte[], RSAEncryptionPadding) instead.
/// </summary>
public override byte[] DecryptValue(byte[] rgb) => base.DecryptValue(rgb);
/// <summary>
/// Dispose the key handles
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
{
_safeKeyHandle.Dispose();
}
if (_safeProvHandle != null && !_safeProvHandle.IsClosed)
{
_safeProvHandle.Dispose();
}
_disposed = true;
}
}
/// <summary>
/// Encrypt raw data, generally used for encrypting symmetric key material.
/// </summary>
/// <remarks>
/// This method can only encrypt (keySize - 88 bits) of data, so should not be used for encrypting
/// arbitrary byte arrays. Instead, encrypt a symmetric key with this method, and use the symmetric
/// key to encrypt the sensitive data.
/// </remarks>
/// <param name="rgb">raw data to encrypt</param>
/// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param>
/// <returns>Encrypted key</returns>
public byte[] Encrypt(byte[] rgb, bool fOAEP)
{
if (rgb == null)
{
throw new ArgumentNullException(nameof(rgb));
}
if (fOAEP)
{
int rsaSize = (KeySize + 7) / 8;
const int OaepSha1Overhead = 20 + 20 + 2;
// Normalize the Windows 7 and Windows 8.1+ exception
if (rsaSize - OaepSha1Overhead < rgb.Length)
{
const int NTE_BAD_LENGTH = unchecked((int)0x80090004);
throw NTE_BAD_LENGTH.ToCryptographicException();
}
}
byte[] encryptedKey = null;
CapiHelper.EncryptKey(SafeKeyHandle, rgb, rgb.Length, fOAEP, ref encryptedKey);
return encryptedKey;
}
/// <summary>
/// This method is not supported. Use Encrypt(byte[], RSAEncryptionPadding) instead.
/// </summary>
public override byte[] EncryptValue(byte[] rgb) => base.EncryptValue(rgb);
/// <summary>
///Exports a blob containing the key information associated with an RSACryptoServiceProvider object.
/// </summary>
public byte[] ExportCspBlob(bool includePrivateParameters)
{
return CapiHelper.ExportKeyBlob(includePrivateParameters, SafeKeyHandle);
}
/// <summary>
/// Exports the RSAParameters
/// </summary>
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
byte[] cspBlob = ExportCspBlob(includePrivateParameters);
return cspBlob.ToRSAParameters(includePrivateParameters);
}
/// <summary>
/// This method helps Acquire the default CSP and avoids the need for static SafeProvHandle
/// in CapiHelper class
/// </summary>
private SafeProvHandle AcquireSafeProviderHandle()
{
SafeProvHandle safeProvHandle;
CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultRsaProviderType), out safeProvHandle);
return safeProvHandle;
}
/// <summary>
/// Imports a blob that represents RSA key information
/// </summary>
/// <param name="keyBlob"></param>
public void ImportCspBlob(byte[] keyBlob)
{
ThrowIfDisposed();
SafeKeyHandle safeKeyHandle;
if (IsPublic(keyBlob))
{
SafeProvHandle safeProvHandleTemp = AcquireSafeProviderHandle();
CapiHelper.ImportKeyBlob(safeProvHandleTemp, (CspProviderFlags)0, false, keyBlob, out safeKeyHandle);
// The property set will take care of releasing any already-existing resources.
SafeProvHandle = safeProvHandleTemp;
}
else
{
CapiHelper.ImportKeyBlob(SafeProvHandle, _parameters.Flags, false, keyBlob, out safeKeyHandle);
}
// The property set will take care of releasing any already-existing resources.
SafeKeyHandle = safeKeyHandle;
}
/// <summary>
/// Imports the specified RSAParameters
/// </summary>
public override void ImportParameters(RSAParameters parameters)
{
byte[] keyBlob = parameters.ToKeyBlob();
ImportCspBlob(keyBlob);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the
/// specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="buffer">The input data for which to compute the hash</param>
/// <param name="offset">The offset into the array from which to begin using data</param>
/// <param name="count">The number of bytes in the array to use as data. </param>
/// <param name="halg">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
public byte[] SignData(byte[] buffer, int offset, int count, object halg)
{
int calgHash = CapiHelper.ObjToHashAlgId(halg);
HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(buffer, offset, count);
return SignHash(hashVal, calgHash);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the
/// specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="buffer">The input data for which to compute the hash</param>
/// <param name="halg">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
public byte[] SignData(byte[] buffer, object halg)
{
int calgHash = CapiHelper.ObjToHashAlgId(halg);
HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(buffer);
return SignHash(hashVal, calgHash);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the
/// specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="inputStream">The input data for which to compute the hash</param>
/// <param name="halg">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
public byte[] SignData(Stream inputStream, object halg)
{
int calgHash = CapiHelper.ObjToHashAlgId(halg);
HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(inputStream);
return SignHash(hashVal, calgHash);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the
/// specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="rgbHash">The input data for which to compute the hash</param>
/// <param name="str">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
public byte[] SignHash(byte[] rgbHash, string str)
{
if (rgbHash == null)
throw new ArgumentNullException(nameof(rgbHash));
if (PublicOnly)
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm);
return SignHash(rgbHash, calgHash);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the
/// specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="rgbHash">The input data for which to compute the hash</param>
/// <param name="calgHash">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
private byte[] SignHash(byte[] rgbHash, int calgHash)
{
Debug.Assert(rgbHash != null);
return CapiHelper.SignValue(
SafeProvHandle,
SafeKeyHandle,
_parameters.KeyNumber,
CapiHelper.CALG_RSA_SIGN,
calgHash,
rgbHash);
}
/// <summary>
/// Verifies the signature of a hash value.
/// </summary>
public bool VerifyData(byte[] buffer, object halg, byte[] signature)
{
int calgHash = CapiHelper.ObjToHashAlgId(halg);
HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(buffer);
return VerifyHash(hashVal, calgHash, signature);
}
/// <summary>
/// Verifies the signature of a hash value.
/// </summary>
public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature)
{
if (rgbHash == null)
throw new ArgumentNullException(nameof(rgbHash));
if (rgbSignature == null)
throw new ArgumentNullException(nameof(rgbSignature));
int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm);
return VerifyHash(rgbHash, calgHash, rgbSignature);
}
/// <summary>
/// Verifies the signature of a hash value.
/// </summary>
private bool VerifyHash(byte[] rgbHash, int calgHash, byte[] rgbSignature)
{
return CapiHelper.VerifySign(
SafeProvHandle,
SafeKeyHandle,
CapiHelper.CALG_RSA_SIGN,
calgHash,
rgbHash,
rgbSignature);
}
/// <summary>
/// find whether an RSA key blob is public.
/// </summary>
private static bool IsPublic(byte[] keyBlob)
{
if (keyBlob == null)
{
throw new ArgumentNullException(nameof(keyBlob));
}
// The CAPI RSA public key representation consists of the following sequence:
// - BLOBHEADER
// - RSAPUBKEY
// The first should be PUBLICKEYBLOB and magic should be RSA_PUB_MAGIC "RSA1"
if (keyBlob[0] != CapiHelper.PUBLICKEYBLOB)
{
return false;
}
if (keyBlob[11] != 0x31 || keyBlob[10] != 0x41 || keyBlob[9] != 0x53 || keyBlob[8] != 0x52)
{
return false;
}
return true;
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
// we're sealed and the base should have checked this already
Debug.Assert(data != null);
Debug.Assert(count >= 0 && count <= data.Length);
Debug.Assert(offset >= 0 && offset <= data.Length - count);
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm))
{
return hash.ComputeHash(data, offset, count);
}
}
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
// we're sealed and the base should have checked this already
Debug.Assert(data != null);
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm))
{
return hash.ComputeHash(data);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "MD5 is used when the user asks for it.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 is used when the user asks for it.")]
private static HashAlgorithm GetHashAlgorithm(HashAlgorithmName hashAlgorithm) =>
hashAlgorithm.Name switch
{
"MD5" => MD5.Create(),
"SHA1" => SHA1.Create(),
"SHA256" => SHA256.Create(),
"SHA384" => SHA384.Create(),
"SHA512" => SHA512.Create(),
_ => throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name),
};
private static int GetAlgorithmId(HashAlgorithmName hashAlgorithm) =>
hashAlgorithm.Name switch
{
"MD5" => CapiHelper.CALG_MD5,
"SHA1" => CapiHelper.CALG_SHA1,
"SHA256" => CapiHelper.CALG_SHA_256,
"SHA384" => CapiHelper.CALG_SHA_384,
"SHA512" => CapiHelper.CALG_SHA_512,
_ => throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name),
};
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (padding == null)
throw new ArgumentNullException(nameof(padding));
if (padding == RSAEncryptionPadding.Pkcs1)
{
return Encrypt(data, fOAEP: false);
}
else if (padding == RSAEncryptionPadding.OaepSHA1)
{
return Encrypt(data, fOAEP: true);
}
else
{
throw PaddingModeNotSupported();
}
}
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (padding == null)
throw new ArgumentNullException(nameof(padding));
if (padding == RSAEncryptionPadding.Pkcs1)
{
return Decrypt(data, fOAEP: false);
}
else if (padding == RSAEncryptionPadding.OaepSHA1)
{
return Decrypt(data, fOAEP: true);
}
else
{
throw PaddingModeNotSupported();
}
}
public override byte[] SignHash(
byte[] hash,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException(nameof(padding));
if (padding != RSASignaturePadding.Pkcs1)
throw PaddingModeNotSupported();
return SignHash(hash, GetAlgorithmId(hashAlgorithm));
}
public override bool VerifyHash(
byte[] hash,
byte[] signature,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
if (signature == null)
throw new ArgumentNullException(nameof(signature));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException(nameof(padding));
if (padding != RSASignaturePadding.Pkcs1)
throw PaddingModeNotSupported();
return VerifyHash(hash, GetAlgorithmId(hashAlgorithm), signature);
}
public override string KeyExchangeAlgorithm
{
get
{
if (_parameters.KeyNumber == (int)Interop.Advapi32.KeySpec.AT_KEYEXCHANGE)
{
return "RSA-PKCS1-KeyEx";
}
return null;
}
}
public override string SignatureAlgorithm
{
get
{
return "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
}
}
private static Exception PaddingModeNotSupported()
{
return new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
private static Exception HashAlgorithmNameNullOrEmpty()
{
return new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm");
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(DSACryptoServiceProvider));
}
}
}
}
| |
using Neo.Cryptography;
using Neo.Cryptography.ECC;
using Neo.IO;
using Neo.Ledger;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.SmartContract.Manifest;
using Neo.VM;
using Neo.VM.Types;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using Array = Neo.VM.Types.Array;
using Boolean = Neo.VM.Types.Boolean;
namespace Neo.SmartContract
{
public static partial class InteropService
{
public const long GasPerByte = 100000;
public const int MaxStorageKeySize = 64;
public const int MaxStorageValueSize = ushort.MaxValue;
public const int MaxNotificationSize = 1024;
private static readonly Dictionary<uint, InteropDescriptor> methods = new Dictionary<uint, InteropDescriptor>();
public static readonly uint System_ExecutionEngine_GetScriptContainer = Register("System.ExecutionEngine.GetScriptContainer", ExecutionEngine_GetScriptContainer, 0_00000250, TriggerType.All);
public static readonly uint System_ExecutionEngine_GetExecutingScriptHash = Register("System.ExecutionEngine.GetExecutingScriptHash", ExecutionEngine_GetExecutingScriptHash, 0_00000400, TriggerType.All);
public static readonly uint System_ExecutionEngine_GetCallingScriptHash = Register("System.ExecutionEngine.GetCallingScriptHash", ExecutionEngine_GetCallingScriptHash, 0_00000400, TriggerType.All);
public static readonly uint System_ExecutionEngine_GetEntryScriptHash = Register("System.ExecutionEngine.GetEntryScriptHash", ExecutionEngine_GetEntryScriptHash, 0_00000400, TriggerType.All);
public static readonly uint System_Runtime_Platform = Register("System.Runtime.Platform", Runtime_Platform, 0_00000250, TriggerType.All);
public static readonly uint System_Runtime_GetTrigger = Register("System.Runtime.GetTrigger", Runtime_GetTrigger, 0_00000250, TriggerType.All);
public static readonly uint System_Runtime_CheckWitness = Register("System.Runtime.CheckWitness", Runtime_CheckWitness, 0_00030000, TriggerType.All);
public static readonly uint System_Runtime_Notify = Register("System.Runtime.Notify", Runtime_Notify, 0_01000000, TriggerType.All);
public static readonly uint System_Runtime_Log = Register("System.Runtime.Log", Runtime_Log, 0_01000000, TriggerType.All);
public static readonly uint System_Runtime_GetTime = Register("System.Runtime.GetTime", Runtime_GetTime, 0_00000250, TriggerType.Application);
public static readonly uint System_Runtime_Serialize = Register("System.Runtime.Serialize", Runtime_Serialize, 0_00100000, TriggerType.All);
public static readonly uint System_Runtime_Deserialize = Register("System.Runtime.Deserialize", Runtime_Deserialize, 0_00500000, TriggerType.All);
public static readonly uint System_Runtime_GetInvocationCounter = Register("System.Runtime.GetInvocationCounter", Runtime_GetInvocationCounter, 0_00000400, TriggerType.All);
public static readonly uint System_Runtime_GetNotifications = Register("System.Runtime.GetNotifications", Runtime_GetNotifications, 0_00010000, TriggerType.All);
public static readonly uint System_Blockchain_GetHeight = Register("System.Blockchain.GetHeight", Blockchain_GetHeight, 0_00000400, TriggerType.Application);
public static readonly uint System_Blockchain_GetBlock = Register("System.Blockchain.GetBlock", Blockchain_GetBlock, 0_02500000, TriggerType.Application);
public static readonly uint System_Blockchain_GetTransaction = Register("System.Blockchain.GetTransaction", Blockchain_GetTransaction, 0_01000000, TriggerType.Application);
public static readonly uint System_Blockchain_GetTransactionHeight = Register("System.Blockchain.GetTransactionHeight", Blockchain_GetTransactionHeight, 0_01000000, TriggerType.Application);
public static readonly uint System_Blockchain_GetTransactionFromBlock = Register("System.Blockchain.GetTransactionFromBlock", Blockchain_GetTransactionFromBlock, 0_01000000, TriggerType.Application);
public static readonly uint System_Blockchain_GetContract = Register("System.Blockchain.GetContract", Blockchain_GetContract, 0_01000000, TriggerType.Application);
public static readonly uint System_Contract_Call = Register("System.Contract.Call", Contract_Call, 0_01000000, TriggerType.System | TriggerType.Application);
public static readonly uint System_Contract_Destroy = Register("System.Contract.Destroy", Contract_Destroy, 0_01000000, TriggerType.Application);
public static readonly uint System_Storage_GetContext = Register("System.Storage.GetContext", Storage_GetContext, 0_00000400, TriggerType.Application);
public static readonly uint System_Storage_GetReadOnlyContext = Register("System.Storage.GetReadOnlyContext", Storage_GetReadOnlyContext, 0_00000400, TriggerType.Application);
public static readonly uint System_Storage_Get = Register("System.Storage.Get", Storage_Get, 0_01000000, TriggerType.Application);
public static readonly uint System_Storage_Put = Register("System.Storage.Put", Storage_Put, GetStoragePrice, TriggerType.Application);
public static readonly uint System_Storage_PutEx = Register("System.Storage.PutEx", Storage_PutEx, GetStoragePrice, TriggerType.Application);
public static readonly uint System_Storage_Delete = Register("System.Storage.Delete", Storage_Delete, 0_01000000, TriggerType.Application);
public static readonly uint System_StorageContext_AsReadOnly = Register("System.StorageContext.AsReadOnly", StorageContext_AsReadOnly, 0_00000400, TriggerType.Application);
private static bool CheckItemForNotification(StackItem state)
{
int size = 0;
List<StackItem> items_checked = new List<StackItem>();
Queue<StackItem> items_unchecked = new Queue<StackItem>();
while (true)
{
switch (state)
{
case Struct array:
foreach (StackItem item in array)
items_unchecked.Enqueue(item);
break;
case Array array:
if (items_checked.All(p => !ReferenceEquals(p, array)))
{
items_checked.Add(array);
foreach (StackItem item in array)
items_unchecked.Enqueue(item);
}
break;
case Boolean _:
case ByteArray _:
case Integer _:
size += state.GetByteLength();
break;
case Null _:
break;
case InteropInterface _:
return false;
case Map map:
if (items_checked.All(p => !ReferenceEquals(p, map)))
{
items_checked.Add(map);
foreach (var pair in map)
{
size += pair.Key.GetByteLength();
items_unchecked.Enqueue(pair.Value);
}
}
break;
}
if (size > MaxNotificationSize) return false;
if (items_unchecked.Count == 0) return true;
state = items_unchecked.Dequeue();
}
}
private static bool CheckStorageContext(ApplicationEngine engine, StorageContext context)
{
ContractState contract = engine.Snapshot.Contracts.TryGet(context.ScriptHash);
if (contract == null) return false;
if (!contract.HasStorage) return false;
return true;
}
public static long GetPrice(uint hash, RandomAccessStack<StackItem> stack)
{
return methods[hash].GetPrice(stack);
}
public static Dictionary<uint, string> SupportedMethods()
{
return methods.ToDictionary(p => p.Key, p => p.Value.Method);
}
private static long GetStoragePrice(RandomAccessStack<StackItem> stack)
{
return (stack.Peek(1).GetByteLength() + stack.Peek(2).GetByteLength()) * GasPerByte;
}
internal static bool Invoke(ApplicationEngine engine, uint method)
{
if (!methods.TryGetValue(method, out InteropDescriptor descriptor))
return false;
if (!descriptor.AllowedTriggers.HasFlag(engine.Trigger))
return false;
return descriptor.Handler(engine);
}
private static uint Register(string method, Func<ApplicationEngine, bool> handler, long price, TriggerType allowedTriggers)
{
InteropDescriptor descriptor = new InteropDescriptor(method, handler, price, allowedTriggers);
methods.Add(descriptor.Hash, descriptor);
return descriptor.Hash;
}
private static uint Register(string method, Func<ApplicationEngine, bool> handler, Func<RandomAccessStack<StackItem>, long> priceCalculator, TriggerType allowedTriggers)
{
InteropDescriptor descriptor = new InteropDescriptor(method, handler, priceCalculator, allowedTriggers);
methods.Add(descriptor.Hash, descriptor);
return descriptor.Hash;
}
private static bool ExecutionEngine_GetScriptContainer(ApplicationEngine engine)
{
engine.CurrentContext.EvaluationStack.Push(
engine.ScriptContainer is IInteroperable value ? value.ToStackItem() :
StackItem.FromInterface(engine.ScriptContainer));
return true;
}
private static bool ExecutionEngine_GetExecutingScriptHash(ApplicationEngine engine)
{
engine.CurrentContext.EvaluationStack.Push(engine.CurrentScriptHash.ToArray());
return true;
}
private static bool ExecutionEngine_GetCallingScriptHash(ApplicationEngine engine)
{
engine.CurrentContext.EvaluationStack.Push(engine.CallingScriptHash?.ToArray() ?? StackItem.Null);
return true;
}
private static bool ExecutionEngine_GetEntryScriptHash(ApplicationEngine engine)
{
engine.CurrentContext.EvaluationStack.Push(engine.EntryScriptHash.ToArray());
return true;
}
private static bool Runtime_Platform(ApplicationEngine engine)
{
engine.CurrentContext.EvaluationStack.Push(Encoding.ASCII.GetBytes("NEO"));
return true;
}
private static bool Runtime_GetTrigger(ApplicationEngine engine)
{
engine.CurrentContext.EvaluationStack.Push((int)engine.Trigger);
return true;
}
internal static bool CheckWitness(ApplicationEngine engine, UInt160 hash)
{
if (engine.ScriptContainer is Transaction tx)
{
Cosigner usage = tx.Cosigners.FirstOrDefault(p => p.Account.Equals(hash));
if (usage is null) return false;
if (usage.Scopes == WitnessScope.Global) return true;
if (usage.Scopes.HasFlag(WitnessScope.CalledByEntry))
{
if (engine.CallingScriptHash == engine.EntryScriptHash)
return true;
}
if (usage.Scopes.HasFlag(WitnessScope.CustomContracts))
{
if (usage.AllowedContracts.Contains(engine.CurrentScriptHash))
return true;
}
if (usage.Scopes.HasFlag(WitnessScope.CustomGroups))
{
var contract = engine.Snapshot.Contracts[engine.CallingScriptHash];
// check if current group is the required one
if (contract.Manifest.Groups.Select(p => p.PubKey).Intersect(usage.AllowedGroups).Any())
return true;
}
return false;
}
// only for non-Transaction types (Block, etc)
var hashes_for_verifying = engine.ScriptContainer.GetScriptHashesForVerifying(engine.Snapshot);
return hashes_for_verifying.Contains(hash);
}
private static bool CheckWitness(ApplicationEngine engine, ECPoint pubkey)
{
return CheckWitness(engine, Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash());
}
private static bool Runtime_CheckWitness(ApplicationEngine engine)
{
byte[] hashOrPubkey = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray();
bool result;
if (hashOrPubkey.Length == 20)
result = CheckWitness(engine, new UInt160(hashOrPubkey));
else if (hashOrPubkey.Length == 33)
result = CheckWitness(engine, ECPoint.DecodePoint(hashOrPubkey, ECCurve.Secp256r1));
else
return false;
engine.CurrentContext.EvaluationStack.Push(result);
return true;
}
private static bool Runtime_Notify(ApplicationEngine engine)
{
StackItem state = engine.CurrentContext.EvaluationStack.Pop();
if (!CheckItemForNotification(state)) return false;
engine.SendNotification(engine.CurrentScriptHash, state);
return true;
}
private static bool Runtime_Log(ApplicationEngine engine)
{
byte[] state = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray();
if (state.Length > MaxNotificationSize) return false;
string message = Encoding.UTF8.GetString(state);
engine.SendLog(engine.CurrentScriptHash, message);
return true;
}
private static bool Runtime_GetTime(ApplicationEngine engine)
{
engine.CurrentContext.EvaluationStack.Push(engine.Snapshot.PersistingBlock.Timestamp);
return true;
}
private static bool Runtime_Serialize(ApplicationEngine engine)
{
byte[] serialized;
try
{
serialized = engine.CurrentContext.EvaluationStack.Pop().Serialize();
}
catch (NotSupportedException)
{
return false;
}
if (serialized.Length > engine.MaxItemSize)
return false;
engine.CurrentContext.EvaluationStack.Push(serialized);
return true;
}
private static bool Runtime_GetNotifications(ApplicationEngine engine)
{
StackItem item = engine.CurrentContext.EvaluationStack.Pop();
IEnumerable<NotifyEventArgs> notifications = engine.Notifications;
if (!item.IsNull) // must filter by scriptHash
{
var hash = new UInt160(item.GetSpan().ToArray());
notifications = notifications.Where(p => p.ScriptHash == hash);
}
if (!engine.CheckArraySize(notifications.Count())) return false;
engine.CurrentContext.EvaluationStack.Push(notifications.Select(u => new VM.Types.Array(new StackItem[] { u.ScriptHash.ToArray(), u.State })).ToArray());
return true;
}
private static bool Runtime_GetInvocationCounter(ApplicationEngine engine)
{
if (!engine.InvocationCounter.TryGetValue(engine.CurrentScriptHash, out var counter))
{
return false;
}
engine.CurrentContext.EvaluationStack.Push(counter);
return true;
}
private static bool Runtime_Deserialize(ApplicationEngine engine)
{
StackItem item;
try
{
item = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray().DeserializeStackItem(engine.MaxArraySize, engine.MaxItemSize);
}
catch (FormatException)
{
return false;
}
catch (IOException)
{
return false;
}
engine.CurrentContext.EvaluationStack.Push(item);
return true;
}
private static bool Blockchain_GetHeight(ApplicationEngine engine)
{
engine.CurrentContext.EvaluationStack.Push(engine.Snapshot.Height);
return true;
}
private static bool Blockchain_GetBlock(ApplicationEngine engine)
{
byte[] data = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray();
UInt256 hash;
if (data.Length <= 5)
hash = Blockchain.Singleton.GetBlockHash((uint)new BigInteger(data));
else if (data.Length == 32)
hash = new UInt256(data);
else
return false;
Block block = hash != null ? engine.Snapshot.GetBlock(hash) : null;
if (block == null)
engine.CurrentContext.EvaluationStack.Push(StackItem.Null);
else
engine.CurrentContext.EvaluationStack.Push(block.ToStackItem());
return true;
}
private static bool Blockchain_GetTransaction(ApplicationEngine engine)
{
byte[] hash = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray();
Transaction tx = engine.Snapshot.GetTransaction(new UInt256(hash));
if (tx == null)
engine.CurrentContext.EvaluationStack.Push(StackItem.Null);
else
engine.CurrentContext.EvaluationStack.Push(tx.ToStackItem());
return true;
}
private static bool Blockchain_GetTransactionHeight(ApplicationEngine engine)
{
byte[] hash = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray();
var tx = engine.Snapshot.Transactions.TryGet(new UInt256(hash));
engine.CurrentContext.EvaluationStack.Push(tx != null ? new BigInteger(tx.BlockIndex) : BigInteger.MinusOne);
return true;
}
private static bool Blockchain_GetTransactionFromBlock(ApplicationEngine engine)
{
byte[] data = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray();
UInt256 hash;
if (data.Length <= 5)
hash = Blockchain.Singleton.GetBlockHash((uint)new BigInteger(data));
else if (data.Length == 32)
hash = new UInt256(data);
else
return false;
TrimmedBlock block = hash != null ? engine.Snapshot.Blocks.TryGet(hash) : null;
if (block == null)
{
engine.CurrentContext.EvaluationStack.Push(StackItem.Null);
}
else
{
int index = (int)engine.CurrentContext.EvaluationStack.Pop().GetBigInteger();
if (index < 0 || index >= block.Hashes.Length - 1) return false;
Transaction tx = engine.Snapshot.GetTransaction(block.Hashes[index + 1]);
if (tx == null)
engine.CurrentContext.EvaluationStack.Push(StackItem.Null);
else
engine.CurrentContext.EvaluationStack.Push(tx.ToStackItem());
}
return true;
}
private static bool Blockchain_GetContract(ApplicationEngine engine)
{
UInt160 hash = new UInt160(engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray());
ContractState contract = engine.Snapshot.Contracts.TryGet(hash);
if (contract == null)
engine.CurrentContext.EvaluationStack.Push(StackItem.Null);
else
engine.CurrentContext.EvaluationStack.Push(contract.ToStackItem());
return true;
}
private static bool Storage_GetContext(ApplicationEngine engine)
{
engine.CurrentContext.EvaluationStack.Push(StackItem.FromInterface(new StorageContext
{
ScriptHash = engine.CurrentScriptHash,
IsReadOnly = false
}));
return true;
}
private static bool Storage_GetReadOnlyContext(ApplicationEngine engine)
{
engine.CurrentContext.EvaluationStack.Push(StackItem.FromInterface(new StorageContext
{
ScriptHash = engine.CurrentScriptHash,
IsReadOnly = true
}));
return true;
}
private static bool Storage_Get(ApplicationEngine engine)
{
if (engine.CurrentContext.EvaluationStack.Pop() is InteropInterface _interface)
{
StorageContext context = _interface.GetInterface<StorageContext>();
if (!CheckStorageContext(engine, context)) return false;
byte[] key = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray();
StorageItem item = engine.Snapshot.Storages.TryGet(new StorageKey
{
ScriptHash = context.ScriptHash,
Key = key
});
engine.CurrentContext.EvaluationStack.Push(item?.Value ?? StackItem.Null);
return true;
}
return false;
}
private static bool StorageContext_AsReadOnly(ApplicationEngine engine)
{
if (engine.CurrentContext.EvaluationStack.Pop() is InteropInterface _interface)
{
StorageContext context = _interface.GetInterface<StorageContext>();
if (!context.IsReadOnly)
context = new StorageContext
{
ScriptHash = context.ScriptHash,
IsReadOnly = true
};
engine.CurrentContext.EvaluationStack.Push(StackItem.FromInterface(context));
return true;
}
return false;
}
private static bool Contract_Call(ApplicationEngine engine)
{
StackItem contractHash = engine.CurrentContext.EvaluationStack.Pop();
ContractState contract = engine.Snapshot.Contracts.TryGet(new UInt160(contractHash.GetSpan().ToArray()));
if (contract is null) return false;
StackItem method = engine.CurrentContext.EvaluationStack.Pop();
StackItem args = engine.CurrentContext.EvaluationStack.Pop();
ContractManifest currentManifest = engine.Snapshot.Contracts.TryGet(engine.CurrentScriptHash)?.Manifest;
if (currentManifest != null && !currentManifest.CanCall(contract.Manifest, method.GetString()))
return false;
if (engine.InvocationCounter.TryGetValue(contract.ScriptHash, out var counter))
{
engine.InvocationCounter[contract.ScriptHash] = counter + 1;
}
else
{
engine.InvocationCounter[contract.ScriptHash] = 1;
}
ExecutionContext context_new = engine.LoadScript(contract.Script, 1);
context_new.EvaluationStack.Push(args);
context_new.EvaluationStack.Push(method);
return true;
}
private static bool Contract_Destroy(ApplicationEngine engine)
{
UInt160 hash = engine.CurrentScriptHash;
ContractState contract = engine.Snapshot.Contracts.TryGet(hash);
if (contract == null) return true;
engine.Snapshot.Contracts.Delete(hash);
if (contract.HasStorage)
foreach (var pair in engine.Snapshot.Storages.Find(hash.ToArray()))
engine.Snapshot.Storages.Delete(pair.Key);
return true;
}
private static bool PutEx(ApplicationEngine engine, StorageContext context, byte[] key, byte[] value, StorageFlags flags)
{
if (key.Length > MaxStorageKeySize) return false;
if (value.Length > MaxStorageValueSize) return false;
if (context.IsReadOnly) return false;
if (!CheckStorageContext(engine, context)) return false;
StorageKey skey = new StorageKey
{
ScriptHash = context.ScriptHash,
Key = key
};
if (engine.Snapshot.Storages.TryGet(skey)?.IsConstant == true) return false;
if (value.Length == 0 && !flags.HasFlag(StorageFlags.Constant))
{
// If put 'value' is empty (and non-const), we remove it (implicit `Storage.Delete`)
engine.Snapshot.Storages.Delete(skey);
}
else
{
StorageItem item = engine.Snapshot.Storages.GetAndChange(skey, () => new StorageItem());
item.Value = value;
item.IsConstant = flags.HasFlag(StorageFlags.Constant);
}
return true;
}
private static bool Storage_Put(ApplicationEngine engine)
{
if (!(engine.CurrentContext.EvaluationStack.Pop() is InteropInterface _interface))
return false;
StorageContext context = _interface.GetInterface<StorageContext>();
byte[] key = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray();
byte[] value = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray();
return PutEx(engine, context, key, value, StorageFlags.None);
}
private static bool Storage_PutEx(ApplicationEngine engine)
{
if (!(engine.CurrentContext.EvaluationStack.Pop() is InteropInterface _interface))
return false;
StorageContext context = _interface.GetInterface<StorageContext>();
byte[] key = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray();
byte[] value = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray();
StorageFlags flags = (StorageFlags)(byte)engine.CurrentContext.EvaluationStack.Pop().GetBigInteger();
return PutEx(engine, context, key, value, flags);
}
private static bool Storage_Delete(ApplicationEngine engine)
{
if (engine.CurrentContext.EvaluationStack.Pop() is InteropInterface _interface)
{
StorageContext context = _interface.GetInterface<StorageContext>();
if (context.IsReadOnly) return false;
if (!CheckStorageContext(engine, context)) return false;
StorageKey key = new StorageKey
{
ScriptHash = context.ScriptHash,
Key = engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray()
};
if (engine.Snapshot.Storages.TryGet(key)?.IsConstant == true) return false;
engine.Snapshot.Storages.Delete(key);
return true;
}
return false;
}
}
}
| |
// GzipInputStream.cs
//
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.IO;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Silverlight.Checksums;
using ICSharpCode.SharpZipLib.Silverlight.Zip.Compression;
using ICSharpCode.SharpZipLib.Silverlight.Zip.Compression.Streams;
namespace ICSharpCode.SharpZipLib.Silverlight.GZip
{
/// <summary>
/// This filter stream is used to decompress a "GZIP" format stream.
/// The "GZIP" format is described baseInputStream RFC 1952.
///
/// author of the original java version : John Leuner
/// </summary>
/// <example> This sample shows how to unzip a gzipped file
/// <code>
/// using System;
/// using System.IO;
///
/// using ICSharpCode.SharpZipLib.Core;
/// using ICSharpCode.SharpZipLib.GZip;
///
/// class MainClass
/// {
/// public static void Main(string[] args)
/// {
/// using (Stream inStream = new GZipInputStream(File.OpenRead(args[0])))
/// using (FileStream outStream = File.Create(Path.GetFileNameWithoutExtension(args[0]))) {
/// byte[] buffer = new byte[4096];
/// StreamUtils.Copy(inStream, outStream, buffer);
/// }
/// }
/// }
/// </code>
/// </example>
public class GZipInputStream : InflaterInputStream
{
#region Instance Fields
/// <summary>
/// CRC-32 value for uncompressed data
/// </summary>
protected Crc32 crc = new Crc32();
/// <summary>
/// Indicates end of stream
/// </summary>
protected bool eos;
// Have we read the GZIP header yet?
private bool readGZIPHeader;
#endregion
#region Constructors
/// <summary>
/// Creates a GZipInputStream with the default buffer size
/// </summary>
/// <param name="baseInputStream">
/// The stream to read compressed data from (baseInputStream GZIP format)
/// </param>
public GZipInputStream(Stream baseInputStream)
: this(baseInputStream, 4096)
{
}
/// <summary>
/// Creates a GZIPInputStream with the specified buffer size
/// </summary>
/// <param name="baseInputStream">
/// The stream to read compressed data from (baseInputStream GZIP format)
/// </param>
/// <param name="size">
/// Size of the buffer to use
/// </param>
public GZipInputStream(Stream baseInputStream, int size)
: base(baseInputStream, new Inflater(true), size)
{
}
#endregion
#region Stream overrides
/// <summary>
/// Reads uncompressed data into an array of bytes
/// </summary>
/// <param name="buffer">
/// The buffer to read uncompressed data into
/// </param>
/// <param name="offset">
/// The offset indicating where the data should be placed
/// </param>
/// <param name="count">
/// The number of uncompressed bytes to be read
/// </param>
/// <returns>Returns the number of bytes actually read.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
// We first have to read the GZIP header, then we feed all the
// rest of the data to the base class.
//
// As we do that we continually update the CRC32. Once the data is
// finished, we check the CRC32
//
// This means we don't need our own buffer, as everything is done
// in baseInputStream the superclass.
if (!readGZIPHeader)
{
ReadHeader();
}
if (eos)
{
return 0;
}
// We don't have to read the header, so we just grab data from the superclass
var bytesRead = base.Read(buffer, offset, count);
if (bytesRead > 0)
{
crc.Update(buffer, offset, bytesRead);
}
if (inf.IsFinished)
{
ReadFooter();
}
return bytesRead;
}
#endregion
#region Support routines
private void ReadHeader()
{
// 1. Check the two magic bytes
var headCRC = new Crc32();
var magic = baseInputStream.ReadByte();
if (magic < 0)
{
throw new EndOfStreamException("EOS reading GZIP header");
}
headCRC.Update(magic);
if (magic != (GZipConstants.GZIP_MAGIC >> 8))
{
throw new GZipException("Error GZIP header, first magic byte doesn't match");
}
magic = baseInputStream.ReadByte();
if (magic < 0)
{
throw new EndOfStreamException("EOS reading GZIP header");
}
if (magic != (GZipConstants.GZIP_MAGIC & 0xFF))
{
throw new GZipException("Error GZIP header, second magic byte doesn't match");
}
headCRC.Update(magic);
// 2. Check the compression type (must be 8)
var compressionType = baseInputStream.ReadByte();
if (compressionType < 0)
{
throw new EndOfStreamException("EOS reading GZIP header");
}
if (compressionType != 8)
{
throw new GZipException("Error GZIP header, data not in deflate format");
}
headCRC.Update(compressionType);
// 3. Check the flags
var flags = baseInputStream.ReadByte();
if (flags < 0)
{
throw new EndOfStreamException("EOS reading GZIP header");
}
headCRC.Update(flags);
/* This flag byte is divided into individual bits as follows:
bit 0 FTEXT
bit 1 FHCRC
bit 2 FEXTRA
bit 3 FNAME
bit 4 FCOMMENT
bit 5 reserved
bit 6 reserved
bit 7 reserved
*/
// 3.1 Check the reserved bits are zero
if ((flags & 0xd0) != 0)
{
throw new GZipException("Reserved flag bits in GZIP header != 0");
}
// 4.-6. Skip the modification time, extra flags, and OS type
for (var i = 0; i < 6; i++)
{
var readByte = baseInputStream.ReadByte();
if (readByte < 0)
{
throw new EndOfStreamException("EOS reading GZIP header");
}
headCRC.Update(readByte);
}
// 7. Read extra field
if ((flags & GZipConstants.FEXTRA) != 0)
{
// Skip subfield id
for (var i = 0; i < 2; i++)
{
var readByte = baseInputStream.ReadByte();
if (readByte < 0)
{
throw new EndOfStreamException("EOS reading GZIP header");
}
headCRC.Update(readByte);
}
if (baseInputStream.ReadByte() < 0 || baseInputStream.ReadByte() < 0)
{
throw new EndOfStreamException("EOS reading GZIP header");
}
var len1 = baseInputStream.ReadByte();
var len2 = baseInputStream.ReadByte();
if ((len1 < 0) || (len2 < 0))
{
throw new EndOfStreamException("EOS reading GZIP header");
}
headCRC.Update(len1);
headCRC.Update(len2);
var extraLen = (len1 << 8) | len2;
for (var i = 0; i < extraLen; i++)
{
var readByte = baseInputStream.ReadByte();
if (readByte < 0)
{
throw new EndOfStreamException("EOS reading GZIP header");
}
headCRC.Update(readByte);
}
}
// 8. Read file name
if ((flags & GZipConstants.FNAME) != 0)
{
int readByte;
while ((readByte = baseInputStream.ReadByte()) > 0)
{
headCRC.Update(readByte);
}
if (readByte < 0)
{
throw new EndOfStreamException("EOS reading GZIP header");
}
headCRC.Update(readByte);
}
// 9. Read comment
if ((flags & GZipConstants.FCOMMENT) != 0)
{
int readByte;
while ((readByte = baseInputStream.ReadByte()) > 0)
{
headCRC.Update(readByte);
}
if (readByte < 0)
{
throw new EndOfStreamException("EOS reading GZIP header");
}
headCRC.Update(readByte);
}
// 10. Read header CRC
if ((flags & GZipConstants.FHCRC) != 0)
{
var crcval = baseInputStream.ReadByte();
if (crcval < 0)
{
throw new EndOfStreamException("EOS reading GZIP header");
}
int tempByte = baseInputStream.ReadByte();
if (tempByte < 0)
{
throw new EndOfStreamException("EOS reading GZIP header");
}
crcval = (crcval << 8) | tempByte;
if (crcval != ((int) headCRC.Value & 0xffff))
{
throw new GZipException("Header CRC value mismatch");
}
}
readGZIPHeader = true;
}
private void ReadFooter()
{
var footer = new byte[8];
var avail = inf.RemainingInput;
if (avail > 8)
{
avail = 8;
}
Array.Copy(inputBuffer.RawData, inputBuffer.RawLength - inf.RemainingInput, footer, 0, avail);
var needed = 8 - avail;
while (needed > 0)
{
var count = baseInputStream.Read(footer, 8 - needed, needed);
if (count <= 0)
{
throw new EndOfStreamException("EOS reading GZIP footer");
}
needed -= count; // Jewel Jan 16
}
var crcval = (footer[0] & 0xff) | ((footer[1] & 0xff) << 8) | ((footer[2] & 0xff) << 16) | (footer[3] << 24);
if (crcval != (int) crc.Value)
{
throw new GZipException("GZIP crc sum mismatch, theirs \"" + crcval + "\" and ours \"" + (int) crc.Value);
}
// NOTE The total here is the original total modulo 2 ^ 32.
var total =
((uint) footer[4] & 0xff) |
(((uint) footer[5] & 0xff) << 8) |
(((uint) footer[6] & 0xff) << 16) |
((uint) footer[7] << 24);
if ((inf.TotalOut & 0xffffffff) != total)
{
throw new GZipException("Number of bytes mismatch in footer");
}
// Should we support multiple gzip members.
// Difficult, since there may be some bytes still in baseInputStream dataBuffer
eos = true;
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// File: HtmlFromXamlConverter.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Prototype for Xaml - Html conversion
//
//---------------------------------------------------------------------------
namespace GAPPSF.UIControls.HtmlEditor
{
using System;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Xml;
/// <summary>
/// HtmlToXamlConverter is a static class that takes an HTML string
/// and converts it into XAML
/// </summary>
internal static class HtmlFromXamlConverter
{
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
internal static string ConvertXamlToHtml(string xamlString)
{
return ConvertXamlToHtml(xamlString, true);
}
/// <summary>
/// Main entry point for Xaml-to-Html converter.
/// Converts a xaml string into html string.
/// </summary>
/// <param name="xamlString">
/// Xaml strinng to convert.
/// </param>
/// <returns>
/// Html string produced from a source xaml.
/// </returns>
internal static string ConvertXamlToHtml(string xamlString, bool asFlowDocument)
{
XmlTextReader xamlReader;
StringBuilder htmlStringBuilder;
XmlTextWriter htmlWriter;
if (!asFlowDocument)
{
xamlString = "<FlowDocument>" + xamlString + "</FlowDocument>";
}
xamlReader = new XmlTextReader(new StringReader(xamlString));
htmlStringBuilder = new StringBuilder(100);
htmlWriter = new XmlTextWriter(new StringWriter(htmlStringBuilder));
if (!WriteFlowDocument(xamlReader, htmlWriter))
{
return "";
}
string htmlString = htmlStringBuilder.ToString();
return htmlString;
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Private Methods
//
// ---------------------------------------------------------------------
#region Private Methods
/// <summary>
/// Processes a root level element of XAML (normally it's FlowDocument element).
/// </summary>
/// <param name="xamlReader">
/// XmlTextReader for a source xaml.
/// </param>
/// <param name="htmlWriter">
/// XmlTextWriter producing resulting html
/// </param>
private static bool WriteFlowDocument(XmlTextReader xamlReader, XmlTextWriter htmlWriter)
{
if (!ReadNextToken(xamlReader))
{
// Xaml content is empty - nothing to convert
return false;
}
if (xamlReader.NodeType != XmlNodeType.Element || xamlReader.Name != "FlowDocument")
{
// Root FlowDocument elemet is missing
return false;
}
// Create a buffer StringBuilder for collecting css properties for inline STYLE attributes
// on every element level (it will be re-initialized on every level).
StringBuilder inlineStyle = new StringBuilder();
htmlWriter.WriteStartElement("HTML");
htmlWriter.WriteStartElement("BODY");
WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle);
WriteElementContent(xamlReader, htmlWriter, inlineStyle);
htmlWriter.WriteEndElement();
htmlWriter.WriteEndElement();
return true;
}
/// <summary>
/// Reads attributes of the current xaml element and converts
/// them into appropriate html attributes or css styles.
/// </summary>
/// <param name="xamlReader">
/// XmlTextReader which is expected to be at XmlNodeType.Element
/// (opening element tag) position.
/// The reader will remain at the same level after function complete.
/// </param>
/// <param name="htmlWriter">
/// XmlTextWriter for output html, which is expected to be in
/// after WriteStartElement state.
/// </param>
/// <param name="inlineStyle">
/// String builder for collecting css properties for inline STYLE attribute.
/// </param>
private static void WriteFormattingProperties(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
{
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
// Clear string builder for the inline style
inlineStyle.Remove(0, inlineStyle.Length);
if (!xamlReader.HasAttributes)
{
return;
}
bool borderSet = false;
while (xamlReader.MoveToNextAttribute())
{
string css = null;
switch (xamlReader.Name)
{
// Character fomatting properties
// ------------------------------
case "Background":
css = "background-color:" + ParseXamlColor(xamlReader.Value) + ";";
break;
case "FontFamily":
css = "font-family:" + xamlReader.Value + ";";
break;
case "FontStyle":
css = "font-style:" + xamlReader.Value.ToLower() + ";";
break;
case "FontWeight":
css = "font-weight:" + xamlReader.Value.ToLower() + ";";
break;
case "FontStretch":
break;
case "FontSize":
css = "font-size:" + xamlReader.Value + ";";
break;
case "Foreground":
css = "color:" + ParseXamlColor(xamlReader.Value) + ";";
break;
case "TextDecorations":
css = "text-decoration:underline;";
break;
case "TextEffects":
break;
case "Emphasis":
break;
case "StandardLigatures":
break;
case "Variants":
break;
case "Capitals":
break;
case "Fraction":
break;
// Paragraph formatting properties
// -------------------------------
case "Padding":
css = "padding:" + ParseXamlThickness(xamlReader.Value) + ";";
break;
case "Margin":
css = "margin:" + ParseXamlThickness(xamlReader.Value) + ";";
break;
case "BorderThickness":
css = "border-width:" + ParseXamlThickness(xamlReader.Value) + ";";
borderSet = true;
break;
case "BorderBrush":
css = "border-color:" + ParseXamlColor(xamlReader.Value) + ";";
borderSet = true;
break;
case "LineHeight":
break;
case "TextIndent":
css = "text-indent:" + xamlReader.Value + ";";
break;
case "TextAlignment":
css = "text-align:" + xamlReader.Value + ";";
break;
case "IsKeptTogether":
break;
case "IsKeptWithNext":
break;
case "ColumnBreakBefore":
break;
case "PageBreakBefore":
break;
case "FlowDirection":
break;
// Table attributes
// ----------------
case "Width":
css = "width:" + xamlReader.Value + ";";
break;
case "ColumnSpan":
htmlWriter.WriteAttributeString("COLSPAN", xamlReader.Value);
break;
case "RowSpan":
htmlWriter.WriteAttributeString("ROWSPAN", xamlReader.Value);
break;
}
if (css != null)
{
inlineStyle.Append(css);
}
}
if (borderSet)
{
inlineStyle.Append("border-style:solid;mso-element:para-border-div;");
}
// Return the xamlReader back to element level
xamlReader.MoveToElement();
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
}
private static string ParseXamlColor(string color)
{
if (color.StartsWith("#"))
{
// Remove transparancy value
color = "#" + color.Substring(3);
}
return color;
}
private static string ParseXamlThickness(string thickness)
{
string[] values = thickness.Split(',');
for (int i = 0; i < values.Length; i++)
{
double value;
if (double.TryParse(values[i], out value))
{
values[i] = Math.Ceiling(value).ToString();
}
else
{
values[i] = "1";
}
}
string cssThickness;
switch (values.Length)
{
case 1:
cssThickness = thickness;
break;
case 2:
cssThickness = values[1] + " " + values[0];
break;
case 4:
cssThickness = values[1] + " " + values[2] + " " + values[3] + " " + values[0];
break;
default:
cssThickness = values[0];
break;
}
return cssThickness;
}
/// <summary>
/// Reads a content of current xaml element, converts it
/// </summary>
/// <param name="xamlReader">
/// XmlTextReader which is expected to be at XmlNodeType.Element
/// (opening element tag) position.
/// </param>
/// <param name="htmlWriter">
/// May be null, in which case we are skipping the xaml element;
/// witout producing any output to html.
/// </param>
/// <param name="inlineStyle">
/// StringBuilder used for collecting css properties for inline STYLE attribute.
/// </param>
private static void WriteElementContent(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
{
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
bool elementContentStarted = false;
if (xamlReader.IsEmptyElement)
{
if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0)
{
// Output STYLE attribute and clear inlineStyle buffer.
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
inlineStyle.Remove(0, inlineStyle.Length);
}
elementContentStarted = true;
}
else
{
while (ReadNextToken(xamlReader) && xamlReader.NodeType != XmlNodeType.EndElement)
{
switch (xamlReader.NodeType)
{
case XmlNodeType.Element:
if (xamlReader.Name.Contains("."))
{
AddComplexProperty(xamlReader, inlineStyle);
}
else
{
if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0)
{
// Output STYLE attribute and clear inlineStyle buffer.
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
inlineStyle.Remove(0, inlineStyle.Length);
}
elementContentStarted = true;
WriteElement(xamlReader, htmlWriter, inlineStyle);
}
Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement || xamlReader.NodeType == XmlNodeType.Element && xamlReader.IsEmptyElement);
break;
case XmlNodeType.Comment:
if (htmlWriter != null)
{
if (!elementContentStarted && inlineStyle.Length > 0)
{
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
}
htmlWriter.WriteComment(xamlReader.Value);
}
elementContentStarted = true;
break;
case XmlNodeType.CDATA:
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
if (htmlWriter != null)
{
if (!elementContentStarted && inlineStyle.Length > 0)
{
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
}
htmlWriter.WriteString(xamlReader.Value);
}
elementContentStarted = true;
break;
}
}
Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement);
}
}
/// <summary>
/// Conberts an element notation of complex property into
/// </summary>
/// <param name="xamlReader">
/// On entry this XmlTextReader must be on Element start tag;
/// on exit - on EndElement tag.
/// </param>
/// <param name="inlineStyle">
/// StringBuilder containing a value for STYLE attribute.
/// </param>
private static void AddComplexProperty(XmlTextReader xamlReader, StringBuilder inlineStyle)
{
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
if (inlineStyle != null && xamlReader.Name.EndsWith(".TextDecorations"))
{
inlineStyle.Append("text-decoration:underline;");
}
// Skip the element representing the complex property
WriteElementContent(xamlReader, /*htmlWriter:*/null, /*inlineStyle:*/null);
}
/// <summary>
/// Converts a xaml element into an appropriate html element.
/// </summary>
/// <param name="xamlReader">
/// On entry this XmlTextReader must be on Element start tag;
/// on exit - on EndElement tag.
/// </param>
/// <param name="htmlWriter">
/// May be null, in which case we are skipping xaml content
/// without producing any html output
/// </param>
/// <param name="inlineStyle">
/// StringBuilder used for collecting css properties for inline STYLE attributes on every level.
/// </param>
private static void WriteElement(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
{
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
if (htmlWriter == null)
{
// Skipping mode; recurse into the xaml element without any output
WriteElementContent(xamlReader, /*htmlWriter:*/null, null);
}
else
{
string htmlElementName = null;
switch (xamlReader.Name)
{
case "Run" :
case "Span":
htmlElementName = "SPAN";
break;
case "InlineUIContainer":
htmlElementName = "SPAN";
break;
case "Bold":
htmlElementName = "B";
break;
case "Italic" :
htmlElementName = "I";
break;
case "Paragraph" :
htmlElementName = "P";
break;
case "BlockUIContainer":
htmlElementName = "DIV";
break;
case "Section":
htmlElementName = "DIV";
break;
case "Table":
htmlElementName = "TABLE";
break;
case "TableColumn":
htmlElementName = "COL";
break;
case "TableRowGroup" :
htmlElementName = "TBODY";
break;
case "TableRow" :
htmlElementName = "TR";
break;
case "TableCell" :
htmlElementName = "TD";
break;
case "List" :
string marker = xamlReader.GetAttribute("MarkerStyle");
if (marker == null || marker == "None" || marker == "Disc" || marker == "Circle" || marker == "Square" || marker == "Box")
{
htmlElementName = "UL";
}
else
{
htmlElementName = "OL";
}
break;
case "ListItem" :
htmlElementName = "LI";
break;
default :
htmlElementName = null; // Ignore the element
break;
}
if (htmlWriter != null && htmlElementName != null)
{
htmlWriter.WriteStartElement(htmlElementName);
WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle);
WriteElementContent(xamlReader, htmlWriter, inlineStyle);
htmlWriter.WriteEndElement();
}
else
{
// Skip this unrecognized xaml element
WriteElementContent(xamlReader, /*htmlWriter:*/null, null);
}
}
}
// Reader advance helpers
// ----------------------
/// <summary>
/// Reads several items from xamlReader skipping all non-significant stuff.
/// </summary>
/// <param name="xamlReader">
/// XmlTextReader from tokens are being read.
/// </param>
/// <returns>
/// True if new token is available; false if end of stream reached.
/// </returns>
private static bool ReadNextToken(XmlReader xamlReader)
{
while (xamlReader.Read())
{
Debug.Assert(xamlReader.ReadState == ReadState.Interactive, "Reader is expected to be in Interactive state (" + xamlReader.ReadState + ")");
switch (xamlReader.NodeType)
{
case XmlNodeType.Element:
case XmlNodeType.EndElement:
case XmlNodeType.None:
case XmlNodeType.CDATA:
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
return true;
case XmlNodeType.Whitespace:
if (xamlReader.XmlSpace == XmlSpace.Preserve)
{
return true;
}
// ignore insignificant whitespace
break;
case XmlNodeType.EndEntity:
case XmlNodeType.EntityReference:
// Implement entity reading
//xamlReader.ResolveEntity();
//xamlReader.Read();
//ReadChildNodes( parent, parentBaseUri, xamlReader, positionInfo);
break; // for now we ignore entities as insignificant stuff
case XmlNodeType.Comment:
return true;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.DocumentType:
case XmlNodeType.XmlDeclaration:
default:
// Ignorable stuff
break;
}
}
return false;
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
#endregion Private Fields
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics.CodeAnalysis;
namespace System.Management.Automation.Language
{
/// <summary>
/// Each Visit* method in <see ref="AstVisitor"/> returns one of these values to control
/// how visiting nodes in the AST should proceed.
/// </summary>
public enum AstVisitAction
{
/// <summary>
/// Continue visiting all nodes the ast.
/// </summary>
Continue,
/// <summary>
/// Skip visiting child nodes of currently visited node, but continue visiting other nodes.
/// </summary>
SkipChildren,
/// <summary>
/// Stop visiting all nodes.
/// </summary>
StopVisit,
}
/// <summary>
/// AstVisitor is used for basic scenarios requiring traversal of the nodes in an Ast.
/// An implementation of AstVisitor does not explicitly traverse the Ast, instead,
/// the engine traverses all nodes in the Ast and calls the appropriate method on each node.
/// </summary>
public abstract class AstVisitor
{
internal AstVisitAction CheckForPostAction(Ast ast, AstVisitAction action)
{
var postActionHandler = this as IAstPostVisitHandler;
if (postActionHandler != null)
{
postActionHandler.PostVisit(ast);
}
return action;
}
/// <summary/>
public virtual AstVisitAction DefaultVisit(Ast ast) => AstVisitAction.Continue;
/// <summary/>
public virtual AstVisitAction VisitErrorStatement(ErrorStatementAst errorStatementAst) => DefaultVisit(errorStatementAst);
/// <summary/>
public virtual AstVisitAction VisitErrorExpression(ErrorExpressionAst errorExpressionAst) => DefaultVisit(errorExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitScriptBlock(ScriptBlockAst scriptBlockAst) => DefaultVisit(scriptBlockAst);
/// <summary/>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Param")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "param")]
public virtual AstVisitAction VisitParamBlock(ParamBlockAst paramBlockAst) => DefaultVisit(paramBlockAst);
/// <summary/>
public virtual AstVisitAction VisitNamedBlock(NamedBlockAst namedBlockAst) => DefaultVisit(namedBlockAst);
/// <summary/>
public virtual AstVisitAction VisitTypeConstraint(TypeConstraintAst typeConstraintAst) => DefaultVisit(typeConstraintAst);
/// <summary/>
public virtual AstVisitAction VisitAttribute(AttributeAst attributeAst) => DefaultVisit(attributeAst);
/// <summary/>
public virtual AstVisitAction VisitParameter(ParameterAst parameterAst) => DefaultVisit(parameterAst);
/// <summary/>
public virtual AstVisitAction VisitTypeExpression(TypeExpressionAst typeExpressionAst) => DefaultVisit(typeExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) => DefaultVisit(functionDefinitionAst);
/// <summary/>
public virtual AstVisitAction VisitStatementBlock(StatementBlockAst statementBlockAst) => DefaultVisit(statementBlockAst);
/// <summary/>
public virtual AstVisitAction VisitIfStatement(IfStatementAst ifStmtAst) => DefaultVisit(ifStmtAst);
/// <summary/>
public virtual AstVisitAction VisitTrap(TrapStatementAst trapStatementAst) => DefaultVisit(trapStatementAst);
/// <summary/>
public virtual AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst) => DefaultVisit(switchStatementAst);
/// <summary/>
public virtual AstVisitAction VisitDataStatement(DataStatementAst dataStatementAst) => DefaultVisit(dataStatementAst);
/// <summary/>
public virtual AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) => DefaultVisit(forEachStatementAst);
/// <summary/>
public virtual AstVisitAction VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) => DefaultVisit(doWhileStatementAst);
/// <summary/>
public virtual AstVisitAction VisitForStatement(ForStatementAst forStatementAst) => DefaultVisit(forStatementAst);
/// <summary/>
public virtual AstVisitAction VisitWhileStatement(WhileStatementAst whileStatementAst) => DefaultVisit(whileStatementAst);
/// <summary/>
public virtual AstVisitAction VisitCatchClause(CatchClauseAst catchClauseAst) => DefaultVisit(catchClauseAst);
/// <summary/>
public virtual AstVisitAction VisitTryStatement(TryStatementAst tryStatementAst) => DefaultVisit(tryStatementAst);
/// <summary/>
public virtual AstVisitAction VisitBreakStatement(BreakStatementAst breakStatementAst) => DefaultVisit(breakStatementAst);
/// <summary/>
public virtual AstVisitAction VisitContinueStatement(ContinueStatementAst continueStatementAst) => DefaultVisit(continueStatementAst);
/// <summary/>
public virtual AstVisitAction VisitReturnStatement(ReturnStatementAst returnStatementAst) => DefaultVisit(returnStatementAst);
/// <summary/>
public virtual AstVisitAction VisitExitStatement(ExitStatementAst exitStatementAst) => DefaultVisit(exitStatementAst);
/// <summary/>
public virtual AstVisitAction VisitThrowStatement(ThrowStatementAst throwStatementAst) => DefaultVisit(throwStatementAst);
/// <summary/>
public virtual AstVisitAction VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) => DefaultVisit(doUntilStatementAst);
/// <summary/>
public virtual AstVisitAction VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) => DefaultVisit(assignmentStatementAst);
/// <summary/>
public virtual AstVisitAction VisitPipeline(PipelineAst pipelineAst) => DefaultVisit(pipelineAst);
/// <summary/>
public virtual AstVisitAction VisitCommand(CommandAst commandAst) => DefaultVisit(commandAst);
/// <summary/>
public virtual AstVisitAction VisitCommandExpression(CommandExpressionAst commandExpressionAst) => DefaultVisit(commandExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitCommandParameter(CommandParameterAst commandParameterAst) => DefaultVisit(commandParameterAst);
/// <summary/>
public virtual AstVisitAction VisitMergingRedirection(MergingRedirectionAst redirectionAst) => DefaultVisit(redirectionAst);
/// <summary/>
public virtual AstVisitAction VisitFileRedirection(FileRedirectionAst redirectionAst) => DefaultVisit(redirectionAst);
/// <summary/>
public virtual AstVisitAction VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) => DefaultVisit(binaryExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) => DefaultVisit(unaryExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitConvertExpression(ConvertExpressionAst convertExpressionAst) => DefaultVisit(convertExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitConstantExpression(ConstantExpressionAst constantExpressionAst) => DefaultVisit(constantExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) => DefaultVisit(stringConstantExpressionAst);
/// <summary/>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SubExpression")]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "subExpression")]
public virtual AstVisitAction VisitSubExpression(SubExpressionAst subExpressionAst) => DefaultVisit(subExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitUsingExpression(UsingExpressionAst usingExpressionAst) => DefaultVisit(usingExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitVariableExpression(VariableExpressionAst variableExpressionAst) => DefaultVisit(variableExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitMemberExpression(MemberExpressionAst memberExpressionAst) => DefaultVisit(memberExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst) => DefaultVisit(methodCallAst);
/// <summary/>
public virtual AstVisitAction VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) => DefaultVisit(arrayExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) => DefaultVisit(arrayLiteralAst);
/// <summary/>
public virtual AstVisitAction VisitHashtable(HashtableAst hashtableAst) => DefaultVisit(hashtableAst);
/// <summary/>
public virtual AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) => DefaultVisit(scriptBlockExpressionAst);
/// <summary/>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Paren")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "paren")]
public virtual AstVisitAction VisitParenExpression(ParenExpressionAst parenExpressionAst) => DefaultVisit(parenExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) => DefaultVisit(expandableStringExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitIndexExpression(IndexExpressionAst indexExpressionAst) => DefaultVisit(indexExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) => DefaultVisit(attributedExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitBlockStatement(BlockStatementAst blockStatementAst) => DefaultVisit(blockStatementAst);
/// <summary/>
public virtual AstVisitAction VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) => DefaultVisit(namedAttributeArgumentAst);
}
/// <summary>
/// AstVisitor for new Ast node types.
/// </summary>
public abstract class AstVisitor2 : AstVisitor
{
/// <summary/>
public virtual AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) => DefaultVisit(typeDefinitionAst);
/// <summary/>
public virtual AstVisitAction VisitPropertyMember(PropertyMemberAst propertyMemberAst) => DefaultVisit(propertyMemberAst);
/// <summary/>
public virtual AstVisitAction VisitFunctionMember(FunctionMemberAst functionMemberAst) => DefaultVisit(functionMemberAst);
/// <summary/>
public virtual AstVisitAction VisitBaseCtorInvokeMemberExpression(BaseCtorInvokeMemberExpressionAst baseCtorInvokeMemberExpressionAst) => DefaultVisit(baseCtorInvokeMemberExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitUsingStatement(UsingStatementAst usingStatementAst) => DefaultVisit(usingStatementAst);
/// <summary/>
public virtual AstVisitAction VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst) => DefaultVisit(configurationDefinitionAst);
/// <summary/>
public virtual AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordStatementAst) => DefaultVisit(dynamicKeywordStatementAst);
/// <summary/>
public virtual AstVisitAction VisitTernaryExpression(TernaryExpressionAst ternaryExpressionAst) => DefaultVisit(ternaryExpressionAst);
/// <summary/>
public virtual AstVisitAction VisitPipelineChain(PipelineChainAst statementChain) => DefaultVisit(statementChain);
}
/// <summary>
/// Implement this interface when you implement <see cref="AstVisitor"/> or <see cref="AstVisitor2"/> when
/// you want to do something after possibly visiting the children of the ast.
/// </summary>
#nullable enable
public interface IAstPostVisitHandler
{
/// <summary>
/// The function called on each ast node after processing it's children.
/// </summary>
/// <param name="ast">The ast whose children have all been processed and whose siblings
/// and parents are about to be processed.</param>
void PostVisit(Ast ast);
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
namespace TheArtOfDev.HtmlRenderer.Adapters.Entities
{
/// <summary>
/// Represents an ordered pair of floating-point x- and y-coordinates that defines a point in a two-dimensional plane.
/// </summary>
public struct RPoint
{
/// <summary>
/// Represents a new instance of the <see cref="RPoint" /> class with member data left uninitialized.
/// </summary>
/// <filterpriority>1</filterpriority>
public static readonly RPoint Empty = new RPoint();
private double _x;
private double _y;
static RPoint()
{ }
/// <summary>
/// Initializes a new instance of the <see cref="RPoint" /> class with the specified coordinates.
/// </summary>
/// <param name="x">The horizontal position of the point. </param>
/// <param name="y">The vertical position of the point. </param>
public RPoint(double x, double y)
{
_x = x;
_y = y;
}
/// <summary>
/// Gets a value indicating whether this <see cref="RPoint" /> is empty.
/// </summary>
/// <returns>
/// true if both <see cref="RPoint.X" /> and
/// <see
/// cref="RPoint.Y" />
/// are 0; otherwise, false.
/// </returns>
/// <filterpriority>1</filterpriority>
public bool IsEmpty
{
get
{
if (Math.Abs(_x - 0.0) < 0.001)
return Math.Abs(_y - 0.0) < 0.001;
else
return false;
}
}
/// <summary>
/// Gets or sets the x-coordinate of this <see cref="RPoint" />.
/// </summary>
/// <returns>
/// The x-coordinate of this <see cref="RPoint" />.
/// </returns>
/// <filterpriority>1</filterpriority>
public double X
{
get { return _x; }
set { _x = value; }
}
/// <summary>
/// Gets or sets the y-coordinate of this <see cref="RPoint" />.
/// </summary>
/// <returns>
/// The y-coordinate of this <see cref="RPoint" />.
/// </returns>
/// <filterpriority>1</filterpriority>
public double Y
{
get { return _y; }
set { _y = value; }
}
/// <summary>
/// Translates the <see cref="RPoint" /> by the specified
/// <see
/// cref="T:System.Drawing.SizeF" />
/// .
/// </summary>
/// <returns>
/// The translated <see cref="RPoint" />.
/// </returns>
/// <param name="pt">
/// The <see cref="RPoint" /> to translate.
/// </param>
/// <param name="sz">
/// The <see cref="T:System.Drawing.SizeF" /> that specifies the numbers to add to the x- and y-coordinates of the
/// <see
/// cref="RPoint" />
/// .
/// </param>
public static RPoint operator +(RPoint pt, RSize sz)
{
return Add(pt, sz);
}
/// <summary>
/// Translates a <see cref="RPoint" /> by the negative of a specified
/// <see
/// cref="T:System.Drawing.SizeF" />
/// .
/// </summary>
/// <returns>
/// The translated <see cref="RPoint" />.
/// </returns>
/// <param name="pt">
/// The <see cref="RPoint" /> to translate.
/// </param>
/// <param name="sz">
/// The <see cref="T:System.Drawing.SizeF" /> that specifies the numbers to subtract from the coordinates of
/// <paramref
/// name="pt" />
/// .
/// </param>
public static RPoint operator -(RPoint pt, RSize sz)
{
return Subtract(pt, sz);
}
/// <summary>
/// Compares two <see cref="RPoint" /> structures. The result specifies whether the values of the
/// <see
/// cref="RPoint.X" />
/// and <see cref="RPoint.Y" /> properties of the two
/// <see
/// cref="RPoint" />
/// structures are equal.
/// </summary>
/// <returns>
/// true if the <see cref="RPoint.X" /> and
/// <see
/// cref="RPoint.Y" />
/// values of the left and right
/// <see
/// cref="RPoint" />
/// structures are equal; otherwise, false.
/// </returns>
/// <param name="left">
/// A <see cref="RPoint" /> to compare.
/// </param>
/// <param name="right">
/// A <see cref="RPoint" /> to compare.
/// </param>
/// <filterpriority>3</filterpriority>
public static bool operator ==(RPoint left, RPoint right)
{
if (left.X == right.X)
return left.Y == right.Y;
else
return false;
}
/// <summary>
/// Determines whether the coordinates of the specified points are not equal.
/// </summary>
/// <returns>
/// true to indicate the <see cref="RPoint.X" /> and
/// <see
/// cref="RPoint.Y" />
/// values of <paramref name="left" /> and
/// <paramref
/// name="right" />
/// are not equal; otherwise, false.
/// </returns>
/// <param name="left">
/// A <see cref="RPoint" /> to compare.
/// </param>
/// <param name="right">
/// A <see cref="RPoint" /> to compare.
/// </param>
/// <filterpriority>3</filterpriority>
public static bool operator !=(RPoint left, RPoint right)
{
return !(left == right);
}
/// <summary>
/// Translates a given <see cref="RPoint" /> by a specified
/// <see
/// cref="T:System.Drawing.SizeF" />
/// .
/// </summary>
/// <returns>
/// The translated <see cref="RPoint" />.
/// </returns>
/// <param name="pt">
/// The <see cref="RPoint" /> to translate.
/// </param>
/// <param name="sz">
/// The <see cref="T:System.Drawing.SizeF" /> that specifies the numbers to add to the coordinates of
/// <paramref
/// name="pt" />
/// .
/// </param>
public static RPoint Add(RPoint pt, RSize sz)
{
return new RPoint(pt.X + sz.Width, pt.Y + sz.Height);
}
/// <summary>
/// Translates a <see cref="RPoint" /> by the negative of a specified size.
/// </summary>
/// <returns>
/// The translated <see cref="RPoint" />.
/// </returns>
/// <param name="pt">
/// The <see cref="RPoint" /> to translate.
/// </param>
/// <param name="sz">
/// The <see cref="T:System.Drawing.SizeF" /> that specifies the numbers to subtract from the coordinates of
/// <paramref
/// name="pt" />
/// .
/// </param>
public static RPoint Subtract(RPoint pt, RSize sz)
{
return new RPoint(pt.X - sz.Width, pt.Y - sz.Height);
}
/// <summary>
/// Specifies whether this <see cref="RPoint" /> contains the same coordinates as the specified
/// <see
/// cref="T:System.Object" />
/// .
/// </summary>
/// <returns>
/// This method returns true if <paramref name="obj" /> is a <see cref="RPoint" /> and has the same coordinates as this
/// <see
/// cref="T:System.Drawing.Point" />
/// .
/// </returns>
/// <param name="obj">
/// The <see cref="T:System.Object" /> to test.
/// </param>
/// <filterpriority>1</filterpriority>
public override bool Equals(object obj)
{
if (!(obj is RPoint))
return false;
var pointF = (RPoint)obj;
if (pointF.X == X && pointF.Y == Y)
return pointF.GetType().Equals(GetType());
else
return false;
}
/// <summary>
/// Returns a hash code for this <see cref="RPoint" /> structure.
/// </summary>
/// <returns>
/// An integer value that specifies a hash value for this <see cref="RPoint" /> structure.
/// </returns>
/// <filterpriority>1</filterpriority>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Converts this <see cref="RPoint" /> to a human readable string.
/// </summary>
/// <returns>
/// A string that represents this <see cref="RPoint" />.
/// </returns>
/// <filterpriority>1</filterpriority>
public override string ToString()
{
return string.Format("{{X={0}, Y={1}}}", new object[]
{
_x,
_y
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace MoreLinq.Test
{
/// <summary>
/// Tests that verify the behavior of the SortedMerge operator.
/// </summary>
[TestFixture]
public class SortedMergeTests
{
/// <summary>
/// Verify that SortedMerge behaves in a lazy manner.
/// </summary>
[Test]
public void TestSortedMergeIsLazy()
{
var sequenceA = new BreakingSequence<int>();
var sequenceB = new BreakingSequence<int>();
sequenceA.SortedMerge(OrderByDirection.Ascending, sequenceB);
}
/// <summary>
/// Verify that SortedMerge throws an exception if invoked on a <c>null</c> sequence.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void TestSortedMergeSequenceNullException()
{
const IEnumerable<int> sequenceA = null;
var sequenceB = new BreakingSequence<int>();
sequenceA.SortedMerge(OrderByDirection.Ascending, sequenceB);
}
/// <summary>
/// Verify that SortedMerge throws an exception if invoked with a <c>null</c> <c>otherSequences</c> argument.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void TestSortedMergeOtherSequencesNullException()
{
var sequenceA = new BreakingSequence<int>();
sequenceA.SortedMerge(OrderByDirection.Ascending, (IEnumerable<int>[])null);
}
/// <summary>
/// Verify that SortedMerge disposes those enumerators that it managed
/// to open successfully
/// </summary>
[Test]
public void TestSortedMergeDisposesOnError()
{
using (var sequenceA = TestingSequence.Of<int>())
{
try
{
sequenceA.SortedMerge(OrderByDirection.Ascending, new BreakingSequence<int>()).ToArray();
Assert.Fail("{0} was expected", typeof(InvalidOperationException));
}
catch (InvalidOperationException)
{
// Expected and thrown by BreakingSequence
}
}
}
/// <summary>
/// Verify that SortedMerge throws an exception if invoked on a <c>null</c> sequence.
/// </summary>
[Test]
public void TestSortedMergeComparerNull()
{
var sequenceA = Enumerable.Range(1, 3);
var sequenceB = Enumerable.Range(4, 3);
var result = sequenceA.SortedMerge(OrderByDirection.Ascending, (IComparer<int>)null, sequenceB);
Assert.IsTrue(result.SequenceEqual(sequenceA.Concat(sequenceB)));
}
/// <summary>
/// Verify that if <c>otherSequences</c> is empty, SortedMerge yields the contents of <c>sequence</c>
/// </summary>
[Test]
public void TestSortedMergeOtherSequencesEmpty()
{
const int count = 10;
var sequenceA = Enumerable.Range(1, count);
var result = sequenceA.SortedMerge(OrderByDirection.Ascending);
Assert.IsTrue(result.SequenceEqual(sequenceA));
}
/// <summary>
/// Verify that if all sequences passed to SortedMerge are empty, the result is an empty sequence.
/// </summary>
[Test]
public void TestSortedMergeAllSequencesEmpty()
{
var sequenceA = Enumerable.Empty<int>();
var sequenceB = Enumerable.Empty<int>();
var sequenceC = Enumerable.Empty<int>();
var result = sequenceA.SortedMerge(OrderByDirection.Ascending, sequenceB, sequenceC);
Assert.IsTrue(result.SequenceEqual(sequenceA));
}
/// <summary>
/// Verify that if the primary sequence is empty, SortedMerge correctly merges <c>otherSequences</c>
/// </summary>
[Test]
public void TestSortedMergeFirstSequenceEmpty()
{
var sequenceA = Enumerable.Empty<int>();
var sequenceB = new[] { 1, 3, 5, 7, 9, 11 };
var sequenceC = new[] { 2, 4, 6, 8, 10, 12 };
var expectedResult = Enumerable.Range(1, 12);
var result = sequenceA.SortedMerge(OrderByDirection.Ascending, sequenceB, sequenceC);
Assert.IsTrue(result.SequenceEqual(expectedResult));
}
/// <summary>
/// Verify that SortedMerge correctly merges sequences of equal length.
/// </summary>
[Test]
public void TestSortedMergeEqualLengthSequences()
{
const int count = 10;
var sequenceA = Enumerable.Range(0, count).Select(x => x * 3 + 0);
var sequenceB = Enumerable.Range(0, count).Select(x => x * 3 + 1);
var sequenceC = Enumerable.Range(0, count).Select(x => x * 3 + 2);
var expectedResult = Enumerable.Range(0, count * 3);
var result = sequenceA.SortedMerge(OrderByDirection.Ascending, sequenceB, sequenceC);
Assert.IsTrue(result.SequenceEqual(expectedResult));
}
/// <summary>
/// Verify that sorted merge correctly merges sequences of unequal length.
/// </summary>
[Test]
public void TestSortedMergeUnequalLengthSequences()
{
const int count = 30;
var sequenceA = Enumerable.Range(0, count).Select(x => x * 3 + 0);
var sequenceB = Enumerable.Range(0, count).Select(x => x * 3 + 1).Take(count / 2);
var sequenceC = Enumerable.Range(0, count).Select(x => x * 3 + 2).Take(count / 3);
var expectedResult = sequenceA.Concat(sequenceB).Concat(sequenceC).OrderBy(x => x);
var result = sequenceA.SortedMerge(OrderByDirection.Ascending, sequenceB, sequenceC);
Assert.IsTrue(result.SequenceEqual(expectedResult));
}
/// <summary>
/// Verify that sorted merge correctly merges descending-ordered sequences.
/// </summary>
[Test]
public void TestSortedMergeDescendingOrder()
{
const int count = 10;
var sequenceA = Enumerable.Range(0, count).Select(x => x * 3 + 0).Reverse();
var sequenceB = Enumerable.Range(0, count).Select(x => x * 3 + 1).Reverse();
var sequenceC = Enumerable.Range(0, count).Select(x => x * 3 + 2).Reverse();
var expectedResult = Enumerable.Range(0, count * 3).Reverse();
var result = sequenceA.SortedMerge(OrderByDirection.Descending, sequenceB, sequenceC);
Assert.IsTrue(result.SequenceEqual(expectedResult));
}
/// <summary>
/// Verify that sorted merge correctly uses a custom comparer supplied to it.
/// </summary>
[Test]
public void TestSortedMergeCustomComparer()
{
var sequenceA = new[] { "a", "D", "G", "h", "i", "J", "O", "t", "z" };
var sequenceB = new[] { "b", "E", "k", "q", "r", "u", "V", "x", "Y" };
var sequenceC = new[] { "C", "F", "l", "m", "N", "P", "s", "w" };
var expectedResult = sequenceA.Concat(sequenceB).Concat(sequenceC)
.OrderBy(a => a, StringComparer.CurrentCultureIgnoreCase);
var result = sequenceA.SortedMerge(OrderByDirection.Ascending, sequenceB, sequenceC);
Assert.IsTrue(result.SequenceEqual(expectedResult));
}
/// <summary>
/// Verify that sorted merge disposes enumerators of all sequences that are passed to it.
/// </summary>
[Test]
public void TestSortedMergeAllSequencesDisposed()
{
var disposedSequenceA = false;
var disposedSequenceB = false;
var disposedSequenceC = false;
var disposedSequenceD = false;
const int count = 10;
var sequenceA = Enumerable.Range(1, count).AsVerifiable().WhenDisposed(s => disposedSequenceA = true);
var sequenceB = Enumerable.Range(1, count - 1).AsVerifiable().WhenDisposed(s => disposedSequenceB = true);
var sequenceC = Enumerable.Range(1, count - 5).AsVerifiable().WhenDisposed(s => disposedSequenceC = true);
var sequenceD = Enumerable.Range(1, 0).AsVerifiable().WhenDisposed(s => disposedSequenceD = true);
var result = sequenceA.SortedMerge(OrderByDirection.Ascending, sequenceB, sequenceC, sequenceD);
result.Count(); // ensures the sequences are actually merged and iterators are obtained
Assert.IsTrue(disposedSequenceA && disposedSequenceB && disposedSequenceC && disposedSequenceD);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Metadata.Builders;
using Microsoft.Data.Entity.Relational.Migrations;
using Microsoft.Data.Entity.Relational.Migrations.Builders;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
using Microsoft.Data.Entity.Relational.Migrations.Operations;
using Humanizer.vNextSample.Models;
namespace Humanizer.vNextSample.Migrations
{
public partial class CreateIdentitySchema : Migration
{
public override void Up(MigrationBuilder migration)
{
migration.CreateTable(
name: "AspNetUsers",
columns: table => new
{
AccessFailedCount = table.Column(type: "int", nullable: false),
ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true),
Email = table.Column(type: "nvarchar(max)", nullable: true),
EmailConfirmed = table.Column(type: "bit", nullable: false),
Id = table.Column(type: "nvarchar(450)", nullable: true),
LockoutEnabled = table.Column(type: "bit", nullable: false),
LockoutEnd = table.Column(type: "datetimeoffset", nullable: true),
NormalizedEmail = table.Column(type: "nvarchar(max)", nullable: true),
NormalizedUserName = table.Column(type: "nvarchar(max)", nullable: true),
PasswordHash = table.Column(type: "nvarchar(max)", nullable: true),
PhoneNumber = table.Column(type: "nvarchar(max)", nullable: true),
PhoneNumberConfirmed = table.Column(type: "bit", nullable: false),
SecurityStamp = table.Column(type: "nvarchar(max)", nullable: true),
TwoFactorEnabled = table.Column(type: "bit", nullable: false),
UserName = table.Column(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migration.CreateTable(
name: "AspNetRoles",
columns: table => new
{
ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true),
Id = table.Column(type: "nvarchar(450)", nullable: true),
Name = table.Column(type: "nvarchar(max)", nullable: true),
NormalizedName = table.Column(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migration.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
ClaimType = table.Column(type: "nvarchar(max)", nullable: true),
ClaimValue = table.Column(type: "nvarchar(max)", nullable: true),
Id = table.Column(type: "int", nullable: false)
.Annotation("SqlServer:ValueGeneration", "Identity"),
UserId = table.Column(type: "nvarchar(450)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
columns: x => x.UserId,
referencedTable: "AspNetUsers",
referencedColumn: "Id");
});
migration.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column(type: "nvarchar(450)", nullable: true),
ProviderDisplayName = table.Column(type: "nvarchar(max)", nullable: true),
ProviderKey = table.Column(type: "nvarchar(450)", nullable: true),
UserId = table.Column(type: "nvarchar(450)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
columns: x => x.UserId,
referencedTable: "AspNetUsers",
referencedColumn: "Id");
});
migration.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
ClaimType = table.Column(type: "nvarchar(max)", nullable: true),
ClaimValue = table.Column(type: "nvarchar(max)", nullable: true),
Id = table.Column(type: "int", nullable: false)
.Annotation("SqlServer:ValueGeneration", "Identity"),
RoleId = table.Column(type: "nvarchar(450)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
columns: x => x.RoleId,
referencedTable: "AspNetRoles",
referencedColumn: "Id");
});
migration.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
RoleId = table.Column(type: "nvarchar(450)", nullable: true),
UserId = table.Column(type: "nvarchar(450)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
columns: x => x.RoleId,
referencedTable: "AspNetRoles",
referencedColumn: "Id");
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
columns: x => x.UserId,
referencedTable: "AspNetUsers",
referencedColumn: "Id");
});
}
public override void Down(MigrationBuilder migration)
{
migration.DropTable("AspNetUserRoles");
migration.DropTable("AspNetRoleClaims");
migration.DropTable("AspNetUserLogins");
migration.DropTable("AspNetUserClaims");
migration.DropTable("AspNetRoles");
migration.DropTable("AspNetUsers");
}
}
[ContextType(typeof(ApplicationDbContext))]
partial class CreateIdentitySchema
{
public override string Id
{
get { return "00000000000000_CreateIdentitySchema"; }
}
public override string ProductVersion
{
get { return "7.0.0-beta4"; }
}
public override IModel Target
{
get
{
var builder = new BasicModelBuilder()
.Annotation("SqlServer:ValueGeneration", "Identity");
builder.Entity("Humanizer.vNextSample.Models.ApplicationUser", b =>
{
b.Property<int>("AccessFailedCount")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Email")
.Annotation("OriginalValueIndex", 2);
b.Property<bool>("EmailConfirmed")
.Annotation("OriginalValueIndex", 3);
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 4);
b.Property<bool>("LockoutEnabled")
.Annotation("OriginalValueIndex", 5);
b.Property<DateTimeOffset?>("LockoutEnd")
.Annotation("OriginalValueIndex", 6);
b.Property<string>("NormalizedEmail")
.Annotation("OriginalValueIndex", 7);
b.Property<string>("NormalizedUserName")
.Annotation("OriginalValueIndex", 8);
b.Property<string>("PasswordHash")
.Annotation("OriginalValueIndex", 9);
b.Property<string>("PhoneNumber")
.Annotation("OriginalValueIndex", 10);
b.Property<bool>("PhoneNumberConfirmed")
.Annotation("OriginalValueIndex", 11);
b.Property<string>("SecurityStamp")
.Annotation("OriginalValueIndex", 12);
b.Property<bool>("TwoFactorEnabled")
.Annotation("OriginalValueIndex", 13);
b.Property<string>("UserName")
.Annotation("OriginalValueIndex", 14);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("NormalizedName")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 1);
b.Property<int>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 2)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 1);
b.Property<int>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 2)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.Property<string>("LoginProvider")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ProviderDisplayName")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ProviderKey")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 1);
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.ForeignKey("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", "RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.ForeignKey("Humanizer.vNextSample.Models.ApplicationUser", "UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.ForeignKey("Humanizer.vNextSample.Models.ApplicationUser", "UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.ForeignKey("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", "RoleId");
b.ForeignKey("Humanizer.vNextSample.Models.ApplicationUser", "UserId");
});
return builder.Model;
}
}
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class MemberAccessTests
{
private class UnreadableIndexableClass
{
public int this[int index]
{
set { }
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessStructInstanceFieldTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
Expression.Constant(new FS() { II = 42 }),
"II"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessStructStaticFieldTest(bool useInterpreter)
{
FS.SI = 42;
try
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
null,
typeof(FS),
"SI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
finally
{
FS.SI = 0;
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessStructConstFieldTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
null,
typeof(FS),
"CI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessStructStaticReadOnlyFieldTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
null,
typeof(FS),
"RI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessStructInstancePropertyTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Property(
Expression.Constant(new PS() { II = 42 }),
"II"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessStructStaticPropertyTest(bool useInterpreter)
{
PS.SI = 42;
try
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Property(
null,
typeof(PS),
"SI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
finally
{
PS.SI = 0;
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void NullNullableValueException(bool useInterpreter)
{
string localizedMessage = null;
try
{
int dummy = default(int?).Value;
}
catch (InvalidOperationException ioe)
{
localizedMessage = ioe.Message;
}
Expression<Func<long>> e = () => default(long?).Value;
Func<long> f = e.Compile(useInterpreter);
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => f());
Assert.Equal(localizedMessage, exception.Message);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstanceFieldTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
Expression.Constant(new FC() { II = 42 }),
"II"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassStaticFieldTest(bool useInterpreter)
{
FC.SI = 42;
try
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
null,
typeof(FC),
"SI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
finally
{
FC.SI = 0;
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassConstFieldTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
null,
typeof(FC),
"CI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassStaticReadOnlyFieldTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
null,
typeof(FC),
"RI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Fact]
public static void Field_NullField_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("field", () => Expression.Field(null, (FieldInfo)null));
AssertExtensions.Throws<ArgumentNullException>("fieldName", () => Expression.Field(Expression.Constant(new FC()), (string)null));
}
[Fact]
public static void Field_NullType_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Field(Expression.Constant(new FC()), null, "AField"));
}
[Fact]
public static void Field_StaticField_NonNullExpression_ThrowsArgumentException()
{
Expression expression = Expression.Constant(new FC());
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Field(expression, typeof(FC), nameof(FC.SI)));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Field(expression, typeof(FC).GetField(nameof(FC.SI))));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.MakeMemberAccess(expression, typeof(FC).GetField(nameof(FC.SI))));
}
[Fact]
public static void Field_ByrefTypeFieldAccessor_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(null, typeof(GenericClass<string>).MakeByRefType(), nameof(GenericClass<string>.Field)));
}
[Fact]
public static void Field_GenericFieldAccessor_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(null, typeof(GenericClass<>), nameof(GenericClass<string>.Field)));
}
[Fact]
public static void Field_InstanceField_NullExpression_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.Field(null, "fieldName"));
AssertExtensions.Throws<ArgumentException>("field", () => Expression.Field(null, typeof(FC), nameof(FC.II)));
AssertExtensions.Throws<ArgumentException>("field", () => Expression.Field(null, typeof(FC).GetField(nameof(FC.II))));
AssertExtensions.Throws<ArgumentException>("field", () => Expression.MakeMemberAccess(null, typeof(FC).GetField(nameof(FC.II))));
}
[Fact]
public static void Field_ExpressionNotReadable_ThrowsArgumentException()
{
Expression expression = Expression.Property(null, typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Field(expression, "fieldName"));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Field(expression, typeof(FC), nameof(FC.SI)));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Field(expression, typeof(FC).GetField(nameof(FC.SI))));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.MakeMemberAccess(expression, typeof(FC).GetField(nameof(FC.SI))));
}
[Fact]
public static void Field_ExpressionNotTypeOfDeclaringType_ThrowsArgumentException()
{
Expression expression = Expression.Constant(new PC());
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Field(expression, typeof(FC), nameof(FC.II)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Field(expression, typeof(FC).GetField(nameof(FC.II))));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.MakeMemberAccess(expression, typeof(FC).GetField(nameof(FC.II))));
}
[Fact]
public static void Field_NoSuchFieldName_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Field(Expression.Constant(new FC()), "NoSuchField"));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Field(Expression.Constant(new FC()), typeof(FC), "NoSuchField"));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstancePropertyTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Property(
Expression.Constant(new PC() { II = 42 }),
"II"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassStaticPropertyTest(bool useInterpreter)
{
PC.SI = 42;
try
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Property(
null,
typeof(PC),
"SI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
finally
{
PC.SI = 0;
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstanceFieldNullReferenceTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
Expression.Constant(null, typeof(FC)),
"II"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Throws<NullReferenceException>(() => f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstanceFieldAssignNullReferenceTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Assign(
Expression.Field(
Expression.Constant(null, typeof(FC)),
"II"),
Expression.Constant(1)),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Throws<NullReferenceException>(() => f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstancePropertyNullReferenceTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Property(
Expression.Constant(null, typeof(PC)),
"II"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Throws<NullReferenceException>(() => f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstanceIndexerNullReferenceTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Property(
Expression.Constant(null, typeof(PC)),
"Item",
Expression.Constant(1)),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Throws<NullReferenceException>(() => f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstanceIndexerAssignNullReferenceTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Assign(
Expression.Property(
Expression.Constant(null, typeof(PC)),
"Item",
Expression.Constant(1)),
Expression.Constant(1)),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Throws<NullReferenceException>(() => f());
}
[Fact]
public static void AccessIndexedPropertyWithoutIndex()
{
AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(Expression.Default(typeof(List<int>)), typeof(List<int>).GetProperty("Item")));
}
[Fact]
public static void AccessIndexedPropertyWithoutIndexWriteOnly()
{
AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(Expression.Default(typeof(UnreadableIndexableClass)), typeof(UnreadableIndexableClass).GetProperty("Item")));
}
[Fact]
public static void Property_NullProperty_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("property", () => Expression.Property(null, (PropertyInfo)null));
AssertExtensions.Throws<ArgumentNullException>("propertyName", () => Expression.Property(Expression.Constant(new PC()), (string)null));
}
[Fact]
public static void Property_NullType_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Property(Expression.Constant(new PC()), null, "AProperty"));
}
[Fact]
public static void Property_StaticProperty_NonNullExpression_ThrowsArgumentException()
{
Expression expression = Expression.Constant(new PC());
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC), nameof(PC.SI)));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.SI))));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.SI)).GetGetMethod()));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.MakeMemberAccess(expression, typeof(PC).GetProperty(nameof(PC.SI))));
}
[Fact]
public static void Property_InstanceProperty_NullExpression_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.Property(null, "propertyName"));
AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(null, typeof(PC), nameof(PC.II)));
AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(null, typeof(PC).GetProperty(nameof(PC.II))));
AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(null, typeof(PC).GetProperty(nameof(PC.II)).GetGetMethod()));
AssertExtensions.Throws<ArgumentException>("property", () => Expression.MakeMemberAccess(null, typeof(PC).GetProperty(nameof(PC.II))));
}
[Fact]
public static void Property_ExpressionNotReadable_ThrowsArgumentException()
{
Expression expression = Expression.Property(null, typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, "fieldName"));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC), nameof(PC.SI)));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.SI))));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.SI)).GetGetMethod()));
}
[Fact]
public static void Property_ExpressionNotTypeOfDeclaringType_ThrowsArgumentException()
{
Expression expression = Expression.Constant(new FC());
AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(expression, typeof(PC), nameof(PC.II)));
AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.II))));
AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.II)).GetGetMethod()));
AssertExtensions.Throws<ArgumentException>("property", () => Expression.MakeMemberAccess(expression, typeof(PC).GetProperty(nameof(PC.II))));
}
[Fact]
public static void Property_NoSuchPropertyName_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(Expression.Constant(new PC()), "NoSuchProperty"));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(Expression.Constant(new PC()), typeof(PC), "NoSuchProperty"));
}
[Fact]
public static void Property_NullPropertyAccessor_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("propertyAccessor", () => Expression.Property(Expression.Constant(new PC()), (MethodInfo)null));
}
[Fact]
public static void Property_GenericPropertyAccessor_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.Property(null, typeof(GenericClass<>).GetProperty(nameof(GenericClass<string>.Property)).GetGetMethod()));
AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.Property(null, typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.GenericMethod))));
AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(null, typeof(GenericClass<>).GetProperty(nameof(GenericClass<string>.Property))));
}
[Fact]
public static void Property_PropertyAccessorNotFromProperty_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.Property(null, typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticMethod))));
}
[Fact]
public static void Property_ByRefStaticAccess_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(null, typeof(NonGenericClass).MakeByRefType(), nameof(NonGenericClass.NonGenericProperty)));
}
[Fact]
public static void PropertyOrField_NullExpression_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.PropertyOrField(null, "APropertyOrField"));
}
[Fact]
public static void PropertyOrField_ExpressionNotReadable_ThrowsArgumentNullException()
{
Expression expression = Expression.Property(null, typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.PropertyOrField(expression, "APropertyOrField"));
}
[Fact]
public static void PropertyOrField_NoSuchPropertyOrField_ThrowsArgumentException()
{
Expression expression = Expression.Constant(new PC());
AssertExtensions.Throws<ArgumentException>("propertyOrFieldName", () => Expression.PropertyOrField(expression, "NoSuchPropertyOrField"));
}
[Fact]
public static void MakeMemberAccess_NullMember_ThrowsArgumentNullExeption()
{
AssertExtensions.Throws<ArgumentNullException>("member", () => Expression.MakeMemberAccess(Expression.Constant(new PC()), null));
}
[Fact]
public static void MakeMemberAccess_MemberNotFieldOrProperty_ThrowsArgumentExeption()
{
MemberInfo member = typeof(NonGenericClass).GetEvent("Event");
AssertExtensions.Throws<ArgumentException>("member", () => Expression.MakeMemberAccess(Expression.Constant(new PC()), member));
}
#if FEATURE_COMPILE
[Fact]
public static void Property_NoGetOrSetAccessors_ThrowsArgumentException()
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Module");
TypeBuilder type = module.DefineType("Type");
PropertyBuilder property = type.DefineProperty("Property", PropertyAttributes.None, typeof(void), new Type[0]);
TypeInfo createdType = type.CreateTypeInfo();
PropertyInfo createdProperty = createdType.DeclaredProperties.First();
Expression expression = Expression.Constant(Activator.CreateInstance(createdType));
AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(expression, createdProperty));
AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(expression, createdProperty.Name));
AssertExtensions.Throws<ArgumentException>("property", () => Expression.PropertyOrField(expression, createdProperty.Name));
AssertExtensions.Throws<ArgumentException>("property", () => Expression.MakeMemberAccess(expression, createdProperty));
}
#endif
[Fact]
public static void ToStringTest()
{
MemberExpression e1 = Expression.Property(null, typeof(DateTime).GetProperty(nameof(DateTime.Now)));
Assert.Equal("DateTime.Now", e1.ToString());
MemberExpression e2 = Expression.Property(Expression.Parameter(typeof(DateTime), "d"), typeof(DateTime).GetProperty(nameof(DateTime.Year)));
Assert.Equal("d.Year", e2.ToString());
}
[Fact]
public static void UpdateSameResturnsSame()
{
var exp = Expression.Constant(new PS {II = 42});
var pro = Expression.Property(exp, nameof(PS.II));
Assert.Same(pro, pro.Update(exp));
}
[Fact]
public static void UpdateStaticResturnsSame()
{
var pro = Expression.Property(null, typeof(PS), nameof(PS.SI));
Assert.Same(pro, pro.Update(null));
}
[Fact]
public static void UpdateDifferentResturnsDifferent()
{
var pro = Expression.Property(Expression.Constant(new PS {II = 42}), nameof(PS.II));
Assert.NotSame(pro, pro.Update(Expression.Constant(new PS {II = 42})));
}
}
}
| |
#pragma warning disable 1591
#pragma warning disable 0108
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Team Development for Sitecore.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Glass.Mapper.Sc.Configuration.Attributes;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Fields;
using Sitecore.Globalization;
using Sitecore.Data;
namespace TDSTesting.TDSTesting
{
public partial interface IGlassBase{
[SitecoreId]
Guid Id{ get; }
[SitecoreInfo(SitecoreInfoType.Language)]
Language Language{ get; }
[SitecoreInfo(SitecoreInfoType.Version)]
int Version { get; }
}
public abstract partial class GlassBase : IGlassBase{
[SitecoreId]
public virtual Guid Id{ get; private set;}
[SitecoreInfo(SitecoreInfoType.Language)]
public virtual Language Language{ get; private set; }
[SitecoreInfo(SitecoreInfoType.Version)]
public virtual int Version { get; private set; }
[SitecoreInfo(SitecoreInfoType.Url)]
public virtual string Url { get; private set; }
}
}
namespace TDSTesting.TDSTesting.sitecore.templates.Testing
{
/// <summary>
/// IA_New_Template Interface
/// <para></para>
/// <para>Path: /sitecore/templates/Testing/A new Template</para>
/// <para>ID: e974ac12-1313-4bfd-bb61-c0d943a2c67a</para>
/// </summary>
[SitecoreType(TemplateId=IA_New_TemplateConstants.TemplateIdString )] //, Cachable = true
public partial interface IA_New_Template : IGlassBase
{
/// <summary>
/// The First field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: fb1aa7f4-6cd9-447f-9cdb-564a6299229b</para>
/// <para>Custom Data: </para>
/// </summary>
[SitecoreField(IA_New_TemplateConstants.FirstFieldName)]
string First {get; set;}
/// <summary>
/// The Fourthh field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 27e6f98a-a6ba-4e1f-874f-e1b5414bec80</para>
/// <para>Custom Data: </para>
/// </summary>
[SitecoreField(IA_New_TemplateConstants.FourthhFieldName)]
string Fourthh {get; set;}
/// <summary>
/// The Second field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 30530e87-81d5-4b65-9d89-2f9a608a5262</para>
/// <para>Custom Data: </para>
/// </summary>
[SitecoreField(IA_New_TemplateConstants.SecondFieldName)]
string Second {get; set;}
/// <summary>
/// The Third field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 86360e6e-1714-4b35-a3b2-3b54c28fc3be</para>
/// <para>Custom Data: </para>
/// </summary>
[SitecoreField(IA_New_TemplateConstants.ThirdFieldName)]
string Third {get; set;}
}
public static partial class IA_New_TemplateConstants{
public const string TemplateIdString = "e974ac12-1313-4bfd-bb61-c0d943a2c67a";
public static readonly ID TemplateId = new ID(TemplateIdString);
public const string TemplateName = "A new Template";
public static readonly ID FirstFieldId = new ID("fb1aa7f4-6cd9-447f-9cdb-564a6299229b");
public const string FirstFieldName = "First";
public static readonly ID FourthhFieldId = new ID("27e6f98a-a6ba-4e1f-874f-e1b5414bec80");
public const string FourthhFieldName = "Fourthh";
public static readonly ID SecondFieldId = new ID("30530e87-81d5-4b65-9d89-2f9a608a5262");
public const string SecondFieldName = "Second";
public static readonly ID ThirdFieldId = new ID("86360e6e-1714-4b35-a3b2-3b54c28fc3be");
public const string ThirdFieldName = "Third";
}
/// <summary>
/// A_New_Template
/// <para></para>
/// <para>Path: /sitecore/templates/Testing/A new Template</para>
/// <para>ID: e974ac12-1313-4bfd-bb61-c0d943a2c67a</para>
/// </summary>
[SitecoreType(TemplateId=IA_New_TemplateConstants.TemplateIdString)] //, Cachable = true
public partial class A_New_Template : GlassBase, IA_New_Template
{
/// <summary>
/// The First field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: fb1aa7f4-6cd9-447f-9cdb-564a6299229b</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField(IA_New_TemplateConstants.FirstFieldName)]
public virtual string First {get; set;}
/// <summary>
/// The Fourthh field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 27e6f98a-a6ba-4e1f-874f-e1b5414bec80</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField(IA_New_TemplateConstants.FourthhFieldName)]
public virtual string Fourthh {get; set;}
/// <summary>
/// The Second field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 30530e87-81d5-4b65-9d89-2f9a608a5262</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField(IA_New_TemplateConstants.SecondFieldName)]
public virtual string Second {get; set;}
/// <summary>
/// The Third field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 86360e6e-1714-4b35-a3b2-3b54c28fc3be</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField(IA_New_TemplateConstants.ThirdFieldName)]
public virtual string Third {get; set;}
}
}
namespace TDSTesting.TDSTesting.sitecore.templates.Testing
{
/// <summary>
/// ITdsTemplate Interface
/// <para></para>
/// <para>Path: /sitecore/templates/Testing/TdsTemplate</para>
/// <para>ID: fd6aa65c-da67-4e3c-a93b-7c61c658114e</para>
/// </summary>
[SitecoreType(TemplateId=ITdsTemplateConstants.TemplateIdString )] //, Cachable = true
public partial interface ITdsTemplate : IGlassBase
{
/// <summary>
/// The ASDF field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: dea28280-33ad-431b-8f5b-a8bba3980560</para>
/// <para>Custom Data: </para>
/// </summary>
[SitecoreField(ITdsTemplateConstants.ASDFFieldName)]
string ASDF {get; set;}
/// <summary>
/// The Testing field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 85721cb6-cc1e-4e12-b222-f2479cfc284f</para>
/// <para>Custom Data: </para>
/// </summary>
[SitecoreField(ITdsTemplateConstants.TestingFieldName)]
string Testing {get; set;}
/// <summary>
/// The Wup field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 2c7fa073-f071-4a97-9899-6e5dc31bbff1</para>
/// <para>Custom Data: </para>
/// </summary>
[SitecoreField(ITdsTemplateConstants.WupFieldName)]
string Wup {get; set;}
/// <summary>
/// The Wurf field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 66d222e7-88dd-4257-97e0-8934487796db</para>
/// <para>Custom Data: </para>
/// </summary>
[SitecoreField(ITdsTemplateConstants.WurfFieldName)]
string Wurf {get; set;}
}
public static partial class ITdsTemplateConstants{
public const string TemplateIdString = "fd6aa65c-da67-4e3c-a93b-7c61c658114e";
public static readonly ID TemplateId = new ID(TemplateIdString);
public const string TemplateName = "TdsTemplate";
public static readonly ID ASDFFieldId = new ID("dea28280-33ad-431b-8f5b-a8bba3980560");
public const string ASDFFieldName = "ASDF";
public static readonly ID TestingFieldId = new ID("85721cb6-cc1e-4e12-b222-f2479cfc284f");
public const string TestingFieldName = "Testing";
public static readonly ID WupFieldId = new ID("2c7fa073-f071-4a97-9899-6e5dc31bbff1");
public const string WupFieldName = "Wup";
public static readonly ID WurfFieldId = new ID("66d222e7-88dd-4257-97e0-8934487796db");
public const string WurfFieldName = "Wurf";
}
/// <summary>
/// TdsTemplate
/// <para></para>
/// <para>Path: /sitecore/templates/Testing/TdsTemplate</para>
/// <para>ID: fd6aa65c-da67-4e3c-a93b-7c61c658114e</para>
/// </summary>
[SitecoreType(TemplateId=ITdsTemplateConstants.TemplateIdString)] //, Cachable = true
public partial class TdsTemplate : GlassBase, ITdsTemplate
{
/// <summary>
/// The ASDF field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: dea28280-33ad-431b-8f5b-a8bba3980560</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField(ITdsTemplateConstants.ASDFFieldName)]
public virtual string ASDF {get; set;}
/// <summary>
/// The Testing field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 85721cb6-cc1e-4e12-b222-f2479cfc284f</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField(ITdsTemplateConstants.TestingFieldName)]
public virtual string Testing {get; set;}
/// <summary>
/// The Wup field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 2c7fa073-f071-4a97-9899-6e5dc31bbff1</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField(ITdsTemplateConstants.WupFieldName)]
public virtual string Wup {get; set;}
/// <summary>
/// The Wurf field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 66d222e7-88dd-4257-97e0-8934487796db</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField(ITdsTemplateConstants.WurfFieldName)]
public virtual string Wurf {get; set;}
}
}
| |
// MIT License
//
// Copyright (c) 2017 Maarten van Sambeek.
//
// 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.
namespace ConnectQl.Tools.Mef
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConnectQl.Intellisense;
using ConnectQl.Interfaces;
using ConnectQl.Results;
using ConnectQl.Tools.Mef.Intellisense;
using Interfaces;
using JetBrains.Annotations;
using Microsoft.VisualStudio.Text;
/// <summary>
/// The ConnectQl document.
/// </summary>
internal class ConnectQlDocument : IDocument
{
/// <summary>
/// The session.
/// </summary>
private readonly IntellisenseSession session;
/// <summary>
/// The functions.
/// </summary>
private IReadOnlyList<IFunctionDescriptor> functions = new IFunctionDescriptor[0];
/// <summary>
/// The messages.
/// </summary>
private IReadOnlyList<IMessage> messages = new IMessage[0];
/// <summary>
/// The sources.
/// </summary>
private IReadOnlyList<IDataSourceDescriptorRange> sources = new IDataSourceDescriptorRange[0];
/// <summary>
/// The tokens.
/// </summary>
private IReadOnlyList<IClassifiedToken> tokens = new IClassifiedToken[0];
/// <summary>
/// The variables.
/// </summary>
private IReadOnlyList<IVariableDescriptorRange> variables = new IVariableDescriptorRange[0];
/// <summary>
/// The plugins.
/// </summary>
private IReadOnlyList<string> plugins = new string[0];
/// <summary>
/// Initializes a new instance of the <see cref="ConnectQlDocument"/> class.
/// </summary>
/// <param name="session">
/// The session this document is part of.
/// </param>
/// <param name="filename">
/// The filename.
/// </param>
public ConnectQlDocument(IntellisenseSession session, string filename)
{
this.session = session;
this.Filename = filename;
}
/// <summary>
/// Raised when the document changed.
/// </summary>
public event EventHandler<DocumentChangedEventArgs> DocumentChanged;
/// <summary>
/// Gets or sets the content.
/// </summary>
public string Content { get; set; }
/// <summary>
/// Gets the filename.
/// </summary>
public string Filename { get; }
/// <summary>
/// Gets or sets the version of the document.
/// </summary>
public int Version { get; set; }
/// <summary>
/// Gets the classified tokens for the specified span.
/// </summary>
/// <param name="span">
/// The span.
/// </param>
/// <returns>
/// The tokens.
/// </returns>
[NotNull]
public IEnumerable<IClassifiedToken> GetClassifiedTokens(SnapshotSpan span)
{
return this.tokens.SkipWhile(t => t.End < span.Start.Position).TakeWhile(t => t.Start < span.End.Position);
}
/// <summary>
/// Gets the functions by name.
/// </summary>
/// <param name="name">
/// The name of the functions.
/// </param>
/// <returns>
/// The function descriptors.
/// </returns>
[NotNull]
public IEnumerable<IFunctionDescriptor> GetFunctionsByName(string name)
{
return this.functions.Where(f => string.Equals(f.Name, name, StringComparison.InvariantCultureIgnoreCase));
}
/// <summary>
/// Gets the available functions.
/// </summary>
/// <returns>
/// The <see cref="IEnumerable{T}"/>.
/// </returns>
public IEnumerable<IFunctionDescriptor> GetAvailableFunctions()
{
return this.functions;
}
/// <summary>
/// Gets the messages for the document.
/// </summary>
/// <param name="span">
/// The span.
/// </param>
/// <returns>
/// The messages.
/// </returns>
public IEnumerable<IMessage> GetMessages(SnapshotSpan span)
{
return this.messages;
}
/// <summary>
/// Gets the messages for the document.
/// </summary>
/// <returns>
/// All messages for this document.
/// </returns>
public IEnumerable<IMessage> GetMessages()
{
return this.messages;
}
/// <summary>
/// Gets the classified tokens at the specified point.
/// </summary>
/// <param name="point">
/// The point to get the token at.
/// </param>
/// <returns>
/// The tokens.
/// </returns>
[CanBeNull]
public IClassifiedToken GetTokenAt(SnapshotPoint point)
{
return this.tokens.SkipWhile(t => t.End < point.Position).FirstOrDefault();
}
/// <summary>
/// Updates the classifications for this document.
/// </summary>
/// <param name="document">
/// The document received from the app domain.
/// </param>
public void UpdateClassification([NotNull] IDocumentDescriptor document)
{
var changeType = DocumentChangeType.None;
if (document.Tokens != null)
{
this.tokens = document.Tokens;
changeType |= DocumentChangeType.Tokens;
}
if (document.Messages != null)
{
this.messages = document.Messages;
changeType |= DocumentChangeType.Messages;
}
if (document.Functions != null)
{
this.functions = document.Functions;
changeType |= DocumentChangeType.Functions;
}
if (document.Sources != null)
{
this.sources = document.Sources;
changeType |= DocumentChangeType.Sources;
}
if (document.Variables != null)
{
this.variables = document.Variables;
changeType |= DocumentChangeType.Variables;
}
if (document.Plugins != null)
{
this.plugins = document.Plugins;
changeType |= DocumentChangeType.Plugins;
}
this.DocumentChanged?.Invoke(this, new DocumentChangedEventArgs(changeType));
}
/// <summary>
/// Gets the available sources.
/// </summary>
/// <param name="snapshotPoint">
/// The snapshot point.
/// </param>
/// <returns>
/// The sources.
/// </returns>
[NotNull]
public IEnumerable<IDataSourceDescriptor> GetAvailableSources(SnapshotPoint snapshotPoint)
{
return this.sources.Where(s => s.Start <= snapshotPoint.Position && s.End >= snapshotPoint.Position).Select(s => s.DataSource);
}
/// <summary>
/// Gets the available variables..
/// </summary>
/// <param name="snapshotPoint">
/// The snapshot point.
/// </param>
/// <returns>
/// The variables.
/// </returns>
[NotNull]
public IEnumerable<IVariableDescriptor> GetAvailableVariables(SnapshotPoint snapshotPoint)
{
return this.variables.Where(v => v.Start < snapshotPoint.Position).OrderByDescending(v => v.Start).Select(v => v.Variable);
}
/// <summary>
/// Gets the classified tokens at the specified token.
/// </summary>
/// <param name="token">
/// The token to get the token at.
/// </param>
/// <returns>
/// The tokens.
/// </returns>
[CanBeNull]
public IClassifiedToken GetTokenBefore(IClassifiedToken token)
{
return this.tokens.TakeWhile(t => !t.Equals(token)).LastOrDefault();
}
/// <summary>
/// Gets the available plugins.
/// </summary>
/// <returns>
/// The list of plugin names.
/// </returns>
public IEnumerable<string> GetAvailablePlugins()
{
return this.plugins;
}
/// <summary>
/// Gets the automatic completions.
/// </summary>
/// <param name="current">The current token.</param>
/// <returns>The completions.</returns>
public IAutoCompletions GetAutoCompletions(IClassifiedToken current)
{
return AutoComplete.GetCompletions(this.tokens, current);
}
/// <summary>
/// Executes the query in the document.
/// </summary>
/// <returns>
/// The execute result.
/// </returns>
public async Task<IExecuteResult> ExecuteAsync()
{
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(this.Content)))
{
return await this.session.ExecuteAsync(this.Filename, ms);
}
}
}
}
| |
// 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.Linq;
using Xunit;
namespace System.IO.Tests
{
public class Directory_CreateDirectory : FileSystemTest
{
#region Utilities
public virtual DirectoryInfo Create(string path)
{
return Directory.CreateDirectory(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullAsPath_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => Create(null));
}
[Fact]
public void EmptyAsPath_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => Create(string.Empty));
}
[Theory, MemberData(nameof(PathsWithInvalidCharacters))]
public void PathWithInvalidCharactersAsPath_ThrowsArgumentException(string invalidPath)
{
if (invalidPath.Equals(@"\\?\") && !PathFeatures.IsUsingLegacyPathNormalization())
Assert.Throws<IOException>(() => Create(invalidPath));
else if (invalidPath.Contains(@"\\?\") && !PathFeatures.IsUsingLegacyPathNormalization())
Assert.Throws<DirectoryNotFoundException>(() => Create(invalidPath));
else
Assert.Throws<ArgumentException>(() => Create(invalidPath));
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
Assert.Throws<IOException>(() => Create(path));
Assert.Throws<IOException>(() => Create(IOServices.AddTrailingSlashIfNeeded(path)));
Assert.Throws<IOException>(() => Create(IOServices.RemoveTrailingSlash(path)));
}
[Theory]
[InlineData(FileAttributes.Hidden)]
[InlineData(FileAttributes.ReadOnly)]
[InlineData(FileAttributes.Normal)]
public void PathAlreadyExistsAsDirectory(FileAttributes attributes)
{
DirectoryInfo testDir = Create(GetTestFilePath());
FileAttributes original = testDir.Attributes;
try
{
testDir.Attributes = attributes;
Assert.Equal(testDir.FullName, Create(testDir.FullName).FullName);
}
finally
{
testDir.Attributes = original;
}
}
[Fact]
public void RootPath()
{
string dirName = Path.GetPathRoot(Directory.GetCurrentDirectory());
DirectoryInfo dir = Create(dirName);
Assert.Equal(dir.FullName, dirName);
}
[Fact]
public void DotIsCurrentDirectory()
{
string path = GetTestFilePath();
DirectoryInfo result = Create(Path.Combine(path, "."));
Assert.Equal(IOServices.RemoveTrailingSlash(path), result.FullName);
result = Create(Path.Combine(path, ".") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(path), result.FullName);
}
[Fact]
public void CreateCurrentDirectory()
{
DirectoryInfo result = Create(Directory.GetCurrentDirectory());
Assert.Equal(Directory.GetCurrentDirectory(), result.FullName);
}
[Fact]
public void DotDotIsParentDirectory()
{
DirectoryInfo result = Create(Path.Combine(GetTestFilePath(), ".."));
Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName);
result = Create(Path.Combine(GetTestFilePath(), "..") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName);
}
[Fact]
public void ValidPathWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component));
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(result.Exists);
});
}
[ConditionalFact(nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // trailing slash
public void ValidExtendedPathWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = IOInputs.ExtendedPrefix + IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component));
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(result.Exists);
});
}
[Fact]
public void ValidPathWithoutTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = testDir.FullName + Path.DirectorySeparatorChar + component;
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
public void ValidPathWithMultipleSubdirectories()
{
string dirName = Path.Combine(GetTestFilePath(), "Test", "Test", "Test");
DirectoryInfo dir = Create(dirName);
Assert.Equal(dir.FullName, dirName);
}
[Fact]
public void AllowedSymbols()
{
string dirName = Path.Combine(TestDirectory, Path.GetRandomFileName() + "!@#$%^&");
DirectoryInfo dir = Create(dirName);
Assert.Equal(dir.FullName, dirName);
}
[Fact]
public void DirectoryEqualToMaxDirectory_CanBeCreated()
{
DirectoryInfo testDir = Create(GetTestFilePath());
PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, IOInputs.MaxComponent);
Assert.All(path.SubPaths, (subpath) =>
{
DirectoryInfo result = Create(subpath);
Assert.Equal(subpath, result.FullName);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
public void DirectoryEqualToMaxDirectory_CanBeCreatedAllAtOnce()
{
DirectoryInfo testDir = Create(GetTestFilePath());
PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, maxComponent: 10);
DirectoryInfo result = Create(path.FullPath);
Assert.Equal(path.FullPath, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
public void DirectoryWithComponentLongerThanMaxComponentAsPath_ThrowsPathTooLongException()
{
// While paths themselves can be up to 260 characters including trailing null, file systems
// limit each components of the path to a total of 255 characters.
var paths = IOInputs.GetPathsWithComponentLongerThanMaxComponent();
Assert.All(paths, (path) =>
{
Assert.Throws<PathTooLongException>(() => Create(path));
});
}
#endregion
#region PlatformSpecific
[Theory, MemberData(nameof(PathsWithInvalidColons))]
[PlatformSpecific(TestPlatforms.Windows)] // invalid colons throws ArgumentException
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Versions of netfx older than 4.6.2 throw an ArgumentException instead of NotSupportedException. Until all of our machines run netfx against the actual latest version, these will fail.")]
public void PathWithInvalidColons_ThrowsNotSupportedException(string invalidPath)
{
Assert.Throws<NotSupportedException>(() => Create(invalidPath));
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // long directory path succeeds
public void DirectoryLongerThanMaxPath_Succeeds()
{
var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath());
Assert.All(paths, (path) =>
{
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // long directory path throws PathTooLongException
public void DirectoryLongerThanMaxLongPath_ThrowsPathTooLongException()
{
var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath());
Assert.All(paths, (path) =>
{
Assert.Throws<PathTooLongException>(() => Create(path));
});
}
[ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // long directory path with extended syntax throws PathTooLongException
public void DirectoryLongerThanMaxLongPathWithExtendedSyntax_ThrowsPathTooLongException()
{
var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath(), useExtendedSyntax: true);
Assert.All(paths, (path) =>
{
Assert.Throws<PathTooLongException>(() => Create(path));
});
}
[ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // long directory path with extended syntax succeeds
public void ExtendedDirectoryLongerThanLegacyMaxPath_Succeeds()
{
var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath(), useExtendedSyntax: true);
Assert.All(paths, (path) =>
{
Assert.True(Create(path).Exists);
});
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // long directory path succeeds
public void DirectoryLongerThanMaxDirectoryAsPath_Succeeds()
{
var paths = IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath());
Assert.All(paths, (path) =>
{
var result = Create(path);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // long directory path allowed
public void UnixPathLongerThan256_Allowed()
{
DirectoryInfo testDir = Create(GetTestFilePath());
PathInfo path = IOServices.GetPath(testDir.FullName, 257, IOInputs.MaxComponent);
DirectoryInfo result = Create(path.FullPath);
Assert.Equal(path.FullPath, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // deeply nested directories allowed
public void UnixPathWithDeeplyNestedDirectories()
{
DirectoryInfo parent = Create(GetTestFilePath());
for (int i = 1; i <= 100; i++) // 100 == arbitrarily large number of directories
{
parent = Create(Path.Combine(parent.FullName, "dir" + i));
Assert.True(Directory.Exists(parent.FullName));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // whitespace as path throws ArgumentException on Windows
public void WindowsWhiteSpaceAsPath_ThrowsArgumentException()
{
var paths = IOInputs.GetWhiteSpace();
Assert.All(paths, (path) =>
{
Assert.Throws<ArgumentException>(() => Create(path));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // whitespace as path allowed
public void UnixWhiteSpaceAsPath_Allowed()
{
var paths = IOInputs.GetWhiteSpace();
Assert.All(paths, (path) =>
{
Create(Path.Combine(TestDirectory, path));
Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // trailing whitespace in path is removed on Windows
public void WindowsTrailingWhiteSpace()
{
// Windows will remove all non-significant whitespace in a path
DirectoryInfo testDir = Create(GetTestFilePath());
var components = IOInputs.GetWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
});
}
[ConditionalFact(nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // extended syntax with whitespace
public void WindowsExtendedSyntaxWhiteSpace()
{
var paths = IOInputs.GetSimpleWhiteSpace();
foreach (var path in paths)
{
string extendedPath = Path.Combine(IOInputs.ExtendedPrefix + TestDirectory, path);
Directory.CreateDirectory(extendedPath);
Assert.True(Directory.Exists(extendedPath), extendedPath);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // trailing whitespace in path treated as significant on Unix
public void UnixNonSignificantTrailingWhiteSpace()
{
// Unix treats trailing/prename whitespace as significant and a part of the name.
DirectoryInfo testDir = Create(GetTestFilePath());
var components = IOInputs.GetWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // alternate data streams
public void PathWithAlternateDataStreams_ThrowsNotSupportedException()
{
var paths = IOInputs.GetPathsWithAlternativeDataStreams();
Assert.All(paths, (path) =>
{
Assert.Throws<NotSupportedException>(() => Create(path));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // device name prefixes
public void PathWithReservedDeviceNameAsPath_ThrowsDirectoryNotFoundException()
{ // Throws DirectoryNotFoundException, when the behavior really should be an invalid path
var paths = IOInputs.GetPathsWithReservedDeviceNames();
Assert.All(paths, (path) =>
{
Assert.Throws<DirectoryNotFoundException>(() => Create(path));
});
}
[ConditionalFact(nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // device name prefixes
public void PathWithReservedDeviceNameAsExtendedPath()
{
var paths = IOInputs.GetReservedDeviceNames();
Assert.All(paths, (path) =>
{
Assert.True(Create(IOInputs.ExtendedPrefix + Path.Combine(TestDirectory, path)).Exists, path);
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // UNC shares
public void UncPathWithoutShareNameAsPath_ThrowsArgumentException()
{
var paths = IOInputs.GetUncPathsWithoutShareName();
foreach (var path in paths)
{
Assert.Throws<ArgumentException>(() => Create(path));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // UNC shares
public void UNCPathWithOnlySlashes()
{
Assert.Throws<ArgumentException>(() => Create("//"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // drive labels
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
public void CDriveCase()
{
DirectoryInfo dir = Create("c:\\");
DirectoryInfo dir2 = Create("C:\\");
Assert.NotEqual(dir.FullName, dir2.FullName);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // drive letters
public void DriveLetter_Windows()
{
// On Windows, DirectoryInfo will replace "<DriveLetter>:" with "."
var driveLetter = Create(Directory.GetCurrentDirectory()[0] + ":");
var current = Create(".");
Assert.Equal(current.Name, driveLetter.Name);
Assert.Equal(current.FullName, driveLetter.FullName);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // drive letters casing
public void DriveLetter_Unix()
{
// On Unix, there's no special casing for drive letters. These may or may not be valid names, depending
// on the file system underlying the current directory. Unix file systems typically allow these, but,
// for example, these names are not allowed if running on a file system mounted from a Windows machine.
DirectoryInfo driveLetter;
try
{
driveLetter = Create("C:");
}
catch (IOException)
{
return;
}
var current = Create(".");
Assert.Equal("C:", driveLetter.Name);
Assert.Equal(Path.Combine(current.FullName, "C:"), driveLetter.FullName);
try
{
// If this test is inherited then it's possible this call will fail due to the "C:" directory
// being deleted in that other test before this call. What we care about testing (proper path
// handling) is unaffected by this race condition.
Directory.Delete("C:");
}
catch (DirectoryNotFoundException) { }
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // testing drive labels
public void NonExistentDriveAsPath_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
Create(IOServices.GetNonExistentDrive());
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // testing drive labels
public void SubdirectoryOnNonExistentDriveAsPath_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
Create(Path.Combine(IOServices.GetNonExistentDrive(), "Subdirectory"));
});
}
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(TestPlatforms.Windows)] // testing drive labels
public void NotReadyDriveAsPath_ThrowsDirectoryNotFoundException()
{ // Behavior is suspect, should really have thrown IOException similar to the SubDirectory case
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
Assert.Throws<DirectoryNotFoundException>(() =>
{
Create(drive);
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // testing drive labels
[ActiveIssue(1221)]
public void SubdirectoryOnNotReadyDriveAsPath_ThrowsIOException()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
// 'Device is not ready'
Assert.Throws<IOException>(() =>
{
Create(Path.Combine(drive, "Subdirectory"));
});
}
#if !TEST_WINRT // Cannot set current directory to root from appcontainer with it's default ACL
/*
[Fact]
public void DotDotAsPath_WhenCurrentDirectoryIsRoot_DoesNotThrow()
{
string root = Path.GetPathRoot(Directory.GetCurrentDirectory());
using (CurrentDirectoryContext context = new CurrentDirectoryContext(root))
{
DirectoryInfo result = Create("..");
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(root, result.FullName);
}
}
*/
#endif
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Document = Lucene.Net.Documents.Document;
using FieldSelector = Lucene.Net.Documents.FieldSelector;
using CorruptIndexException = Lucene.Net.Index.CorruptIndexException;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using ReaderUtil = Lucene.Net.Util.ReaderUtil;
namespace Lucene.Net.Search
{
/// <summary>Implements search over a set of <code>Searchables</code>.
///
/// <p/>Applications usually need only call the inherited {@link #Search(Query)}
/// or {@link #Search(Query,Filter)} methods.
/// </summary>
public class MultiSearcher:Searcher
{
private class AnonymousClassCollector:Collector
{
public AnonymousClassCollector(Lucene.Net.Search.Collector collector, int start, MultiSearcher enclosingInstance)
{
InitBlock(collector, start, enclosingInstance);
}
private void InitBlock(Lucene.Net.Search.Collector collector, int start, MultiSearcher enclosingInstance)
{
this.collector = collector;
this.start = start;
this.enclosingInstance = enclosingInstance;
}
private Lucene.Net.Search.Collector collector;
private int start;
private MultiSearcher enclosingInstance;
public MultiSearcher Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public override void SetScorer(Scorer scorer)
{
collector.SetScorer(scorer);
}
public override void Collect(int doc)
{
collector.Collect(doc);
}
public override void SetNextReader(IndexReader reader, int docBase)
{
collector.SetNextReader(reader, start + docBase);
}
public override bool AcceptsDocsOutOfOrder()
{
return collector.AcceptsDocsOutOfOrder();
}
}
/// <summary> Document Frequency cache acting as a Dummy-Searcher. This class is no
/// full-fledged Searcher, but only supports the methods necessary to
/// initialize Weights.
/// </summary>
private class CachedDfSource:Searcher
{
private System.Collections.IDictionary dfMap; // Map from Terms to corresponding doc freqs
private int maxDoc; // document count
public CachedDfSource(System.Collections.IDictionary dfMap, int maxDoc, Similarity similarity)
{
this.dfMap = dfMap;
this.maxDoc = maxDoc;
SetSimilarity(similarity);
}
public override int DocFreq(Term term)
{
int df;
try
{
df = ((System.Int32) dfMap[term]);
}
catch (System.NullReferenceException e)
{
throw new System.ArgumentException("df for term " + term.Text() + " not available");
}
return df;
}
public override int[] DocFreqs(Term[] terms)
{
int[] result = new int[terms.Length];
for (int i = 0; i < terms.Length; i++)
{
result[i] = DocFreq(terms[i]);
}
return result;
}
public override int MaxDoc()
{
return maxDoc;
}
public override Query Rewrite(Query query)
{
// this is a bit of a hack. We know that a query which
// creates a Weight based on this Dummy-Searcher is
// always already rewritten (see preparedWeight()).
// Therefore we just return the unmodified query here
return query;
}
public override void Close()
{
throw new System.NotSupportedException();
}
/// <summary>
/// .NET
/// </summary>
public override void Dispose()
{
Close();
}
public override Document Doc(int i)
{
throw new System.NotSupportedException();
}
public override Document Doc(int i, FieldSelector fieldSelector)
{
throw new System.NotSupportedException();
}
public override Explanation Explain(Weight weight, int doc)
{
throw new System.NotSupportedException();
}
public override void Search(Weight weight, Filter filter, Collector results)
{
throw new System.NotSupportedException();
}
public override TopDocs Search(Weight weight, Filter filter, int n)
{
throw new System.NotSupportedException();
}
public override TopFieldDocs Search(Weight weight, Filter filter, int n, Sort sort)
{
throw new System.NotSupportedException();
}
}
private Searchable[] searchables;
private int[] starts;
private int maxDoc = 0;
/// <summary>Creates a searcher which searches <i>searchers</i>. </summary>
public MultiSearcher(Searchable[] searchables)
{
this.searchables = searchables;
starts = new int[searchables.Length + 1]; // build starts array
for (int i = 0; i < searchables.Length; i++)
{
starts[i] = maxDoc;
maxDoc += searchables[i].MaxDoc(); // compute maxDocs
}
starts[searchables.Length] = maxDoc;
}
/// <summary>Return the array of {@link Searchable}s this searches. </summary>
public virtual Searchable[] GetSearchables()
{
return searchables;
}
protected internal virtual int[] GetStarts()
{
return starts;
}
// inherit javadoc
public override void Close()
{
for (int i = 0; i < searchables.Length; i++)
searchables[i].Close();
}
/// <summary>
/// .NET
/// </summary>
public override void Dispose()
{
Close();
}
public override int DocFreq(Term term)
{
int docFreq = 0;
for (int i = 0; i < searchables.Length; i++)
docFreq += searchables[i].DocFreq(term);
return docFreq;
}
// inherit javadoc
public override Document Doc(int n)
{
int i = SubSearcher(n); // find searcher index
return searchables[i].Doc(n - starts[i]); // dispatch to searcher
}
// inherit javadoc
public override Document Doc(int n, FieldSelector fieldSelector)
{
int i = SubSearcher(n); // find searcher index
return searchables[i].Doc(n - starts[i], fieldSelector); // dispatch to searcher
}
/// <summary>Returns index of the searcher for document <code>n</code> in the array
/// used to construct this searcher.
/// </summary>
public virtual int SubSearcher(int n)
{
// find searcher for doc n:
return ReaderUtil.SubIndex(n, starts);
}
/// <summary>Returns the document number of document <code>n</code> within its
/// sub-index.
/// </summary>
public virtual int SubDoc(int n)
{
return n - starts[SubSearcher(n)];
}
public override int MaxDoc()
{
return maxDoc;
}
public override TopDocs Search(Weight weight, Filter filter, int nDocs)
{
HitQueue hq = new HitQueue(nDocs, false);
int totalHits = 0;
for (int i = 0; i < searchables.Length; i++)
{
// search each searcher
TopDocs docs = searchables[i].Search(weight, filter, nDocs);
totalHits += docs.TotalHits; // update totalHits
ScoreDoc[] scoreDocs = docs.ScoreDocs;
for (int j = 0; j < scoreDocs.Length; j++)
{
// merge scoreDocs into hq
ScoreDoc scoreDoc = scoreDocs[j];
scoreDoc.doc += starts[i]; // convert doc
if (!hq.Insert(scoreDoc))
break; // no more scores > minScore
}
}
ScoreDoc[] scoreDocs2 = new ScoreDoc[hq.Size()];
for (int i = hq.Size() - 1; i >= 0; i--)
// put docs in array
scoreDocs2[i] = (ScoreDoc) hq.Pop();
float maxScore = (totalHits == 0)?System.Single.NegativeInfinity:scoreDocs2[0].score;
return new TopDocs(totalHits, scoreDocs2, maxScore);
}
public override TopFieldDocs Search(Weight weight, Filter filter, int n, Sort sort)
{
FieldDocSortedHitQueue hq = null;
int totalHits = 0;
float maxScore = System.Single.NegativeInfinity;
for (int i = 0; i < searchables.Length; i++)
{
// search each searcher
TopFieldDocs docs = searchables[i].Search(weight, filter, n, sort);
// If one of the Sort fields is FIELD_DOC, need to fix its values, so that
// it will break ties by doc Id properly. Otherwise, it will compare to
// 'relative' doc Ids, that belong to two different searchers.
for (int j = 0; j < docs.fields.Length; j++)
{
if (docs.fields[j].GetType() == SortField.DOC)
{
// iterate over the score docs and change their fields value
for (int j2 = 0; j2 < docs.ScoreDocs.Length; j2++)
{
FieldDoc fd = (FieldDoc) docs.ScoreDocs[j2];
fd.fields[j] = (System.Int32) (((System.Int32) fd.fields[j]) + starts[i]);
}
break;
}
}
if (hq == null)
hq = new FieldDocSortedHitQueue(docs.fields, n);
totalHits += docs.TotalHits; // update totalHits
maxScore = System.Math.Max(maxScore, docs.GetMaxScore());
ScoreDoc[] scoreDocs = docs.ScoreDocs;
for (int j = 0; j < scoreDocs.Length; j++)
{
// merge scoreDocs into hq
ScoreDoc scoreDoc = scoreDocs[j];
scoreDoc.doc += starts[i]; // convert doc
if (!hq.Insert(scoreDoc))
break; // no more scores > minScore
}
}
ScoreDoc[] scoreDocs2 = new ScoreDoc[hq.Size()];
for (int i = hq.Size() - 1; i >= 0; i--)
// put docs in array
scoreDocs2[i] = (ScoreDoc) hq.Pop();
return new TopFieldDocs(totalHits, scoreDocs2, hq.GetFields(), maxScore);
}
// inherit javadoc
public override void Search(Weight weight, Filter filter, Collector collector)
{
for (int i = 0; i < searchables.Length; i++)
{
int start = starts[i];
Collector hc = new AnonymousClassCollector(collector, start, this);
searchables[i].Search(weight, filter, hc);
}
}
public override Query Rewrite(Query original)
{
Query[] queries = new Query[searchables.Length];
for (int i = 0; i < searchables.Length; i++)
{
queries[i] = searchables[i].Rewrite(original);
}
return queries[0].Combine(queries);
}
public override Explanation Explain(Weight weight, int doc)
{
int i = SubSearcher(doc); // find searcher index
return searchables[i].Explain(weight, doc - starts[i]); // dispatch to searcher
}
/// <summary> Create weight in multiple index scenario.
///
/// Distributed query processing is done in the following steps:
/// 1. rewrite query
/// 2. extract necessary terms
/// 3. collect dfs for these terms from the Searchables
/// 4. create query weight using aggregate dfs.
/// 5. distribute that weight to Searchables
/// 6. merge results
///
/// Steps 1-4 are done here, 5+6 in the search() methods
///
/// </summary>
/// <returns> rewritten queries
/// </returns>
public /*protected internal*/ override Weight CreateWeight(Query original)
{
// step 1
Query rewrittenQuery = Rewrite(original);
// step 2
System.Collections.Hashtable terms = new System.Collections.Hashtable();
rewrittenQuery.ExtractTerms(terms);
// step3
Term[] allTermsArray = new Term[terms.Count];
int index = 0;
System.Collections.IEnumerator e = terms.Keys.GetEnumerator();
while (e.MoveNext())
allTermsArray[index++] = e.Current as Term;
int[] aggregatedDfs = new int[terms.Count];
for (int i = 0; i < searchables.Length; i++)
{
int[] dfs = searchables[i].DocFreqs(allTermsArray);
for (int j = 0; j < aggregatedDfs.Length; j++)
{
aggregatedDfs[j] += dfs[j];
}
}
System.Collections.Hashtable dfMap = new System.Collections.Hashtable();
for (int i = 0; i < allTermsArray.Length; i++)
{
dfMap[allTermsArray[i]] = (System.Int32) aggregatedDfs[i];
}
// step4
int numDocs = MaxDoc();
CachedDfSource cacheSim = new CachedDfSource(dfMap, numDocs, GetSimilarity());
return rewrittenQuery.Weight(cacheSim);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Xml
{
public enum ConformanceLevel
{
Auto = 0,
Document = 2,
Fragment = 1,
}
public enum DtdProcessing
{
Ignore = 1,
Prohibit = 0,
}
public partial interface IXmlLineInfo
{
int LineNumber { get; }
int LinePosition { get; }
bool HasLineInfo();
}
public partial interface IXmlNamespaceResolver
{
System.Collections.Generic.IDictionary<string, string> GetNamespacesInScope(System.Xml.XmlNamespaceScope scope);
string LookupNamespace(string prefix);
string LookupPrefix(string namespaceName);
}
[System.FlagsAttribute]
public enum NamespaceHandling
{
Default = 0,
OmitDuplicates = 1,
}
public partial class NameTable : System.Xml.XmlNameTable
{
public NameTable() { }
public override string Add(char[] key, int start, int len) { return default(string); }
public override string Add(string key) { return default(string); }
public override string Get(char[] key, int start, int len) { return default(string); }
public override string Get(string value) { return default(string); }
}
public enum NewLineHandling
{
Entitize = 1,
None = 2,
Replace = 0,
}
public enum ReadState
{
Closed = 4,
EndOfFile = 3,
Error = 2,
Initial = 0,
Interactive = 1,
}
public enum WriteState
{
Attribute = 3,
Closed = 5,
Content = 4,
Element = 2,
Error = 6,
Prolog = 1,
Start = 0,
}
public static partial class XmlConvert
{
public static string DecodeName(string name) { return default(string); }
public static string EncodeLocalName(string name) { return default(string); }
public static string EncodeName(string name) { return default(string); }
public static string EncodeNmToken(string name) { return default(string); }
public static bool ToBoolean(string s) { return default(bool); }
public static byte ToByte(string s) { return default(byte); }
public static char ToChar(string s) { return default(char); }
public static System.DateTime ToDateTime(string s, System.Xml.XmlDateTimeSerializationMode dateTimeOption) { return default(System.DateTime); }
public static System.DateTimeOffset ToDateTimeOffset(string s) { return default(System.DateTimeOffset); }
public static System.DateTimeOffset ToDateTimeOffset(string s, string format) { return default(System.DateTimeOffset); }
public static System.DateTimeOffset ToDateTimeOffset(string s, string[] formats) { return default(System.DateTimeOffset); }
public static decimal ToDecimal(string s) { return default(decimal); }
public static double ToDouble(string s) { return default(double); }
public static System.Guid ToGuid(string s) { return default(System.Guid); }
public static short ToInt16(string s) { return default(short); }
public static int ToInt32(string s) { return default(int); }
public static long ToInt64(string s) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string s) { return default(sbyte); }
public static float ToSingle(string s) { return default(float); }
public static string ToString(bool value) { return default(string); }
public static string ToString(byte value) { return default(string); }
public static string ToString(char value) { return default(string); }
public static string ToString(System.DateTime value, System.Xml.XmlDateTimeSerializationMode dateTimeOption) { return default(string); }
public static string ToString(System.DateTimeOffset value) { return default(string); }
public static string ToString(System.DateTimeOffset value, string format) { return default(string); }
public static string ToString(decimal value) { return default(string); }
public static string ToString(double value) { return default(string); }
public static string ToString(System.Guid value) { return default(string); }
public static string ToString(short value) { return default(string); }
public static string ToString(int value) { return default(string); }
public static string ToString(long value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(sbyte value) { return default(string); }
public static string ToString(float value) { return default(string); }
public static string ToString(System.TimeSpan value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ushort value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(uint value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ulong value) { return default(string); }
public static System.TimeSpan ToTimeSpan(string s) { return default(System.TimeSpan); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(string s) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(string s) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(string s) { return default(ulong); }
public static string VerifyName(string name) { return default(string); }
public static string VerifyNCName(string name) { return default(string); }
public static string VerifyNMTOKEN(string name) { return default(string); }
public static string VerifyPublicId(string publicId) { return default(string); }
public static string VerifyWhitespace(string content) { return default(string); }
public static string VerifyXmlChars(string content) { return default(string); }
}
public enum XmlDateTimeSerializationMode
{
Local = 0,
RoundtripKind = 3,
Unspecified = 2,
Utc = 1,
}
public partial class XmlException : System.Exception
{
public XmlException() { }
public XmlException(string message) { }
public XmlException(string message, System.Exception innerException) { }
public XmlException(string message, System.Exception innerException, int lineNumber, int linePosition) { }
public int LineNumber { get { return default(int); } }
public int LinePosition { get { return default(int); } }
public override string Message { get { return default(string); } }
}
public partial class XmlNamespaceManager : System.Collections.IEnumerable, System.Xml.IXmlNamespaceResolver
{
public XmlNamespaceManager(System.Xml.XmlNameTable nameTable) { }
public virtual string DefaultNamespace { get { return default(string); } }
public virtual System.Xml.XmlNameTable NameTable { get { return default(System.Xml.XmlNameTable); } }
public virtual void AddNamespace(string prefix, string uri) { }
public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
public virtual System.Collections.Generic.IDictionary<string, string> GetNamespacesInScope(System.Xml.XmlNamespaceScope scope) { return default(System.Collections.Generic.IDictionary<string, string>); }
public virtual bool HasNamespace(string prefix) { return default(bool); }
public virtual string LookupNamespace(string prefix) { return default(string); }
public virtual string LookupPrefix(string uri) { return default(string); }
public virtual bool PopScope() { return default(bool); }
public virtual void PushScope() { }
public virtual void RemoveNamespace(string prefix, string uri) { }
}
public enum XmlNamespaceScope
{
All = 0,
ExcludeXml = 1,
Local = 2,
}
public abstract partial class XmlNameTable
{
protected XmlNameTable() { }
public abstract string Add(char[] array, int offset, int length);
public abstract string Add(string array);
public abstract string Get(char[] array, int offset, int length);
public abstract string Get(string array);
}
public enum XmlNodeType
{
Attribute = 2,
CDATA = 4,
Comment = 8,
Document = 9,
DocumentFragment = 11,
DocumentType = 10,
Element = 1,
EndElement = 15,
EndEntity = 16,
Entity = 6,
EntityReference = 5,
None = 0,
Notation = 12,
ProcessingInstruction = 7,
SignificantWhitespace = 14,
Text = 3,
Whitespace = 13,
XmlDeclaration = 17,
}
public partial class XmlParserContext
{
public XmlParserContext(System.Xml.XmlNameTable nt, System.Xml.XmlNamespaceManager nsMgr, string docTypeName, string pubId, string sysId, string internalSubset, string baseURI, string xmlLang, System.Xml.XmlSpace xmlSpace) { }
public XmlParserContext(System.Xml.XmlNameTable nt, System.Xml.XmlNamespaceManager nsMgr, string docTypeName, string pubId, string sysId, string internalSubset, string baseURI, string xmlLang, System.Xml.XmlSpace xmlSpace, System.Text.Encoding enc) { }
public XmlParserContext(System.Xml.XmlNameTable nt, System.Xml.XmlNamespaceManager nsMgr, string xmlLang, System.Xml.XmlSpace xmlSpace) { }
public XmlParserContext(System.Xml.XmlNameTable nt, System.Xml.XmlNamespaceManager nsMgr, string xmlLang, System.Xml.XmlSpace xmlSpace, System.Text.Encoding enc) { }
public string BaseURI { get { return default(string); } set { } }
public string DocTypeName { get { return default(string); } set { } }
public System.Text.Encoding Encoding { get { return default(System.Text.Encoding); } set { } }
public string InternalSubset { get { return default(string); } set { } }
public System.Xml.XmlNamespaceManager NamespaceManager { get { return default(System.Xml.XmlNamespaceManager); } set { } }
public System.Xml.XmlNameTable NameTable { get { return default(System.Xml.XmlNameTable); } set { } }
public string PublicId { get { return default(string); } set { } }
public string SystemId { get { return default(string); } set { } }
public string XmlLang { get { return default(string); } set { } }
public System.Xml.XmlSpace XmlSpace { get { return default(System.Xml.XmlSpace); } set { } }
}
public partial class XmlQualifiedName
{
public static readonly System.Xml.XmlQualifiedName Empty;
public XmlQualifiedName() { }
public XmlQualifiedName(string name) { }
public XmlQualifiedName(string name, string ns) { }
public bool IsEmpty { get { return default(bool); } }
public string Name { get { return default(string); } }
public string Namespace { get { return default(string); } }
public override bool Equals(object other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Xml.XmlQualifiedName a, System.Xml.XmlQualifiedName b) { return default(bool); }
public static bool operator !=(System.Xml.XmlQualifiedName a, System.Xml.XmlQualifiedName b) { return default(bool); }
public override string ToString() { return default(string); }
public static string ToString(string name, string ns) { return default(string); }
}
public abstract partial class XmlReader : System.IDisposable
{
protected XmlReader() { }
public abstract int AttributeCount { get; }
public abstract string BaseURI { get; }
public virtual bool CanReadBinaryContent { get { return default(bool); } }
public virtual bool CanReadValueChunk { get { return default(bool); } }
public virtual bool CanResolveEntity { get { return default(bool); } }
public abstract int Depth { get; }
public abstract bool EOF { get; }
public virtual bool HasAttributes { get { return default(bool); } }
public virtual bool HasValue { get { return default(bool); } }
public virtual bool IsDefault { get { return default(bool); } }
public abstract bool IsEmptyElement { get; }
public virtual string this[int i] { get { return default(string); } }
public virtual string this[string name] { get { return default(string); } }
public virtual string this[string name, string namespaceURI] { get { return default(string); } }
public abstract string LocalName { get; }
public virtual string Name { get { return default(string); } }
public abstract string NamespaceURI { get; }
public abstract System.Xml.XmlNameTable NameTable { get; }
public abstract System.Xml.XmlNodeType NodeType { get; }
public abstract string Prefix { get; }
public abstract System.Xml.ReadState ReadState { get; }
public virtual System.Xml.XmlReaderSettings Settings { get { return default(System.Xml.XmlReaderSettings); } }
public abstract string Value { get; }
public virtual System.Type ValueType { get { return default(System.Type); } }
public virtual string XmlLang { get { return default(string); } }
public virtual System.Xml.XmlSpace XmlSpace { get { return default(System.Xml.XmlSpace); } }
public static System.Xml.XmlReader Create(System.IO.Stream input) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(System.IO.Stream input, System.Xml.XmlReaderSettings settings) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(System.IO.Stream input, System.Xml.XmlReaderSettings settings, System.Xml.XmlParserContext inputContext) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(System.IO.TextReader input) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(System.IO.TextReader input, System.Xml.XmlReaderSettings settings) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(System.IO.TextReader input, System.Xml.XmlReaderSettings settings, System.Xml.XmlParserContext inputContext) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(string inputUri) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(string inputUri, System.Xml.XmlReaderSettings settings) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(System.Xml.XmlReader reader, System.Xml.XmlReaderSettings settings) { return default(System.Xml.XmlReader); }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract string GetAttribute(int i);
public abstract string GetAttribute(string name);
public abstract string GetAttribute(string name, string namespaceURI);
public virtual System.Threading.Tasks.Task<string> GetValueAsync() { return default(System.Threading.Tasks.Task<string>); }
public static bool IsName(string str) { return default(bool); }
public static bool IsNameToken(string str) { return default(bool); }
public virtual bool IsStartElement() { return default(bool); }
public virtual bool IsStartElement(string name) { return default(bool); }
public virtual bool IsStartElement(string localname, string ns) { return default(bool); }
public abstract string LookupNamespace(string prefix);
public virtual void MoveToAttribute(int i) { }
public abstract bool MoveToAttribute(string name);
public abstract bool MoveToAttribute(string name, string ns);
public virtual System.Xml.XmlNodeType MoveToContent() { return default(System.Xml.XmlNodeType); }
public virtual System.Threading.Tasks.Task<System.Xml.XmlNodeType> MoveToContentAsync() { return default(System.Threading.Tasks.Task<System.Xml.XmlNodeType>); }
public abstract bool MoveToElement();
public abstract bool MoveToFirstAttribute();
public abstract bool MoveToNextAttribute();
public abstract bool Read();
public virtual System.Threading.Tasks.Task<bool> ReadAsync() { return default(System.Threading.Tasks.Task<bool>); }
public abstract bool ReadAttributeValue();
public virtual object ReadContentAs(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver) { return default(object); }
public virtual System.Threading.Tasks.Task<object> ReadContentAsAsync(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver) { return default(System.Threading.Tasks.Task<object>); }
public virtual int ReadContentAsBase64(byte[] buffer, int index, int count) { return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual int ReadContentAsBinHex(byte[] buffer, int index, int count) { return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual bool ReadContentAsBoolean() { return default(bool); }
public virtual System.DateTimeOffset ReadContentAsDateTimeOffset() { return default(System.DateTimeOffset); }
public virtual decimal ReadContentAsDecimal() { return default(decimal); }
public virtual double ReadContentAsDouble() { return default(double); }
public virtual float ReadContentAsFloat() { return default(float); }
public virtual int ReadContentAsInt() { return default(int); }
public virtual long ReadContentAsLong() { return default(long); }
public virtual object ReadContentAsObject() { return default(object); }
public virtual System.Threading.Tasks.Task<object> ReadContentAsObjectAsync() { return default(System.Threading.Tasks.Task<object>); }
public virtual string ReadContentAsString() { return default(string); }
public virtual System.Threading.Tasks.Task<string> ReadContentAsStringAsync() { return default(System.Threading.Tasks.Task<string>); }
public virtual object ReadElementContentAs(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver) { return default(object); }
public virtual object ReadElementContentAs(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver, string localName, string namespaceURI) { return default(object); }
public virtual System.Threading.Tasks.Task<object> ReadElementContentAsAsync(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver) { return default(System.Threading.Tasks.Task<object>); }
public virtual int ReadElementContentAsBase64(byte[] buffer, int index, int count) { return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual bool ReadElementContentAsBoolean() { return default(bool); }
public virtual bool ReadElementContentAsBoolean(string localName, string namespaceURI) { return default(bool); }
public virtual decimal ReadElementContentAsDecimal() { return default(decimal); }
public virtual decimal ReadElementContentAsDecimal(string localName, string namespaceURI) { return default(decimal); }
public virtual double ReadElementContentAsDouble() { return default(double); }
public virtual double ReadElementContentAsDouble(string localName, string namespaceURI) { return default(double); }
public virtual float ReadElementContentAsFloat() { return default(float); }
public virtual float ReadElementContentAsFloat(string localName, string namespaceURI) { return default(float); }
public virtual int ReadElementContentAsInt() { return default(int); }
public virtual int ReadElementContentAsInt(string localName, string namespaceURI) { return default(int); }
public virtual long ReadElementContentAsLong() { return default(long); }
public virtual long ReadElementContentAsLong(string localName, string namespaceURI) { return default(long); }
public virtual object ReadElementContentAsObject() { return default(object); }
public virtual object ReadElementContentAsObject(string localName, string namespaceURI) { return default(object); }
public virtual System.Threading.Tasks.Task<object> ReadElementContentAsObjectAsync() { return default(System.Threading.Tasks.Task<object>); }
public virtual string ReadElementContentAsString() { return default(string); }
public virtual string ReadElementContentAsString(string localName, string namespaceURI) { return default(string); }
public virtual System.Threading.Tasks.Task<string> ReadElementContentAsStringAsync() { return default(System.Threading.Tasks.Task<string>); }
public virtual void ReadEndElement() { }
public virtual string ReadInnerXml() { return default(string); }
public virtual System.Threading.Tasks.Task<string> ReadInnerXmlAsync() { return default(System.Threading.Tasks.Task<string>); }
public virtual string ReadOuterXml() { return default(string); }
public virtual System.Threading.Tasks.Task<string> ReadOuterXmlAsync() { return default(System.Threading.Tasks.Task<string>); }
public virtual void ReadStartElement() { }
public virtual void ReadStartElement(string name) { }
public virtual void ReadStartElement(string localname, string ns) { }
public virtual System.Xml.XmlReader ReadSubtree() { return default(System.Xml.XmlReader); }
public virtual bool ReadToDescendant(string name) { return default(bool); }
public virtual bool ReadToDescendant(string localName, string namespaceURI) { return default(bool); }
public virtual bool ReadToFollowing(string name) { return default(bool); }
public virtual bool ReadToFollowing(string localName, string namespaceURI) { return default(bool); }
public virtual bool ReadToNextSibling(string name) { return default(bool); }
public virtual bool ReadToNextSibling(string localName, string namespaceURI) { return default(bool); }
public virtual int ReadValueChunk(char[] buffer, int index, int count) { return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadValueChunkAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public abstract void ResolveEntity();
public virtual void Skip() { }
public virtual System.Threading.Tasks.Task SkipAsync() { return default(System.Threading.Tasks.Task); }
}
public sealed partial class XmlReaderSettings
{
public XmlReaderSettings() { }
public bool Async { get { return default(bool); } set { } }
public bool CheckCharacters { get { return default(bool); } set { } }
public bool CloseInput { get { return default(bool); } set { } }
public System.Xml.ConformanceLevel ConformanceLevel { get { return default(System.Xml.ConformanceLevel); } set { } }
public System.Xml.DtdProcessing DtdProcessing { get { return default(System.Xml.DtdProcessing); } set { } }
public bool IgnoreComments { get { return default(bool); } set { } }
public bool IgnoreProcessingInstructions { get { return default(bool); } set { } }
public bool IgnoreWhitespace { get { return default(bool); } set { } }
public int LineNumberOffset { get { return default(int); } set { } }
public int LinePositionOffset { get { return default(int); } set { } }
public long MaxCharactersFromEntities { get { return default(long); } set { } }
public long MaxCharactersInDocument { get { return default(long); } set { } }
public System.Xml.XmlNameTable NameTable { get { return default(System.Xml.XmlNameTable); } set { } }
public System.Xml.XmlReaderSettings Clone() { return default(System.Xml.XmlReaderSettings); }
public void Reset() { }
}
public enum XmlSpace
{
Default = 1,
None = 0,
Preserve = 2,
}
public abstract partial class XmlWriter : System.IDisposable
{
protected XmlWriter() { }
public virtual System.Xml.XmlWriterSettings Settings { get { return default(System.Xml.XmlWriterSettings); } }
public abstract System.Xml.WriteState WriteState { get; }
public virtual string XmlLang { get { return default(string); } }
public virtual System.Xml.XmlSpace XmlSpace { get { return default(System.Xml.XmlSpace); } }
public static System.Xml.XmlWriter Create(System.IO.Stream output) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.IO.Stream output, System.Xml.XmlWriterSettings settings) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.IO.TextWriter output) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.IO.TextWriter output, System.Xml.XmlWriterSettings settings) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.Text.StringBuilder output) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.Text.StringBuilder output, System.Xml.XmlWriterSettings settings) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.Xml.XmlWriter output) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.Xml.XmlWriter output, System.Xml.XmlWriterSettings settings) { return default(System.Xml.XmlWriter); }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract void Flush();
public virtual System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); }
public abstract string LookupPrefix(string ns);
public virtual void WriteAttributes(System.Xml.XmlReader reader, bool defattr) { }
public virtual System.Threading.Tasks.Task WriteAttributesAsync(System.Xml.XmlReader reader, bool defattr) { return default(System.Threading.Tasks.Task); }
public void WriteAttributeString(string localName, string value) { }
public void WriteAttributeString(string localName, string ns, string value) { }
public void WriteAttributeString(string prefix, string localName, string ns, string value) { }
public System.Threading.Tasks.Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value) { return default(System.Threading.Tasks.Task); }
public abstract void WriteBase64(byte[] buffer, int index, int count);
public virtual System.Threading.Tasks.Task WriteBase64Async(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public virtual void WriteBinHex(byte[] buffer, int index, int count) { }
public virtual System.Threading.Tasks.Task WriteBinHexAsync(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public abstract void WriteCData(string text);
public virtual System.Threading.Tasks.Task WriteCDataAsync(string text) { return default(System.Threading.Tasks.Task); }
public abstract void WriteCharEntity(char ch);
public virtual System.Threading.Tasks.Task WriteCharEntityAsync(char ch) { return default(System.Threading.Tasks.Task); }
public abstract void WriteChars(char[] buffer, int index, int count);
public virtual System.Threading.Tasks.Task WriteCharsAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public abstract void WriteComment(string text);
public virtual System.Threading.Tasks.Task WriteCommentAsync(string text) { return default(System.Threading.Tasks.Task); }
public abstract void WriteDocType(string name, string pubid, string sysid, string subset);
public virtual System.Threading.Tasks.Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { return default(System.Threading.Tasks.Task); }
public void WriteElementString(string localName, string value) { }
public void WriteElementString(string localName, string ns, string value) { }
public void WriteElementString(string prefix, string localName, string ns, string value) { }
public System.Threading.Tasks.Task WriteElementStringAsync(string prefix, string localName, string ns, string value) { return default(System.Threading.Tasks.Task); }
public abstract void WriteEndAttribute();
protected internal virtual System.Threading.Tasks.Task WriteEndAttributeAsync() { return default(System.Threading.Tasks.Task); }
public abstract void WriteEndDocument();
public virtual System.Threading.Tasks.Task WriteEndDocumentAsync() { return default(System.Threading.Tasks.Task); }
public abstract void WriteEndElement();
public virtual System.Threading.Tasks.Task WriteEndElementAsync() { return default(System.Threading.Tasks.Task); }
public abstract void WriteEntityRef(string name);
public virtual System.Threading.Tasks.Task WriteEntityRefAsync(string name) { return default(System.Threading.Tasks.Task); }
public abstract void WriteFullEndElement();
public virtual System.Threading.Tasks.Task WriteFullEndElementAsync() { return default(System.Threading.Tasks.Task); }
public virtual void WriteName(string name) { }
public virtual System.Threading.Tasks.Task WriteNameAsync(string name) { return default(System.Threading.Tasks.Task); }
public virtual void WriteNmToken(string name) { }
public virtual System.Threading.Tasks.Task WriteNmTokenAsync(string name) { return default(System.Threading.Tasks.Task); }
public virtual void WriteNode(System.Xml.XmlReader reader, bool defattr) { }
public virtual System.Threading.Tasks.Task WriteNodeAsync(System.Xml.XmlReader reader, bool defattr) { return default(System.Threading.Tasks.Task); }
public abstract void WriteProcessingInstruction(string name, string text);
public virtual System.Threading.Tasks.Task WriteProcessingInstructionAsync(string name, string text) { return default(System.Threading.Tasks.Task); }
public virtual void WriteQualifiedName(string localName, string ns) { }
public virtual System.Threading.Tasks.Task WriteQualifiedNameAsync(string localName, string ns) { return default(System.Threading.Tasks.Task); }
public abstract void WriteRaw(char[] buffer, int index, int count);
public abstract void WriteRaw(string data);
public virtual System.Threading.Tasks.Task WriteRawAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteRawAsync(string data) { return default(System.Threading.Tasks.Task); }
public void WriteStartAttribute(string localName) { }
public void WriteStartAttribute(string localName, string ns) { }
public abstract void WriteStartAttribute(string prefix, string localName, string ns);
protected internal virtual System.Threading.Tasks.Task WriteStartAttributeAsync(string prefix, string localName, string ns) { return default(System.Threading.Tasks.Task); }
public abstract void WriteStartDocument();
public abstract void WriteStartDocument(bool standalone);
public virtual System.Threading.Tasks.Task WriteStartDocumentAsync() { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteStartDocumentAsync(bool standalone) { return default(System.Threading.Tasks.Task); }
public void WriteStartElement(string localName) { }
public void WriteStartElement(string localName, string ns) { }
public abstract void WriteStartElement(string prefix, string localName, string ns);
public virtual System.Threading.Tasks.Task WriteStartElementAsync(string prefix, string localName, string ns) { return default(System.Threading.Tasks.Task); }
public abstract void WriteString(string text);
public virtual System.Threading.Tasks.Task WriteStringAsync(string text) { return default(System.Threading.Tasks.Task); }
public abstract void WriteSurrogateCharEntity(char lowChar, char highChar);
public virtual System.Threading.Tasks.Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { return default(System.Threading.Tasks.Task); }
public virtual void WriteValue(bool value) { }
public virtual void WriteValue(System.DateTimeOffset value) { }
public virtual void WriteValue(decimal value) { }
public virtual void WriteValue(double value) { }
public virtual void WriteValue(int value) { }
public virtual void WriteValue(long value) { }
public virtual void WriteValue(object value) { }
public virtual void WriteValue(float value) { }
public virtual void WriteValue(string value) { }
public abstract void WriteWhitespace(string ws);
public virtual System.Threading.Tasks.Task WriteWhitespaceAsync(string ws) { return default(System.Threading.Tasks.Task); }
}
public sealed partial class XmlWriterSettings
{
public XmlWriterSettings() { }
public bool Async { get { return default(bool); } set { } }
public bool CheckCharacters { get { return default(bool); } set { } }
public bool CloseOutput { get { return default(bool); } set { } }
public System.Xml.ConformanceLevel ConformanceLevel { get { return default(System.Xml.ConformanceLevel); } set { } }
public System.Text.Encoding Encoding { get { return default(System.Text.Encoding); } set { } }
public bool Indent { get { return default(bool); } set { } }
public string IndentChars { get { return default(string); } set { } }
public System.Xml.NamespaceHandling NamespaceHandling { get { return default(System.Xml.NamespaceHandling); } set { } }
public string NewLineChars { get { return default(string); } set { } }
public System.Xml.NewLineHandling NewLineHandling { get { return default(System.Xml.NewLineHandling); } set { } }
public bool NewLineOnAttributes { get { return default(bool); } set { } }
public bool OmitXmlDeclaration { get { return default(bool); } set { } }
public bool WriteEndDocumentOnClose { get { return default(bool); } set { } }
public System.Xml.XmlWriterSettings Clone() { return default(System.Xml.XmlWriterSettings); }
public void Reset() { }
}
}
namespace System.Xml.Schema
{
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public partial class XmlSchema
{
internal XmlSchema() { }
}
public enum XmlSchemaForm
{
None = 0,
Qualified = 1,
Unqualified = 2,
}
}
namespace System.Xml.Serialization
{
public partial interface IXmlSerializable
{
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
System.Xml.Schema.XmlSchema GetSchema();
void ReadXml(System.Xml.XmlReader reader);
void WriteXml(System.Xml.XmlWriter writer);
}
[System.AttributeUsageAttribute((System.AttributeTargets)(1036))]
public sealed partial class XmlSchemaProviderAttribute : System.Attribute
{
public XmlSchemaProviderAttribute(string methodName) { }
public bool IsAny { get { return default(bool); } set { } }
public string MethodName { get { return default(string); } }
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SkipUrlEncodingOperations.
/// </summary>
public static partial class SkipUrlEncodingOperationsExtensions
{
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
public static void GetMethodPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodPathValidAsync(unencodedPathParam), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodPathValidAsync(this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetMethodPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
public static void GetPathPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetPathPathValidAsync(unencodedPathParam), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetPathPathValidAsync(this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetPathPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void GetSwaggerPathValid(this ISkipUrlEncodingOperations operations)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetSwaggerPathValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetSwaggerPathValidAsync(this ISkipUrlEncodingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetSwaggerPathValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
public static void GetMethodQueryValid(this ISkipUrlEncodingOperations operations, string q1)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodQueryValidAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodQueryValidAsync(this ISkipUrlEncodingOperations operations, string q1, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetMethodQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
public static void GetMethodQueryNull(this ISkipUrlEncodingOperations operations, string q1 = default(string))
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodQueryNullAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodQueryNullAsync(this ISkipUrlEncodingOperations operations, string q1 = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetMethodQueryNullWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
public static void GetPathQueryValid(this ISkipUrlEncodingOperations operations, string q1)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetPathQueryValidAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetPathQueryValidAsync(this ISkipUrlEncodingOperations operations, string q1, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetPathQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void GetSwaggerQueryValid(this ISkipUrlEncodingOperations operations)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetSwaggerQueryValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetSwaggerQueryValidAsync(this ISkipUrlEncodingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetSwaggerQueryValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
// 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.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal abstract class PlaceholderLocalSymbol : EELocalSymbolBase
{
private readonly MethodSymbol _method;
private readonly string _name;
private readonly TypeSymbol _type;
internal readonly string DisplayName;
internal PlaceholderLocalSymbol(MethodSymbol method, string name, string displayName, TypeSymbol type)
{
_method = method;
_name = name;
_type = type;
this.DisplayName = displayName;
}
internal static LocalSymbol Create(
TypeNameDecoder<PEModuleSymbol, TypeSymbol> typeNameDecoder,
MethodSymbol containingMethod,
AssemblySymbol sourceAssembly,
Alias alias)
{
var typeName = alias.Type;
Debug.Assert(typeName.Length > 0);
var type = typeNameDecoder.GetTypeSymbolForSerializedType(typeName);
Debug.Assert((object)type != null);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(alias.CustomTypeInfoId, alias.CustomTypeInfo, out dynamicFlags, out tupleElementNames);
if (dynamicFlags != null)
{
type = DecodeDynamicTypes(type, sourceAssembly, dynamicFlags);
}
type = TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, tupleElementNames.AsImmutableOrNull());
var name = alias.FullName;
var displayName = alias.Name;
switch (alias.Kind)
{
case DkmClrAliasKind.Exception:
return new ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetExceptionMethodName);
case DkmClrAliasKind.StowedException:
return new ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetStowedExceptionMethodName);
case DkmClrAliasKind.ReturnValue:
{
int index;
PseudoVariableUtilities.TryParseReturnValueIndex(name, out index);
Debug.Assert(index >= 0);
return new ReturnValueLocalSymbol(containingMethod, name, displayName, type, index);
}
case DkmClrAliasKind.ObjectId:
return new ObjectIdLocalSymbol(containingMethod, type, name, displayName, isWritable: false);
case DkmClrAliasKind.Variable:
return new ObjectIdLocalSymbol(containingMethod, type, name, displayName, isWritable: true);
default:
throw ExceptionUtilities.UnexpectedValue(alias.Kind);
}
}
internal override LocalDeclarationKind DeclarationKind
{
get { return LocalDeclarationKind.RegularVariable; }
}
internal override SyntaxToken IdentifierToken
{
get { throw ExceptionUtilities.Unreachable; }
}
public override TypeSymbol Type
{
get { return _type; }
}
internal override bool IsPinned
{
get { return false; }
}
internal override bool IsCompilerGenerated
{
get { return true; }
}
internal override RefKind RefKind
{
get { return RefKind.None; }
}
public override Symbol ContainingSymbol
{
get { return _method; }
}
public override ImmutableArray<Location> Locations
{
get { return NoLocations; }
}
public override string Name
{
get { return _name; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { return ImmutableArray<SyntaxReference>.Empty; }
}
internal abstract override bool IsWritable { get; }
internal override EELocalSymbolBase ToOtherMethod(MethodSymbol method, TypeMap typeMap)
{
// Placeholders should be rewritten (as method calls)
// rather than copied as locals to the target method.
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// Rewrite the local reference as a call to a synthesized method.
/// </summary>
internal abstract BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, DiagnosticBag diagnostics);
internal static BoundExpression ConvertToLocalType(CSharpCompilation compilation, BoundExpression expr, TypeSymbol type, DiagnosticBag diagnostics)
{
if (type.IsPointerType())
{
var syntax = expr.Syntax;
var intPtrType = compilation.GetSpecialType(SpecialType.System_IntPtr);
Binder.ReportUseSiteDiagnostics(intPtrType, diagnostics, syntax);
MethodSymbol conversionMethod;
if (Binder.TryGetSpecialTypeMember(compilation, SpecialMember.System_IntPtr__op_Explicit_ToPointer, syntax, diagnostics, out conversionMethod))
{
var temp = ConvertToLocalTypeHelper(compilation, expr, intPtrType, diagnostics);
expr = BoundCall.Synthesized(
syntax,
receiverOpt: null,
method: conversionMethod,
arg0: temp);
}
else
{
return new BoundBadExpression(
syntax,
LookupResultKind.Empty,
ImmutableArray<Symbol>.Empty,
ImmutableArray.Create<BoundNode>(expr),
type);
}
}
return ConvertToLocalTypeHelper(compilation, expr, type, diagnostics);
}
private static BoundExpression ConvertToLocalTypeHelper(CSharpCompilation compilation, BoundExpression expr, TypeSymbol type, DiagnosticBag diagnostics)
{
// NOTE: This conversion can fail if some of the types involved are from not-yet-loaded modules.
// For example, if System.Exception hasn't been loaded, then this call will fail for $stowedexception.
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
var conversion = compilation.Conversions.ClassifyConversionFromExpression(expr, type, ref useSiteDiagnostics);
diagnostics.Add(expr.Syntax, useSiteDiagnostics);
Debug.Assert(conversion.IsValid || diagnostics.HasAnyErrors());
return BoundConversion.Synthesized(
expr.Syntax,
expr,
conversion,
@checked: false,
explicitCastInCode: false,
constantValueOpt: null,
type: type,
hasErrors: !conversion.IsValid);
}
internal static MethodSymbol GetIntrinsicMethod(CSharpCompilation compilation, string methodName)
{
var type = compilation.GetTypeByMetadataName(ExpressionCompilerConstants.IntrinsicAssemblyTypeMetadataName);
var members = type.GetMembers(methodName);
Debug.Assert(members.Length == 1);
return (MethodSymbol)members[0];
}
private static TypeSymbol DecodeDynamicTypes(TypeSymbol type, AssemblySymbol sourceAssembly, ReadOnlyCollection<byte> bytes)
{
var builder = ArrayBuilder<bool>.GetInstance();
DynamicFlagsCustomTypeInfo.CopyTo(bytes, builder);
var dynamicType = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(
type,
sourceAssembly,
RefKind.None,
builder.ToImmutableAndFree(),
checkLength: false);
Debug.Assert((object)dynamicType != null);
Debug.Assert(dynamicType != type);
return dynamicType;
}
}
}
| |
using System;
using System.Threading;
using System.Collections.Generic;
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using NUnit.Framework;
using System.IO;
using BinaryDocValuesField = BinaryDocValuesField;
using Bits = Lucene.Net.Util.Bits;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using IOUtils = Lucene.Net.Util.IOUtils;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using NumericDocValuesField = NumericDocValuesField;
using Store = Field.Store;
using StringField = StringField;
using TestUtil = Lucene.Net.Util.TestUtil;
/*
* 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.
*/
[TestFixture]
public class TestMixedDocValuesUpdates : LuceneTestCase
{
[Test]
public virtual void TestManyReopensAndFields()
{
Directory dir = NewDirectory();
Random random = Random();
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random));
LogMergePolicy lmp = NewLogMergePolicy();
lmp.MergeFactor = 3; // merge often
conf.SetMergePolicy(lmp);
IndexWriter writer = new IndexWriter(dir, conf);
bool isNRT = random.NextBoolean();
DirectoryReader reader;
if (isNRT)
{
reader = DirectoryReader.Open(writer, true);
}
else
{
writer.Commit();
reader = DirectoryReader.Open(dir);
}
int numFields = random.Next(4) + 3; // 3-7
int numNDVFields = random.Next(numFields / 2) + 1; // 1-3
long[] fieldValues = new long[numFields];
bool[] fieldHasValue = new bool[numFields];
Arrays.Fill(fieldHasValue, true);
for (int i = 0; i < fieldValues.Length; i++)
{
fieldValues[i] = 1;
}
int numRounds = AtLeast(15);
int docID = 0;
for (int i = 0; i < numRounds; i++)
{
int numDocs = AtLeast(5);
// System.out.println("[" + Thread.currentThread().getName() + "]: round=" + i + ", numDocs=" + numDocs);
for (int j = 0; j < numDocs; j++)
{
Document doc = new Document();
doc.Add(new StringField("id", "doc-" + docID, Store.NO));
doc.Add(new StringField("key", "all", Store.NO)); // update key
// add all fields with their current value
for (int f = 0; f < fieldValues.Length; f++)
{
if (f < numNDVFields)
{
doc.Add(new NumericDocValuesField("f" + f, fieldValues[f]));
}
else
{
doc.Add(new BinaryDocValuesField("f" + f, TestBinaryDocValuesUpdates.ToBytes(fieldValues[f])));
}
}
writer.AddDocument(doc);
++docID;
}
// if field's value was unset before, unset it from all new added documents too
for (int field = 0; field < fieldHasValue.Length; field++)
{
if (!fieldHasValue[field])
{
if (field < numNDVFields)
{
writer.UpdateNumericDocValue(new Term("key", "all"), "f" + field, null);
}
else
{
writer.UpdateBinaryDocValue(new Term("key", "all"), "f" + field, null);
}
}
}
int fieldIdx = random.Next(fieldValues.Length);
string updateField = "f" + fieldIdx;
if (random.NextBoolean())
{
// System.out.println("[" + Thread.currentThread().getName() + "]: unset field '" + updateField + "'");
fieldHasValue[fieldIdx] = false;
if (fieldIdx < numNDVFields)
{
writer.UpdateNumericDocValue(new Term("key", "all"), updateField, null);
}
else
{
writer.UpdateBinaryDocValue(new Term("key", "all"), updateField, null);
}
}
else
{
fieldHasValue[fieldIdx] = true;
if (fieldIdx < numNDVFields)
{
writer.UpdateNumericDocValue(new Term("key", "all"), updateField, ++fieldValues[fieldIdx]);
}
else
{
writer.UpdateBinaryDocValue(new Term("key", "all"), updateField, TestBinaryDocValuesUpdates.ToBytes(++fieldValues[fieldIdx]));
}
// System.out.println("[" + Thread.currentThread().getName() + "]: updated field '" + updateField + "' to value " + fieldValues[fieldIdx]);
}
if (random.NextDouble() < 0.2)
{
int deleteDoc = random.Next(docID); // might also delete an already deleted document, ok!
writer.DeleteDocuments(new Term("id", "doc-" + deleteDoc));
// System.out.println("[" + Thread.currentThread().getName() + "]: deleted document: doc-" + deleteDoc);
}
// verify reader
if (!isNRT)
{
writer.Commit();
}
// System.out.println("[" + Thread.currentThread().getName() + "]: reopen reader: " + reader);
DirectoryReader newReader = DirectoryReader.OpenIfChanged(reader);
Assert.IsNotNull(newReader);
reader.Dispose();
reader = newReader;
// System.out.println("[" + Thread.currentThread().getName() + "]: reopened reader: " + reader);
Assert.IsTrue(reader.NumDocs > 0); // we delete at most one document per round
BytesRef scratch = new BytesRef();
foreach (AtomicReaderContext context in reader.Leaves)
{
AtomicReader r = context.AtomicReader;
// System.out.println(((SegmentReader) r).getSegmentName());
Bits liveDocs = r.LiveDocs;
for (int field = 0; field < fieldValues.Length; field++)
{
string f = "f" + field;
BinaryDocValues bdv = r.GetBinaryDocValues(f);
NumericDocValues ndv = r.GetNumericDocValues(f);
Bits docsWithField = r.GetDocsWithField(f);
if (field < numNDVFields)
{
Assert.IsNotNull(ndv);
Assert.IsNull(bdv);
}
else
{
Assert.IsNull(ndv);
Assert.IsNotNull(bdv);
}
int maxDoc = r.MaxDoc;
for (int doc = 0; doc < maxDoc; doc++)
{
if (liveDocs == null || liveDocs.Get(doc))
{
// System.out.println("doc=" + (doc + context.DocBase) + " f='" + f + "' vslue=" + getValue(bdv, doc, scratch));
if (fieldHasValue[field])
{
Assert.IsTrue(docsWithField.Get(doc));
if (field < numNDVFields)
{
Assert.AreEqual(fieldValues[field], ndv.Get(doc), "invalid value for doc=" + doc + ", field=" + f + ", reader=" + r);
}
else
{
Assert.AreEqual(fieldValues[field], TestBinaryDocValuesUpdates.GetValue(bdv, doc, scratch), "invalid value for doc=" + doc + ", field=" + f + ", reader=" + r);
}
}
else
{
Assert.IsFalse(docsWithField.Get(doc));
}
}
}
}
}
// System.out.println();
}
IOUtils.Close(writer, reader, dir);
}
[Test]
public virtual void TestStressMultiThreading()
{
Directory dir = NewDirectory();
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
IndexWriter writer = new IndexWriter(dir, conf);
// create index
int numThreads = TestUtil.NextInt(Random(), 3, 6);
int numDocs = AtLeast(2000);
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
doc.Add(new StringField("id", "doc" + i, Store.NO));
double group = Random().NextDouble();
string g;
if (group < 0.1)
{
g = "g0";
}
else if (group < 0.5)
{
g = "g1";
}
else if (group < 0.8)
{
g = "g2";
}
else
{
g = "g3";
}
doc.Add(new StringField("updKey", g, Store.NO));
for (int j = 0; j < numThreads; j++)
{
long value = Random().Next();
doc.Add(new BinaryDocValuesField("f" + j, TestBinaryDocValuesUpdates.ToBytes(value)));
doc.Add(new NumericDocValuesField("cf" + j, value * 2)); // control, always updated to f * 2
}
writer.AddDocument(doc);
}
CountdownEvent done = new CountdownEvent(numThreads);
AtomicInteger numUpdates = new AtomicInteger(AtLeast(100));
// same thread updates a field as well as reopens
ThreadClass[] threads = new ThreadClass[numThreads];
for (int i = 0; i < threads.Length; i++)
{
string f = "f" + i;
string cf = "cf" + i;
threads[i] = new ThreadAnonymousInnerClassHelper(this, "UpdateThread-" + i, writer, numDocs, done, numUpdates, f, cf);
}
foreach (ThreadClass t in threads)
{
t.Start();
}
done.Wait();
writer.Dispose();
DirectoryReader reader = DirectoryReader.Open(dir);
BytesRef scratch = new BytesRef();
foreach (AtomicReaderContext context in reader.Leaves)
{
AtomicReader r = context.AtomicReader;
for (int i = 0; i < numThreads; i++)
{
BinaryDocValues bdv = r.GetBinaryDocValues("f" + i);
NumericDocValues control = r.GetNumericDocValues("cf" + i);
Bits docsWithBdv = r.GetDocsWithField("f" + i);
Bits docsWithControl = r.GetDocsWithField("cf" + i);
Bits liveDocs = r.LiveDocs;
for (int j = 0; j < r.MaxDoc; j++)
{
if (liveDocs == null || liveDocs.Get(j))
{
Assert.AreEqual(docsWithBdv.Get(j), docsWithControl.Get(j));
if (docsWithBdv.Get(j))
{
long ctrlValue = control.Get(j);
long bdvValue = TestBinaryDocValuesUpdates.GetValue(bdv, j, scratch) * 2;
// if (ctrlValue != bdvValue) {
// System.out.println("seg=" + r + ", f=f" + i + ", doc=" + j + ", group=" + r.Document(j).Get("updKey") + ", ctrlValue=" + ctrlValue + ", bdvBytes=" + scratch);
// }
Assert.AreEqual(ctrlValue, bdvValue);
}
}
}
}
}
reader.Dispose();
dir.Dispose();
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
private readonly TestMixedDocValuesUpdates OuterInstance;
private IndexWriter Writer;
private int NumDocs;
private CountdownEvent Done;
private AtomicInteger NumUpdates;
private string f;
private string Cf;
public ThreadAnonymousInnerClassHelper(TestMixedDocValuesUpdates outerInstance, string str, IndexWriter writer, int numDocs, CountdownEvent done, AtomicInteger numUpdates, string f, string cf)
: base(str)
{
this.OuterInstance = outerInstance;
this.Writer = writer;
this.NumDocs = numDocs;
this.Done = done;
this.NumUpdates = numUpdates;
this.f = f;
this.Cf = cf;
}
public override void Run()
{
DirectoryReader reader = null;
bool success = false;
try
{
Random random = Random();
while (NumUpdates.GetAndDecrement() > 0)
{
double group = random.NextDouble();
Term t;
if (group < 0.1)
{
t = new Term("updKey", "g0");
}
else if (group < 0.5)
{
t = new Term("updKey", "g1");
}
else if (group < 0.8)
{
t = new Term("updKey", "g2");
}
else
{
t = new Term("updKey", "g3");
}
// System.out.println("[" + Thread.currentThread().getName() + "] numUpdates=" + numUpdates + " updateTerm=" + t);
if (random.NextBoolean()) // sometimes unset a value
{
// System.err.println("[" + Thread.currentThread().getName() + "] t=" + t + ", f=" + f + ", updValue=UNSET");
Writer.UpdateBinaryDocValue(t, f, null);
Writer.UpdateNumericDocValue(t, Cf, null);
}
else
{
long updValue = random.Next();
// System.err.println("[" + Thread.currentThread().getName() + "] t=" + t + ", f=" + f + ", updValue=" + updValue);
Writer.UpdateBinaryDocValue(t, f, TestBinaryDocValuesUpdates.ToBytes(updValue));
Writer.UpdateNumericDocValue(t, Cf, updValue * 2);
}
if (random.NextDouble() < 0.2)
{
// delete a random document
int doc = random.Next(NumDocs);
// System.out.println("[" + Thread.currentThread().getName() + "] deleteDoc=doc" + doc);
Writer.DeleteDocuments(new Term("id", "doc" + doc));
}
if (random.NextDouble() < 0.05) // commit every 20 updates on average
{
// System.out.println("[" + Thread.currentThread().getName() + "] commit");
Writer.Commit();
}
if (random.NextDouble() < 0.1) // reopen NRT reader (apply updates), on average once every 10 updates
{
if (reader == null)
{
// System.out.println("[" + Thread.currentThread().getName() + "] open NRT");
reader = DirectoryReader.Open(Writer, true);
}
else
{
// System.out.println("[" + Thread.currentThread().getName() + "] reopen NRT");
DirectoryReader r2 = DirectoryReader.OpenIfChanged(reader, Writer, true);
if (r2 != null)
{
reader.Dispose();
reader = r2;
}
}
}
}
// System.out.println("[" + Thread.currentThread().getName() + "] DONE");
success = true;
}
catch (IOException e)
{
throw new Exception(e.Message, e);
}
finally
{
if (reader != null)
{
try
{
reader.Dispose();
}
catch (IOException e)
{
if (success) // suppress this exception only if there was another exception
{
throw new Exception(e.Message, e);
}
}
}
Done.Signal();
}
}
}
[Test]
public virtual void TestUpdateDifferentDocsInDifferentGens()
{
// update same document multiple times across generations
Directory dir = NewDirectory();
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
conf.SetMaxBufferedDocs(4);
IndexWriter writer = new IndexWriter(dir, conf);
int numDocs = AtLeast(10);
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
doc.Add(new StringField("id", "doc" + i, Store.NO));
long value = Random().Next();
doc.Add(new BinaryDocValuesField("f", TestBinaryDocValuesUpdates.ToBytes(value)));
doc.Add(new NumericDocValuesField("cf", value * 2));
writer.AddDocument(doc);
}
int numGens = AtLeast(5);
BytesRef scratch = new BytesRef();
for (int i = 0; i < numGens; i++)
{
int doc = Random().Next(numDocs);
Term t = new Term("id", "doc" + doc);
long value = Random().NextLong();
writer.UpdateBinaryDocValue(t, "f", TestBinaryDocValuesUpdates.ToBytes(value));
writer.UpdateNumericDocValue(t, "cf", value * 2);
DirectoryReader reader = DirectoryReader.Open(writer, true);
foreach (AtomicReaderContext context in reader.Leaves)
{
AtomicReader r = context.AtomicReader;
BinaryDocValues fbdv = r.GetBinaryDocValues("f");
NumericDocValues cfndv = r.GetNumericDocValues("cf");
for (int j = 0; j < r.MaxDoc; j++)
{
Assert.AreEqual(cfndv.Get(j), TestBinaryDocValuesUpdates.GetValue(fbdv, j, scratch) * 2);
}
}
reader.Dispose();
}
writer.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestTonsOfUpdates()
{
// LUCENE-5248: make sure that when there are many updates, we don't use too much RAM
Directory dir = NewDirectory();
Random random = Random();
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random));
conf.SetRAMBufferSizeMB(IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB);
conf.SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH); // don't flush by doc
IndexWriter writer = new IndexWriter(dir, conf);
// test data: lots of documents (few 10Ks) and lots of update terms (few hundreds)
int numDocs = AtLeast(20000);
int numBinaryFields = AtLeast(5);
int numTerms = TestUtil.NextInt(random, 10, 100); // terms should affect many docs
HashSet<string> updateTerms = new HashSet<string>();
while (updateTerms.Count < numTerms)
{
updateTerms.Add(TestUtil.RandomSimpleString(random));
}
// System.out.println("numDocs=" + numDocs + " numBinaryFields=" + numBinaryFields + " numTerms=" + numTerms);
// build a large index with many BDV fields and update terms
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
int numUpdateTerms = TestUtil.NextInt(random, 1, numTerms / 10);
for (int j = 0; j < numUpdateTerms; j++)
{
doc.Add(new StringField("upd", RandomInts.RandomFrom(random, updateTerms), Store.NO));
}
for (int j = 0; j < numBinaryFields; j++)
{
long val = random.Next();
doc.Add(new BinaryDocValuesField("f" + j, TestBinaryDocValuesUpdates.ToBytes(val)));
doc.Add(new NumericDocValuesField("cf" + j, val * 2));
}
writer.AddDocument(doc);
}
writer.Commit(); // commit so there's something to apply to
// set to flush every 2048 bytes (approximately every 12 updates), so we get
// many flushes during binary updates
writer.Config.SetRAMBufferSizeMB(2048.0 / 1024 / 1024);
int numUpdates = AtLeast(100);
// System.out.println("numUpdates=" + numUpdates);
for (int i = 0; i < numUpdates; i++)
{
int field = random.Next(numBinaryFields);
Term updateTerm = new Term("upd", RandomInts.RandomFrom(random, updateTerms));
long value = random.Next();
writer.UpdateBinaryDocValue(updateTerm, "f" + field, TestBinaryDocValuesUpdates.ToBytes(value));
writer.UpdateNumericDocValue(updateTerm, "cf" + field, value * 2);
}
writer.Dispose();
DirectoryReader reader = DirectoryReader.Open(dir);
BytesRef scratch = new BytesRef();
foreach (AtomicReaderContext context in reader.Leaves)
{
for (int i = 0; i < numBinaryFields; i++)
{
AtomicReader r = context.AtomicReader;
BinaryDocValues f = r.GetBinaryDocValues("f" + i);
NumericDocValues cf = r.GetNumericDocValues("cf" + i);
for (int j = 0; j < r.MaxDoc; j++)
{
Assert.AreEqual(cf.Get(j), TestBinaryDocValuesUpdates.GetValue(f, j, scratch) * 2, "reader=" + r + ", field=f" + i + ", doc=" + j);
}
}
}
reader.Dispose();
dir.Dispose();
}
}
}
| |
/*
Copyright 2006 - 2010 Intel 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.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using OpenSource.UPnP;
namespace UPnPAuthor
{
/// <summary>
/// Summary description for ComplexTypeProperty.
/// </summary>
public class ComplexTypeProperty : System.Windows.Forms.Form
{
public string LocalName
{
get
{
return (LocalNameTextBox.Text);
}
}
public string Namespace
{
get
{
return (NamespaceTextBox.Text);
}
}
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.TextBox NamespaceTextBox;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox LocalNameTextBox;
private System.Windows.Forms.Button OKButton;
private System.Windows.Forms.Button CancelButton;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public ComplexTypeProperty()
: this(null)
{
}
public ComplexTypeProperty(UPnPComplexType c)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
if (c != null)
{
NamespaceTextBox.Text = c.Name_NAMESPACE;
LocalNameTextBox.Text = c.Name_LOCAL;
}
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox3 = new System.Windows.Forms.TextBox();
this.NamespaceTextBox = new System.Windows.Forms.TextBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.LocalNameTextBox = new System.Windows.Forms.TextBox();
this.OKButton = new System.Windows.Forms.Button();
this.CancelButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(8, 32);
this.textBox3.Name = "textBox3";
this.textBox3.ReadOnly = true;
this.textBox3.Size = new System.Drawing.Size(72, 20);
this.textBox3.TabIndex = 5;
this.textBox3.TabStop = false;
this.textBox3.Text = "Local Name";
//
// NamespaceTextBox
//
this.NamespaceTextBox.Location = new System.Drawing.Point(80, 8);
this.NamespaceTextBox.Name = "NamespaceTextBox";
this.NamespaceTextBox.Size = new System.Drawing.Size(312, 20);
this.NamespaceTextBox.TabIndex = 4;
this.NamespaceTextBox.Text = "http://www.vendor.org/Schemas";
this.NamespaceTextBox.TextChanged += new System.EventHandler(this.OnTextBoxChanged);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(8, 8);
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(72, 20);
this.textBox1.TabIndex = 3;
this.textBox1.TabStop = false;
this.textBox1.Text = "Namespace";
//
// LocalNameTextBox
//
this.LocalNameTextBox.Location = new System.Drawing.Point(80, 32);
this.LocalNameTextBox.Name = "LocalNameTextBox";
this.LocalNameTextBox.Size = new System.Drawing.Size(312, 20);
this.LocalNameTextBox.TabIndex = 6;
this.LocalNameTextBox.TextChanged += new System.EventHandler(this.OnTextBoxChanged);
//
// OKButton
//
this.OKButton.Enabled = false;
this.OKButton.Location = new System.Drawing.Point(312, 64);
this.OKButton.Name = "OKButton";
this.OKButton.Size = new System.Drawing.Size(75, 23);
this.OKButton.TabIndex = 7;
this.OKButton.Text = "OK";
this.OKButton.Click += new System.EventHandler(this.OKButton_Click);
//
// CancelButton
//
this.CancelButton.Location = new System.Drawing.Point(232, 64);
this.CancelButton.Name = "CancelButton";
this.CancelButton.Size = new System.Drawing.Size(75, 23);
this.CancelButton.TabIndex = 8;
this.CancelButton.Text = "Cancel";
this.CancelButton.Click += new System.EventHandler(this.CancelButton_Click);
//
// ComplexTypeProperty
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(400, 94);
this.Controls.Add(this.CancelButton);
this.Controls.Add(this.OKButton);
this.Controls.Add(this.LocalNameTextBox);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.NamespaceTextBox);
this.Controls.Add(this.textBox1);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ComplexTypeProperty";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Complex Type Property";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void OnTextBoxChanged(object sender, System.EventArgs e)
{
if (NamespaceTextBox.Text != "" && LocalNameTextBox.Text != "")
{
OKButton.Enabled = true;
}
else
{
OKButton.Enabled = false;
}
}
private void OKButton_Click(object sender, System.EventArgs e)
{
DialogResult = DialogResult.OK;
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
using BestHTTP.Caching;
#endif
using BestHTTP.Extensions;
using BestHTTP.Logger;
using BestHTTP.Statistics;
namespace BestHTTP
{
/// <summary>
///
/// </summary>
public static class HTTPManager
{
// Static constructor. Setup default values
static HTTPManager()
{
MaxConnectionPerServer = 4;
KeepAliveDefaultValue = true;
MaxPathLength = 255;
MaxConnectionIdleTime = TimeSpan.FromSeconds(30);
#if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
IsCookiesEnabled = true;
#endif
CookieJarSize = 10 * 1024 * 1024;
EnablePrivateBrowsing = false;
ConnectTimeout = TimeSpan.FromSeconds(20);
RequestTimeout = TimeSpan.FromSeconds(60);
// Set the default logger mechanism
logger = new BestHTTP.Logger.DefaultLogger();
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
DefaultCertificateVerifyer = null;
UseAlternateSSLDefaultValue = false;
#endif
}
#region Global Options
/// <summary>
/// The maximum active tcp connections that the client will maintain to a server. Default value is 4. Minimum value is 1.
/// </summary>
public static byte MaxConnectionPerServer
{
get{ return maxConnectionPerServer; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("MaxConnectionPerServer must be greater than 0!");
maxConnectionPerServer = value;
}
}
private static byte maxConnectionPerServer;
/// <summary>
/// Default value of a http request's IsKeepAlive value. Default value is true. If you make rare request to the server it's should be changed to false.
/// </summary>
public static bool KeepAliveDefaultValue { get; set; }
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
/// <summary>
/// Set to true, if caching is prohibited.
/// </summary>
public static bool IsCachingDisabled { get; set; }
#endif
/// <summary>
/// How many time must be passed to destroy that connection after a connection finished it's last request. It's default value is 30 seconds.
/// </summary>
public static TimeSpan MaxConnectionIdleTime { get; set; }
#if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
/// <summary>
/// Set to false to disable all Cookie. It's default value is true.
/// </summary>
public static bool IsCookiesEnabled { get; set; }
#endif
/// <summary>
/// Size of the Cookie Jar in bytes. It's default value is 10485760 (10 MB).
/// </summary>
public static uint CookieJarSize { get; set; }
/// <summary>
/// If this property is set to true, then new cookies treated as session cookies and these cookies are not saved to disk. It's default value is false;
/// </summary>
public static bool EnablePrivateBrowsing { get; set; }
/// <summary>
/// Global, default value of the HTTPRequest's ConnectTimeout property. Default value is 20 seconds.
/// </summary>
public static TimeSpan ConnectTimeout { get; set; }
/// <summary>
/// Global, default value of the HTTPRequest's Timeout property. Default value is 60 seconds.
/// </summary>
public static TimeSpan RequestTimeout { get; set; }
#if !((BESTHTTP_DISABLE_CACHING && BESTHTTP_DISABLE_COOKIES) || (UNITY_WEBGL && !UNITY_EDITOR))
/// <summary>
/// By default the plugin will save all cache and cookie data under the path returned by Application.persistentDataPath.
/// You can assign a function to this delegate to return a custom root path to define a new path.
/// <remarks>This delegate will be called on a non Unity thread!</remarks>
/// </summary>
public static System.Func<string> RootCacheFolderProvider { get; set; }
#endif
#if !BESTHTTP_DISABLE_PROXY
/// <summary>
/// The global, default proxy for all HTTPRequests. The HTTPRequest's Proxy still can be changed per-request. Default value is null.
/// </summary>
public static HTTPProxy Proxy { get; set; }
#endif
/// <summary>
/// Heartbeat manager to use less threads in the plugin. The heartbeat updates are called from the OnUpdate function.
/// </summary>
public static HeartbeatManager Heartbeats
{
get
{
if (heartbeats == null)
heartbeats = new HeartbeatManager();
return heartbeats;
}
}
private static HeartbeatManager heartbeats;
/// <summary>
/// A basic BestHTTP.Logger.ILogger implementation to be able to log intelligently additional informations about the plugin's internal mechanism.
/// </summary>
public static BestHTTP.Logger.ILogger Logger
{
get
{
// Make sure that it has a valid logger instance.
if (logger == null)
{
logger = new DefaultLogger();
logger.Level = Loglevels.None;
}
return logger;
}
set { logger = value; }
}
private static BestHTTP.Logger.ILogger logger;
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
/// <summary>
/// The default ICertificateVerifyer implementation that the plugin will use when the request's UseAlternateSSL property is set to true.
/// </summary>
public static Org.BouncyCastle.Crypto.Tls.ICertificateVerifyer DefaultCertificateVerifyer { get; set; }
/// <summary>
/// The default IClientCredentialsProvider implementation that the plugin will use when the request's UseAlternateSSL property is set to true.
/// </summary>
public static Org.BouncyCastle.Crypto.Tls.IClientCredentialsProvider DefaultClientCredentialsProvider { get; set; }
/// <summary>
/// The default value for the HTTPRequest's UseAlternateSSL property.
/// </summary>
public static bool UseAlternateSSLDefaultValue { get; set; }
#endif
/// <summary>
/// On most systems the maximum length of a path is around 255 character. If a cache entity's path is longer than this value it doesn't get cached. There no patform independent API to query the exact value on the current system, but it's
/// exposed here and can be overridden. It's default value is 255.
/// </summary>
internal static int MaxPathLength { get; set; }
#endregion
#region Manager variables
/// <summary>
/// All connection has a reference in this Dictionary untill it's removed completly.
/// </summary>
private static Dictionary<string, List<ConnectionBase>> Connections = new Dictionary<string, List<ConnectionBase>>();
/// <summary>
/// Active connections. These connections all has a request to process.
/// </summary>
private static List<ConnectionBase> ActiveConnections = new List<ConnectionBase>();
/// <summary>
/// Free connections. They can be removed completly after a specified time.
/// </summary>
private static List<ConnectionBase> FreeConnections = new List<ConnectionBase>();
/// <summary>
/// Connections that recycled in the Update loop. If they are not used in the same loop to process a request, they will be transferred to the FreeConnections list.
/// </summary>
private static List<ConnectionBase> RecycledConnections = new List<ConnectionBase>();
/// <summary>
/// List of request that have to wait until there is a free connection to the server.
/// </summary>
private static List<HTTPRequest> RequestQueue = new List<HTTPRequest>();
private static bool IsCallingCallbacks;
internal static System.Object Locker = new System.Object();
#endregion
#region Public Interface
public static void Setup()
{
HTTPUpdateDelegator.CheckInstance();
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
HTTPCacheService.CheckSetup();
#endif
#if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
Cookies.CookieJar.SetupFolder();
#endif
}
public static HTTPRequest SendRequest(string url, OnRequestFinishedDelegate callback)
{
return SendRequest(new HTTPRequest(new Uri(url), HTTPMethods.Get, callback));
}
public static HTTPRequest SendRequest(string url, HTTPMethods methodType, OnRequestFinishedDelegate callback)
{
return SendRequest(new HTTPRequest(new Uri(url), methodType, callback));
}
public static HTTPRequest SendRequest(string url, HTTPMethods methodType, bool isKeepAlive, OnRequestFinishedDelegate callback)
{
return SendRequest(new HTTPRequest(new Uri(url), methodType, isKeepAlive, callback));
}
public static HTTPRequest SendRequest(string url, HTTPMethods methodType, bool isKeepAlive, bool disableCache, OnRequestFinishedDelegate callback)
{
return SendRequest(new HTTPRequest(new Uri(url), methodType, isKeepAlive, disableCache, callback));
}
public static HTTPRequest SendRequest(HTTPRequest request)
{
lock (Locker)
{
Setup();
// TODO: itt meg csak adja hozza egy sorhoz, es majd a LateUpdate-ben hivodjon a SendRequestImpl.
// Igy ha egy callback-ben kuldenenk ugyanarra a szerverre request-et, akkor feltudjuk hasznalni az elozo connection-t.
if (IsCallingCallbacks)
{
request.State = HTTPRequestStates.Queued;
RequestQueue.Add(request);
}
else
SendRequestImpl(request);
return request;
}
}
public static GeneralStatistics GetGeneralStatistics(StatisticsQueryFlags queryFlags)
{
GeneralStatistics stat = new GeneralStatistics();
stat.QueryFlags = queryFlags;
if ((queryFlags & StatisticsQueryFlags.Connections) != 0)
{
int connections = 0;
foreach(var conn in HTTPManager.Connections)
{
if (conn.Value != null)
connections += conn.Value.Count;
}
#if !BESTHTTP_DISABLE_WEBSOCKET && UNITY_WEBGL && !UNITY_EDITOR
connections += WebSocket.WebSocket.WebSockets.Count;
#endif
stat.Connections = connections;
stat.ActiveConnections = ActiveConnections.Count
#if !BESTHTTP_DISABLE_WEBSOCKET && UNITY_WEBGL && !UNITY_EDITOR
+ WebSocket.WebSocket.WebSockets.Count
#endif
;
stat.FreeConnections = FreeConnections.Count;
stat.RecycledConnections = RecycledConnections.Count;
stat.RequestsInQueue = RequestQueue.Count;
}
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
if ((queryFlags & StatisticsQueryFlags.Cache) != 0)
{
stat.CacheEntityCount = HTTPCacheService.GetCacheEntityCount();
stat.CacheSize = HTTPCacheService.GetCacheSize();
}
#endif
#if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
if ((queryFlags & StatisticsQueryFlags.Cookies) != 0)
{
List<Cookies.Cookie> cookies = Cookies.CookieJar.GetAll();
stat.CookieCount = cookies.Count;
uint cookiesSize = 0;
for (int i = 0; i < cookies.Count; ++i)
cookiesSize += cookies[i].GuessSize();
stat.CookieJarSize = cookiesSize;
}
#endif
return stat;
}
#endregion
#region Private Functions
private static void SendRequestImpl(HTTPRequest request)
{
ConnectionBase conn = FindOrCreateFreeConnection(request);
if (conn != null)
{
// found a free connection: put it in the ActiveConnection list(they will be checked periodically in the OnUpdate call)
if (ActiveConnections.Find((c) => c == conn) == null)
ActiveConnections.Add(conn);
FreeConnections.Remove(conn);
request.State = HTTPRequestStates.Processing;
request.Prepare();
// then start process the request
conn.Process(request);
}
else
{
// If no free connection found and creation prohibited, we will put back to the queue
request.State = HTTPRequestStates.Queued;
RequestQueue.Add(request);
}
}
private static string GetKeyForRequest(HTTPRequest request)
{
if (request.CurrentUri.IsFile)
return request.CurrentUri.ToString();
// proxyUri + requestUri
// HTTP and HTTPS needs different connections.
return
#if !BESTHTTP_DISABLE_PROXY
(request.Proxy != null ? new UriBuilder(request.Proxy.Address.Scheme, request.Proxy.Address.Host, request.Proxy.Address.Port).Uri.ToString() : string.Empty) +
#endif
new UriBuilder(request.CurrentUri.Scheme, request.CurrentUri.Host, request.CurrentUri.Port).Uri.ToString();
}
/// <summary>
/// Factory method to create a concrete connection object.
/// </summary>
private static ConnectionBase CreateConnection(HTTPRequest request, string serverUrl)
{
if (request.CurrentUri.IsFile)
return new FileConnection(serverUrl);
#if UNITY_WEBGL && !UNITY_EDITOR
return new WebGLConnection(serverUrl);
#else
return new HTTPConnection(serverUrl);
#endif
}
private static ConnectionBase FindOrCreateFreeConnection(HTTPRequest request)
{
ConnectionBase conn = null;
List<ConnectionBase> connections;
string serverUrl = GetKeyForRequest(request);
if (Connections.TryGetValue(serverUrl, out connections))
{
// count active connections
int activeConnections = 0;
for (int i = 0; i < connections.Count; ++i)
if (connections[i].IsActive)
activeConnections++;
if (activeConnections <= MaxConnectionPerServer)
// search for a Free connection
for (int i = 0; i < connections.Count && conn == null; ++i)
{
var tmpConn = connections[i];
if (tmpConn != null &&
tmpConn.IsFree &&
(
#if !BESTHTTP_DISABLE_PROXY
!tmpConn.HasProxy ||
#endif
tmpConn.LastProcessedUri == null ||
tmpConn.LastProcessedUri.Host.Equals(request.CurrentUri.Host, StringComparison.OrdinalIgnoreCase)))
conn = tmpConn;
}
}
else
Connections.Add(serverUrl, connections = new List<ConnectionBase>(MaxConnectionPerServer));
// No free connection found?
if (conn == null)
{
// Max connection reached?
if (connections.Count >= MaxConnectionPerServer)
return null;
// if no, create a new one
connections.Add(conn = CreateConnection(request, serverUrl));
}
return conn;
}
/// <summary>
/// Will return with true when there at least one request that can be processed from the RequestQueue.
/// </summary>
private static bool CanProcessFromQueue()
{
for (int i = 0; i < RequestQueue.Count; ++i)
if (FindOrCreateFreeConnection(RequestQueue[i]) != null)
return true;
return false;
}
private static void RecycleConnection(ConnectionBase conn)
{
conn.Recycle(OnConnectionRecylced);
}
private static void OnConnectionRecylced(ConnectionBase conn)
{
lock (RecycledConnections)
{
RecycledConnections.Add(conn);
}
}
#endregion
#region Internal Helper Functions
/// <summary>
/// Will return the ConnectionBase object that processing the given request.
/// </summary>
internal static ConnectionBase GetConnectionWith(HTTPRequest request)
{
lock (Locker)
{
for (int i = 0; i < ActiveConnections.Count; ++i)
{
var connection = ActiveConnections[i];
if (connection.CurrentRequest == request)
return connection;
}
return null;
}
}
internal static bool RemoveFromQueue(HTTPRequest request)
{
return RequestQueue.Remove(request);
}
#if !((BESTHTTP_DISABLE_CACHING && BESTHTTP_DISABLE_COOKIES) || (UNITY_WEBGL && !UNITY_EDITOR))
/// <summary>
/// Will return where the various caches should be saved.
/// </summary>
internal static string GetRootCacheFolder()
{
try
{
if (RootCacheFolderProvider != null)
return RootCacheFolderProvider();
}
catch(Exception ex)
{
HTTPManager.Logger.Exception("HTTPManager", "GetRootCacheFolder", ex);
}
#if NETFX_CORE
return Windows.Storage.ApplicationData.Current.LocalFolder.Path;
#else
return Application.persistentDataPath;
#endif
}
#endif
#endregion
#region MonoBehaviour Events (Called from HTTPUpdateDelegator)
/// <summary>
/// Update function that should be called regularly from a Unity event(Update, LateUpdate). Callbacks are dispatched from this function.
/// </summary>
public static void OnUpdate()
{
lock (Locker)
{
IsCallingCallbacks = true;
try
{
for (int i = 0; i < ActiveConnections.Count; ++i)
{
ConnectionBase conn = ActiveConnections[i];
switch (conn.State)
{
case HTTPConnectionStates.Processing:
conn.HandleProgressCallback();
if (conn.CurrentRequest.UseStreaming && conn.CurrentRequest.Response != null && conn.CurrentRequest.Response.HasStreamedFragments())
conn.HandleCallback();
if (((!conn.CurrentRequest.UseStreaming && conn.CurrentRequest.UploadStream == null) || conn.CurrentRequest.EnableTimoutForStreaming) &&
DateTime.UtcNow - conn.StartTime > conn.CurrentRequest.Timeout)
conn.Abort(HTTPConnectionStates.TimedOut);
break;
case HTTPConnectionStates.TimedOut:
// The connection is still in TimedOut state, and if we waited enough time, we will dispatch the
// callback and recycle the connection
if (DateTime.UtcNow - conn.TimedOutStart > TimeSpan.FromMilliseconds(500))
{
HTTPManager.Logger.Information("HTTPManager", "Hard aborting connection becouse of a long waiting TimedOut state");
conn.CurrentRequest.Response = null;
conn.CurrentRequest.State = HTTPRequestStates.TimedOut;
conn.HandleCallback();
// this will set the connection's CurrentRequest to null
RecycleConnection(conn);
}
break;
case HTTPConnectionStates.Redirected:
// If the server redirected us, we need to find or create a connection to the new server and send out the request again.
SendRequest(conn.CurrentRequest);
RecycleConnection(conn);
break;
case HTTPConnectionStates.WaitForRecycle:
// If it's a streamed request, it's finished now
conn.CurrentRequest.FinishStreaming();
// Call the callback
conn.HandleCallback();
// Then recycle the connection
RecycleConnection(conn);
break;
case HTTPConnectionStates.Upgraded:
// The connection upgraded to an other protocol
conn.HandleCallback();
break;
case HTTPConnectionStates.WaitForProtocolShutdown:
var ws = conn.CurrentRequest.Response as IProtocol;
if (ws != null)
ws.HandleEvents();
if (ws == null || ws.IsClosed)
{
conn.HandleCallback();
// After both sending and receiving a Close message, an endpoint considers the WebSocket connection closed and MUST close the underlying TCP connection.
conn.Dispose();
RecycleConnection(conn);
}
break;
case HTTPConnectionStates.AbortRequested:
// Corner case: we aborted a WebSocket connection
{
ws = conn.CurrentRequest.Response as IProtocol;
if (ws != null)
{
ws.HandleEvents();
if (ws.IsClosed)
{
conn.HandleCallback();
conn.Dispose();
RecycleConnection(conn);
}
}
}
break;
case HTTPConnectionStates.Closed:
// If it's a streamed request, it's finished now
conn.CurrentRequest.FinishStreaming();
// Call the callback
conn.HandleCallback();
// It will remove from the ActiveConnections
RecycleConnection(conn);
break;
case HTTPConnectionStates.Free:
RecycleConnection(conn);
break;
}
}
}
finally
{
IsCallingCallbacks = false;
}
lock (RecycledConnections)
{
if (RecycledConnections.Count > 0)
{
for (int i = 0; i < RecycledConnections.Count; ++i)
{
var connection = RecycledConnections[i];
// If in a callback made a request that aquired this connection, then we will not remove it from the
// active connections.
if (connection.IsFree)
{
ActiveConnections.Remove(connection);
FreeConnections.Add(connection);
}
}
RecycledConnections.Clear();
}
}
if (FreeConnections.Count > 0)
for (int i = 0; i < FreeConnections.Count; i++)
{
var connection = FreeConnections[i];
if (connection.IsRemovable)
{
// Remove the connection from the connection reference table
List<ConnectionBase> connections = null;
if (Connections.TryGetValue(connection.ServerAddress, out connections))
connections.Remove(connection);
// Dispose the connection
connection.Dispose();
FreeConnections.RemoveAt(i);
i--;
}
}
if (CanProcessFromQueue())
{
// Sort the queue by priority, only if we have to
if (RequestQueue.Find((req) => req.Priority != 0) != null)
RequestQueue.Sort((req1, req2) => req1.Priority - req2.Priority);
// Create an array from the queue and clear it. When we call the SendRequest while still no room for new connections, the same queue will be rebuilt.
var queue = RequestQueue.ToArray();
RequestQueue.Clear();
for (int i = 0; i < queue.Length; ++i)
SendRequest(queue[i]);
}
} // lock(Locker)
if (heartbeats != null)
heartbeats.Update();
}
public static void OnQuit()
{
lock (Locker)
{
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
Caching.HTTPCacheService.SaveLibrary();
#endif
var queue = RequestQueue.ToArray();
RequestQueue.Clear();
foreach (var req in queue)
req.Abort();
// Close all tcp connections when the application is terminating.
foreach (var kvp in Connections)
{
foreach (var conn in kvp.Value)
{
conn.Abort(HTTPConnectionStates.Closed);
conn.Dispose();
}
kvp.Value.Clear();
}
Connections.Clear();
OnUpdate();
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Text;
using Solenoid.Expressions.Parser.antlr.collections.impl;
using Solenoid.Expressions.Parser.antlr.debug;
namespace Solenoid.Expressions.Parser.antlr
{
/*ANTLR Translator Generator
* Project led by Terence Parr at http://www.jGuru.com
* Software rights: http://www.antlr.org/license.html
*
* $Id:$
*/
//
// ANTLR C# Code Generator by Micheal Jordan
// Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com
// Anthony Oguntimehin
//
// With many thanks to Eric V. Smith from the ANTLR list.
//
public abstract class CharScanner : TokenStream, ICharScannerDebugSubject
{
internal const char NO_CHAR = (char) (0);
public static readonly char EOF_CHAR = Char.MaxValue;
// Used to store event delegates
private EventHandlerList events_ = new EventHandlerList();
protected internal EventHandlerList Events
{
get { return events_; }
}
// The unique keys for each event that CharScanner [objects] can generate
internal static readonly object EnterRuleEventKey = new object();
internal static readonly object ExitRuleEventKey = new object();
internal static readonly object DoneEventKey = new object();
internal static readonly object ReportErrorEventKey = new object();
internal static readonly object ReportWarningEventKey = new object();
internal static readonly object NewLineEventKey = new object();
internal static readonly object MatchEventKey = new object();
internal static readonly object MatchNotEventKey = new object();
internal static readonly object MisMatchEventKey = new object();
internal static readonly object MisMatchNotEventKey = new object();
internal static readonly object ConsumeEventKey = new object();
internal static readonly object LAEventKey = new object();
internal static readonly object SemPredEvaluatedEventKey = new object();
internal static readonly object SynPredStartedEventKey = new object();
internal static readonly object SynPredFailedEventKey = new object();
internal static readonly object SynPredSucceededEventKey = new object();
protected internal StringBuilder text; // text of current token
protected bool saveConsumedInput = true; // does consume() save characters?
/// <summary>Used for creating Token instances.</summary>
protected TokenCreator tokenCreator;
/// <summary>Used for caching lookahead characters.</summary>
protected char cached_LA1;
protected char cached_LA2;
protected bool caseSensitive = true;
protected bool caseSensitiveLiterals = true;
protected Hashtable literals; // set by subclass
/*Tab chars are handled by tab() according to this value; override
* method to do anything weird with tabs.
*/
protected internal int tabsize = 8;
protected internal IToken returnToken_ = null; // used to return tokens w/o using return val.
protected internal LexerSharedInputState inputState;
/*Used during filter mode to indicate that path is desired.
* A subsequent scan error will report an error as usual if
* acceptPath=true;
*/
protected internal bool commitToPath = false;
/*Used to keep track of indentdepth for traceIn/Out */
protected internal int traceDepth = 0;
public CharScanner()
{
text = new StringBuilder();
setTokenCreator(new CommonToken.CommonTokenCreator());
}
public CharScanner(InputBuffer cb) : this()
{
inputState = new LexerSharedInputState(cb);
cached_LA2 = inputState.input.LA(2);
cached_LA1 = inputState.input.LA(1);
}
public CharScanner(LexerSharedInputState sharedState) : this()
{
inputState = sharedState;
if (inputState != null)
{
cached_LA2 = inputState.input.LA(2);
cached_LA1 = inputState.input.LA(1);
}
}
public event TraceEventHandler EnterRule
{
add { Events.AddHandler(EnterRuleEventKey, value); }
remove { Events.RemoveHandler(EnterRuleEventKey, value); }
}
public event TraceEventHandler ExitRule
{
add { Events.AddHandler(ExitRuleEventKey, value); }
remove { Events.RemoveHandler(ExitRuleEventKey, value); }
}
public event TraceEventHandler Done
{
add { Events.AddHandler(DoneEventKey, value); }
remove { Events.RemoveHandler(DoneEventKey, value); }
}
public event MessageEventHandler ErrorReported
{
add { Events.AddHandler(ReportErrorEventKey, value); }
remove { Events.RemoveHandler(ReportErrorEventKey, value); }
}
public event MessageEventHandler WarningReported
{
add { Events.AddHandler(ReportWarningEventKey, value); }
remove { Events.RemoveHandler(ReportWarningEventKey, value); }
}
public event NewLineEventHandler HitNewLine
{
add { Events.AddHandler(NewLineEventKey, value); }
remove { Events.RemoveHandler(NewLineEventKey, value); }
}
public event MatchEventHandler MatchedChar
{
add { Events.AddHandler(MatchEventKey, value); }
remove { Events.RemoveHandler(MatchEventKey, value); }
}
public event MatchEventHandler MatchedNotChar
{
add { Events.AddHandler(MatchNotEventKey, value); }
remove { Events.RemoveHandler(MatchNotEventKey, value); }
}
public event MatchEventHandler MisMatchedChar
{
add { Events.AddHandler(MisMatchEventKey, value); }
remove { Events.RemoveHandler(MisMatchEventKey, value); }
}
public event MatchEventHandler MisMatchedNotChar
{
add { Events.AddHandler(MisMatchNotEventKey, value); }
remove { Events.RemoveHandler(MisMatchNotEventKey, value); }
}
public event TokenEventHandler ConsumedChar
{
add { Events.AddHandler(ConsumeEventKey, value); }
remove { Events.RemoveHandler(ConsumeEventKey, value); }
}
public event TokenEventHandler CharLA
{
add { Events.AddHandler(LAEventKey, value); }
remove { Events.RemoveHandler(LAEventKey, value); }
}
public event SemanticPredicateEventHandler SemPredEvaluated
{
add { Events.AddHandler(SemPredEvaluatedEventKey, value); }
remove { Events.RemoveHandler(SemPredEvaluatedEventKey, value); }
}
public event SyntacticPredicateEventHandler SynPredStarted
{
add { Events.AddHandler(SynPredStartedEventKey, value); }
remove { Events.RemoveHandler(SynPredStartedEventKey, value); }
}
public event SyntacticPredicateEventHandler SynPredFailed
{
add { Events.AddHandler(SynPredFailedEventKey, value); }
remove { Events.RemoveHandler(SynPredFailedEventKey, value); }
}
public event SyntacticPredicateEventHandler SynPredSucceeded
{
add { Events.AddHandler(SynPredSucceededEventKey, value); }
remove { Events.RemoveHandler(SynPredSucceededEventKey, value); }
}
// From interface TokenStream
public virtual IToken nextToken() { return null; }
public virtual void append(char c)
{
if (saveConsumedInput)
{
text.Append(c);
}
}
public virtual void append(string s)
{
if (saveConsumedInput)
{
text.Append(s);
}
}
public virtual void commit()
{
inputState.input.commit();
}
public virtual void recover(RecognitionException ex, BitSet tokenSet)
{
consume();
consumeUntil(tokenSet);
}
public virtual void consume()
{
if (inputState.guessing == 0)
{
if (caseSensitive)
{
append(cached_LA1);
}
else
{
// use input.LA(), not LA(), to get original case
// CharScanner.LA() would toLower it.
append(inputState.input.LA(1));
}
if (cached_LA1 == '\t')
{
tab();
}
else
{
inputState.column++;
}
}
if (caseSensitive)
{
cached_LA1 = inputState.input.consume();
cached_LA2 = inputState.input.LA(2);
}
else
{
cached_LA1 = toLower(inputState.input.consume());
cached_LA2 = toLower(inputState.input.LA(2));
}
}
/*Consume chars until one matches the given char */
public virtual void consumeUntil(int c)
{
while ((EOF_CHAR != cached_LA1) && (c != cached_LA1))
{
consume();
}
}
/*Consume chars until one matches the given set */
public virtual void consumeUntil(BitSet bset)
{
while (cached_LA1 != EOF_CHAR && !bset.member(cached_LA1))
{
consume();
}
}
public virtual bool getCaseSensitive()
{
return caseSensitive;
}
public bool getCaseSensitiveLiterals()
{
return caseSensitiveLiterals;
}
public virtual int getColumn()
{
return inputState.column;
}
public virtual void setColumn(int c)
{
inputState.column = c;
}
public virtual bool getCommitToPath()
{
return commitToPath;
}
public virtual string getFilename()
{
return inputState.filename;
}
public virtual InputBuffer getInputBuffer()
{
return inputState.input;
}
public virtual LexerSharedInputState getInputState()
{
return inputState;
}
public virtual void setInputState(LexerSharedInputState state)
{
inputState = state;
}
public virtual int getLine()
{
return inputState.line;
}
/*return a copy of the current text buffer */
public virtual string getText()
{
return text.ToString();
}
public virtual IToken getTokenObject()
{
return returnToken_;
}
public virtual char LA(int i)
{
if (i == 1)
{
return cached_LA1;
}
if (i == 2)
{
return cached_LA2;
}
if (caseSensitive)
{
return inputState.input.LA(i);
}
else
{
return toLower(inputState.input.LA(i));
}
}
protected internal virtual IToken makeToken(int t)
{
IToken newToken = null;
bool typeCreated;
try
{
newToken = tokenCreator.Create();
if (newToken != null)
{
newToken.Type = t;
newToken.setColumn(inputState.tokenStartColumn);
newToken.setLine(inputState.tokenStartLine);
// tracking real start line now: newToken.setLine(inputState.line);
newToken.setFilename(inputState.filename);
}
typeCreated = true;
}
catch
{
typeCreated = false;
}
if (!typeCreated)
{
panic("Can't create Token object '" + tokenCreator.TokenTypeName + "'");
newToken = Token.badToken;
}
return newToken;
}
public virtual int mark()
{
return inputState.input.mark();
}
public virtual void match(char c)
{
match((int) c);
}
public virtual void match(int c)
{
if (cached_LA1 != c)
{
throw new MismatchedCharException(cached_LA1, Convert.ToChar(c), false, this);
}
consume();
}
public virtual void match(BitSet b)
{
if (!b.member(cached_LA1))
{
throw new MismatchedCharException(cached_LA1, b, false, this);
}
consume();
}
public virtual void match(string s)
{
var len = s.Length;
for (var i = 0; i < len; i++)
{
if (cached_LA1 != s[i])
{
throw new MismatchedCharException(cached_LA1, s[i], false, this);
}
consume();
}
}
public virtual void matchNot(char c)
{
matchNot((int) c);
}
public virtual void matchNot(int c)
{
if (cached_LA1 == c)
{
throw new MismatchedCharException(cached_LA1, Convert.ToChar(c), true, this);
}
consume();
}
public virtual void matchRange(int c1, int c2)
{
if (cached_LA1 < c1 || cached_LA1 > c2)
{
throw new MismatchedCharException(cached_LA1, Convert.ToChar(c1), Convert.ToChar(c2), false, this);
}
consume();
}
public virtual void matchRange(char c1, char c2)
{
matchRange((int) c1, (int) c2);
}
public virtual void newline()
{
inputState.line++;
inputState.column = 1;
}
/*advance the current column number by an appropriate amount
* according to tab size. This method is called from consume().
*/
public virtual void tab()
{
var c = getColumn();
var nc = (((c - 1) / tabsize) + 1) * tabsize + 1; // calculate tab stop
setColumn(nc);
}
public virtual void setTabSize(int size)
{
tabsize = size;
}
public virtual int getTabSize()
{
return tabsize;
}
public virtual void panic()
{
//Console.Error.WriteLine("CharScanner: panic");
//Environment.Exit(1);
panic("");
}
/// <summary>
/// This method is executed by ANTLR internally when it detected an illegal
/// state that cannot be recovered from.
/// The previous implementation of this method called <see cref="Environment.Exit"/>
/// and writes directly to <see cref="Console.Error"/>, which is usually not
/// appropriate when a translator is embedded into a larger application.
/// </summary>
/// <param name="s">Error message.</param>
public virtual void panic(string s)
{
//Console.Error.WriteLine("CharScanner; panic: " + s);
//Environment.Exit(1);
throw new ANTLRPanicException("CharScanner::panic: " + s);
}
/*Parser error-reporting function can be overridden in subclass */
public virtual void reportError(RecognitionException ex)
{
Console.Error.WriteLine(ex);
}
/*Parser error-reporting function can be overridden in subclass */
public virtual void reportError(string s)
{
if (getFilename() == null)
{
Console.Error.WriteLine("error: " + s);
}
else
{
Console.Error.WriteLine(getFilename() + ": error: " + s);
}
}
/*Parser warning-reporting function can be overridden in subclass */
public virtual void reportWarning(string s)
{
if (getFilename() == null)
{
Console.Error.WriteLine("warning: " + s);
}
else
{
Console.Error.WriteLine(getFilename() + ": warning: " + s);
}
}
public virtual void refresh()
{
if (caseSensitive)
{
cached_LA2 = inputState.input.LA(2);
cached_LA1 = inputState.input.LA(1);
}
else
{
cached_LA2 = toLower(inputState.input.LA(2));
cached_LA1 = toLower(inputState.input.LA(1));
}
}
public virtual void resetState(InputBuffer ib)
{
text.Length = 0;
traceDepth = 0;
inputState.resetInput(ib);
refresh();
}
public void resetState(Stream s)
{
resetState(new ByteBuffer(s));
}
public void resetState(TextReader tr)
{
resetState(new CharBuffer(tr));
}
public virtual void resetText()
{
text.Length = 0;
inputState.tokenStartColumn = inputState.column;
inputState.tokenStartLine = inputState.line;
}
public virtual void rewind(int pos)
{
inputState.input.rewind(pos);
//setColumn(inputState.tokenStartColumn);
if (caseSensitive)
{
cached_LA2 = inputState.input.LA(2);
cached_LA1 = inputState.input.LA(1);
}
else
{
cached_LA2 = toLower(inputState.input.LA(2));
cached_LA1 = toLower(inputState.input.LA(1));
}
}
public virtual void setCaseSensitive(bool t)
{
caseSensitive = t;
if (caseSensitive)
{
cached_LA2 = inputState.input.LA(2);
cached_LA1 = inputState.input.LA(1);
}
else
{
cached_LA2 = toLower(inputState.input.LA(2));
cached_LA1 = toLower(inputState.input.LA(1));
}
}
public virtual void setCommitToPath(bool commit)
{
commitToPath = commit;
}
public virtual void setFilename(string f)
{
inputState.filename = f;
}
public virtual void setLine(int line)
{
inputState.line = line;
}
public virtual void setText(string s)
{
resetText();
text.Append(s);
}
public virtual void setTokenObjectClass(string cl)
{
this.tokenCreator = new ReflectionBasedTokenCreator(this, cl);
}
public virtual void setTokenCreator(TokenCreator tokenCreator)
{
this.tokenCreator = tokenCreator;
}
// Test the token text against the literals table
// Override this method to perform a different literals test
public virtual int testLiteralsTable(int ttype)
{
var tokenText = text.ToString();
if ( (tokenText == null) || (tokenText == string.Empty) )
return ttype;
else
{
var typeAsObject = literals[tokenText];
return (typeAsObject == null) ? ttype : ((int) typeAsObject);
}
}
/*Test the text passed in against the literals table
* Override this method to perform a different literals test
* This is used primarily when you want to test a portion of
* a token.
*/
public virtual int testLiteralsTable(string someText, int ttype)
{
if ( (someText == null) || (someText == string.Empty) )
return ttype;
else
{
var typeAsObject = literals[someText];
return (typeAsObject == null) ? ttype : ((int) typeAsObject);
}
}
// Override this method to get more specific case handling
public virtual char toLower(int c)
{
return Char.ToLower(Convert.ToChar(c), System.Globalization.CultureInfo.InvariantCulture);
}
public virtual void traceIndent()
{
for (var i = 0; i < traceDepth; i++)
Console.Out.Write(" ");
}
public virtual void traceIn(string rname)
{
traceDepth += 1;
traceIndent();
Console.Out.WriteLine("> lexer " + rname + "; c==" + LA(1));
}
public virtual void traceOut(string rname)
{
traceIndent();
Console.Out.WriteLine("< lexer " + rname + "; c==" + LA(1));
traceDepth -= 1;
}
/*This method is called by YourLexer.nextToken() when the lexer has
* hit EOF condition. EOF is NOT a character.
* This method is not called if EOF is reached during
* syntactic predicate evaluation or during evaluation
* of normal lexical rules, which presumably would be
* an IOException. This traps the "normal" EOF condition.
*
* uponEOF() is called after the complete evaluation of
* the previous token and only if your parser asks
* for another token beyond that last non-EOF token.
*
* You might want to throw token or char stream exceptions
* like: "Heh, premature eof" or a retry stream exception
* ("I found the end of this file, go back to referencing file").
*/
public virtual void uponEOF()
{
}
private class ReflectionBasedTokenCreator : TokenCreator
{
protected ReflectionBasedTokenCreator() {}
public ReflectionBasedTokenCreator(CharScanner owner, string tokenTypeName)
{
this.owner = owner;
SetTokenType(tokenTypeName);
}
private CharScanner owner;
/// <summary>
/// The fully qualified name of the Token type to create.
/// </summary>
private string tokenTypeName;
/// <summary>
/// Type object used as a template for creating tokens by reflection.
/// </summary>
private Type tokenTypeObject;
/// <summary>
/// Returns the fully qualified name of the Token type that this
/// class creates.
/// </summary>
private void SetTokenType(string tokenTypeName)
{
this.tokenTypeName = tokenTypeName;
foreach (var assem in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
tokenTypeObject = assem.GetType(tokenTypeName);
if (tokenTypeObject != null)
{
break;
}
}
catch
{
throw new TypeLoadException("Unable to load Type for Token class '" + tokenTypeName + "'");
}
}
if (tokenTypeObject==null)
throw new TypeLoadException("Unable to load Type for Token class '" + tokenTypeName + "'");
}
/// <summary>
/// Returns the fully qualified name of the Token type that this
/// class creates.
/// </summary>
public override string TokenTypeName
{
get
{
return tokenTypeName;
}
}
/// <summary>
/// Constructs a <see cref="Token"/> instance.
/// </summary>
public override IToken Create()
{
IToken newToken = null;
try
{
newToken = (Token) Activator.CreateInstance(tokenTypeObject);
}
catch
{
// supress exception
}
return newToken;
}
}
}
}
| |
using De.Osthus.Ambeth.Bytecode.Behavior;
using De.Osthus.Ambeth.CompositeId;
using De.Osthus.Ambeth.Merge.Model;
using De.Osthus.Ambeth.Metadata;
using De.Osthus.Ambeth.Mixin;
using De.Osthus.Ambeth.Typeinfo;
using De.Osthus.Ambeth.Util;
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
namespace De.Osthus.Ambeth.Bytecode.Visitor
{
public class ObjRefVisitor : ClassVisitor
{
public static readonly Type templateType = typeof(ObjRefMixin);
protected static readonly String templatePropertyName = templateType.Name;
private static readonly ConstructorInstance c_stringBuilder = new ConstructorInstance(typeof(StringBuilder).GetConstructor(Type.EmptyTypes));
private static readonly PropertyInstance template_p_realType = PropertyInstance.FindByTemplate(typeof(IObjRef), "RealType", typeof(Type), false);
private static readonly PropertyInstance template_p_idIndex = PropertyInstance.FindByTemplate(typeof(IObjRef), "IdNameIndex", typeof(sbyte), false);
private static readonly PropertyInstance template_p_id = PropertyInstance.FindByTemplate(typeof(IObjRef), "Id", typeof(Object), false);
private static readonly PropertyInstance template_p_version = PropertyInstance.FindByTemplate(typeof(IObjRef), "Version", typeof(Object), false);
private static readonly MethodInstance template_m_equals = new MethodInstance(null, typeof(Object), typeof(bool), "Equals", typeof(Object));
private static readonly MethodInstance template_m_hashCode = new MethodInstance(null, typeof(Object), typeof(int), "GetHashCode");
private static readonly MethodInstance template_m_toString = new MethodInstance(null, typeof(Object), typeof(String), "ToString");
private static readonly MethodInstance template_m_toStringSb = new MethodInstance(null, typeof(IPrintable), typeof(void), "ToString", typeof(StringBuilder));
private static readonly MethodInstance m_objRef_equals = new MethodInstance(null, templateType, typeof(bool), "ObjRefEquals", typeof(IObjRef), typeof(Object));
private static readonly MethodInstance m_objRef_hashCode = new MethodInstance(null, templateType, typeof(int), "ObjRefHashCode", typeof(IObjRef));
private static readonly MethodInstance m_objRef_toStringSb = new MethodInstance(null, templateType, typeof(void), "ObjRefToString", typeof(IObjRef),
typeof(StringBuilder));
public static PropertyInstance GetObjRefTemplatePI(IClassVisitor cv)
{
Object bean = State.BeanContext.GetService(templateType);
PropertyInstance pi = State.GetProperty(templatePropertyName, NewType.GetType(bean.GetType()));
if (pi != null)
{
return pi;
}
return cv.ImplementAssignedReadonlyProperty(templatePropertyName, bean);
}
public static PropertyInstance GetConversionHelperPI(IClassVisitor cv)
{
Object bean = State.BeanContext.GetService<IConversionHelper>();
PropertyInstance pi = State.GetProperty("ConversionHelper", NewType.GetType(bean.GetType()));
if (pi != null)
{
return pi;
}
return cv.ImplementAssignedReadonlyProperty("ConversionHelper", bean);
}
protected readonly IEntityMetaData metaData;
protected readonly int idIndex;
public ObjRefVisitor(IClassVisitor cv, IEntityMetaData metaData, int idIndex)
: base(new InterfaceAdder(cv, typeof(IObjRef)))
{
this.metaData = metaData;
this.idIndex = idIndex;
}
public override void VisitEnd()
{
ImplementRealType();
ImplementIdIndex();
PropertyInstance p_id = ImplementId();
PropertyInstance p_version = ImplementVersion();
ImplementDefaultConstructor();
ImplementIdVersionConstructor(p_id, p_version);
ImplementToString();
ImplementEquals();
ImplementHashCode();
base.VisitEnd();
}
protected void ImplementDefaultConstructor()
{
IMethodVisitor mv = VisitMethod(ConstructorInstance.defaultConstructor);
mv.LoadThis();
mv.InvokeSuperOfCurrentMethod();
mv.ReturnValue();
mv.EndMethod();
}
protected void ImplementIdVersionConstructor(PropertyInstance p_id, PropertyInstance p_version)
{
ConstructorInfo superConstructor = State.CurrentType.GetConstructor(Type.EmptyTypes);
ConstructorInstance ci_super = new ConstructorInstance(superConstructor);
IMethodVisitor mv = VisitMethod(new ConstructorInstance(MethodAttributes.Public, typeof(Object), typeof(Object)));
mv.LoadThis();
mv.InvokeConstructor(ci_super);
mv.CallThisSetter(p_id, delegate(IMethodVisitor mg)
{
mg.LoadArg(0);
});
mv.CallThisSetter(p_version, delegate(IMethodVisitor mg)
{
mg.LoadArg(1);
});
mv.ReturnValue();
mv.EndMethod();
}
protected void ImplementRealType()
{
ImplementProperty(template_p_realType, delegate(IMethodVisitor mg)
{
mg.Push(metaData.EntityType);
mg.ReturnValue();
}, delegate(IMethodVisitor mg)
{
mg.ThrowException(typeof(NotSupportedException), "Property is read-only");
mg.ReturnValue();
});
}
protected void ImplementIdIndex()
{
ImplementProperty(template_p_idIndex, delegate(IMethodVisitor mg)
{
mg.Push(idIndex);
mg.ReturnValue();
}, delegate(IMethodVisitor mg)
{
mg.ThrowException(typeof(NotSupportedException), "Property is read-only");
mg.ReturnValue();
});
}
protected PropertyInstance ImplementPotentialPrimitive(PropertyInstance property, Member member)
{
if (member == null)
{
return ImplementProperty(property, delegate(IMethodVisitor mg)
{
mg.PushNull();
mg.ReturnValue();
}, delegate(IMethodVisitor mg)
{
Label l_isNull = mg.NewLabel();
mg.LoadArg(0);
mg.IfNull(l_isNull);
mg.ThrowException(typeof(NotSupportedException), "Property is read-only");
mg.Mark(l_isNull);
mg.ReturnValue();
});
}
PropertyInstance p_conversionHelper = GetConversionHelperPI(this);
MethodInstance m_convertValueToType = new MethodInstance(ReflectUtil.GetDeclaredMethod(false, typeof(IConversionHelper), typeof(Object),
"ConvertValueToType", typeof(Type), typeof(Object)));
Type type = member.RealType;
FieldInstance field = ImplementField(new FieldInstance(FieldAttributes.Public, "f_" + property.Name, type));
return ImplementProperty(property, delegate(IMethodVisitor mg)
{
if (field.Type.Type.IsPrimitive)
{
Label l_isNull = mg.NewLabel();
LocalVariableInfo loc_value = mg.NewLocal(field.Type);
mg.GetThisField(field);
mg.StoreLocal(loc_value);
mg.LoadLocal(loc_value);
mg.IfZCmp(field.Type, CompareOperator.EQ, l_isNull);
mg.LoadLocal(loc_value);
mg.Box(type);
mg.ReturnValue();
mg.Mark(l_isNull);
mg.PushNull();
}
else if (field.Type.Type.IsValueType)
{
Type pType = field.Type.Type;
mg.GetThisField(field);
MethodInfo m_hasValue = pType.GetMethod("get_HasValue");
if (m_hasValue != null)
{
LocalVariableInfo loc_value = mg.NewLocal(pType);
mg.StoreLocal(loc_value);
mg.LoadLocal(loc_value);
MethodInfo m_getValue = pType.GetMethod("get_Value");
LocalVariableInfo loc_realValue = mg.NewLocal(m_getValue.ReturnType);
Label l_hasNoValue = mg.NewLabel();
mg.InvokeOnExactOwner(m_hasValue);
mg.IfZCmp(CompareOperator.EQ, l_hasNoValue);
mg.LoadLocal(loc_value);
mg.InvokeOnExactOwner(m_getValue);
mg.StoreLocal(loc_realValue);
mg.LoadLocal(loc_realValue);
mg.IfZCmp(CompareOperator.EQ, l_hasNoValue);
mg.LoadLocal(loc_realValue);
mg.ValueOf(m_getValue.ReturnType);
mg.ReturnValue();
mg.Mark(l_hasNoValue);
mg.PushNullOrZero(mg.Method.ReturnType);
}
else
{
mg.Box(pType);
}
}
else
{
mg.GetThisField(field);
}
mg.ReturnValue();
}, delegate(IMethodVisitor mg)
{
mg.PutThisField(field, delegate(IMethodVisitor mg2)
{
Label l_isNull = mg2.NewLabel();
Label l_finish = mg2.NewLabel();
mg2.LoadArg(0);
mg2.IfNull(l_isNull);
mg.CallThisGetter(p_conversionHelper);
mg.Push(type);
mg.LoadArg(0);
mg.InvokeVirtual(m_convertValueToType);
mg2.Unbox(type);
mg2.GoTo(l_finish);
mg2.Mark(l_isNull);
mg2.PushNullOrZero(field.Type);
mg2.Mark(l_finish);
});
mg.ReturnValue();
});
}
protected PropertyInstance ImplementId()
{
return ImplementPotentialPrimitive(template_p_id, metaData.GetIdMemberByIdIndex((sbyte)idIndex));
}
protected PropertyInstance ImplementVersion()
{
return ImplementPotentialPrimitive(template_p_version, metaData.VersionMember);
}
protected void ImplementToString()
{
PropertyInstance p_objRefTemplate = GetObjRefTemplatePI(this);
MethodInstance methodSb;
{
methodSb = MethodInstance.FindByTemplate(template_m_toStringSb, true);
if (methodSb == null || methodSb.Access.HasFlag(MethodAttributes.Abstract))
{
IMethodVisitor mg = VisitMethod(template_m_toStringSb);
mg.CallThisGetter(p_objRefTemplate);
mg.LoadThis();
mg.LoadArgs();
mg.InvokeVirtual(m_objRef_toStringSb);
mg.ReturnValue();
mg.EndMethod();
methodSb = mg.Method;
}
}
{
MethodInstance method = MethodInstance.FindByTemplate(template_m_toString, true);
if (method == null || NewType.GetType(typeof(Object)).Equals(method.Owner) || methodSb.Access.HasFlag(MethodAttributes.Abstract))
{
IMethodVisitor mg = VisitMethod(template_m_toString);
LocalVariableInfo loc_sb = mg.NewLocal(typeof(StringBuilder));
mg.LoadThis();
mg.NewInstance(c_stringBuilder, null);
mg.StoreLocal(loc_sb);
mg.LoadLocal(loc_sb);
mg.InvokeVirtual(methodSb);
mg.LoadLocal(loc_sb);
mg.InvokeVirtual(new MethodInstance(null, typeof(StringBuilder), typeof(String), "ToString"));
mg.ReturnValue();
mg.EndMethod();
}
}
}
protected void ImplementEquals()
{
PropertyInstance p_objRefTemplate = GetObjRefTemplatePI(this);
MethodInstance method = MethodInstance.FindByTemplate(template_m_equals, true);
if (method == null || method.Access.HasFlag(MethodAttributes.Abstract))
{
IMethodVisitor mg = VisitMethod(template_m_equals);
mg.CallThisGetter(p_objRefTemplate);
mg.LoadThis();
mg.LoadArgs();
mg.InvokeVirtual(m_objRef_equals);
mg.ReturnValue();
mg.EndMethod();
}
}
protected void ImplementHashCode()
{
PropertyInstance p_objRefTemplate = GetObjRefTemplatePI(this);
MethodInstance method = MethodInstance.FindByTemplate(template_m_hashCode, true);
if (method == null || method.Access.HasFlag(MethodAttributes.Abstract))
{
IMethodVisitor mg = VisitMethod(template_m_hashCode);
mg.CallThisGetter(p_objRefTemplate);
mg.LoadThis();
mg.LoadArgs();
mg.InvokeVirtual(m_objRef_hashCode);
mg.ReturnValue();
mg.EndMethod();
}
}
}
}
| |
using System;
using System.Globalization;
/// <summary>
/// DateTime.Subtract(TimeSpan)
/// </summary>
public class DateTimeSubtract2
{
public static int Main()
{
DateTimeSubtract2 dtsub2 = new DateTimeSubtract2();
TestLibrary.TestFramework.BeginTestCase("DataTimeSubtract2");
if (dtsub2.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("[PosTest]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[NegTest]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
DateTime resultTime;
TestLibrary.TestFramework.BeginScenario("PosTest1: The return dateTime is in the range of MinValue and MaxValue 1");
try
{
DateTime date1 = new DateTime(2000, 1, 1).ToLocalTime();
TimeSpan timeSpan = new TimeSpan(365, 0, 0, 0);
resultTime = date1.Subtract(timeSpan);
if (resultTime!= new DateTime(1999,1,1).ToLocalTime())
{
TestLibrary.TestFramework.LogError("001", "The ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
DateTime resultTime;
TestLibrary.TestFramework.BeginScenario("PosTest2: The return dateTime is in the range of MinValue and MaxValue 2");
try
{
DateTime date1 = new DateTime(1999, 1, 1).ToLocalTime();
TimeSpan timeSpan = new TimeSpan(-365, 0, 0, 0);
resultTime = date1.Subtract(timeSpan);
if (resultTime != new DateTime(2000, 1, 1).ToLocalTime())
{
TestLibrary.TestFramework.LogError("003", "The ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
DateTime resultTime;
TestLibrary.TestFramework.BeginScenario("PosTest3: The return dateTime is in the range of MinValue and MaxValue 3");
try
{
DateTime date1 = new DateTime(this.GetInt32(1,9999),this.GetInt32(1,12),this.GetInt32(1,28)).ToLocalTime();
TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0);
resultTime = date1.Subtract(timeSpan);
if (resultTime != date1)
{
TestLibrary.TestFramework.LogError("005", "The ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
DateTime resultTime;
TestLibrary.TestFramework.BeginScenario("PosTest4: The return dateTime is in the range of MinValue and MaxValue 4");
try
{
DateTime date1 = new DateTime(2001, 1, 1).ToLocalTime();
TimeSpan timeSpan = new TimeSpan(366, 0, 0, 0);
resultTime = date1.Subtract(timeSpan);
if (resultTime != new DateTime(2000, 1, 1).ToLocalTime())
{
TestLibrary.TestFramework.LogError("007", "The ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
DateTime resultTime;
TestLibrary.TestFramework.BeginScenario("PosTest5: The return dateTime is in the range of MinValue and MaxValue 5");
try
{
DateTime date1 = new DateTime(2000, 1, 1).ToLocalTime();
TimeSpan timeSpan = new TimeSpan(-366, 0, 0, 0);
resultTime = date1.Subtract(timeSpan);
if (resultTime != new DateTime(2001, 1, 1).ToLocalTime())
{
TestLibrary.TestFramework.LogError("009", "The ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
DateTime resultTime;
TestLibrary.TestFramework.BeginScenario("NegTest1: The return dateTime is out the range of MinValue and MaxValue 1");
try
{
DateTime date1 = DateTime.MinValue.ToLocalTime();
TimeSpan timeSpan = new TimeSpan(365, 0, 0, 0);
resultTime = date1.Subtract(timeSpan);
TestLibrary.TestFramework.LogError("N001", "The return datetime is less than MinValue but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
DateTime resultTime;
TestLibrary.TestFramework.BeginScenario("NegTest2: The return dateTime is out the range of MinValue and MaxValue 1");
try
{
DateTime date1 = DateTime.MaxValue.ToLocalTime();
TimeSpan timeSpan = new TimeSpan(-365, 0, 0, 0);
resultTime = date1.Subtract(timeSpan);
retVal = false;
TestLibrary.TestFramework.LogError("N003", "The return datetime is greater than MaxValue but not throw exception");
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region HelpMethod
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Tortuga.Chain;
using Tortuga.Chain.SqlServer;
namespace Tortuga.Drydock.Models.SqlServer
{
/// <summary>
/// This represents a database connection and any cached data about that database.
/// This class is specialized for SQL Server.
/// </summary>
/// <seealso cref="Tortuga.Drydock.Models.Database{Tortuga.Chain.SqlServerDataSource}" />
public class SqlServerDatabase : DatabaseVM<SqlServerDataSource, SqlServerObjectName, SqlDbType>
{
public SqlServerDatabase(SqlServerDataSource dataSource)
{
DataSource = dataSource;
}
public override sealed async Task LoadSchemaAsync()
{
StartWork();
try
{
await (Task.Run(() =>
{
DataSource.DatabaseMetadata.PreloadTables();
DataSource.DatabaseMetadata.PreloadViews();
})); //Task-10, we need an async version of this.
Tables.AddRange(DataSource.DatabaseMetadata.GetTablesAndViews().Where(t => t.IsTable).OrderBy(t => t.Name.Schema).ThenBy(t => t.Name.Name).Select(t => new SqlServerTableVM(DataSource, (SqlServerTableOrViewMetadata<SqlDbType>)t)));
Views.AddRange(DataSource.DatabaseMetadata.GetTablesAndViews().Where(t => !t.IsTable).OrderBy(t => t.Name.Schema).ThenBy(t => t.Name.Name).Select(t => new ViewVM(t)));
const string tableDescriptionsSql = @"SELECT s.name AS SchemaName, t.name AS TableName, ep.value FROM sys.extended_properties ep
INNER JOIN sys.tables t ON ep.major_id = t.object_id AND ep.minor_id = 0
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
AND ep.name = 'MS_Description';";
var tableDescriptions = await DataSource.Sql(tableDescriptionsSql).ToTable().ExecuteAsync();
foreach (var item in tableDescriptions.Rows)
{
var table = Tables.Single(t => t.Table.Name.Schema == (string)item["SchemaName"] && t.Table.Name.Name == (string)item["TableName"]);
table.Description = (string)item["value"];
}
const string columnDescriptionsSql = @"SELECT s.name AS SchemaName, t.name AS TableName, c.name AS ColumnName, ep.value FROM sys.extended_properties ep
INNER JOIN sys.tables t ON ep.major_id = t.object_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN sys.columns c ON c.object_id = ep.major_id AND c.column_id = ep.minor_id
AND ep.name = 'MS_Description'";
var columnDescriptions = await DataSource.Sql(columnDescriptionsSql).ToTable().ExecuteAsync();
foreach (var item in columnDescriptions.Rows)
{
var table = Tables.Single(t => t.Table.Name.Schema == (string)item["SchemaName"] && t.Table.Name.Name == (string)item["TableName"]);
var column = (SqlServerColumnModel)table.Columns.Single(c => c.Name == (string)item["ColumnName"]);
column.Description = (string)item["value"];
}
const string sparseColumnsSql = @"SELECT s.name AS SchemaName, t.name AS TableName, c.name AS ColumnName, c.is_sparse
FROM sys.tables t
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN sys.columns c ON c.object_id = t.object_id";
var sparseColumns = await DataSource.Sql(sparseColumnsSql).ToTable().ExecuteAsync();
foreach (var item in sparseColumns.Rows)
{
var table = Tables.Single(t => t.Table.Name.Schema == (string)item["SchemaName"] && t.Table.Name.Name == (string)item["TableName"]);
var column = (SqlServerColumnModel)table.Columns.Single(c => c.Name == (string)item["ColumnName"]);
column.IsSparse = (bool)item["is_sparse"];
}
const string relatedTablesSql = @"SELECT s.name AS SchemaName, t.name AS TableName, s2.name AS ReferencedSchemaName, t2.name AS ReferencedTableName
FROM sys.foreign_key_columns fkc
INNER JOIN sys.tables t
ON fkc.parent_object_id = t.object_id
INNER JOIN sys.columns c
ON c.column_id = fkc.parent_column_id
AND c.object_id = fkc.parent_object_id
INNER JOIN sys.schemas s
ON s.schema_id = t.schema_id
INNER JOIN sys.tables t2
ON fkc.referenced_object_id = t2.object_id
INNER JOIN sys.columns c2
ON c2.column_id = fkc.referenced_column_id
AND c2.object_id = fkc.referenced_object_id
INNER JOIN sys.schemas s2
ON s2.schema_id = t2.schema_id
INNER JOIN sys.foreign_keys fk
ON fk.object_id = fkc.constraint_object_id";
var relatedTables = await DataSource.Sql(relatedTablesSql).ToTable().ExecuteAsync();
foreach (var item in relatedTables.Rows)
{
var table = Tables.Single(t => t.Table.Name.Schema == (string)item["SchemaName"] && t.Table.Name.Name == (string)item["TableName"]);
var relatedTable = Tables.Single(t => t.Table.Name.Schema == (string)item["ReferencedSchemaName"] && t.Table.Name.Name == (string)item["ReferencedTableName"]);
if (!table.ReferencedTables.Contains(relatedTable))
table.ReferencedTables.Add(relatedTable);
if (!relatedTable.ReferencedByTables.Contains(table))
relatedTable.ReferencedByTables.Add(table);
}
}
finally
{
StopWork();
}
}
async public override Task PreliminaryAnalysisAsync(TableVM table)
{
var typedTable = (SqlServerTableVM)table;
const string sql = @"SELECT S.name AS [Schema],
T.name AS Name,
CONVERT( BIT,
CASE
WHEN NOT EXISTS
(
SELECT *
FROM sys.indexes AS i
WHERE i.object_id = T.object_id
AND type = 1
) THEN
1
ELSE
0
END
) AS IsHeap,
(
SELECT COUNT(*)
FROM sys.indexes AS i
WHERE i.object_id = T.object_id
AND type <> 0
) AS IndexCount,
(
SELECT SUM(p.rows)
FROM sys.partitions AS p
WHERE p.index_id < 2
AND p.object_id = T.object_id
) AS [RowCount],
ROW_NUMBER() OVER (ORDER BY S.name, T.name) AS SortIndex,
T.object_id AS ObjectId
FROM sys.tables AS T
INNER JOIN sys.schemas AS S
ON T.schema_id = S.schema_id
WHERE T.name = @Name
AND S.name = @Schema
ORDER BY S.name,
T.name;";
var tableData = await DataSource.Sql(sql, new { typedTable.Table.Name.Schema, typedTable.Table.Name.Name }).ToObject<TableData>().ExecuteAsync();
typedTable.ObjectId = tableData.ObjectId;
typedTable.RowCount = tableData.RowCount;
typedTable.IndexCount = tableData.IndexCount;
typedTable.IsHeap = tableData.IsHeap;
table.FixItOperations.RefreshAll();
}
async public override Task PreliminaryAnalysisAsync()
{
const string sql = @"SELECT S.name AS [Schema],
T.name AS Name,
CONVERT( BIT,
CASE
WHEN NOT EXISTS
(
SELECT *
FROM sys.indexes AS i
WHERE i.object_id = T.object_id
AND type = 1
) THEN
1
ELSE
0
END
) AS IsHeap,
(
SELECT COUNT(*)
FROM sys.indexes AS i
WHERE i.object_id = T.object_id
AND type <> 0
) AS IndexCount,
(
SELECT SUM(p.rows)
FROM sys.partitions AS p
WHERE p.index_id < 2
AND p.object_id = T.object_id
) AS [RowCount],
ROW_NUMBER() OVER (ORDER BY S.name, T.name) AS SortIndex,
T.object_id AS ObjectId
FROM sys.tables AS T
INNER JOIN sys.schemas AS S
ON T.schema_id = S.schema_id
ORDER BY S.name,
T.name;";
var data = await DataSource.Sql(sql).ToCollection<TableData>().ExecuteAsync();
foreach (SqlServerTableVM table in Tables)
{
foreach (var tableData in data)
{
if (tableData.Schema == table.Table.Name.Schema && tableData.Name == table.Table.Name.Name)
{
table.ObjectId = tableData.ObjectId;
table.RowCount = tableData.RowCount;
table.IndexCount = tableData.IndexCount;
table.IsHeap = tableData.IsHeap;
table.FixItOperations.RefreshAll();
table.SortIndex = tableData.SortIndex;
break;
}
}
}
}
class TableData
{
public string Name { get; set; }
public string Schema { get; set; }
public int ColumnCount { get; set; }
public bool IsHeap { get; set; }
public int IndexCount { get; set; }
public long ObjectId { get; set; }
public long RowCount { get; set; }
public int SortIndex { get; set; }
}
}
}
| |
/*
* 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 NUnit.Framework;
using Directory = Lucene.Net.Store.Directory;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
namespace Lucene.Net.Util
{
/// <summary> <c>TestBitVector</c> tests the <c>BitVector</c>, obviously.
///
///
/// </summary>
/// <version> $Id: TestBitVector.java 765649 2009-04-16 14:29:26Z mikemccand $
/// </version>
[TestFixture]
public class TestBitVector:LuceneTestCase
{
/// <summary> Test the default constructor on BitVectors of various sizes.</summary>
/// <throws> Exception </throws>
[Test]
public virtual void TestConstructSize()
{
DoTestConstructOfSize(8);
DoTestConstructOfSize(20);
DoTestConstructOfSize(100);
DoTestConstructOfSize(1000);
}
private void DoTestConstructOfSize(int n)
{
BitVector bv = new BitVector(n);
Assert.AreEqual(n, bv.Size());
}
/// <summary> Test the get() and set() methods on BitVectors of various sizes.</summary>
/// <throws> Exception </throws>
[Test]
public virtual void TestGetSet()
{
DoTestGetSetVectorOfSize(8);
DoTestGetSetVectorOfSize(20);
DoTestGetSetVectorOfSize(100);
DoTestGetSetVectorOfSize(1000);
}
private void DoTestGetSetVectorOfSize(int n)
{
BitVector bv = new BitVector(n);
for (int i = 0; i < bv.Size(); i++)
{
// ensure a set bit can be git'
Assert.IsFalse(bv.Get(i));
bv.Set(i);
Assert.IsTrue(bv.Get(i));
}
}
/// <summary> Test the clear() method on BitVectors of various sizes.</summary>
/// <throws> Exception </throws>
[Test]
public virtual void TestClear()
{
DoTestClearVectorOfSize(8);
DoTestClearVectorOfSize(20);
DoTestClearVectorOfSize(100);
DoTestClearVectorOfSize(1000);
}
private void DoTestClearVectorOfSize(int n)
{
BitVector bv = new BitVector(n);
for (int i = 0; i < bv.Size(); i++)
{
// ensure a set bit is cleared
Assert.IsFalse(bv.Get(i));
bv.Set(i);
Assert.IsTrue(bv.Get(i));
bv.Clear(i);
Assert.IsFalse(bv.Get(i));
}
}
/// <summary> Test the count() method on BitVectors of various sizes.</summary>
/// <throws> Exception </throws>
[Test]
public virtual void TestCount()
{
DoTestCountVectorOfSize(8);
DoTestCountVectorOfSize(20);
DoTestCountVectorOfSize(100);
DoTestCountVectorOfSize(1000);
}
private void DoTestCountVectorOfSize(int n)
{
BitVector bv = new BitVector(n);
// test count when incrementally setting bits
for (int i = 0; i < bv.Size(); i++)
{
Assert.IsFalse(bv.Get(i));
Assert.AreEqual(i, bv.Count());
bv.Set(i);
Assert.IsTrue(bv.Get(i));
Assert.AreEqual(i + 1, bv.Count());
}
bv = new BitVector(n);
// test count when setting then clearing bits
for (int i = 0; i < bv.Size(); i++)
{
Assert.IsFalse(bv.Get(i));
Assert.AreEqual(0, bv.Count());
bv.Set(i);
Assert.IsTrue(bv.Get(i));
Assert.AreEqual(1, bv.Count());
bv.Clear(i);
Assert.IsFalse(bv.Get(i));
Assert.AreEqual(0, bv.Count());
}
}
/// <summary> Test writing and construction to/from Directory.</summary>
/// <throws> Exception </throws>
[Test]
public virtual void TestWriteRead()
{
DoTestWriteRead(8);
DoTestWriteRead(20);
DoTestWriteRead(100);
DoTestWriteRead(1000);
}
private void DoTestWriteRead(int n)
{
Directory d = new RAMDirectory();
BitVector bv = new BitVector(n);
// test count when incrementally setting bits
for (int i = 0; i < bv.Size(); i++)
{
Assert.IsFalse(bv.Get(i));
Assert.AreEqual(i, bv.Count());
bv.Set(i);
Assert.IsTrue(bv.Get(i));
Assert.AreEqual(i + 1, bv.Count());
bv.Write(d, "TESTBV");
BitVector compare = new BitVector(d, "TESTBV");
// compare bit vectors with bits set incrementally
Assert.IsTrue(DoCompare(bv, compare));
}
}
/// <summary> Test r/w when size/count cause switching between bit-set and d-gaps file formats. </summary>
/// <throws> Exception </throws>
[Test]
public virtual void TestDgaps()
{
DoTestDgaps(1, 0, 1);
DoTestDgaps(10, 0, 1);
DoTestDgaps(100, 0, 1);
DoTestDgaps(1000, 4, 7);
DoTestDgaps(10000, 40, 43);
DoTestDgaps(100000, 415, 418);
DoTestDgaps(1000000, 3123, 3126);
}
private void DoTestDgaps(int size, int count1, int count2)
{
Directory d = new RAMDirectory();
BitVector bv = new BitVector(size);
for (int i = 0; i < count1; i++)
{
bv.Set(i);
Assert.AreEqual(i + 1, bv.Count());
}
bv.Write(d, "TESTBV");
// gradually increase number of set bits
for (int i = count1; i < count2; i++)
{
BitVector bv2 = new BitVector(d, "TESTBV");
Assert.IsTrue(DoCompare(bv, bv2));
bv = bv2;
bv.Set(i);
Assert.AreEqual(i + 1, bv.Count());
bv.Write(d, "TESTBV");
}
// now start decreasing number of set bits
for (int i = count2 - 1; i >= count1; i--)
{
BitVector bv2 = new BitVector(d, "TESTBV");
Assert.IsTrue(DoCompare(bv, bv2));
bv = bv2;
bv.Clear(i);
Assert.AreEqual(i, bv.Count());
bv.Write(d, "TESTBV");
}
}
/// <summary> Compare two BitVectors.
/// This should really be an equals method on the BitVector itself.
/// </summary>
/// <param name="bv">One bit vector
/// </param>
/// <param name="compare">The second to compare
/// </param>
private bool DoCompare(BitVector bv, BitVector compare)
{
bool equal = true;
for (int i = 0; i < bv.Size(); i++)
{
// bits must be equal
if (bv.Get(i) != compare.Get(i))
{
equal = false;
break;
}
}
return equal;
}
private static int[] subsetPattern = new int[]{1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1};
/// <summary> Tests BitVector.subset() against the above pattern</summary>
[Test]
public virtual void TestSubset()
{
DoTestSubset(0, 0);
DoTestSubset(0, 20);
DoTestSubset(0, 7);
DoTestSubset(0, 8);
DoTestSubset(0, 9);
DoTestSubset(0, 15);
DoTestSubset(0, 16);
DoTestSubset(0, 17);
DoTestSubset(1, 7);
DoTestSubset(1, 8);
DoTestSubset(1, 9);
DoTestSubset(1, 15);
DoTestSubset(1, 16);
DoTestSubset(1, 17);
DoTestSubset(2, 20);
DoTestSubset(3, 20);
DoTestSubset(4, 20);
DoTestSubset(5, 20);
DoTestSubset(6, 20);
DoTestSubset(7, 14);
DoTestSubset(7, 15);
DoTestSubset(7, 16);
DoTestSubset(8, 15);
DoTestSubset(9, 20);
DoTestSubset(10, 20);
DoTestSubset(11, 20);
DoTestSubset(12, 20);
DoTestSubset(13, 20);
}
/// <summary> Compare a subset against the corresponding portion of the test pattern</summary>
private void DoTestSubset(int start, int end)
{
BitVector full = CreateSubsetTestVector();
BitVector subset = full.Subset(start, end);
Assert.AreEqual(end - start, subset.Size());
int count = 0;
for (int i = start, j = 0; i < end; i++, j++)
{
if (subsetPattern[i] == 1)
{
count++;
Assert.IsTrue(subset.Get(j));
}
else
{
Assert.IsFalse(subset.Get(j));
}
}
Assert.AreEqual(count, subset.Count());
}
private BitVector CreateSubsetTestVector()
{
BitVector bv = new BitVector(subsetPattern.Length);
for (int i = 0; i < subsetPattern.Length; i++)
{
if (subsetPattern[i] == 1)
{
bv.Set(i);
}
}
return bv;
}
}
}
| |
#region License
/*
* WebSocketServiceHostManager.cs
*
* The MIT License
*
* Copyright (c) 2012-2013 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using WebSocketSharp.Net;
namespace WebSocketSharp.Server
{
/// <summary>
/// Manages the WebSocket services provided by the <see cref="HttpServer"/> and
/// <see cref="WebSocketServer"/>.
/// </summary>
public class WebSocketServiceHostManager
{
#region Private Fields
private volatile bool _keepClean;
private Logger _logger;
private Dictionary<string, WebSocketServiceHost> _serviceHosts;
private volatile ServerState _state;
private object _sync;
#endregion
#region Internal Constructors
internal WebSocketServiceHostManager ()
: this (new Logger ())
{
}
internal WebSocketServiceHostManager (Logger logger)
{
_logger = logger;
_keepClean = true;
_serviceHosts = new Dictionary<string, WebSocketServiceHost> ();
_state = ServerState.READY;
_sync = new object ();
}
#endregion
#region Public Properties
/// <summary>
/// Gets the number of the WebSocket services provided by the WebSocket server.
/// </summary>
/// <value>
/// An <see cref="int"/> that contains the number of the WebSocket services.
/// </value>
public int Count {
get {
lock (_sync)
{
return _serviceHosts.Count;
}
}
}
/// <summary>
/// Gets a WebSocket service host with the specified <paramref name="servicePath"/>.
/// </summary>
/// <value>
/// A <see cref="WebSocketServiceHost"/> instance that represents the service host
/// if the service is successfully found; otherwise, <see langword="null"/>.
/// </value>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the service to find.
/// </param>
public WebSocketServiceHost this [string servicePath] {
get {
WebSocketServiceHost host;
TryGetServiceHost (servicePath, out host);
return host;
}
}
/// <summary>
/// Gets a value indicating whether the manager cleans up periodically the every inactive session
/// to the WebSocket services provided by the WebSocket server.
/// </summary>
/// <value>
/// <c>true</c> if the manager cleans up periodically the every inactive session to the WebSocket
/// services; otherwise, <c>false</c>.
/// </value>
public bool KeepClean {
get {
return _keepClean;
}
internal set {
lock (_sync)
{
if (!(value ^ _keepClean))
return;
_keepClean = value;
foreach (var host in _serviceHosts.Values)
host.KeepClean = value;
}
}
}
/// <summary>
/// Gets the collection of the WebSocket service hosts managed by the WebSocket server.
/// </summary>
/// <value>
/// An IEnumerable<WebSocketServiceHost> that contains the collection of the WebSocket
/// service hosts.
/// </value>
public IEnumerable<WebSocketServiceHost> ServiceHosts {
get {
lock (_sync)
{
return _serviceHosts.Values.ToList ();
}
}
}
/// <summary>
/// Gets the collection of every path to the WebSocket services provided by the WebSocket server.
/// </summary>
/// <value>
/// An IEnumerable<string> that contains the collection of every path to the WebSocket services.
/// </value>
public IEnumerable<string> ServicePaths {
get {
lock (_sync)
{
return _serviceHosts.Keys.ToList ();
}
}
}
/// <summary>
/// Gets the number of the sessions to the every WebSocket service
/// provided by the WebSocket server.
/// </summary>
/// <value>
/// An <see cref="int"/> that contains the session count of the WebSocket server.
/// </value>
public int SessionCount {
get {
var count = 0;
foreach (var host in ServiceHosts)
{
if (_state != ServerState.START)
break;
count += host.SessionCount;
}
return count;
}
}
#endregion
#region Private Methods
private void broadcast (Opcode opcode, byte [] data, Action completed)
{
var cache = new Dictionary<CompressionMethod, byte []> ();
try {
foreach (var host in ServiceHosts)
{
if (_state != ServerState.START)
break;
host.Sessions.Broadcast (opcode, data, cache);
}
if (completed != null)
completed ();
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
}
finally {
cache.Clear ();
}
}
private void broadcast (Opcode opcode, Stream stream, Action completed)
{
var cache = new Dictionary<CompressionMethod, Stream> ();
try {
foreach (var host in ServiceHosts)
{
if (_state != ServerState.START)
break;
host.Sessions.Broadcast (opcode, stream, cache);
}
if (completed != null)
completed ();
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
}
finally {
foreach (var cached in cache.Values)
cached.Dispose ();
cache.Clear ();
}
}
private void broadcastAsync (Opcode opcode, byte [] data, Action completed)
{
WaitCallback callback = state =>
{
broadcast (opcode, data, completed);
};
ThreadPool.QueueUserWorkItem (callback);
}
private void broadcastAsync (Opcode opcode, Stream stream, Action completed)
{
WaitCallback callback = state =>
{
broadcast (opcode, stream, completed);
};
ThreadPool.QueueUserWorkItem (callback);
}
private Dictionary<string, Dictionary<string, bool>> broadping (byte [] frameAsBytes, int timeOut)
{
var result = new Dictionary<string, Dictionary<string, bool>> ();
foreach (var host in ServiceHosts)
{
if (_state != ServerState.START)
break;
result.Add (host.ServicePath, host.Sessions.Broadping (frameAsBytes, timeOut));
}
return result;
}
#endregion
#region Internal Methods
internal void Add (string servicePath, WebSocketServiceHost serviceHost)
{
lock (_sync)
{
WebSocketServiceHost host;
if (_serviceHosts.TryGetValue (servicePath, out host))
{
_logger.Error (
"A WebSocket service with the specified path already exists.\npath: " + servicePath);
return;
}
if (_state == ServerState.START)
serviceHost.Sessions.Start ();
_serviceHosts.Add (servicePath, serviceHost);
}
}
internal bool Remove (string servicePath)
{
servicePath = HttpUtility.UrlDecode (servicePath).TrimEndSlash ();
WebSocketServiceHost host;
lock (_sync)
{
if (!_serviceHosts.TryGetValue (servicePath, out host))
{
_logger.Error (
"A WebSocket service with the specified path not found.\npath: " + servicePath);
return false;
}
_serviceHosts.Remove (servicePath);
}
if (host.Sessions.State == ServerState.START)
host.Sessions.Stop (((ushort) CloseStatusCode.AWAY).ToByteArrayInternally (ByteOrder.BIG), true);
return true;
}
internal void Start ()
{
lock (_sync)
{
foreach (var host in _serviceHosts.Values)
host.Sessions.Start ();
_state = ServerState.START;
}
}
internal void Stop (byte [] data, bool send)
{
lock (_sync)
{
_state = ServerState.SHUTDOWN;
var payload = new PayloadData (data);
var args = new CloseEventArgs (payload);
var frameAsBytes = send
? WsFrame.CreateCloseFrame (Mask.UNMASK, payload).ToByteArray ()
: null;
foreach (var host in _serviceHosts.Values)
host.Sessions.Stop (args, frameAsBytes);
_serviceHosts.Clear ();
_state = ServerState.STOP;
}
}
internal bool TryGetServiceHostInternally (string servicePath, out WebSocketServiceHost serviceHost)
{
servicePath = HttpUtility.UrlDecode (servicePath).TrimEndSlash ();
bool result;
lock (_sync)
{
result = _serviceHosts.TryGetValue (servicePath, out serviceHost);
}
if (!result)
_logger.Error ("A WebSocket service with the specified path not found.\npath: " + servicePath);
return result;
}
#endregion
#region Public Methods
/// <summary>
/// Broadcasts a binary <paramref name="data"/> to all clients of the WebSocket services
/// provided by a WebSocket server.
/// </summary>
/// <remarks>
/// This method does not wait for the broadcast to be complete.
/// </remarks>
/// <param name="data">
/// An array of <see cref="byte"/> that contains a binary data to broadcast.
/// </param>
public void Broadcast (byte [] data)
{
Broadcast (data, null);
}
/// <summary>
/// Broadcasts a text <paramref name="data"/> to all clients of the WebSocket services
/// provided by a WebSocket server.
/// </summary>
/// <remarks>
/// This method does not wait for the broadcast to be complete.
/// </remarks>
/// <param name="data">
/// A <see cref="string"/> that contains a text data to broadcast.
/// </param>
public void Broadcast (string data)
{
Broadcast (data, null);
}
/// <summary>
/// Broadcasts a binary <paramref name="data"/> to all clients of the WebSocket services
/// provided by a WebSocket server.
/// </summary>
/// <remarks>
/// This method does not wait for the broadcast to be complete.
/// </remarks>
/// <param name="data">
/// An array of <see cref="byte"/> that contains a binary data to broadcast.
/// </param>
/// <param name="completed">
/// A <see cref="Action"/> delegate that references the method(s) called when
/// the broadcast is complete.
/// </param>
public void Broadcast (byte [] data, Action completed)
{
var msg = _state.CheckIfStarted () ?? data.CheckIfValidSendData ();
if (msg != null)
{
_logger.Error (msg);
return;
}
if (data.LongLength <= WebSocket.FragmentLength)
broadcastAsync (Opcode.BINARY, data, completed);
else
broadcastAsync (Opcode.BINARY, new MemoryStream (data), completed);
}
/// <summary>
/// Broadcasts a text <paramref name="data"/> to all clients of the WebSocket services
/// provided by a WebSocket server.
/// </summary>
/// <remarks>
/// This method does not wait for the broadcast to be complete.
/// </remarks>
/// <param name="data">
/// A <see cref="string"/> that contains a text data to broadcast.
/// </param>
/// <param name="completed">
/// A <see cref="Action"/> delegate that references the method(s) called when
/// the broadcast is complete.
/// </param>
public void Broadcast (string data, Action completed)
{
var msg = _state.CheckIfStarted () ?? data.CheckIfValidSendData ();
if (msg != null)
{
_logger.Error (msg);
return;
}
var rawData = Encoding.UTF8.GetBytes (data);
if (rawData.LongLength <= WebSocket.FragmentLength)
broadcastAsync (Opcode.TEXT, rawData, completed);
else
broadcastAsync (Opcode.TEXT, new MemoryStream (rawData), completed);
}
/// <summary>
/// Broadcasts a binary data from the specified <see cref="Stream"/> to all clients
/// of the WebSocket services provided by a WebSocket server.
/// </summary>
/// <remarks>
/// This method does not wait for the broadcast to be complete.
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> object from which contains a binary data to broadcast.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that contains the number of bytes to broadcast.
/// </param>
public void Broadcast (Stream stream, int length)
{
Broadcast (stream, length, null);
}
/// <summary>
/// Broadcasts a binary data from the specified <see cref="Stream"/> to all clients
/// of the WebSocket services provided by a WebSocket server.
/// </summary>
/// <remarks>
/// This method does not wait for the broadcast to be complete.
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> object from which contains a binary data to broadcast.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that contains the number of bytes to broadcast.
/// </param>
/// <param name="completed">
/// A <see cref="Action"/> delegate that references the method(s) called when
/// the broadcast is complete.
/// </param>
public void Broadcast (Stream stream, int length, Action completed)
{
var msg = _state.CheckIfStarted () ??
stream.CheckIfCanRead () ??
(length < 1 ? "'length' must be greater than 0." : null);
if (msg != null)
{
_logger.Error (msg);
return;
}
stream.ReadBytesAsync (
length,
data =>
{
var len = data.Length;
if (len == 0)
{
_logger.Error ("A data cannot be read from 'stream'.");
return;
}
if (len < length)
_logger.Warn (String.Format (
"A data with 'length' cannot be read from 'stream'.\nexpected: {0} actual: {1}",
length,
len));
if (len <= WebSocket.FragmentLength)
broadcast (Opcode.BINARY, data, completed);
else
broadcast (Opcode.BINARY, new MemoryStream (data), completed);
},
ex =>
{
_logger.Fatal (ex.ToString ());
});
}
/// <summary>
/// Broadcasts a binary <paramref name="data"/> to all clients of a WebSocket service
/// with the specified <paramref name="servicePath"/>.
/// </summary>
/// <remarks>
/// This method does not wait for the broadcast to be complete.
/// </remarks>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="data">
/// An array of <see cref="byte"/> that contains a binary data to broadcast.
/// </param>
public void BroadcastTo (string servicePath, byte [] data)
{
BroadcastTo (servicePath, data, null);
}
/// <summary>
/// Broadcasts a text <paramref name="data"/> to all clients of a WebSocket service
/// with the specified <paramref name="servicePath"/>.
/// </summary>
/// <remarks>
/// This method does not wait for the broadcast to be complete.
/// </remarks>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="data">
/// A <see cref="string"/> that contains a text data to broadcast.
/// </param>
public void BroadcastTo (string servicePath, string data)
{
BroadcastTo (servicePath, data, null);
}
/// <summary>
/// Broadcasts a binary <paramref name="data"/> to all clients of a WebSocket service
/// with the specified <paramref name="servicePath"/>.
/// </summary>
/// <remarks>
/// This method does not wait for the broadcast to be complete.
/// </remarks>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="data">
/// An array of <see cref="byte"/> that contains a binary data to broadcast.
/// </param>
/// <param name="completed">
/// A <see cref="Action"/> delegate that references the method(s) called when
/// the broadcast is complete.
/// </param>
public void BroadcastTo (string servicePath, byte [] data, Action completed)
{
WebSocketServiceHost host;
if (TryGetServiceHost (servicePath, out host))
host.Sessions.Broadcast (data, completed);
}
/// <summary>
/// Broadcasts a text <paramref name="data"/> to all clients of a WebSocket service
/// with the specified <paramref name="servicePath"/>.
/// </summary>
/// <remarks>
/// This method does not wait for the broadcast to be complete.
/// </remarks>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="data">
/// A <see cref="string"/> that contains a text data to broadcast.
/// </param>
/// <param name="completed">
/// A <see cref="Action"/> delegate that references the method(s) called when
/// the broadcast is complete.
/// </param>
public void BroadcastTo (string servicePath, string data, Action completed)
{
WebSocketServiceHost host;
if (TryGetServiceHost (servicePath, out host))
host.Sessions.Broadcast (data, completed);
}
/// <summary>
/// Broadcasts a binary data from the specified <see cref="Stream"/> to all clients
/// of a WebSocket service with the specified <paramref name="servicePath"/>.
/// </summary>
/// <remarks>
/// This method does not wait for the broadcast to be complete.
/// </remarks>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="stream">
/// A <see cref="Stream"/> object from which contains a binary data to broadcast.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that contains the number of bytes to broadcast.
/// </param>
public void BroadcastTo (string servicePath, Stream stream, int length)
{
BroadcastTo (servicePath, stream, length, null);
}
/// <summary>
/// Broadcasts a binary data from the specified <see cref="Stream"/> to all clients
/// of a WebSocket service with the specified <paramref name="servicePath"/>.
/// </summary>
/// <remarks>
/// This method does not wait for the broadcast to be complete.
/// </remarks>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="stream">
/// A <see cref="Stream"/> object from which contains a binary data to broadcast.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that contains the number of bytes to broadcast.
/// </param>
/// <param name="completed">
/// A <see cref="Action"/> delegate that references the method(s) called when
/// the broadcast is complete.
/// </param>
public void BroadcastTo (
string servicePath, Stream stream, int length, Action completed)
{
WebSocketServiceHost host;
if (TryGetServiceHost (servicePath, out host))
host.Sessions.Broadcast (stream, length, completed);
}
/// <summary>
/// Sends Pings to all clients of the WebSocket services provided by a WebSocket server.
/// </summary>
/// <returns>
/// A Dictionary<string, Dictionary<string, bool>> that contains the collection of
/// service paths and pairs of session ID and value indicating whether each WebSocket service
/// received a Pong from each client in a time.
/// </returns>
public Dictionary<string, Dictionary<string, bool>> Broadping ()
{
var msg = _state.CheckIfStarted ();
if (msg != null)
{
_logger.Error (msg);
return null;
}
return broadping (WsFrame.EmptyUnmaskPingData, 1000);
}
/// <summary>
/// Sends Pings with the specified <paramref name="message"/> to all clients of the WebSocket
/// services provided by a WebSocket server.
/// </summary>
/// <returns>
/// A Dictionary<string, Dictionary<string, bool>> that contains the collection of
/// service paths and pairs of session ID and value indicating whether each WebSocket service
/// received a Pong from each client in a time.
/// If <paramref name="message"/> is invalid, returns <see langword="null"/>.
/// </returns>
/// <param name="message">
/// A <see cref="string"/> that contains a message to broadcast.
/// </param>
public Dictionary<string, Dictionary<string, bool>> Broadping (string message)
{
if (message == null || message.Length == 0)
return Broadping ();
byte [] data = null;
var msg = _state.CheckIfStarted () ??
(data = Encoding.UTF8.GetBytes (message)).CheckIfValidPingData ();
if (msg != null)
{
_logger.Error (msg);
return null;
}
return broadping (WsFrame.CreatePingFrame (Mask.UNMASK, data).ToByteArray (), 1000);
}
/// <summary>
/// Sends Pings to all clients of a WebSocket service with
/// the specified <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// A Dictionary<string, bool> that contains the collection of pairs of session ID and
/// value indicating whether the WebSocket service received a Pong from each client in a time.
/// If the WebSocket service not found, returns <see langword="null"/>.
/// </returns>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
public Dictionary<string, bool> BroadpingTo (string servicePath)
{
WebSocketServiceHost host;
return TryGetServiceHost (servicePath, out host)
? host.Sessions.Broadping ()
: null;
}
/// <summary>
/// Sends Pings with the specified <paramref name="message"/> to all clients
/// of a WebSocket service with the specified <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// A Dictionary<string, bool> that contains the collection of pairs of session ID and
/// value indicating whether the WebSocket service received a Pong from each client in a time.
/// If the WebSocket service not found, returns <see langword="null"/>.
/// </returns>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="message">
/// A <see cref="string"/> that contains a message to send.
/// </param>
public Dictionary<string, bool> BroadpingTo (string servicePath, string message)
{
WebSocketServiceHost host;
return TryGetServiceHost (servicePath, out host)
? host.Sessions.Broadping (message)
: null;
}
/// <summary>
/// Closes the session with the specified <paramref name="servicePath"/> and
/// <paramref name="id"/>.
/// </summary>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to a WebSocket service to find.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID to find.
/// </param>
public void CloseSession (string servicePath, string id)
{
WebSocketServiceHost host;
if (TryGetServiceHost (servicePath, out host))
host.Sessions.CloseSession (id);
}
/// <summary>
/// Closes the session with the specified <paramref name="servicePath"/>, <paramref name="id"/>,
/// <paramref name="code"/> and <paramref name="reason"/>.
/// </summary>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to a WebSocket service to find.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID to find.
/// </param>
/// <param name="code">
/// A <see cref="ushort"/> that contains a status code indicating the reason for closure.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that contains the reason for closure.
/// </param>
public void CloseSession (string servicePath, string id, ushort code, string reason)
{
WebSocketServiceHost host;
if (TryGetServiceHost (servicePath, out host))
host.Sessions.CloseSession (id, code, reason);
}
/// <summary>
/// Closes the session with the specified <paramref name="servicePath"/>, <paramref name="id"/>,
/// <paramref name="code"/> and <paramref name="reason"/>.
/// </summary>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to a WebSocket service to find.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID to find.
/// </param>
/// <param name="code">
/// One of the <see cref="CloseStatusCode"/> values that indicate the status codes for closure.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that contains the reason for closure.
/// </param>
public void CloseSession (string servicePath, string id, CloseStatusCode code, string reason)
{
WebSocketServiceHost host;
if (TryGetServiceHost (servicePath, out host))
host.Sessions.CloseSession (id, code, reason);
}
/// <summary>
/// Sends a Ping to the client associated with the specified <paramref name="servicePath"/>
/// and <paramref name="id"/>.
/// </summary>
/// <returns>
/// <c>true</c> if the WebSocket service with <paramref name="servicePath"/> receives
/// a Pong from the client in a time; otherwise, <c>false</c>.
/// </returns>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID that represents the destination
/// for the Ping.
/// </param>
public bool PingTo (string servicePath, string id)
{
WebSocketServiceHost host;
return TryGetServiceHost (servicePath, out host) && host.Sessions.PingTo (id);
}
/// <summary>
/// Sends a Ping with the specified <paramref name="message"/> to the client associated
/// with the specified <paramref name="servicePath"/> and <paramref name="id"/>.
/// </summary>
/// <returns>
/// <c>true</c> if the WebSocket service with <paramref name="servicePath"/> receives
/// a Pong from the client in a time; otherwise, <c>false</c>.
/// </returns>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID that represents the destination
/// for the Ping.
/// </param>
/// <param name="message">
/// A <see cref="string"/> that contains a message to send.
/// </param>
public bool PingTo (string servicePath, string id, string message)
{
WebSocketServiceHost host;
return TryGetServiceHost (servicePath, out host) && host.Sessions.PingTo (id, message);
}
/// <summary>
/// Sends a binary <paramref name="data"/> to the client associated with the specified
/// <paramref name="servicePath"/> and <paramref name="id"/>.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID that represents the destination
/// for the data.
/// </param>
/// <param name="data">
/// An array of <see cref="byte"/> that contains a binary data to send.
/// </param>
public void SendTo (string servicePath, string id, ArraySegment<byte> data)
{
SendTo (servicePath, id, data, null);
}
/// <summary>
/// Sends a text <paramref name="data"/> to the client associated with the specified
/// <paramref name="servicePath"/> and <paramref name="id"/>.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID that represents the destination
/// for the data.
/// </param>
/// <param name="data">
/// A <see cref="string"/> that contains a text data to send.
/// </param>
public void SendTo (string servicePath, string id, string data)
{
SendTo (servicePath, id, data, null);
}
/// <summary>
/// Sends a binary <paramref name="data"/> to the client associated with the specified
/// <paramref name="servicePath"/> and <paramref name="id"/>.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID that represents the destination
/// for the data.
/// </param>
/// <param name="data">
/// An array of <see cref="byte"/> that contains a binary data to send.
/// </param>
/// <param name="completed">
/// An Action<bool> delegate that references the method(s) called when
/// the send is complete.
/// A <see cref="bool"/> passed to this delegate is <c>true</c> if the send is complete
/// successfully; otherwise, <c>false</c>.
/// </param>
public void SendTo (string servicePath, string id, ArraySegment<byte> data, Action<bool> completed)
{
WebSocketServiceHost host;
if (TryGetServiceHost (servicePath, out host))
host.Sessions.SendTo (id, data, completed);
}
/// <summary>
/// Sends a text <paramref name="data"/> to the client associated with the specified
/// <paramref name="servicePath"/> and <paramref name="id"/>.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID that represents the destination
/// for the data.
/// </param>
/// <param name="data">
/// A <see cref="string"/> that contains a text data to send.
/// </param>
/// <param name="completed">
/// An Action<bool> delegate that references the method(s) called when
/// the send is complete.
/// A <see cref="bool"/> passed to this delegate is <c>true</c> if the send is complete
/// successfully; otherwise, <c>false</c>.
/// </param>
public void SendTo (string servicePath, string id, string data, Action<bool> completed)
{
WebSocketServiceHost host;
if (TryGetServiceHost (servicePath, out host))
host.Sessions.SendTo (id, data, completed);
}
/// <summary>
/// Sends a binary data from the specified <see cref="Stream"/> to the client associated with
/// the specified <paramref name="servicePath"/> and <paramref name="id"/>.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID that represents the destination
/// for the data.
/// </param>
/// <param name="stream">
/// A <see cref="Stream"/> object from which contains a binary data to send.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that contains the number of bytes to send.
/// </param>
public void SendTo (string servicePath, string id, Stream stream, int length)
{
SendTo (servicePath, id, stream, length, null);
}
/// <summary>
/// Sends a binary data from the specified <see cref="Stream"/> to the client associated with
/// the specified <paramref name="servicePath"/> and <paramref name="id"/>.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that contains a session ID that represents the destination
/// for the data.
/// </param>
/// <param name="stream">
/// A <see cref="Stream"/> object from which contains a binary data to send.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that contains the number of bytes to send.
/// </param>
/// <param name="completed">
/// An Action<bool> delegate that references the method(s) called when
/// the send is complete.
/// A <see cref="bool"/> passed to this delegate is <c>true</c> if the send is complete
/// successfully; otherwise, <c>false</c>.
/// </param>
public void SendTo (
string servicePath, string id, Stream stream, int length, Action<bool> completed)
{
WebSocketServiceHost host;
if (TryGetServiceHost (servicePath, out host))
host.Sessions.SendTo (id, stream, length, completed);
}
/// <summary>
/// Tries to get a WebSocket service host with the specified <paramref name="servicePath"/>.
/// </summary>
/// <returns>
/// <c>true</c> if the service is successfully found; otherwise, <c>false</c>.
/// </returns>
/// <param name="servicePath">
/// A <see cref="string"/> that contains an absolute path to the service to find.
/// </param>
/// <param name="serviceHost">
/// When this method returns, a <see cref="WebSocketServiceHost"/> instance that represents
/// the service host if the service is successfully found; otherwise, <see langword="null"/>.
/// This parameter is passed uninitialized.
/// </param>
public bool TryGetServiceHost (string servicePath, out WebSocketServiceHost serviceHost)
{
var msg = _state.CheckIfStarted () ?? servicePath.CheckIfValidServicePath ();
if (msg != null)
{
_logger.Error (msg);
serviceHost = null;
return false;
}
return TryGetServiceHostInternally (servicePath, out serviceHost);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using IxMilia.BCad.Collections;
using IxMilia.BCad.Entities;
using IxMilia.BCad.Helpers;
using IxMilia.BCad.Primitives;
namespace IxMilia.BCad.Extensions
{
public static partial class PrimitiveExtensions
{
private static double[] SIN;
private static double[] COS;
public const double DefaultViewportBuffer = 20.0;
static PrimitiveExtensions()
{
SIN = new double[360];
COS = new double[360];
double rad;
for (int i = 0; i < 360; i++)
{
rad = (double)i * MathHelper.DegreesToRadians;
SIN[i] = Math.Sin(rad);
COS[i] = Math.Cos(rad);
}
}
public static double GetThickness(this IPrimitive primitive)
{
switch (primitive.Kind)
{
case PrimitiveKind.Ellipse:
return ((PrimitiveEllipse)primitive).Thickness;
case PrimitiveKind.Line:
return ((PrimitiveLine)primitive).Thickness;
case PrimitiveKind.Point:
case PrimitiveKind.Text:
return 0.0;
default:
throw new InvalidOperationException("Unsupported primitive.");
}
}
public static Point ClosestPoint(this PrimitiveLine line, Point point, bool withinBounds = true)
{
var v = line.P1;
var w = line.P2;
var p = point;
var wv = w - v;
var l2 = wv.LengthSquared;
if (Math.Abs(l2) < MathHelper.Epsilon)
return v;
var t = (p - v).Dot(wv) / l2;
if (withinBounds)
{
t = Math.Max(t, 0.0 - MathHelper.Epsilon);
t = Math.Min(t, 1.0 + MathHelper.Epsilon);
}
var result = v + (wv) * t;
return result;
}
public static double Slope(this PrimitiveLine line)
{
var denom = line.P2.X - line.P1.X;
return denom == 0.0 ? double.NaN : (line.P2.Y - line.P1.Y) / denom;
}
public static double PerpendicularSlope(this PrimitiveLine line)
{
var slope = line.Slope();
if (double.IsNaN(slope))
return 0.0;
else if (slope == 0.0)
return double.NaN;
else
return -1.0 / slope;
}
public static bool IsAngleContained(this PrimitiveEllipse ellipse, double angle)
{
angle = angle.CorrectAngleDegrees();
var startAngle = ellipse.StartAngle;
var endAngle = ellipse.EndAngle;
if (endAngle < startAngle)
{
// we pass zero. angle should either be [startAngle, 360.0] or [0.0, endAngle]
return MathHelper.Between(startAngle, 360.0, angle)
|| MathHelper.Between(0.0, endAngle, angle);
}
else
{
// we're within normal bounds
return MathHelper.Between(startAngle, endAngle, angle)
|| MathHelper.Between(startAngle, endAngle, angle + 360.0);
}
}
public static PrimitiveLine Transform(this PrimitiveLine line, Matrix4 matrix)
{
return new PrimitiveLine(matrix.Transform(line.P1), matrix.Transform(line.P2), line.Color);
}
public static IEnumerable<Point> IntersectionPoints(this IPrimitive primitive, IPrimitive other, bool withinBounds = true)
{
IEnumerable<Point> result;
switch (primitive.Kind)
{
case PrimitiveKind.Line:
result = ((PrimitiveLine)primitive).IntersectionPoints(other, withinBounds);
break;
case PrimitiveKind.Ellipse:
result = ((PrimitiveEllipse)primitive).IntersectionPoints(other, withinBounds);
break;
case PrimitiveKind.Point:
result = ((PrimitivePoint)primitive).IntersectionPoints(other, withinBounds);
break;
case PrimitiveKind.Text:
result = Enumerable.Empty<Point>();
break;
default:
Debug.Assert(false, "Unsupported primitive type");
result = Enumerable.Empty<Point>();
break;
}
return result;
}
#region Point-primitive intersection
public static IEnumerable<Point> IntersectionPoints(this PrimitivePoint point, IPrimitive other, bool withinBounds = true)
{
IEnumerable<Point> result;
switch (other.Kind)
{
case PrimitiveKind.Ellipse:
result = ((PrimitiveEllipse)other).IntersectionPoints(point, withinBounds);
break;
case PrimitiveKind.Line:
result = ((PrimitiveLine)other).IntersectionPoints(point, withinBounds);
break;
case PrimitiveKind.Point:
result = point.IntersectionPoints((PrimitivePoint)other);
break;
case PrimitiveKind.Text:
result = Enumerable.Empty<Point>();
break;
default:
Debug.Assert(false, "Unsupported primitive type");
result = Enumerable.Empty<Point>();
break;
}
return result;
}
public static IEnumerable<Point> IntersectionPoints(this PrimitivePoint first, PrimitivePoint second)
{
if (first.Location.CloseTo(second.Location))
return new Point[] { first.Location };
else
return Enumerable.Empty<Point>();
}
#endregion
#region Line-primitive intersection
public static IEnumerable<Point> IntersectionPoints(this PrimitiveLine line, IPrimitive other, bool withinBounds = true)
{
IEnumerable<Point> result;
switch (other.Kind)
{
case PrimitiveKind.Line:
var p = line.IntersectionPoint((PrimitiveLine)other, withinBounds);
if (p.HasValue)
result = new[] { p.Value };
else
result = new Point[0];
break;
case PrimitiveKind.Ellipse:
result = line.IntersectionPoints((PrimitiveEllipse)other, withinBounds);
break;
case PrimitiveKind.Point:
var point = (PrimitivePoint)other;
if (line.IsPointOnPrimitive(point.Location, withinBounds))
{
result = new Point[] { point.Location };
}
else
{
result = new Point[0];
}
break;
case PrimitiveKind.Text:
result = Enumerable.Empty<Point>();
break;
default:
Debug.Assert(false, "Unsupported primitive type");
result = Enumerable.Empty<Point>();
break;
}
return result;
}
#endregion
#region Line-line intersection
public static Point? IntersectionPoint(this PrimitiveLine first, PrimitiveLine second, bool withinSegment = true)
{
// TODO: need to handle a line's endpoint lying directly on the other line
// TODO: also need to handle colinear lines
var minLength = 0.0000000001;
//http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline3d/
// find real 3D intersection within a minimum distance
var p1 = first.P1;
var p2 = first.P2;
var p3 = second.P1;
var p4 = second.P2;
var p13 = p1 - p3;
var p43 = p4 - p3;
if (p43.LengthSquared < MathHelper.Epsilon)
return null;
var p21 = p2 - p1;
if (p21.LengthSquared < MathHelper.Epsilon)
return null;
var d1343 = p13.Dot(p43);
var d4321 = p43.Dot(p21);
var d1321 = p13.Dot(p21);
var d4343 = p43.Dot(p43);
var d2121 = p21.Dot(p21);
var denom = d2121 * d4343 - d4321 * d4321;
if (Math.Abs(denom) < MathHelper.Epsilon)
return null;
var num = d1343 * d4321 - d1321 * d4343;
var mua = num / denom;
var mub = (d1343 + d4321 * mua) / d4343;
if (withinSegment)
{
if (!MathHelper.Between(0.0, 1.0, mua) ||
!MathHelper.Between(0.0, 1.0, mub))
{
return null;
}
}
var connector = new PrimitiveLine((p21 * mua) + p1, (p43 * mub) + p3);
var cv = connector.P1 - connector.P2;
if (cv.LengthSquared > minLength)
return null;
var point = (Point)((connector.P1 + connector.P2) / 2);
return point;
}
#endregion
#region Line-circle intersection
public static IEnumerable<Point> IntersectionPoints(this PrimitiveLine line, PrimitiveEllipse ellipse, bool withinSegment = true)
{
var empty = Enumerable.Empty<Point>();
var l0 = line.P1;
var l = line.P2 - line.P1;
var p0 = ellipse.Center;
var n = ellipse.Normal;
var right = ellipse.MajorAxis.Normalize();
var up = ellipse.Normal.Cross(right).Normalize();
var radiusX = ellipse.MajorAxis.Length;
var radiusY = radiusX * ellipse.MinorAxisRatio;
var transform = ellipse.FromUnitCircle;
var inverse = transform.Inverse();
var denom = l.Dot(n);
var num = (p0 - l0).Dot(n);
var flatPoints = new List<Point>();
if (Math.Abs(denom) < MathHelper.Epsilon)
{
// plane either contains the line entirely or is parallel
if (Math.Abs(num) < MathHelper.Epsilon)
{
// parallel. normalize the plane and find the intersection
var flatLine = line.Transform(inverse);
// the ellipse is now centered at the origin with a radius of 1.
// find the intersection points then reproject
var dv = flatLine.P2 - flatLine.P1;
var dx = dv.X;
var dy = dv.Y;
var dr2 = dx * dx + dy * dy;
var D = flatLine.P1.X * flatLine.P2.Y - flatLine.P2.X * flatLine.P1.Y;
var det = dr2 - D * D;
var points = new List<Point>();
if (det < 0.0 || Math.Abs(dr2) < MathHelper.Epsilon)
{
// no intersection or line is too short
}
else if (Math.Abs(det) < MathHelper.Epsilon)
{
// 1 point
var x = (D * dy) / dr2;
var y = (-D * dx) / dr2;
points.Add(new Point(x, y, 0.0));
}
else
{
// 2 points
var sgn = dy < 0.0 ? -1.0 : 1.0;
var det2 = Math.Sqrt(det);
points.Add(
new Point(
(D * dy + sgn * dx * det2) / dr2,
(-D * dx + Math.Abs(dy) * det2) / dr2,
0.0));
points.Add(
new Point(
(D * dy - sgn * dx * det2) / dr2,
(-D * dx - Math.Abs(dy) * det2) / dr2,
0.0));
}
// ensure the points are within appropriate bounds
if (withinSegment)
{
// line test
points = points.Where(p =>
MathHelper.Between(flatLine.P1.X, flatLine.P2.X, p.X) &&
MathHelper.Between(flatLine.P1.Y, flatLine.P2.Y, p.Y)).ToList();
// circle test
points = points.Where(p => ellipse.IsAngleContained(((Vector)p).ToAngle())).ToList();
}
return points.Select(p => (Point)transform.Transform(p));
}
}
else
{
// otherwise line and plane intersect in only 1 point, p
var d = num / denom;
var p = (Point)(l * d + l0);
// verify within the line segment
if (withinSegment && !MathHelper.Between(0.0, 1.0, d))
{
return empty;
}
// p is the point of intersection. verify if on transformed unit circle
var unitVector = (Vector)inverse.Transform(p);
if (Math.Abs(unitVector.Length - 1.0) < MathHelper.Epsilon)
{
// point is on the unit circle
if (withinSegment)
{
// verify within the angles specified
var angle = Math.Atan2(unitVector.Y, unitVector.X) * MathHelper.RadiansToDegrees;
if (MathHelper.Between(ellipse.StartAngle, ellipse.EndAngle, angle.CorrectAngleDegrees()))
{
return new[] { p };
}
}
else
{
return new[] { p };
}
}
}
// point is not on unit circle
return empty;
}
#endregion
#region Circle-primitive intersection
public static IEnumerable<Point> IntersectionPoints(this PrimitiveEllipse ellipse, IPrimitive primitive, bool withinBounds = true)
{
IEnumerable<Point> result;
switch (primitive.Kind)
{
case PrimitiveKind.Ellipse:
result = ellipse.IntersectionPoints((PrimitiveEllipse)primitive, withinBounds);
break;
case PrimitiveKind.Line:
result = ((PrimitiveLine)primitive).IntersectionPoints(ellipse, withinBounds);
break;
case PrimitiveKind.Point:
result = ellipse.IntersectionPoints((PrimitivePoint)primitive, withinBounds);
break;
case PrimitiveKind.Text:
result = Enumerable.Empty<Point>();
break;
default:
Debug.Assert(false, "Unsupported primitive type");
result = Enumerable.Empty<Point>();
break;
}
return result;
}
#endregion
#region Circle-point intersection
public static IEnumerable<Point> IntersectionPoints(this PrimitiveEllipse ellipse, PrimitivePoint point, bool withinBounds = true)
{
var fromUnit = ellipse.FromUnitCircle;
var toUnit = fromUnit.Inverse();
var pointOnUnit = (Vector)toUnit.Transform(point.Location);
if (MathHelper.CloseTo(pointOnUnit.LengthSquared, 1.0))
{
if (!withinBounds)
return new Point[] { point.Location }; // always a match
else
{
var pointAngle = pointOnUnit.ToAngle();
if (ellipse.IsAngleContained(pointAngle))
return new Point[] { point.Location };
else
return new Point[0];
}
}
else
{
// wrong distance
return new Point[0];
}
}
#endregion
#region Circle-circle intersection
public static IEnumerable<Point> IntersectionPoints(this PrimitiveEllipse first, PrimitiveEllipse second, bool withinBounds = true)
{
var empty = Enumerable.Empty<Point>();
IEnumerable<Point> results;
// planes either intersect in a line or are parallel
var lineVector = first.Normal.Cross(second.Normal);
if (lineVector.IsZeroVector)
{
// parallel or the same plane
if ((first.Center == second.Center) ||
Math.Abs((second.Center - first.Center).Dot(first.Normal)) < MathHelper.Epsilon)
{
// if they share a point or second.Center is on the first plane, they are the same plane
// project second back to a unit circle and find intersection points
var fromUnit = first.FromUnitCircle;
var toUnit = fromUnit.Inverse();
// transform second ellipse to be on the unit circle's plane
var secondCenter = toUnit.Transform(second.Center);
var secondMajorEnd = toUnit.Transform(second.Center + second.MajorAxis);
var secondMinorEnd = toUnit.Transform(second.Center + (second.Normal.Cross(second.MajorAxis).Normalize() * second.MajorAxis.Length * second.MinorAxisRatio));
RoundedDouble a = (secondMajorEnd - secondCenter).Length;
RoundedDouble b = (secondMinorEnd - secondCenter).Length;
if (a == b)
{
// if second ellipse is a circle we can absolutely solve for the intersection points
// rotate to place the center of the second circle on the x-axis
var angle = ((Vector)secondCenter).ToAngle();
var rotation = Matrix4.RotateAboutZ(angle);
var returnTransform = fromUnit * Matrix4.RotateAboutZ(-angle);
var newSecondCenter = rotation.Transform(secondCenter);
var secondRadius = a;
if (Math.Abs(newSecondCenter.X) > secondRadius + 1.0)
{
// no points of intersection
results = empty;
}
else
{
// 2 points of intersection
var x = (secondRadius * secondRadius - newSecondCenter.X * newSecondCenter.X - 1.0)
/ (-2.0 * newSecondCenter.X);
var y = Math.Sqrt(1.0 - x * x);
results = new[]
{
new Point(x, y, 0),
new Point(x, -y, 0)
};
}
results = results.Distinct().Select(p => returnTransform.Transform(p));
}
else
{
// rotate about the origin to make the major axis align with the x-axis
var angle = (secondMajorEnd - secondCenter).ToAngle();
var rotation = Matrix4.RotateAboutZ(angle);
var finalCenter = rotation.Transform(secondCenter);
fromUnit = fromUnit * Matrix4.RotateAboutZ(-angle);
toUnit = fromUnit.Inverse();
if (a < b)
{
// rotate to ensure a > b
fromUnit = fromUnit * Matrix4.RotateAboutZ(90);
toUnit = fromUnit.Inverse();
finalCenter = Matrix4.RotateAboutZ(-90).Transform(finalCenter);
// and swap a and b
var temp = a;
a = b;
b = temp;
}
RoundedDouble h = finalCenter.X;
RoundedDouble k = finalCenter.Y;
var h2 = h * h;
var k2 = k * k;
var a2 = a * a;
var b2 = b * b;
var a4 = a2 * a2;
var b4 = b2 * b2;
// RoundedDouble is used to ensure all operations are rounded to a certain precision
if (Math.Abs(h) < MathHelper.Epsilon)
{
// ellipse x = 0; wide
// find x values
var A = a2 - a2 * b2 + a2 * k2 - ((2 * a4 * k2) / (a2 - b2));
var B = (2 * a2 * k * Math.Sqrt(b2 * (-a2 + a4 + b2 - a2 * b2 + a2 * k2))) / (a2 - b2);
var C = (RoundedDouble)Math.Sqrt(a2 - b2);
var x1 = -Math.Sqrt(A + B) / C;
var x2 = (RoundedDouble)(-x1);
var x3 = -Math.Sqrt(A - B) / C;
var x4 = (RoundedDouble)(-x3);
// find y values
var D = a2 * k;
var E = Math.Sqrt(-a2 * b2 + a4 * b2 + b4 - a2 * b4 + a2 * b2 * k2);
var F = a2 - b2;
var y1 = (D - E) / F;
var y2 = (D + E) / F;
results = new[] {
new Point(x1, y1, 0),
new Point(x2, y1, 0),
new Point(x3, y2, 0),
new Point(x4, y2, 0)
};
}
else if (Math.Abs(k) < MathHelper.Epsilon)
{
// ellipse y = 0; wide
// find x values
var A = -b2 * h;
var B = Math.Sqrt(a4 - a2 * b2 - a4 * b2 + a2 * b4 + a2 * b2 * h2);
var C = a2 - b2;
var x1 = (A - B) / C;
var x2 = (A + B) / C;
// find y values
var D = -b2 + a2 * b2 - b2 * h2 - ((2 * b4 * h2) / (a2 - b2));
var E = (2 * b2 * h * Math.Sqrt(a2 * (a2 - b2 - a2 * b2 + b4 + b2 * h2))) / (a2 - b2);
var F = (RoundedDouble)Math.Sqrt(a2 - b2);
var y1 = -Math.Sqrt(D - E) / F;
var y2 = (RoundedDouble)(-y1);
var y3 = -Math.Sqrt(D + E) / F;
var y4 = (RoundedDouble)(-y3);
results = new[] {
new Point(x1, y1, 0),
new Point(x1, y2, 0),
new Point(x2, y3, 0),
new Point(x2, y4, 0)
};
}
else
{
// brute-force approximate intersections
results = BruteForceEllipseWithUnitCircle(finalCenter, a, b);
}
results = results
.Where(p => !(double.IsNaN(p.X) || double.IsNaN(p.Y) || double.IsNaN(p.Z)))
.Where(p => !(double.IsInfinity(p.X) || double.IsInfinity(p.Y) || double.IsInfinity(p.Z)))
.Distinct()
.Select(p => fromUnit.Transform(p))
.Select(p => new Point((RoundedDouble)p.X, (RoundedDouble)p.Y, (RoundedDouble)p.Z));
}
}
else
{
// parallel with no intersections
results = empty;
}
}
else
{
// intersection was a line
// find a common point to complete the line then intersect that line with the circles
double x = 0, y = 0, z = 0;
var n = first.Normal;
var m = second.Normal;
var q = first.Center;
var r = second.Center;
if (Math.Abs(lineVector.X) >= MathHelper.Epsilon)
{
x = 0.0;
y = (-m.Z * n.X * q.X - m.Z * n.Y * q.Y - m.Z * n.Z * q.Z + m.X * n.Z * r.X + m.Y * n.Z * r.Y + m.Z * n.Z * r.Z)
/ (-m.Z * n.Y + m.Y * n.Z);
z = (-m.Y * n.X * q.X - m.Y * n.Y * q.Y - m.Y * n.Z * q.Z + m.X * n.Y * r.X + m.Y * n.Y * r.Y + m.Z * n.Y * r.Z)
/ (-m.Z * n.Y + m.Y * n.Z);
}
else if (Math.Abs(lineVector.Y) >= MathHelper.Epsilon)
{
x = (-m.Z * n.X * q.X - m.Z * n.Y * q.Y - m.Z * n.Z * q.Z + m.X * n.Z * r.X + m.Y * n.Z * r.Y + m.Z * n.Z * r.Z)
/ (-m.Z * n.X + m.X * n.Z);
y = 0.0;
z = (-m.X * n.X * q.X - m.X * n.Y * q.Y - m.X * n.Z * q.Z + m.X * n.X * r.X + m.Y * n.X * r.Y + m.Z * n.X * r.Z)
/ (-m.Z * n.X + m.X * n.Z);
}
else if (Math.Abs(lineVector.Z) >= MathHelper.Epsilon)
{
x = (-m.Y * n.X * q.X - m.Y * n.Y * q.Y - m.Y * n.Z * q.Z + m.X * n.Y * r.X + m.Y * n.Y * r.Y + m.Z * n.Y * r.Z)
/ (m.Y * n.X - m.X * n.Y);
y = (-m.X * n.X * q.X - m.X * n.Y * q.Y - m.X * n.Z * q.Z + m.X * n.X * r.X + m.Y * n.X * r.Y + m.Z * n.X * r.Z)
/ (m.Y * n.X - m.X * n.Y);
z = 0.0;
}
else
{
Debug.Assert(false, "zero-vector shouldn't get here");
}
var point = new Point(x, y, z);
var other = point + lineVector;
var intersectionLine = new PrimitiveLine(point, other);
var firstIntersections = intersectionLine.IntersectionPoints(first, false)
.Select(p => new Point((RoundedDouble)p.X, (RoundedDouble)p.Y, (RoundedDouble)p.Z));
var secondIntersections = intersectionLine.IntersectionPoints(second, false)
.Select(p => new Point((RoundedDouble)p.X, (RoundedDouble)p.Y, (RoundedDouble)p.Z));
results = firstIntersections
.Union(secondIntersections)
.Distinct();
}
// verify points are in angle bounds
if (withinBounds)
{
var toFirstUnit = first.FromUnitCircle.Inverse();
var toSecondUnit = second.FromUnitCircle.Inverse();
results = from res in results
// verify point is within first ellipse's angles
let trans1 = toFirstUnit.Transform(res)
let ang1 = ((Vector)trans1).ToAngle()
where first.IsAngleContained(ang1)
// and same for second
let trans2 = toSecondUnit.Transform(res)
let ang2 = ((Vector)trans2).ToAngle()
where second.IsAngleContained(ang2)
select res;
}
return results;
}
private static IEnumerable<Point> BruteForceEllipseWithUnitCircle(Point center, double a, double b)
{
var results = new List<Point>();
Func<int, Point> ellipsePoint = (an) =>
new Point(COS[an] * a + center.X, SIN[an] * b + center.Y, 0);
Func<Point, bool> isInside = (p) => ((p.X * p.X) + (p.Y * p.Y)) <= 1;
var current = ellipsePoint(0);
var inside = isInside(current);
for (int angle = 1; angle < 360; angle++)
{
var nextPoint = ellipsePoint(angle);
var next = isInside(nextPoint);
if (next != inside)
{
results.Add(nextPoint);
}
inside = next;
current = nextPoint;
}
return results;
}
#endregion
public static Entity ToEntity(this IPrimitive primitive)
{
switch (primitive.Kind)
{
case PrimitiveKind.Ellipse:
var el = (PrimitiveEllipse)primitive;
if (el.MinorAxisRatio == 1.0)
{
// circle or arc
if (el.IsClosed)
{
// circle
return new Circle(el);
}
else
{
// arc
return new Arc(el);
}
}
else
{
return new Ellipse(el);
}
case PrimitiveKind.Line:
return new Line((PrimitiveLine)primitive);
case PrimitiveKind.Point:
return new Location((PrimitivePoint)primitive);
case PrimitiveKind.Text:
return new Text((PrimitiveText)primitive);
default:
throw new ArgumentException("primitive.Kind");
}
}
public static IPrimitive Move(this IPrimitive primitive, Vector offset)
{
switch (primitive.Kind)
{
case PrimitiveKind.Ellipse:
var el = (PrimitiveEllipse)primitive;
return new PrimitiveEllipse(
el.Center + offset,
el.MajorAxis,
el.Normal,
el.MinorAxisRatio,
el.StartAngle,
el.EndAngle,
el.Color);
case PrimitiveKind.Line:
var line = (PrimitiveLine)primitive;
return new PrimitiveLine(
line.P1 + offset,
line.P2 + offset,
line.Color);
case PrimitiveKind.Point:
var point = (PrimitivePoint)primitive;
return new PrimitivePoint(
point.Location + offset,
point.Color);
case PrimitiveKind.Text:
var text = (PrimitiveText)primitive;
return new PrimitiveText(
text.Value,
text.Location + offset,
text.Height,
text.Normal,
text.Rotation,
text.Color);
default:
throw new ArgumentException("primitive.Kind");
}
}
public static bool IsPointOnPrimitive(this IPrimitive primitive, Point point)
{
switch (primitive.Kind)
{
case PrimitiveKind.Line:
return IsPointOnPrimitive((PrimitiveLine)primitive, point);
case PrimitiveKind.Ellipse:
return IsPointOnPrimitive((PrimitiveEllipse)primitive, point);
case PrimitiveKind.Text:
return IsPointOnPrimitive((PrimitiveText)primitive, point);
default:
Debug.Assert(false, "unexpected primitive: " + primitive.Kind);
return false;
}
}
private static bool IsPointOnPrimitive(this PrimitiveLine line, Point point, bool withinSegment = true)
{
if (point == line.P1)
return true;
var lineVector = line.P2 - line.P1;
var pointVector = point - line.P1;
return (lineVector.Normalize().CloseTo(pointVector.Normalize()))
&& (!withinSegment
|| MathHelper.Between(0.0, lineVector.LengthSquared, pointVector.LengthSquared));
}
private static bool IsPointOnPrimitive(this PrimitiveEllipse el, Point point)
{
var unitPoint = el.FromUnitCircle.Inverse().Transform(point);
return MathHelper.CloseTo(0.0, unitPoint.Z) // on the XY plane
&& MathHelper.CloseTo(1.0, ((Vector)unitPoint).LengthSquared) // on the unit circle
&& el.IsAngleContained(Math.Atan2(unitPoint.Y, unitPoint.X) * MathHelper.RadiansToDegrees); // within angle bounds
}
private static bool IsPointOnPrimitive(this PrimitiveText text, Point point)
{
// check for plane containment
var plane = new Plane(text.Location, text.Normal);
if (plane.Contains(point))
{
// check for horizontal/vertical containment
var right = Vector.RightVectorFromNormal(text.Normal);
var up = text.Normal.Cross(right).Normalize();
var projection = Matrix4.FromUnitCircleProjection(text.Normal, right, up, text.Location, 1.0, 1.0, 1.0).Inverse();
var projected = projection.Transform(point);
if (MathHelper.Between(0.0, text.Width, projected.X) &&
MathHelper.Between(0.0, text.Height, projected.Y))
{
return true;
}
}
return false;
}
public static double GetAngle(this PrimitiveEllipse ellipse, Point point)
{
var transform = ellipse.FromUnitCircle.Inverse();
var pointFromUnitCircle = transform.Transform(point);
var angle = Math.Atan2(pointFromUnitCircle.Y, pointFromUnitCircle.X) * MathHelper.RadiansToDegrees;
return angle.CorrectAngleDegrees();
}
public static Point GetPoint(this PrimitiveEllipse ellipse, double angle)
{
var pointUnit = new Point(Math.Cos(angle * MathHelper.DegreesToRadians), Math.Sin(angle * MathHelper.DegreesToRadians), 0.0);
var pointTransformed = ellipse.FromUnitCircle.Transform(pointUnit);
return pointTransformed;
}
public static Point[] GetInterestingPoints(this IPrimitive primitive)
{
Point[] points;
switch (primitive.Kind)
{
case PrimitiveKind.Ellipse:
var ellipse = (PrimitiveEllipse)primitive;
points = ellipse.GetInterestingPoints(360);
break;
case PrimitiveKind.Line:
var line = (PrimitiveLine)primitive;
points = new[] { line.P1, line.P2 };
break;
case PrimitiveKind.Point:
points = new[] { ((PrimitivePoint)primitive).Location };
break;
case PrimitiveKind.Text:
var text = (PrimitiveText)primitive;
var rad = text.Rotation * MathHelper.DegreesToRadians;
var right = new Vector(Math.Cos(rad), Math.Sin(rad), 0.0).Normalize() * text.Width;
var up = text.Normal.Cross(right).Normalize() * text.Height;
points = new[]
{
text.Location,
text.Location + right,
text.Location + right + up,
text.Location + up,
text.Location
};
break;
default:
throw new InvalidOperationException();
}
return points;
}
public static Point[] GetInterestingPoints(this PrimitiveEllipse ellipse, int maxSeg)
{
var startAngleDeg = ellipse.StartAngle;
var endAngleDeg = ellipse.EndAngle;
if (endAngleDeg < startAngleDeg)
endAngleDeg += MathHelper.ThreeSixty;
var startAngleRad = startAngleDeg * MathHelper.DegreesToRadians;
var endAngleRad = endAngleDeg * MathHelper.DegreesToRadians;
if (endAngleRad < startAngleRad)
endAngleRad += MathHelper.TwoPI;
var vertexCount = (int)Math.Ceiling((endAngleDeg - startAngleDeg) / MathHelper.ThreeSixty * maxSeg);
var points = new Point[vertexCount + 1];
var angleDelta = MathHelper.ThreeSixty / maxSeg * MathHelper.DegreesToRadians;
var trans = ellipse.FromUnitCircle;
double angle;
int i;
for (angle = startAngleRad, i = 0; i < vertexCount; angle += angleDelta, i++)
{
points[i] = trans.Transform(new Point(Math.Cos(angle), Math.Sin(angle), 0.0));
}
points[i] = trans.Transform(new Point(Math.Cos(angle), Math.Sin(angle), 0.0));
return points;
}
public static Rect GetExtents(this IEnumerable<IPrimitive> primitives, Vector sight)
{
var drawingPlane = new Plane(Point.Origin, sight);
var planeProjection = drawingPlane.ToXYPlaneProjection();
var allPoints = primitives
.SelectMany(p => p.GetInterestingPoints())
.Select(p => planeProjection.Transform(p));
if (allPoints.Count() < 2)
{
// TODO: better handling for 0 or 1 primitives
return new Rect(0, 0, 1, 1);
}
var first = allPoints.First();
var minx = first.X;
var miny = first.Y;
var maxx = first.X;
var maxy = first.Y;
foreach (var point in allPoints.Skip(1))
{
if (point.X < minx)
minx = point.X;
if (point.X > maxx)
maxx = point.X;
if (point.Y < miny)
miny = point.Y;
if (point.Y > maxy)
maxy = point.Y;
}
return new Rect(minx, miny, maxx, maxy);
}
public static ViewPort ShowAllViewPort(this IEnumerable<IPrimitive> primitives, Vector sight, Vector up, double viewPortWidth, double viewPortHeight, double viewportBuffer = DefaultViewportBuffer)
{
return primitives.GetExtents(sight).ShowAllViewPort(sight, up, viewPortWidth, viewPortHeight, viewportBuffer);
}
public static ViewPort ShowAllViewPort(this Rect extents, Vector sight, Vector up, double viewPortWidth, double viewPortHeight, double viewportBuffer = DefaultViewportBuffer)
{
var minx = extents.Left;
var miny = extents.Top;
var maxx = extents.BottomRight.X;
var maxy = extents.BottomRight.Y;
var deltaX = maxx - minx;
var deltaY = maxy - miny;
// translate back out of XY plane
var drawingPlane = new Plane(Point.Origin, sight);
var planeProjection = drawingPlane.ToXYPlaneProjection();
var unproj = planeProjection.Inverse();
var bottomLeft = unproj.Transform(new Point(minx, miny, 0));
var topRight = unproj.Transform(new Point(minx + deltaX, miny + deltaY, 0));
var drawingHeight = deltaY;
var drawingWidth = deltaX;
double viewHeight, drawingToViewScale;
var viewRatio = viewPortWidth / viewPortHeight;
var drawingRatio = drawingWidth / drawingHeight;
if (MathHelper.CloseTo(0.0, drawingHeight) || drawingRatio > viewRatio)
{
// fit to width
var viewWidth = drawingWidth;
viewHeight = viewPortHeight * viewWidth / viewPortWidth;
drawingToViewScale = viewPortWidth / viewWidth;
// add a buffer of some amount of pixels
var pixelWidth = drawingWidth * drawingToViewScale;
var newPixelWidth = pixelWidth + (viewportBuffer * 2.0);
viewHeight *= newPixelWidth / pixelWidth;
}
else
{
// fit to height
viewHeight = drawingHeight;
drawingToViewScale = viewPortHeight / viewHeight;
// add a buffer of some amount of pixels
var pixelHeight = drawingHeight * drawingToViewScale;
var newPixelHeight = pixelHeight + (viewportBuffer * 2.0);
viewHeight *= newPixelHeight / pixelHeight;
}
// center viewport
var tempViewport = new ViewPort(bottomLeft, sight, up, viewHeight);
var pixelMatrix = tempViewport.GetTransformationMatrixWindowsStyle(viewPortWidth, viewPortHeight);
var bottomLeftScreen = pixelMatrix.Transform(bottomLeft);
var topRightScreen = pixelMatrix.Transform(topRight);
// center horizontally
var leftXGap = bottomLeftScreen.X;
var rightXGap = viewPortWidth - topRightScreen.X;
var xAdjust = Math.Abs((rightXGap - leftXGap) / 2.0) / drawingToViewScale;
// center vertically
var topYGap = topRightScreen.Y;
var bottomYGap = viewPortHeight - bottomLeftScreen.Y;
var yAdjust = Math.Abs((topYGap - bottomYGap) / 2.0) / drawingToViewScale;
var newBottomLeft = new Point(bottomLeft.X - xAdjust, bottomLeft.Y - yAdjust, bottomLeft.Z);
var newVp = tempViewport.Update(bottomLeft: newBottomLeft, viewHeight: viewHeight);
return newVp;
}
public static Point StartPoint(this IPrimitive primitive)
{
switch (primitive.Kind)
{
case PrimitiveKind.Line:
return ((PrimitiveLine)primitive).P1;
case PrimitiveKind.Ellipse:
var el = (PrimitiveEllipse)primitive;
return el.GetPoint(el.StartAngle);
case PrimitiveKind.Point:
return ((PrimitivePoint)primitive).Location;
default:
throw new ArgumentException($"{nameof(primitive)}.{nameof(primitive.Kind)}");
}
}
public static Point EndPoint(this IPrimitive primitive)
{
switch (primitive.Kind)
{
case PrimitiveKind.Line:
return ((PrimitiveLine)primitive).P2;
case PrimitiveKind.Ellipse:
var el = (PrimitiveEllipse)primitive;
return el.GetPoint(el.EndAngle);
case PrimitiveKind.Point:
return ((PrimitivePoint)primitive).Location;
default:
throw new ArgumentException($"{nameof(primitive)}.{nameof(primitive.Kind)}");
}
}
public static Point MidPoint(this IPrimitive primitive)
{
switch (primitive.Kind)
{
case PrimitiveKind.Line:
var line = (PrimitiveLine)primitive;
return (line.P1 + line.P2) / 2;
case PrimitiveKind.Ellipse:
var el = (PrimitiveEllipse)primitive;
var endAngle = el.EndAngle;
if (endAngle < el.StartAngle)
{
endAngle += MathHelper.ThreeSixty;
}
return el.GetPoint((el.StartAngle + endAngle) * 0.5);
case PrimitiveKind.Point:
return ((PrimitivePoint)primitive).Location;
case PrimitiveKind.Text:
default:
throw new ArgumentException($"{nameof(primitive)}.{nameof(primitive.Kind)}");
}
}
public static IEnumerable<Point> GetProjectedVerticies(this IPrimitive primitive, Matrix4 transformationMatrix)
{
switch (primitive.Kind)
{
case PrimitiveKind.Line:
case PrimitiveKind.Point:
case PrimitiveKind.Text:
return primitive.GetInterestingPoints().Select(p => transformationMatrix.Transform(p));
case PrimitiveKind.Ellipse:
return ((PrimitiveEllipse)primitive).GetProjectedVerticies(transformationMatrix, 360);
default:
throw new InvalidOperationException();
}
}
public static IEnumerable<Point> GetProjectedVerticies(this PrimitiveEllipse ellipse, Matrix4 transformationMatrix, int maxSeg)
{
return ellipse.GetInterestingPoints(maxSeg)
.Select(p => transformationMatrix.Transform(p));
}
public static IEnumerable<IEnumerable<IPrimitive>> GetLineStripsFromPrimitives(this IEnumerable<IPrimitive> primitives)
{
var remainingPrimitives = new HashSet<IPrimitive>(primitives);
var result = new List<List<IPrimitive>>();
while (remainingPrimitives.Count > 0)
{
var shapePrimitives = new List<IPrimitive>();
var first = remainingPrimitives.First();
remainingPrimitives.Remove(first);
shapePrimitives.Add(first);
while (remainingPrimitives.Count > 0)
{
var lastPrimitive = shapePrimitives.Last();
var lastStartPoint = lastPrimitive.StartPoint();
var lastEndPoint = lastPrimitive.EndPoint();
var nextPrimitive = remainingPrimitives.FirstOrDefault(l =>
l.StartPoint().CloseTo(lastStartPoint) ||
l.EndPoint().CloseTo(lastStartPoint) ||
l.StartPoint().CloseTo(lastEndPoint) ||
l.EndPoint().CloseTo(lastEndPoint));
if (nextPrimitive == null)
{
// no more segments
break;
}
remainingPrimitives.Remove(nextPrimitive);
shapePrimitives.Add(nextPrimitive);
}
result.Add(shapePrimitives);
}
return result;
}
public static IEnumerable<Polyline> GetPolylinesFromSegments(this IEnumerable<IPrimitive> primitives)
{
return primitives
.GetLineStripsFromPrimitives()
.GetPolylinesFromPrimitives();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace System.IO
{
public sealed partial class DriveInfo
{
private static string NormalizeDriveName(string driveName)
{
Debug.Assert(driveName != null);
string name;
if (driveName.Length == 1)
name = driveName + ":\\";
else
{
name = Path.GetPathRoot(driveName);
// Disallow null or empty drive letters and UNC paths
if (name == null || name.Length == 0 || name.StartsWith("\\\\", StringComparison.Ordinal))
throw new ArgumentException(SR.Arg_MustBeDriveLetterOrRootDir);
}
// We want to normalize to have a trailing backslash so we don't have two equivalent forms and
// because some Win32 API don't work without it.
if (name.Length == 2 && name[1] == ':')
{
name = name + "\\";
}
// Now verify that the drive letter could be a real drive name.
// On Windows this means it's between A and Z, ignoring case.
char letter = driveName[0];
if (!((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z')))
throw new ArgumentException(SR.Arg_MustBeDriveLetterOrRootDir);
return name;
}
public DriveType DriveType
{
get
{
// GetDriveType can't fail
return (DriveType)Interop.Kernel32.GetDriveType(Name);
}
}
public String DriveFormat
{
get
{
const int volNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
const int fileSystemNameLen = 50;
StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
int serialNumber, maxFileNameLen, fileSystemFlags;
uint oldMode;
bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode);
try
{
bool r = Interop.Kernel32.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
if (!r)
{
throw Error.GetExceptionForLastWin32DriveError(Name);
}
}
finally
{
if (success)
Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
}
return fileSystemName.ToString();
}
}
public long AvailableFreeSpace
{
get
{
long userBytes, totalBytes, freeBytes;
uint oldMode;
bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode);
try
{
bool r = Interop.Kernel32.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
throw Error.GetExceptionForLastWin32DriveError(Name);
}
finally
{
if (success)
Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
}
return userBytes;
}
}
public long TotalFreeSpace
{
get
{
long userBytes, totalBytes, freeBytes;
uint oldMode;
bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode);
try
{
bool r = Interop.Kernel32.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
throw Error.GetExceptionForLastWin32DriveError(Name);
}
finally
{
if (success)
Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
}
return freeBytes;
}
}
public long TotalSize
{
get
{
// Don't cache this, to handle variable sized floppy drives
// or other various removable media drives.
long userBytes, totalBytes, freeBytes;
uint oldMode;
bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode);
try
{
bool r = Interop.Kernel32.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
throw Error.GetExceptionForLastWin32DriveError(Name);
}
finally
{
Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
}
return totalBytes;
}
}
public static DriveInfo[] GetDrives()
{
string[] drives = DriveInfoInternal.GetLogicalDrives();
DriveInfo[] result = new DriveInfo[drives.Length];
for (int i = 0; i < drives.Length; i++)
{
result[i] = new DriveInfo(drives[i]);
}
return result;
}
// Null is a valid volume label.
public String VolumeLabel
{
get
{
// NTFS uses a limit of 32 characters for the volume label,
// as of Windows Server 2003.
const int volNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
const int fileSystemNameLen = 50;
StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
int serialNumber, maxFileNameLen, fileSystemFlags;
uint oldMode;
bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode);
try
{
bool r = Interop.Kernel32.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
// Win9x appears to return ERROR_INVALID_DATA when a
// drive doesn't exist.
if (errorCode == Interop.Errors.ERROR_INVALID_DATA)
errorCode = Interop.Errors.ERROR_INVALID_DRIVE;
throw Error.GetExceptionForWin32DriveError(errorCode, Name);
}
}
finally
{
if (success)
Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
}
return volumeName.ToString();
}
set
{
uint oldMode;
bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode);
try
{
bool r = Interop.Kernel32.SetVolumeLabel(Name, value);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
// Provide better message
if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED)
throw new UnauthorizedAccessException(SR.InvalidOperation_SetVolumeLabelFailed);
throw Error.GetExceptionForWin32DriveError(errorCode, Name);
}
}
finally
{
if (success)
Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.Authentication.Tests;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.AspNetCore.Authentication
{
public abstract class SharedAuthenticationTests<TOptions> where TOptions : AuthenticationSchemeOptions
{
protected TestClock Clock { get; } = new TestClock();
protected abstract string DefaultScheme { get; }
protected virtual string DisplayName { get; }
protected abstract Type HandlerType { get; }
protected virtual bool SupportsSignIn { get => true; }
protected virtual bool SupportsSignOut { get => true; }
protected abstract void RegisterAuth(AuthenticationBuilder services, Action<TOptions> configure);
[Fact]
public async Task CanForwardDefault()
{
var services = new ServiceCollection().AddLogging();
var builder = services.AddAuthentication(o =>
{
o.DefaultScheme = DefaultScheme;
o.AddScheme<TestHandler>("auth1", "auth1");
});
RegisterAuth(builder, o => o.ForwardDefault = "auth1");
var forwardDefault = new TestHandler();
services.AddSingleton(forwardDefault);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
Assert.Equal(0, forwardDefault.AuthenticateCount);
Assert.Equal(0, forwardDefault.ForbidCount);
Assert.Equal(0, forwardDefault.ChallengeCount);
Assert.Equal(0, forwardDefault.SignInCount);
Assert.Equal(0, forwardDefault.SignOutCount);
await context.AuthenticateAsync();
Assert.Equal(1, forwardDefault.AuthenticateCount);
await context.ForbidAsync();
Assert.Equal(1, forwardDefault.ForbidCount);
await context.ChallengeAsync();
Assert.Equal(1, forwardDefault.ChallengeCount);
if (SupportsSignOut)
{
await context.SignOutAsync();
Assert.Equal(1, forwardDefault.SignOutCount);
}
else
{
await Assert.ThrowsAsync<InvalidOperationException>(() => context.SignOutAsync());
}
if (SupportsSignIn)
{
await context.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity("whatever")));
Assert.Equal(1, forwardDefault.SignInCount);
}
else
{
await Assert.ThrowsAsync<InvalidOperationException>(() => context.SignInAsync(new ClaimsPrincipal()));
}
}
[Fact]
public async Task ForwardSignInWinsOverDefault()
{
if (SupportsSignIn)
{
var services = new ServiceCollection().AddLogging();
var builder = services.AddAuthentication(o =>
{
o.DefaultScheme = DefaultScheme;
o.AddScheme<TestHandler2>("auth1", "auth1");
o.AddScheme<TestHandler>("specific", "specific");
});
RegisterAuth(builder, o =>
{
o.ForwardDefault = "auth1";
o.ForwardSignIn = "specific";
});
var specific = new TestHandler();
services.AddSingleton(specific);
var forwardDefault = new TestHandler2();
services.AddSingleton(forwardDefault);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
await context.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity("whatever")));
Assert.Equal(1, specific.SignInCount);
Assert.Equal(0, specific.AuthenticateCount);
Assert.Equal(0, specific.ForbidCount);
Assert.Equal(0, specific.ChallengeCount);
Assert.Equal(0, specific.SignOutCount);
Assert.Equal(0, forwardDefault.AuthenticateCount);
Assert.Equal(0, forwardDefault.ForbidCount);
Assert.Equal(0, forwardDefault.ChallengeCount);
Assert.Equal(0, forwardDefault.SignInCount);
Assert.Equal(0, forwardDefault.SignOutCount);
}
}
[Fact]
public async Task ForwardSignOutWinsOverDefault()
{
if (SupportsSignOut)
{
var services = new ServiceCollection().AddLogging();
var builder = services.AddAuthentication(o =>
{
o.DefaultScheme = DefaultScheme;
o.AddScheme<TestHandler2>("auth1", "auth1");
o.AddScheme<TestHandler>("specific", "specific");
});
RegisterAuth(builder, o =>
{
o.ForwardDefault = "auth1";
o.ForwardSignOut = "specific";
});
var specific = new TestHandler();
services.AddSingleton(specific);
var forwardDefault = new TestHandler2();
services.AddSingleton(forwardDefault);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
await context.SignOutAsync();
Assert.Equal(1, specific.SignOutCount);
Assert.Equal(0, specific.AuthenticateCount);
Assert.Equal(0, specific.ForbidCount);
Assert.Equal(0, specific.ChallengeCount);
Assert.Equal(0, specific.SignInCount);
Assert.Equal(0, forwardDefault.AuthenticateCount);
Assert.Equal(0, forwardDefault.ForbidCount);
Assert.Equal(0, forwardDefault.ChallengeCount);
Assert.Equal(0, forwardDefault.SignInCount);
Assert.Equal(0, forwardDefault.SignOutCount);
}
}
[Fact]
public async Task ForwardForbidWinsOverDefault()
{
var services = new ServiceCollection().AddLogging();
var builder = services.AddAuthentication(o =>
{
o.DefaultScheme = DefaultScheme;
o.AddScheme<TestHandler2>("auth1", "auth1");
o.AddScheme<TestHandler>("specific", "specific");
});
RegisterAuth(builder, o =>
{
o.ForwardDefault = "auth1";
o.ForwardForbid = "specific";
});
var specific = new TestHandler();
services.AddSingleton(specific);
var forwardDefault = new TestHandler2();
services.AddSingleton(forwardDefault);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
await context.ForbidAsync();
Assert.Equal(0, specific.SignOutCount);
Assert.Equal(0, specific.AuthenticateCount);
Assert.Equal(1, specific.ForbidCount);
Assert.Equal(0, specific.ChallengeCount);
Assert.Equal(0, specific.SignInCount);
Assert.Equal(0, forwardDefault.AuthenticateCount);
Assert.Equal(0, forwardDefault.ForbidCount);
Assert.Equal(0, forwardDefault.ChallengeCount);
Assert.Equal(0, forwardDefault.SignInCount);
Assert.Equal(0, forwardDefault.SignOutCount);
}
private class RunOnce : IClaimsTransformation
{
public int Ran = 0;
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
Ran++;
return Task.FromResult(new ClaimsPrincipal());
}
}
[Fact]
public async Task ForwardAuthenticateOnlyRunsTransformOnceByDefault()
{
var services = new ServiceCollection().AddLogging();
var transform = new RunOnce();
var builder = services.AddSingleton<IClaimsTransformation>(transform).AddAuthentication(o =>
{
o.DefaultScheme = DefaultScheme;
o.AddScheme<TestHandler2>("auth1", "auth1");
o.AddScheme<TestHandler>("specific", "specific");
});
RegisterAuth(builder, o =>
{
o.ForwardDefault = "auth1";
o.ForwardAuthenticate = "specific";
});
var specific = new TestHandler();
services.AddSingleton(specific);
var forwardDefault = new TestHandler2();
services.AddSingleton(forwardDefault);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
await context.AuthenticateAsync();
Assert.Equal(1, transform.Ran);
}
[Fact]
public async Task ForwardAuthenticateWinsOverDefault()
{
var services = new ServiceCollection().AddLogging();
var builder = services.AddAuthentication(o =>
{
o.DefaultScheme = DefaultScheme;
o.AddScheme<TestHandler2>("auth1", "auth1");
o.AddScheme<TestHandler>("specific", "specific");
});
RegisterAuth(builder, o =>
{
o.ForwardDefault = "auth1";
o.ForwardAuthenticate = "specific";
});
var specific = new TestHandler();
services.AddSingleton(specific);
var forwardDefault = new TestHandler2();
services.AddSingleton(forwardDefault);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
await context.AuthenticateAsync();
Assert.Equal(0, specific.SignOutCount);
Assert.Equal(1, specific.AuthenticateCount);
Assert.Equal(0, specific.ForbidCount);
Assert.Equal(0, specific.ChallengeCount);
Assert.Equal(0, specific.SignInCount);
Assert.Equal(0, forwardDefault.AuthenticateCount);
Assert.Equal(0, forwardDefault.ForbidCount);
Assert.Equal(0, forwardDefault.ChallengeCount);
Assert.Equal(0, forwardDefault.SignInCount);
Assert.Equal(0, forwardDefault.SignOutCount);
}
[Fact]
public async Task ForwardChallengeWinsOverDefault()
{
var services = new ServiceCollection().AddLogging();
var builder = services.AddAuthentication(o =>
{
o.DefaultScheme = DefaultScheme;
o.AddScheme<TestHandler2>("auth1", "auth1");
o.AddScheme<TestHandler>("specific", "specific");
});
RegisterAuth(builder, o =>
{
o.ForwardDefault = "auth1";
o.ForwardChallenge = "specific";
});
var specific = new TestHandler();
services.AddSingleton(specific);
var forwardDefault = new TestHandler2();
services.AddSingleton(forwardDefault);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
await context.ChallengeAsync();
Assert.Equal(0, specific.SignOutCount);
Assert.Equal(0, specific.AuthenticateCount);
Assert.Equal(0, specific.ForbidCount);
Assert.Equal(1, specific.ChallengeCount);
Assert.Equal(0, specific.SignInCount);
Assert.Equal(0, forwardDefault.AuthenticateCount);
Assert.Equal(0, forwardDefault.ForbidCount);
Assert.Equal(0, forwardDefault.ChallengeCount);
Assert.Equal(0, forwardDefault.SignInCount);
Assert.Equal(0, forwardDefault.SignOutCount);
}
[Fact]
public async Task ForwardSelectorWinsOverDefault()
{
var services = new ServiceCollection().AddLogging();
var builder = services.AddAuthentication(o =>
{
o.DefaultScheme = DefaultScheme;
o.AddScheme<TestHandler2>("auth1", "auth1");
o.AddScheme<TestHandler3>("selector", "selector");
o.AddScheme<TestHandler>("specific", "specific");
});
RegisterAuth(builder, o =>
{
o.ForwardDefault = "auth1";
o.ForwardDefaultSelector = _ => "selector";
});
var specific = new TestHandler();
services.AddSingleton(specific);
var forwardDefault = new TestHandler2();
services.AddSingleton(forwardDefault);
var selector = new TestHandler3();
services.AddSingleton(selector);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
await context.AuthenticateAsync();
Assert.Equal(1, selector.AuthenticateCount);
await context.ForbidAsync();
Assert.Equal(1, selector.ForbidCount);
await context.ChallengeAsync();
Assert.Equal(1, selector.ChallengeCount);
if (SupportsSignOut)
{
await context.SignOutAsync();
Assert.Equal(1, selector.SignOutCount);
}
else
{
await Assert.ThrowsAsync<InvalidOperationException>(() => context.SignOutAsync());
}
if (SupportsSignIn)
{
await context.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity("whatever")));
Assert.Equal(1, selector.SignInCount);
}
else
{
await Assert.ThrowsAsync<InvalidOperationException>(() => context.SignInAsync(new ClaimsPrincipal()));
}
Assert.Equal(0, forwardDefault.AuthenticateCount);
Assert.Equal(0, forwardDefault.ForbidCount);
Assert.Equal(0, forwardDefault.ChallengeCount);
Assert.Equal(0, forwardDefault.SignInCount);
Assert.Equal(0, forwardDefault.SignOutCount);
Assert.Equal(0, specific.AuthenticateCount);
Assert.Equal(0, specific.ForbidCount);
Assert.Equal(0, specific.ChallengeCount);
Assert.Equal(0, specific.SignInCount);
Assert.Equal(0, specific.SignOutCount);
}
[Fact]
public async Task NullForwardSelectorUsesDefault()
{
var services = new ServiceCollection().AddLogging();
var builder = services.AddAuthentication(o =>
{
o.DefaultScheme = DefaultScheme;
o.AddScheme<TestHandler2>("auth1", "auth1");
o.AddScheme<TestHandler3>("selector", "selector");
o.AddScheme<TestHandler>("specific", "specific");
});
RegisterAuth(builder, o =>
{
o.ForwardDefault = "auth1";
o.ForwardDefaultSelector = _ => null;
});
var specific = new TestHandler();
services.AddSingleton(specific);
var forwardDefault = new TestHandler2();
services.AddSingleton(forwardDefault);
var selector = new TestHandler3();
services.AddSingleton(selector);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
await context.AuthenticateAsync();
Assert.Equal(1, forwardDefault.AuthenticateCount);
await context.ForbidAsync();
Assert.Equal(1, forwardDefault.ForbidCount);
await context.ChallengeAsync();
Assert.Equal(1, forwardDefault.ChallengeCount);
if (SupportsSignOut)
{
await context.SignOutAsync();
Assert.Equal(1, forwardDefault.SignOutCount);
}
else
{
await Assert.ThrowsAsync<InvalidOperationException>(() => context.SignOutAsync());
}
if (SupportsSignIn)
{
await context.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity("whatever")));
Assert.Equal(1, forwardDefault.SignInCount);
}
else
{
await Assert.ThrowsAsync<InvalidOperationException>(() => context.SignInAsync(new ClaimsPrincipal()));
}
Assert.Equal(0, selector.AuthenticateCount);
Assert.Equal(0, selector.ForbidCount);
Assert.Equal(0, selector.ChallengeCount);
Assert.Equal(0, selector.SignInCount);
Assert.Equal(0, selector.SignOutCount);
Assert.Equal(0, specific.AuthenticateCount);
Assert.Equal(0, specific.ForbidCount);
Assert.Equal(0, specific.ChallengeCount);
Assert.Equal(0, specific.SignInCount);
Assert.Equal(0, specific.SignOutCount);
}
[Fact]
public async Task SpecificForwardWinsOverSelectorAndDefault()
{
var services = new ServiceCollection().AddLogging();
var builder = services.AddAuthentication(o =>
{
o.DefaultScheme = DefaultScheme;
o.AddScheme<TestHandler2>("auth1", "auth1");
o.AddScheme<TestHandler3>("selector", "selector");
o.AddScheme<TestHandler>("specific", "specific");
});
RegisterAuth(builder, o =>
{
o.ForwardDefault = "auth1";
o.ForwardDefaultSelector = _ => "selector";
o.ForwardAuthenticate = "specific";
o.ForwardChallenge = "specific";
o.ForwardSignIn = "specific";
o.ForwardSignOut = "specific";
o.ForwardForbid = "specific";
});
var specific = new TestHandler();
services.AddSingleton(specific);
var forwardDefault = new TestHandler2();
services.AddSingleton(forwardDefault);
var selector = new TestHandler3();
services.AddSingleton(selector);
var sp = services.BuildServiceProvider();
var context = new DefaultHttpContext();
context.RequestServices = sp;
await context.AuthenticateAsync();
Assert.Equal(1, specific.AuthenticateCount);
await context.ForbidAsync();
Assert.Equal(1, specific.ForbidCount);
await context.ChallengeAsync();
Assert.Equal(1, specific.ChallengeCount);
if (SupportsSignOut)
{
await context.SignOutAsync();
Assert.Equal(1, specific.SignOutCount);
}
else
{
await Assert.ThrowsAsync<InvalidOperationException>(() => context.SignOutAsync());
}
if (SupportsSignIn)
{
await context.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity("whatever")));
Assert.Equal(1, specific.SignInCount);
}
else
{
await Assert.ThrowsAsync<InvalidOperationException>(() => context.SignInAsync(new ClaimsPrincipal()));
}
Assert.Equal(0, forwardDefault.AuthenticateCount);
Assert.Equal(0, forwardDefault.ForbidCount);
Assert.Equal(0, forwardDefault.ChallengeCount);
Assert.Equal(0, forwardDefault.SignInCount);
Assert.Equal(0, forwardDefault.SignOutCount);
Assert.Equal(0, selector.AuthenticateCount);
Assert.Equal(0, selector.ForbidCount);
Assert.Equal(0, selector.ChallengeCount);
Assert.Equal(0, selector.SignInCount);
Assert.Equal(0, selector.SignOutCount);
}
[Fact]
public async Task VerifySchemeDefaults()
{
var services = new ServiceCollection();
var builder = services.AddAuthentication();
RegisterAuth(builder, o => { });
var sp = services.BuildServiceProvider();
var schemeProvider = sp.GetRequiredService<IAuthenticationSchemeProvider>();
var scheme = await schemeProvider.GetSchemeAsync(DefaultScheme);
Assert.NotNull(scheme);
Assert.Equal(HandlerType, scheme.HandlerType);
Assert.Equal(DisplayName, scheme.DisplayName);
}
}
}
| |
/*
* 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 QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds.Enumerators;
using QuantConnect.Lean.Engine.DataFeeds.WorkScheduling;
using QuantConnect.Logging;
using QuantConnect.Util;
namespace QuantConnect.Lean.Engine.DataFeeds
{
/// <summary>
/// Utilities related to data <see cref="Subscription"/>
/// </summary>
public static class SubscriptionUtils
{
/// <summary>
/// Creates a new <see cref="Subscription"/> which will directly consume the provided enumerator
/// </summary>
/// <param name="request">The subscription data request</param>
/// <param name="enumerator">The data enumerator stack</param>
/// <returns>A new subscription instance ready to consume</returns>
public static Subscription Create(
SubscriptionRequest request,
IEnumerator<BaseData> enumerator)
{
var exchangeHours = request.Security.Exchange.Hours;
var timeZoneOffsetProvider = new TimeZoneOffsetProvider(request.Security.Exchange.TimeZone, request.StartTimeUtc, request.EndTimeUtc);
var dataEnumerator = new SubscriptionDataEnumerator(
request.Configuration,
exchangeHours,
timeZoneOffsetProvider,
enumerator,
request.IsUniverseSubscription
);
return new Subscription(request, dataEnumerator, timeZoneOffsetProvider);
}
/// <summary>
/// Setups a new <see cref="Subscription"/> which will consume a blocking <see cref="EnqueueableEnumerator{T}"/>
/// that will be feed by a worker task
/// </summary>
/// <param name="request">The subscription data request</param>
/// <param name="enumerator">The data enumerator stack</param>
/// <param name="factorFileProvider">The factor file provider</param>
/// <param name="enablePriceScale">Enables price factoring</param>
/// <returns>A new subscription instance ready to consume</returns>
public static Subscription CreateAndScheduleWorker(
SubscriptionRequest request,
IEnumerator<BaseData> enumerator,
IFactorFileProvider factorFileProvider,
bool enablePriceScale)
{
var factorFile = GetFactorFileToUse(request.Configuration, factorFileProvider);
var exchangeHours = request.Security.Exchange.Hours;
var enqueueable = new EnqueueableEnumerator<SubscriptionData>(true);
var timeZoneOffsetProvider = new TimeZoneOffsetProvider(request.Security.Exchange.TimeZone, request.StartTimeUtc, request.EndTimeUtc);
var subscription = new Subscription(request, enqueueable, timeZoneOffsetProvider);
var config = subscription.Configuration;
var lastTradableDate = DateTime.MinValue;
decimal? currentScale = null;
Func<int, bool> produce = (workBatchSize) =>
{
try
{
var count = 0;
while (enumerator.MoveNext())
{
// subscription has been removed, no need to continue enumerating
if (enqueueable.HasFinished)
{
enumerator.DisposeSafely();
return false;
}
var data = enumerator.Current;
// Use our config filter to see if we should emit this
// This currently catches Auxiliary data that we don't want to emit
if (data != null && !config.ShouldEmitData(data, request.IsUniverseSubscription))
{
continue;
}
// In the event we have "Raw" configuration, we will force our subscription data
// to precalculate adjusted data. The data will still be emitted as raw, but
// if the config is changed at any point it can emit adjusted data as well
// See SubscriptionData.Create() and PrecalculatedSubscriptionData for more
var requestMode = config.DataNormalizationMode;
var mode = requestMode != DataNormalizationMode.Raw
? requestMode
: DataNormalizationMode.Adjusted;
// We update our price scale factor when the date changes for non fill forward bars or if we haven't initialized yet.
// We don't take into account auxiliary data because we don't scale it and because the underlying price data could be fill forwarded
if (enablePriceScale && data?.Time.Date > lastTradableDate && data.DataType != MarketDataType.Auxiliary && (!data.IsFillForward || lastTradableDate == DateTime.MinValue))
{
lastTradableDate = data.Time.Date;
currentScale = GetScaleFactor(factorFile, mode, data.Time.Date);
}
SubscriptionData subscriptionData = SubscriptionData.Create(
config,
exchangeHours,
subscription.OffsetProvider,
data,
mode,
enablePriceScale ? currentScale : null);
// drop the data into the back of the enqueueable
enqueueable.Enqueue(subscriptionData);
count++;
// stop executing if added more data than the work batch size, we don't want to fill the ram
if (count > workBatchSize)
{
return true;
}
}
}
catch (Exception exception)
{
Log.Error(exception, $"Subscription worker task exception {request.Configuration}.");
}
// we made it here because MoveNext returned false or we exploded, stop the enqueueable
enqueueable.Stop();
// we have to dispose of the enumerator
enumerator.DisposeSafely();
return false;
};
WeightedWorkScheduler.Instance.QueueWork(config.Symbol, produce,
// if the subscription finished we return 0, so the work is prioritized and gets removed
() =>
{
if (enqueueable.HasFinished)
{
return 0;
}
var count = enqueueable.Count;
return count > WeightedWorkScheduler.MaxWorkWeight ? WeightedWorkScheduler.MaxWorkWeight : count;
}
);
return subscription;
}
/// <summary>
/// Gets <see cref="FactorFile"/> for configuration
/// </summary>
/// <param name="config">Subscription configuration</param>
/// <param name="factorFileProvider">The factor file provider</param>
/// <returns></returns>
public static FactorFile GetFactorFileToUse(
SubscriptionDataConfig config,
IFactorFileProvider factorFileProvider)
{
var factorFileToUse = new FactorFile(config.Symbol.Value, new List<FactorFileRow>());
if (!config.IsCustomData
&& config.SecurityType == SecurityType.Equity)
{
try
{
var factorFile = factorFileProvider.Get(config.Symbol);
if (factorFile != null)
{
factorFileToUse = factorFile;
}
}
catch (Exception err)
{
Log.Error(err, "SubscriptionUtils.GetFactorFileToUse(): Factors File: "
+ config.Symbol.ID + ": ");
}
}
return factorFileToUse;
}
private static decimal GetScaleFactor(FactorFile factorFile, DataNormalizationMode mode, DateTime date)
{
switch (mode)
{
case DataNormalizationMode.Raw:
return 1;
case DataNormalizationMode.TotalReturn:
case DataNormalizationMode.SplitAdjusted:
return factorFile.GetSplitFactor(date);
case DataNormalizationMode.Adjusted:
return factorFile.GetPriceScaleFactor(date);
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
| |
/*
* 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;
using System.Globalization;
using System.Linq;
namespace CoreEditor.MiniJson {
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJson;
//
// 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;
bool succeed = Int64.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out parsedInt);
if(succeed)
return parsedInt;
}
double parsedDouble;
bool parseDoubleSucceed = Double.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out parsedDouble);
if(parseDoubleSucceed)
return 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 Serialize( obj, null );
}
public static string Serialize( object obj, string indent )
{
return Serializer.Serialize( obj, indent );
}
sealed class Serializer {
StringBuilder builder;
string lineEnding;
string indent;
int depth = 0;
Serializer( string indent )
{
builder = new StringBuilder();
lineEnding = (indent == null) ? string.Empty : "\n";
this.indent = indent ?? string.Empty;
}
public static string Serialize( object obj, string indent )
{
var instance = new Serializer( indent );
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('{');
CR();
depth++;
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
CR();
}
Indent();
SerializeString( e.ToString() );
builder.Append( ": " );
SerializeValue(obj[e]);
first = false;
}
CR();
depth--;
Indent();
builder.Append( '}' );
}
void SerializeArray(IList anArray) {
builder.Append('[');
CR();
depth++;
bool first = true;
foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
CR();
}
Indent();
SerializeValue( obj );
first = false;
}
CR();
depth--;
Indent();
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", CultureInfo.InvariantCulture));
}
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", 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", CultureInfo.InvariantCulture));
} else {
SerializeString(value.ToString());
}
}
void Indent()
{
builder.Append( String.Concat( Enumerable.Repeat( indent, depth ).ToArray() ) );
}
void CR()
{
builder.Append( lineEnding );
}
}
}
}
| |
using UnityEngine;
using UnityEngine.Events;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace NewtonVR
{
public class NVRHand : MonoBehaviour
{
public NVRButtons HoldButton = NVRButtons.Grip;
public bool HoldButtonDown { get { return Inputs[HoldButton].PressDown; } }
public bool HoldButtonUp { get { return Inputs[HoldButton].PressUp; } }
public bool HoldButtonPressed { get { return Inputs[HoldButton].IsPressed; } }
public float HoldButtonAxis { get { return Inputs[HoldButton].SingleAxis; } }
public NVRButtons UseButton = NVRButtons.Trigger;
public bool UseButtonDown { get { return Inputs[UseButton].PressDown; } }
public bool UseButtonUp { get { return Inputs[UseButton].PressUp; } }
public bool UseButtonPressed { get { return Inputs[UseButton].IsPressed; } }
public float UseButtonAxis { get { return Inputs[UseButton].SingleAxis; } }
[HideInInspector]
public bool IsRight;
[HideInInspector]
public bool IsLeft;
[HideInInspector]
public NVRPlayer Player;
public Dictionary<NVRButtons, NVRButtonInputs> Inputs;
[HideInInspector]
public InterationStyle CurrentInteractionStyle;
public Rigidbody Rigidbody;
[HideInInspector]
public GameObject CustomModel;
[HideInInspector]
public GameObject CustomPhysicalColliders;
private VisibilityLevel CurrentVisibility = VisibilityLevel.Visible;
private bool VisibilityLocked = false;
[HideInInspector]
public HandState CurrentHandState = HandState.Uninitialized;
private Dictionary<NVRInteractable, Dictionary<Collider, float>> CurrentlyHoveringOver;
public NVRInteractable CurrentlyInteracting;
[Serializable]
public class NVRInteractableEvent : UnityEvent<NVRInteractable> { }
public NVRInteractableEvent OnBeginInteraction = new NVRInteractableEvent();
public NVRInteractableEvent OnEndInteraction = new NVRInteractableEvent();
private int EstimationSampleIndex;
private Vector3[] LastPositions;
private Quaternion[] LastRotations;
private float[] LastDeltas;
private int EstimationSamples = 5;
[HideInInspector]
public NVRPhysicalController PhysicalController;
private Collider[] GhostColliders;
private Renderer[] GhostRenderers;
private NVRInputDevice InputDevice;
private GameObject RenderModel;
public bool IsHovering
{
get
{
return CurrentlyHoveringOver.Any(kvp => kvp.Value.Count > 0);
}
}
public bool IsInteracting
{
get
{
return CurrentlyInteracting != null;
}
}
public bool HasCustomModel
{
get
{
return CustomModel != null;
}
}
public bool IsCurrentlyTracked
{
get
{
if (InputDevice != null)
{
return InputDevice.IsCurrentlyTracked;
}
return false;
}
}
public Vector3 CurrentForward
{
get
{
if (PhysicalController != null && PhysicalController.State == true)
{
return PhysicalController.PhysicalController.transform.forward;
}
else
{
return this.transform.forward;
}
}
}
public Vector3 CurrentPosition
{
get
{
if (PhysicalController != null && PhysicalController.State == true)
{
return PhysicalController.PhysicalController.transform.position;
}
else
{
return this.transform.position;
}
}
}
public virtual void PreInitialize(NVRPlayer player)
{
Player = player;
IsRight = Player.RightHand == this;
IsLeft = Player.LeftHand == this;
CurrentInteractionStyle = Player.InteractionStyle;
CurrentlyHoveringOver = new Dictionary<NVRInteractable, Dictionary<Collider, float>>();
LastPositions = new Vector3[EstimationSamples];
LastRotations = new Quaternion[EstimationSamples];
LastDeltas = new float[EstimationSamples];
EstimationSampleIndex = 0;
VisibilityLocked = false;
Inputs = new Dictionary<NVRButtons, NVRButtonInputs>(new NVRButtonsComparer());
for (int buttonIndex = 0; buttonIndex < NVRButtonsHelper.Array.Length; buttonIndex++)
{
if (Inputs.ContainsKey(NVRButtonsHelper.Array[buttonIndex]) == false)
{
Inputs.Add(NVRButtonsHelper.Array[buttonIndex], new NVRButtonInputs());
}
}
if (Player.CurrentIntegrationType == NVRSDKIntegrations.Oculus)
{
InputDevice = this.gameObject.AddComponent<NVROculusInputDevice>();
if (Player.OverrideOculus == true)
{
if (IsLeft)
{
CustomModel = Player.OverrideOculusLeftHand;
CustomPhysicalColliders = Player.OverrideOculusLeftHandPhysicalColliders;
}
else if (IsRight)
{
CustomModel = Player.OverrideOculusRightHand;
CustomPhysicalColliders = Player.OverrideOculusRightHandPhysicalColliders;
}
else
{
Debug.LogError("[NewtonVR] Error: Unknown hand for oculus model override.");
}
}
}
else if (Player.CurrentIntegrationType == NVRSDKIntegrations.SteamVR)
{
InputDevice = this.gameObject.AddComponent<NVRSteamVRInputDevice>();
if (Player.OverrideSteamVR == true)
{
if (IsLeft)
{
CustomModel = Player.OverrideSteamVRLeftHand;
CustomPhysicalColliders = Player.OverrideSteamVRLeftHandPhysicalColliders;
}
else if (IsRight)
{
CustomModel = Player.OverrideSteamVRRightHand;
CustomPhysicalColliders = Player.OverrideSteamVRRightHandPhysicalColliders;
}
else
{
Debug.LogError("[NewtonVR] Error: Unknown hand for SteamVR model override.");
}
}
}
else
{
//Debug.LogError("[NewtonVR] Critical Error: NVRPlayer.CurrentIntegration not setup.");
return;
}
if (Player.OverrideAll)
{
if (IsLeft)
{
CustomModel = Player.OverrideAllLeftHand;
CustomPhysicalColliders = Player.OverrideAllLeftHandPhysicalColliders;
}
else if (IsRight)
{
CustomModel = Player.OverrideAllRightHand;
CustomPhysicalColliders = Player.OverrideAllRightHandPhysicalColliders;
}
else
{
Debug.LogError("[NewtonVR] Error: Unknown hand for SteamVR model override.");
return;
}
}
InputDevice.Initialize(this);
InitializeRenderModel();
}
protected virtual void Update()
{
if (CurrentHandState == HandState.Uninitialized)
{
if (InputDevice == null || InputDevice.ReadyToInitialize() == false)
{
return;
}
else
{
Initialize();
return;
}
}
UpdateButtonStates();
UpdateInteractions();
UpdateHovering();
UpdateVisibilityAndColliders();
}
protected void UpdateHovering()
{
if (CurrentHandState == HandState.Idle)
{
var hoveringEnumerator = CurrentlyHoveringOver.GetEnumerator();
while (hoveringEnumerator.MoveNext())
{
var hoveringOver = hoveringEnumerator.Current;
if (hoveringOver.Value.Count > 0)
{
hoveringOver.Key.HoveringUpdate(this, Time.time - hoveringOver.Value.OrderBy(colliderTime => colliderTime.Value).First().Value);
}
}
}
}
protected void UpdateButtonStates()
{
for (int index = 0; index < NVRButtonsHelper.Array.Length; index++)
{
NVRButtons nvrbutton = NVRButtonsHelper.Array[index];
NVRButtonInputs button = Inputs[nvrbutton];
button.FrameReset(InputDevice, nvrbutton);
}
}
protected void UpdateInteractions()
{
if (CurrentInteractionStyle == InterationStyle.Hold)
{
if (HoldButtonUp == true)
{
VisibilityLocked = false;
}
if (HoldButtonDown == true)
{
if (CurrentlyInteracting == null)
{
PickupClosest();
}
}
else if (HoldButtonUp == true && CurrentlyInteracting != null)
{
EndInteraction(null);
}
}
else if (CurrentInteractionStyle == InterationStyle.Toggle)
{
if (HoldButtonDown == true)
{
if (CurrentHandState == HandState.Idle)
{
PickupClosest();
if (IsInteracting)
{
CurrentHandState = HandState.GripToggleOnInteracting;
}
else if (Player.PhysicalHands == true)
{
CurrentHandState = HandState.GripToggleOnNotInteracting;
}
}
else if (CurrentHandState == HandState.GripToggleOnInteracting)
{
CurrentHandState = HandState.Idle;
VisibilityLocked = false;
EndInteraction(null);
}
else if (CurrentHandState == HandState.GripToggleOnNotInteracting)
{
CurrentHandState = HandState.Idle;
VisibilityLocked = false;
}
}
}
else if (CurrentInteractionStyle == InterationStyle.ByScript)
{
//this is handled by user customized scripts.
}
if (IsInteracting == true)
{
CurrentlyInteracting.InteractingUpdate(this);
}
}
private void UpdateVisibilityAndColliders()
{
if (Player.PhysicalHands == true)
{
if (CurrentInteractionStyle == InterationStyle.Hold)
{
if (HoldButtonPressed == true && IsInteracting == false)
{
if (CurrentHandState != HandState.GripDownNotInteracting && VisibilityLocked == false)
{
VisibilityLocked = true;
SetVisibility(VisibilityLevel.Visible);
CurrentHandState = HandState.GripDownNotInteracting;
}
}
else if (HoldButtonDown == true && IsInteracting == true)
{
if (CurrentHandState != HandState.GripDownInteracting && VisibilityLocked == false)
{
VisibilityLocked = true;
if (Player.MakeControllerInvisibleOnInteraction == true)
{
SetVisibility(VisibilityLevel.Invisible);
}
else
{
SetVisibility(VisibilityLevel.Ghost);
}
CurrentHandState = HandState.GripDownInteracting;
}
}
else if (IsInteracting == false)
{
if (CurrentHandState != HandState.Idle && VisibilityLocked == false)
{
SetVisibility(VisibilityLevel.Ghost);
CurrentHandState = HandState.Idle;
}
}
}
else if (CurrentInteractionStyle == InterationStyle.Toggle)
{
if (CurrentHandState == HandState.Idle)
{
if (VisibilityLocked == false && CurrentVisibility != VisibilityLevel.Ghost)
{
SetVisibility(VisibilityLevel.Ghost);
}
else
{
VisibilityLocked = false;
}
}
else if (CurrentHandState == HandState.GripToggleOnInteracting)
{
if (VisibilityLocked == false)
{
VisibilityLocked = true;
SetVisibility(VisibilityLevel.Ghost);
}
}
else if (CurrentHandState == HandState.GripToggleOnNotInteracting)
{
if (VisibilityLocked == false)
{
VisibilityLocked = true;
SetVisibility(VisibilityLevel.Visible);
}
}
}
}
else if (Player.PhysicalHands == false && Player.MakeControllerInvisibleOnInteraction == true)
{
if (IsInteracting == true)
{
SetVisibility(VisibilityLevel.Invisible);
}
else if (IsInteracting == false)
{
SetVisibility(VisibilityLevel.Ghost);
}
}
}
public void TriggerHapticPulse(ushort durationMicroSec = 500, NVRButtons button = NVRButtons.Grip)
{
if (InputDevice != null)
{
if (durationMicroSec < 3000)
{
InputDevice.TriggerHapticPulse(durationMicroSec, button);
}
else
{
Debug.LogWarning("You're trying to pulse for over 3000 microseconds, you probably don't want to do that. If you do, use NVRHand.LongHapticPulse(float seconds)");
}
}
}
public void LongHapticPulse(float seconds, NVRButtons button = NVRButtons.Grip)
{
StartCoroutine(DoLongHapticPulse(seconds, button));
}
private IEnumerator DoLongHapticPulse(float seconds, NVRButtons button)
{
float startTime = Time.time;
float endTime = startTime + seconds;
while (Time.time < endTime)
{
TriggerHapticPulse(100, button);
yield return null;
}
}
public Vector3 GetVelocityEstimation()
{
float delta = LastDeltas.Sum();
Vector3 distance = Vector3.zero;
for (int index = 0; index < LastPositions.Length - 1; index++)
{
Vector3 diff = LastPositions[index + 1] - LastPositions[index];
distance += diff;
}
return distance / delta;
}
public Vector3 GetAngularVelocityEstimation()
{
float delta = LastDeltas.Sum();
float angleDegrees = 0.0f;
Vector3 unitAxis = Vector3.zero;
Quaternion rotation = Quaternion.identity;
rotation = LastRotations[LastRotations.Length - 1] * Quaternion.Inverse(LastRotations[LastRotations.Length - 2]);
//Error: the incorrect rotation is sometimes returned
rotation.ToAngleAxis(out angleDegrees, out unitAxis);
return unitAxis * ((angleDegrees * Mathf.Deg2Rad) / delta);
}
public Vector3 GetPositionDelta()
{
int last = EstimationSampleIndex - 1;
int secondToLast = EstimationSampleIndex - 2;
if (last < 0)
last += EstimationSamples;
if (secondToLast < 0)
secondToLast += EstimationSamples;
return LastPositions[last] - LastPositions[secondToLast];
}
public Quaternion GetRotationDelta()
{
int last = EstimationSampleIndex - 1;
int secondToLast = EstimationSampleIndex - 2;
if (last < 0)
last += EstimationSamples;
if (secondToLast < 0)
secondToLast += EstimationSamples;
return LastRotations[last] * Quaternion.Inverse(LastRotations[secondToLast]);
}
protected virtual void FixedUpdate()
{
if (CurrentHandState == HandState.Uninitialized)
{
return;
}
LastPositions[EstimationSampleIndex] = this.transform.position;
LastRotations[EstimationSampleIndex] = this.transform.rotation;
LastDeltas[EstimationSampleIndex] = Time.deltaTime;
EstimationSampleIndex++;
if (EstimationSampleIndex >= LastPositions.Length)
EstimationSampleIndex = 0;
if (InputDevice != null && IsInteracting == false && IsHovering == true)
{
if (Player.VibrateOnHover == true)
{
InputDevice.TriggerHapticPulse(100);
}
}
}
public virtual void BeginInteraction(NVRInteractable interactable)
{
if (interactable.CanAttach == true)
{
if (interactable.AttachedHand != null)
{
interactable.AttachedHand.EndInteraction(null);
}
CurrentlyInteracting = interactable;
CurrentlyInteracting.BeginInteraction(this);
if (OnBeginInteraction != null)
{
OnBeginInteraction.Invoke(interactable);
}
}
}
public virtual void EndInteraction(NVRInteractable item)
{
if (item != null && CurrentlyHoveringOver.ContainsKey(item) == true)
CurrentlyHoveringOver.Remove(item);
if (CurrentlyInteracting != null)
{
CurrentlyInteracting.EndInteraction();
if (OnEndInteraction != null)
{
OnEndInteraction.Invoke(CurrentlyInteracting);
}
CurrentlyInteracting = null;
}
if (CurrentInteractionStyle == InterationStyle.Toggle)
{
if (CurrentHandState != HandState.Idle)
{
CurrentHandState = HandState.Idle;
}
}
}
private bool PickupClosest()
{
NVRInteractable closest = null;
float closestDistance = float.MaxValue;
foreach (var hovering in CurrentlyHoveringOver)
{
if (hovering.Key == null)
continue;
float distance = Vector3.Distance(this.transform.position, hovering.Key.transform.position);
if (distance < closestDistance)
{
closestDistance = distance;
closest = hovering.Key;
}
}
if (closest != null)
{
BeginInteraction(closest);
return true;
}
else
{
return false;
}
}
protected virtual void OnTriggerEnter(Collider collider)
{
NVRInteractable interactable = NVRInteractables.GetInteractable(collider);
if (interactable == null || interactable.enabled == false)
return;
if (CurrentlyHoveringOver.ContainsKey(interactable) == false)
CurrentlyHoveringOver[interactable] = new Dictionary<Collider, float>();
if (CurrentlyHoveringOver[interactable].ContainsKey(collider) == false)
CurrentlyHoveringOver[interactable][collider] = Time.time;
}
protected virtual void OnTriggerStay(Collider collider)
{
NVRInteractable interactable = NVRInteractables.GetInteractable(collider);
if (interactable == null || interactable.enabled == false)
return;
if (CurrentlyHoveringOver.ContainsKey(interactable) == false)
CurrentlyHoveringOver[interactable] = new Dictionary<Collider, float>();
if (CurrentlyHoveringOver[interactable].ContainsKey(collider) == false)
CurrentlyHoveringOver[interactable][collider] = Time.time;
}
protected virtual void OnTriggerExit(Collider collider)
{
NVRInteractable interactable = NVRInteractables.GetInteractable(collider);
if (interactable == null)
return;
if (CurrentlyHoveringOver.ContainsKey(interactable) == true)
{
if (CurrentlyHoveringOver[interactable].ContainsKey(collider) == true)
{
CurrentlyHoveringOver[interactable].Remove(collider);
if (CurrentlyHoveringOver[interactable].Count == 0)
{
CurrentlyHoveringOver.Remove(interactable);
}
}
}
}
public string GetDeviceName()
{
if (InputDevice != null)
return InputDevice.GetDeviceName();
else
return null;
}
public Collider[] SetupDefaultPhysicalColliders(Transform ModelParent)
{
return InputDevice.SetupDefaultPhysicalColliders(ModelParent);
}
public void DeregisterInteractable(NVRInteractable interactable)
{
if (CurrentlyInteracting == interactable)
CurrentlyInteracting = null;
if (CurrentlyHoveringOver != null && CurrentlyHoveringOver.ContainsKey(interactable))
CurrentlyHoveringOver.Remove(interactable);
}
private void SetVisibility(VisibilityLevel visibility)
{
if (CurrentVisibility != visibility)
{
if (visibility == VisibilityLevel.Invisible)
{
if (PhysicalController != null)
{
PhysicalController.Off();
}
if (Player.AutomaticallySetControllerTransparency == true)
{
for (int index = 0; index < GhostRenderers.Length; index++)
{
GhostRenderers[index].enabled = false;
}
for (int index = 0; index < GhostColliders.Length; index++)
{
GhostColliders[index].enabled = false;
}
}
}
if (visibility == VisibilityLevel.Ghost)
{
if (PhysicalController != null)
{
PhysicalController.Off();
}
if (Player.AutomaticallySetControllerTransparency == true)
{
for (int index = 0; index < GhostRenderers.Length; index++)
{
GhostRenderers[index].enabled = true;
}
for (int index = 0; index < GhostColliders.Length; index++)
{
GhostColliders[index].enabled = true;
}
}
}
if (visibility == VisibilityLevel.Visible)
{
if (PhysicalController != null)
{
PhysicalController.On();
}
if (Player.AutomaticallySetControllerTransparency == true)
{
for (int index = 0; index < GhostRenderers.Length; index++)
{
GhostRenderers[index].enabled = false;
}
for (int index = 0; index < GhostColliders.Length; index++)
{
GhostColliders[index].enabled = false;
}
}
}
}
CurrentVisibility = visibility;
}
protected void InitializeRenderModel()
{
if (CustomModel == null)
{
RenderModel = InputDevice.SetupDefaultRenderModel();
}
else
{
RenderModel = GameObject.Instantiate(CustomModel);
RenderModel.transform.parent = this.transform;
RenderModel.transform.localScale = RenderModel.transform.localScale;
RenderModel.transform.localPosition = Vector3.zero;
RenderModel.transform.localRotation = Quaternion.identity;
}
}
public void Initialize()
{
Rigidbody = this.GetComponent<Rigidbody>();
if (Rigidbody == null)
Rigidbody = this.gameObject.AddComponent<Rigidbody>();
Rigidbody.isKinematic = true;
Rigidbody.maxAngularVelocity = float.MaxValue;
Rigidbody.useGravity = false;
Collider[] colliders = null;
if (CustomModel == null)
{
colliders = InputDevice.SetupDefaultColliders();
}
else
{
colliders = RenderModel.GetComponentsInChildren<Collider>(); //note: these should be trigger colliders
}
Player.RegisterHand(this);
if (Player.PhysicalHands == true)
{
if (PhysicalController != null)
{
PhysicalController.Kill();
}
PhysicalController = this.gameObject.AddComponent<NVRPhysicalController>();
PhysicalController.Initialize(this, false);
if (Player.AutomaticallySetControllerTransparency == true)
{
Color transparentcolor = Color.white;
transparentcolor.a = (float)VisibilityLevel.Ghost / 100f;
GhostRenderers = this.GetComponentsInChildren<Renderer>();
for (int rendererIndex = 0; rendererIndex < GhostRenderers.Length; rendererIndex++)
{
NVRHelpers.SetTransparent(GhostRenderers[rendererIndex].material, transparentcolor);
}
}
if (colliders != null)
{
GhostColliders = colliders;
}
CurrentVisibility = VisibilityLevel.Ghost;
}
else
{
if (Player.AutomaticallySetControllerTransparency == true)
{
Color transparentcolor = Color.white;
transparentcolor.a = (float)VisibilityLevel.Ghost / 100f;
GhostRenderers = this.GetComponentsInChildren<Renderer>();
for (int rendererIndex = 0; rendererIndex < GhostRenderers.Length; rendererIndex++)
{
NVRHelpers.SetTransparent(GhostRenderers[rendererIndex].material, transparentcolor);
}
}
if (colliders != null)
{
GhostColliders = colliders;
}
CurrentVisibility = VisibilityLevel.Ghost;
}
CurrentHandState = HandState.Idle;
}
public void ForceGhost()
{
SetVisibility(VisibilityLevel.Ghost);
PhysicalController.Off();
}
}
public enum VisibilityLevel
{
Invisible = 0,
Ghost = 70,
Visible = 100,
}
public enum HandState
{
Uninitialized,
Idle,
GripDownNotInteracting,
GripDownInteracting,
GripToggleOnNotInteracting,
GripToggleOnInteracting,
GripToggleOff
}
public enum InterationStyle
{
Hold,
Toggle,
ByScript,
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using NQuery.Compilation;
namespace NQuery.Runtime.ExecutionPlan
{
// TODO: Implement Right Semi Join, Right Anti Semi Join
internal sealed class HashMatchIterator : BinaryIterator
{
private sealed class Entry
{
public object[] RowValues;
public Entry Next;
public bool Matched;
}
private enum Phase
{
ProduceMatch,
ReturnUnmatchedRowsFromBuildInput
}
public IteratorInput BuildKeyEntry;
public IteratorInput ProbeEntry;
public RuntimeExpression ProbeResidual;
public JoinType LogicalOp;
private Hashtable _hashTable;
private object[] _keys;
private Entry _entry;
private int _currentKeyIndex;
private Phase _currentPhase;
private bool _rightMatched;
public override void Open()
{
Left.Open();
Right.Open();
BuildHashtable();
_entry = null;
_currentKeyIndex = -1;
_currentPhase = Phase.ProduceMatch;
_rightMatched = true;
}
private void BuildHashtable()
{
_hashTable = new Hashtable();
while (Left.Read())
{
object keyValue = Left.RowBuffer[BuildKeyEntry.SourceIndex];
if (keyValue != null)
{
object[] rowValues = new object[Left.RowBuffer.Length];
Array.Copy(Left.RowBuffer, rowValues, rowValues.Length);
AddToHashtable(keyValue, rowValues);
}
}
_keys = new object[_hashTable.Keys.Count];
_hashTable.Keys.CopyTo(_keys, 0);
}
private void AddToHashtable(object keyValue, object[] values)
{
Entry entry = _hashTable[keyValue] as Entry;
if (entry == null)
{
entry = new Entry();
}
else
{
Entry newEntry = new Entry();
newEntry.Next = entry;
entry = newEntry;
}
entry.RowValues = values;
_hashTable[keyValue] = entry;
}
private bool CheckIfProbeResidualIsTrue()
{
if (ProbeResidual == null)
return true;
object result = ProbeResidual.GetValue();
return (result != null && Convert.ToBoolean(result, CultureInfo.InvariantCulture));
}
public override bool Read()
{
switch (_currentPhase)
{
case Phase.ProduceMatch:
{
bool matchFound = false;
while (!matchFound)
{
if (_entry != null)
_entry = _entry.Next;
if (_entry == null)
{
// All rows having the same key value are exhausted.
if (!_rightMatched && (LogicalOp == JoinType.FullOuter || LogicalOp == JoinType.RightOuter))
{
_rightMatched = true;
WriteRightWithNullLeftToRowBuffer();
return true;
}
// Read next row from probe input.
if (!Right.Read())
{
// The probe input is exhausted. If we have a full outer or left outer
// join we are not finished. We have to return all rows from the build
// input that have not been matched with the probe input.
if (LogicalOp == JoinType.FullOuter || LogicalOp == JoinType.LeftOuter)
{
_currentPhase = Phase.ReturnUnmatchedRowsFromBuildInput;
_entry = null;
goto case Phase.ReturnUnmatchedRowsFromBuildInput;
}
return false;
}
// Get probe value
_rightMatched = false;
object probeValue = Right.RowBuffer[ProbeEntry.SourceIndex];
// Seek first occurence of probe value
if (probeValue != null)
_entry = (Entry) _hashTable[probeValue];
}
if (_entry != null)
{
Array.Copy(_entry.RowValues, Left.RowBuffer, Left.RowBuffer.Length);
if (CheckIfProbeResidualIsTrue())
{
_entry.Matched = true;
WriteLeftAndRightToRowBuffer();
matchFound = true;
_rightMatched = true;
}
}
}
return true;
}
case Phase.ReturnUnmatchedRowsFromBuildInput:
{
bool unmatchedFound = false;
while (!unmatchedFound)
{
if (_entry != null)
_entry = _entry.Next;
if (_entry == null)
{
// All rows having the same key value are exhausted.
// Read next key from build input.
_currentKeyIndex++;
if (_currentKeyIndex >= _keys.Length)
{
// We have read all keys. So we are finished.
return false;
}
_entry = (Entry)_hashTable[_keys[_currentKeyIndex]];
}
unmatchedFound = !_entry.Matched;
}
Array.Copy(_entry.RowValues, Left.RowBuffer, Left.RowBuffer.Length);
WriteLeftWithNullRightToRowBuffer();
return true;
}
default:
throw ExceptionBuilder.UnhandledCaseLabel(_currentPhase);
}
}
}
}
| |
using System;
using System.IO;
using System.Data;
using System.Xml;
using System.Net;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using CabinetFile;
namespace HWD
{
public delegate void AvanceDownload(long receivedBytes, long totalBytes);
public enum WindowsVersions
{
Windows2000AdvancedServer = 143,
Windows2000DatacenterServer= 144,
Windows2000Professional=145,
Windows2000Server=146,
// Windows95=147,
// Windows98=148,
// Windows98SE=151,
// WindowsMe=152,
// WindowsNTServer40=170,
// WindowsNTServer40EnterpriseEdition=171,
// WindowsNTServer40TerminalServerEdition=172,
// WindowsNTWorkstation40=173,
WindowsServer2003forSmallBusinessServer=176,
WindowsServer2003DatacenterEdition=177,
WindowsServer2003EnterpriseEdition=178,
WindowsServer2003StandardEdition=179,
WindowsServer2003WebEdition=180,
WindowsXPHomeEdition=181,
WindowsXPProfessional=183
}
public class HotFixUpdaterForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private CabinetFile.TCabinetFile m_CabinetFile = new TCabinetFile();
private System.Windows.Forms.ProgressBar progressBar1;
public HotFixUpdaterForm()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(8, 24);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(352, 40);
this.progressBar1.Step = 1;
this.progressBar1.TabIndex = 0;
//
// label1
//
this.label1.Location = new System.Drawing.Point(88, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(272, 16);
this.label1.TabIndex = 1;
this.label1.Text = "0%";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// button1
//
this.button1.BackColor = System.Drawing.Color.SaddleBrown;
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.ForeColor = System.Drawing.Color.OldLace;
this.button1.Location = new System.Drawing.Point(208, 72);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(72, 24);
this.button1.TabIndex = 2;
this.button1.Text = "Download";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.BackColor = System.Drawing.Color.SaddleBrown;
this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button2.ForeColor = System.Drawing.Color.OldLace;
this.button2.Location = new System.Drawing.Point(288, 72);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(72, 24);
this.button2.TabIndex = 3;
this.button2.Text = "Cancel";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// m_CabinetFile
//
// this.m_CabinetFile.FileFound +=new EventHandler(CabinetFile_FileFound);
this.m_CabinetFile.FileExtractBefore +=new EventHandler(CabinetFile_FileExtractBefore);
// this.m_CabinetFile.FileExtractComplete += new EventHandler(CabinetFile_FileExtractComplete);
//
// HotFixUpdaterForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.Color.Tan;
this.ClientSize = new System.Drawing.Size(368, 103);
this.ControlBox = false;
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.label1);
this.Controls.Add(this.progressBar1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximumSize = new System.Drawing.Size(374, 128);
this.MinimumSize = new System.Drawing.Size(374, 128);
this.Name = "HotFixUpdaterForm";
this.Text = "Downloading Definition File";
this.ResumeLayout(false);
}
private void CabinetFile_FileExtractBefore(object sender, System.EventArgs e)
{
TFile file = (TFile)sender;
System.ComponentModel.CancelEventArgs cancel = (System.ComponentModel.CancelEventArgs)e;
}
private void UpdateProgress(long receivedBytes, long totalBytes)
{
this.progressBar1.Value = Convert.ToInt32(Math.Floor((receivedBytes * 100) / totalBytes));
this.label1.Text = this.progressBar1.Value.ToString();
}
private void Clean()
{
if(File.Exists("mssecure.cab"))
{
File.Delete("mssecure.cab");
}
if(File.Exists("mssecure.xml"))
{
File.Delete("mssecure.xml");
}
if(File.Exists("hwdhf.xml"))
{
File.Delete("hwdhf.xml");
}
}
private void DownloadFile(string remoteFilename, string localFilename)
{
int bytesProcessed = 0;
Stream remoteStream = null;
Stream localStream = null;
WebResponse response = null;
try
{
WebRequest request = WebRequest.Create(remoteFilename);
if (request != null)
{
response = request.GetResponse();
if (response != null)
{
remoteStream = response.GetResponseStream();
localStream = File.Create(localFilename);
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = remoteStream.Read (buffer, 0, buffer.Length);
localStream.Write (buffer, 0, bytesRead);
bytesProcessed += bytesRead;
this.Invoke(new AvanceDownload(UpdateProgress), new object[] {bytesProcessed,response.ContentLength});
} while (bytesRead > 0);
}
}
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
if (response != null) response.Close();
if (remoteStream != null) remoteStream.Close();
if (localStream != null) localStream.Close();
}
return;
}
private void UpdateDef()
{
DownloadFile("http://go.microsoft.com/fwlink/?LinkId=18922",
"mssecure.cab");
if (File.Exists("mssecure.cab"))
{
this.m_CabinetFile.IgnoreInsidePath = true;
this.m_CabinetFile.Name = "mssecure.cab";
this.m_CabinetFile.ExtractAll();
this.label1.Text = "Parsing file...";
XmlDocument doc = new XmlDocument();
doc.Load("mssecure.xml");
XmlNode nodeList = doc.ChildNodes[1];
nodeList.RemoveChild(nodeList.ChildNodes[3]);
doc.Save("mssecure.xml");
XmlTextWriter writer = new XmlTextWriter("hwdhf.xml",null);
writer.Formatting = Formatting.Indented;
writer.Indentation = 3;
DataSet ds = new DataSet("BulletinDatastore");
ds.ReadXml("mssecure.xml");
writer.WriteStartDocument(true);
DataColumn [] x = new DataColumn[1];
x[0] =ds.Tables["Location"].Columns["LocationID"];
ds.Tables["Location"].PrimaryKey = x;
DataRow t2;
writer.WriteStartElement("HotFixes");
for(int i=0;i<ds.Tables["Bulletin"].Rows.Count-1;i++)
{
{
DataRow [] dr,dr2;
dr = ds.Tables["Bulletin"].Rows[i].GetChildRows("Bulletin_Patches");
dr2 = dr[0].GetChildRows("Patches_Patch");
foreach(DataRow dr4 in dr2)
{
DataRow [] dr5 = dr4.GetChildRows("Patch_AffectedProduct");
foreach(DataRow dr6 in dr5)
{
Int32 productId = Convert.ToInt32(dr6["ProductID"].ToString());
DataRow t = ds.Tables["Product"].Rows.Find(productId-1);
t2 = ds.Tables["Location"].Rows.Find(dr4["PatchLocationID"]);
try
{
if (Enum.IsDefined(typeof(WindowsVersions), productId))
{
writer.WriteStartElement("HotFix");
writer.WriteStartElement("BulletinID");
writer.WriteString(ds.Tables["Bulletin"].Rows[i]["BulletinID"].ToString());
writer.WriteEndElement();
writer.WriteStartElement("Summary");
writer.WriteString(ds.Tables["Bulletin"].Rows[i]["Summary"].ToString());
writer.WriteEndElement();
DataRow [] QNumbers = ds.Tables["Bulletin"].Rows[i].GetChildRows("Bulletin_QNumbers");
DataRow [] QNumber = QNumbers[0].GetChildRows("QNumbers_QNumber");
writer.WriteStartElement("ID");
writer.WriteString("KB"+QNumber[0]["QNumber"].ToString());
writer.WriteEndElement();
writer.WriteStartElement("Product");
writer.WriteString(t["Name"].ToString());
writer.WriteEndElement();
writer.WriteStartElement("ProductID");
writer.WriteString(productId.ToString());
writer.WriteEndElement();
writer.WriteStartElement("UrlPatch");
writer.WriteString(t2["Path"].ToString().Replace("&", "&"));
writer.WriteEndElement();
writer.WriteEndElement();
}
}
catch
{
MessageBox.Show("Can't create definition file");
}
}
}
}
}
writer.WriteEndElement();
writer.Close();
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
this.label1.Text = "Error downloading file";
}
}
private void button2_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, System.EventArgs e)
{
this.button1.Enabled = false;
this.Clean();
this.UpdateDef();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Diagnostics
{
public partial class BooleanSwitch : System.Diagnostics.Switch
{
public BooleanSwitch(string displayName, string description) : base(default(string), default(string)) { }
public BooleanSwitch(string displayName, string description, string defaultSwitchValue) : base(default(string), default(string)) { }
public bool Enabled { get { return default(bool); } set { } }
protected override void OnValueChanged() { }
}
public partial class DefaultTraceListener : System.Diagnostics.TraceListener
{
public DefaultTraceListener() { }
public override void Fail(string message) { }
public override void Fail(string message, string detailMessage) { }
public override void Write(string message) { }
public override void WriteLine(string message) { }
}
public partial class EventTypeFilter : System.Diagnostics.TraceFilter
{
public EventTypeFilter(System.Diagnostics.SourceLevels level) { }
public System.Diagnostics.SourceLevels EventType { get { return default(System.Diagnostics.SourceLevels); } set { } }
public override bool ShouldTrace(System.Diagnostics.TraceEventCache cache, string source, System.Diagnostics.TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data) { return default(bool); }
}
public partial class SourceFilter : System.Diagnostics.TraceFilter
{
public SourceFilter(string source) { }
public string Source { get { return default(string); } set { } }
public override bool ShouldTrace(System.Diagnostics.TraceEventCache cache, string source, System.Diagnostics.TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data) { return default(bool); }
}
[System.FlagsAttribute]
public enum SourceLevels
{
All = -1,
Critical = 1,
Error = 3,
Information = 15,
Off = 0,
Verbose = 31,
Warning = 7,
}
public partial class SourceSwitch : System.Diagnostics.Switch
{
public SourceSwitch(string name) : base(default(string), default(string)) { }
public SourceSwitch(string displayName, string defaultSwitchValue) : base(default(string), default(string)) { }
public System.Diagnostics.SourceLevels Level { get { return default(System.Diagnostics.SourceLevels); } set { } }
protected override void OnValueChanged() { }
public bool ShouldTrace(System.Diagnostics.TraceEventType eventType) { return default(bool); }
}
public abstract partial class Switch
{
protected Switch(string displayName, string description) { }
protected Switch(string displayName, string description, string defaultSwitchValue) { }
public string Description { get { return default(string); } }
public string DisplayName { get { return default(string); } }
protected int SwitchSetting { get { return default(int); } set { } }
protected string Value { get { return default(string); } set { } }
protected virtual void OnSwitchSettingChanged() { }
protected virtual void OnValueChanged() { }
}
public sealed partial class Trace
{
internal Trace() { }
public static bool AutoFlush { get { return default(bool); } set { } }
public static int IndentLevel { get { return default(int); } set { } }
public static int IndentSize { get { return default(int); } set { } }
public static System.Diagnostics.TraceListenerCollection Listeners { get { return default(System.Diagnostics.TraceListenerCollection); } }
public static bool UseGlobalLock { get { return default(bool); } set { } }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Assert(bool condition) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Assert(bool condition, string message) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Assert(bool condition, string message, string detailMessage) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Close() { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Fail(string message) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Fail(string message, string detailMessage) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Flush() { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Indent() { }
public static void Refresh() { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void TraceError(string message) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void TraceError(string format, params object[] args) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void TraceInformation(string message) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void TraceInformation(string format, params object[] args) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void TraceWarning(string message) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void TraceWarning(string format, params object[] args) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Unindent() { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Write(object value) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Write(object value, string category) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Write(string message) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void Write(string message, string category) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void WriteIf(bool condition, object value) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void WriteIf(bool condition, object value, string category) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void WriteIf(bool condition, string message) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void WriteIf(bool condition, string message, string category) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void WriteLine(object value) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void WriteLine(object value, string category) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void WriteLine(string message) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void WriteLine(string message, string category) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void WriteLineIf(bool condition, object value) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void WriteLineIf(bool condition, object value, string category) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void WriteLineIf(bool condition, string message) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public static void WriteLineIf(bool condition, string message, string category) { }
}
public partial class TraceEventCache
{
public TraceEventCache() { }
public System.DateTime DateTime { get { return default(System.DateTime); } }
public int ProcessId { get { return default(int); } }
public string ThreadId { get { return default(string); } }
public long Timestamp { get { return default(long); } }
}
public enum TraceEventType
{
Critical = 1,
Error = 2,
Information = 8,
Verbose = 16,
Warning = 4,
}
public abstract partial class TraceFilter
{
protected TraceFilter() { }
public abstract bool ShouldTrace(System.Diagnostics.TraceEventCache cache, string source, System.Diagnostics.TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data);
}
public enum TraceLevel
{
Error = 1,
Info = 3,
Off = 0,
Verbose = 4,
Warning = 2,
}
public abstract partial class TraceListener : System.IDisposable
{
protected TraceListener() { }
protected TraceListener(string name) { }
public System.Diagnostics.TraceFilter Filter { get { return default(System.Diagnostics.TraceFilter); } set { } }
public int IndentLevel { get { return default(int); } set { } }
public int IndentSize { get { return default(int); } set { } }
public virtual bool IsThreadSafe { get { return default(bool); } }
public virtual string Name { get { return default(string); } set { } }
protected bool NeedIndent { get { return default(bool); } set { } }
public System.Diagnostics.TraceOptions TraceOutputOptions { get { return default(System.Diagnostics.TraceOptions); } set { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual void Fail(string message) { }
public virtual void Fail(string message, string detailMessage) { }
public virtual void Flush() { }
public virtual void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, object data) { }
public virtual void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, params object[] data) { }
public virtual void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id) { }
public virtual void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, string message) { }
public virtual void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, string format, params object[] args) { }
public virtual void Write(object o) { }
public virtual void Write(object o, string category) { }
public abstract void Write(string message);
public virtual void Write(string message, string category) { }
protected virtual void WriteIndent() { }
public virtual void WriteLine(object o) { }
public virtual void WriteLine(object o, string category) { }
public abstract void WriteLine(string message);
public virtual void WriteLine(string message, string category) { }
}
public partial class TraceListenerCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
internal TraceListenerCollection() { }
public int Count { get { return default(int); } }
public System.Diagnostics.TraceListener this[int i] { get { return default(System.Diagnostics.TraceListener); } set { } }
public System.Diagnostics.TraceListener this[string name] { get { return default(System.Diagnostics.TraceListener); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
bool System.Collections.IList.IsFixedSize { get { return default(bool); } }
bool System.Collections.IList.IsReadOnly { get { return default(bool); } }
object System.Collections.IList.this[int index] { get { return default(object); } set { } }
public int Add(System.Diagnostics.TraceListener listener) { return default(int); }
public void AddRange(System.Diagnostics.TraceListener[] value) { }
public void AddRange(System.Diagnostics.TraceListenerCollection value) { }
public void Clear() { }
public bool Contains(System.Diagnostics.TraceListener listener) { return default(bool); }
public void CopyTo(System.Diagnostics.TraceListener[] listeners, int index) { }
public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
public int IndexOf(System.Diagnostics.TraceListener listener) { return default(int); }
public void Insert(int index, System.Diagnostics.TraceListener listener) { }
public void Remove(System.Diagnostics.TraceListener listener) { }
public void Remove(string name) { }
public void RemoveAt(int index) { }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
int System.Collections.IList.Add(object value) { return default(int); }
bool System.Collections.IList.Contains(object value) { return default(bool); }
int System.Collections.IList.IndexOf(object value) { return default(int); }
void System.Collections.IList.Insert(int index, object value) { }
void System.Collections.IList.Remove(object value) { }
}
[System.FlagsAttribute]
public enum TraceOptions
{
DateTime = 2,
None = 0,
ProcessId = 8,
ThreadId = 16,
Timestamp = 4,
}
public partial class TraceSource
{
public TraceSource(string name) { }
public TraceSource(string name, System.Diagnostics.SourceLevels defaultLevel) { }
public System.Diagnostics.TraceListenerCollection Listeners { get { return default(System.Diagnostics.TraceListenerCollection); } }
public string Name { get { return default(string); } }
public System.Diagnostics.SourceSwitch Switch { get { return default(System.Diagnostics.SourceSwitch); } set { } }
public void Close() { }
public void Flush() { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public void TraceData(System.Diagnostics.TraceEventType eventType, int id, object data) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public void TraceData(System.Diagnostics.TraceEventType eventType, int id, params object[] data) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public void TraceEvent(System.Diagnostics.TraceEventType eventType, int id) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public void TraceEvent(System.Diagnostics.TraceEventType eventType, int id, string message) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public void TraceEvent(System.Diagnostics.TraceEventType eventType, int id, string format, params object[] args) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public void TraceInformation(string message) { }
[System.Diagnostics.ConditionalAttribute("TRACE")]
public void TraceInformation(string format, params object[] args) { }
}
public partial class TraceSwitch : System.Diagnostics.Switch
{
public TraceSwitch(string displayName, string description) : base(default(string), default(string)) { }
public TraceSwitch(string displayName, string description, string defaultSwitchValue) : base(default(string), default(string)) { }
public System.Diagnostics.TraceLevel Level { get { return default(System.Diagnostics.TraceLevel); } set { } }
public bool TraceError { get { return default(bool); } }
public bool TraceInfo { get { return default(bool); } }
public bool TraceVerbose { get { return default(bool); } }
public bool TraceWarning { get { return default(bool); } }
protected override void OnSwitchSettingChanged() { }
protected override void OnValueChanged() { }
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Transactions;
using Rhino.Queues.Tests.Protocol;
using Xunit;
namespace Rhino.Queues.Tests
{
public class UsingSubQueues : WithDebugging, IDisposable
{
private readonly QueueManager sender, receiver;
public UsingSubQueues()
{
if (Directory.Exists("test.esent"))
Directory.Delete("test.esent", true);
if (Directory.Exists("test2.esent"))
Directory.Delete("test2.esent", true);
sender = new QueueManager(new IPEndPoint(IPAddress.Loopback, 23456), "test.esent");
sender.Start();
receiver = new QueueManager(new IPEndPoint(IPAddress.Loopback, 23457), "test2.esent");
receiver.CreateQueues("h", "a");
receiver.Start();
}
[Fact]
public void Can_send_and_receive_subqueue()
{
using (var tx = new TransactionScope())
{
sender.Send(
new Uri("rhino.queues://localhost:23457/h/a"),
new MessagePayload
{
Data = Encoding.Unicode.GetBytes("subzero")
});
tx.Complete();
}
using (var tx = new TransactionScope())
{
var message = receiver.Receive("h", "a");
Assert.Equal("subzero", Encoding.Unicode.GetString(message.Data));
tx.Complete();
}
}
[Fact]
public void Can_remove_and_move_msg_to_subqueue()
{
using (var tx = new TransactionScope())
{
sender.Send(
new Uri("rhino.queues://localhost:23457/h"),
new MessagePayload
{
Data = Encoding.Unicode.GetBytes("subzero")
});
tx.Complete();
}
using (var tx = new TransactionScope())
{
var message = receiver.Receive("h");
receiver.MoveTo("b", message);
tx.Complete();
}
using (var tx = new TransactionScope())
{
var message = receiver.Receive("h", "b");
Assert.Equal("subzero", Encoding.Unicode.GetString(message.Data));
tx.Complete();
}
}
[Fact]
public void Can_peek_and_move_msg_to_subqueue()
{
using (var tx = new TransactionScope())
{
sender.Send(
new Uri("rhino.queues://localhost:23457/h"),
new MessagePayload
{
Data = Encoding.Unicode.GetBytes("subzero")
});
tx.Complete();
}
var message = receiver.Peek("h");
using (var tx = new TransactionScope())
{
receiver.MoveTo("b", message);
tx.Complete();
}
using (var tx = new TransactionScope())
{
message = receiver.Receive("h", "b");
Assert.Equal("subzero", Encoding.Unicode.GetString(message.Data));
tx.Complete();
}
}
[Fact]
public void Moving_to_subqueue_should_remove_from_main_queue()
{
using (var tx = new TransactionScope())
{
sender.Send(
new Uri("rhino.queues://localhost:23457/h"),
new MessagePayload
{
Data = Encoding.Unicode.GetBytes("subzero")
});
tx.Complete();
}
var message = receiver.Peek("h");
using (var tx = new TransactionScope())
{
receiver.MoveTo("b", message);
tx.Complete();
}
using (var tx = new TransactionScope())
{
Assert.NotNull(receiver.Receive("h", "b"));
Assert.Throws<TimeoutException>(() => receiver.Receive("h", TimeSpan.FromSeconds(1)));
tx.Complete();
}
}
[Fact]
public void Moving_to_subqueue_will_not_be_completed_until_tx_is_completed()
{
using (var tx = new TransactionScope())
{
sender.Send(
new Uri("rhino.queues://localhost:23457/h"),
new MessagePayload
{
Data = Encoding.Unicode.GetBytes("subzero")
});
tx.Complete();
}
using (var tx = new TransactionScope())
{
var message = receiver.Receive("h");
receiver.MoveTo("b", message);
Assert.Throws<TimeoutException>(() => receiver.Receive("h", "b", TimeSpan.FromSeconds(1)));
tx.Complete();
}
}
[Fact]
public void Moving_to_subqueue_will_be_reverted_by_transaction_rollback()
{
using (var tx = new TransactionScope())
{
sender.Send(
new Uri("rhino.queues://localhost:23457/h"),
new MessagePayload
{
Data = Encoding.Unicode.GetBytes("subzero")
});
tx.Complete();
}
using (new TransactionScope())
{
var message = receiver.Receive("h");
receiver.MoveTo("b", message);
}
using (var tx = new TransactionScope())
{
var message = receiver.Receive("h");
Assert.NotNull(message);
tx.Complete();
}
}
[Fact]
public void Can_scan_messages_in_main_queue_without_seeing_messages_from_subqueue()
{
using (var tx = new TransactionScope())
{
receiver.EnqueueDirectlyTo("h", null, new MessagePayload
{
Data = Encoding.Unicode.GetBytes("1234")
});
receiver.EnqueueDirectlyTo("h", "c", new MessagePayload
{
Data = Encoding.Unicode.GetBytes("4321")
});
tx.Complete();
}
var messages = receiver.GetAllMessages("h", null);
Assert.Equal(1, messages.Length);
Assert.Equal("1234", Encoding.Unicode.GetString(messages[0].Data));
messages = receiver.GetAllMessages("h", "c");
Assert.Equal(1, messages.Length);
Assert.Equal("4321", Encoding.Unicode.GetString(messages[0].Data));
}
[Fact]
public void Can_get_list_of_subqueues()
{
using (var tx = new TransactionScope())
{
receiver.EnqueueDirectlyTo("h", "b", new MessagePayload
{
Data = Encoding.Unicode.GetBytes("1234")
});
receiver.EnqueueDirectlyTo("h", "c", new MessagePayload
{
Data = Encoding.Unicode.GetBytes("4321")
});
receiver.EnqueueDirectlyTo("h", "c", new MessagePayload
{
Data = Encoding.Unicode.GetBytes("4321")
});
receiver.EnqueueDirectlyTo("h", "u", new MessagePayload
{
Data = Encoding.Unicode.GetBytes("4321")
});
tx.Complete();
}
var q = receiver.GetQueue("h");
Assert.Equal(new[] { "b", "c", "u" }, q.GetSubqeueues());
}
[Fact]
public void Can_get_number_of_messages()
{
using (var tx = new TransactionScope())
{
receiver.EnqueueDirectlyTo("h", "b", new MessagePayload
{
Data = Encoding.Unicode.GetBytes("1234")
});
receiver.EnqueueDirectlyTo("h", "c", new MessagePayload
{
Data = Encoding.Unicode.GetBytes("4321")
});
receiver.EnqueueDirectlyTo("h", "c", new MessagePayload
{
Data = Encoding.Unicode.GetBytes("4321")
});
receiver.EnqueueDirectlyTo("h", "u", new MessagePayload
{
Data = Encoding.Unicode.GetBytes("4321")
});
tx.Complete();
}
Assert.Equal(4, receiver.GetNumberOfMessages("h"));
Assert.Equal(4, receiver.GetNumberOfMessages("h"));
}
public void Dispose()
{
sender.Dispose();
receiver.Dispose();
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id$")]
namespace Elmah
{
#region Imports
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Collections.Generic;
#endregion
/// <summary>
/// Represents a source code control (SCC) stamp and its components.
/// </summary>
[ Serializable ]
public sealed class SccStamp
{
private readonly string _id;
private readonly string _author;
private readonly string _fileName;
private readonly int _revision;
private readonly DateTime _lastChanged;
private static readonly Regex _regex;
static SccStamp()
{
//
// Expression to help parse:
//
// STAMP := "$Id:" FILENAME REVISION DATE TIME "Z" USERNAME "$"
// DATE := 4-DIGIT-YEAR "-" 2-DIGIT-MONTH "-" 2-DIGIT-DAY
// TIME := HH ":" MM ":" SS
//
string escapedNonFileNameChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
_regex = new Regex(
@"\$ id: \s*
(?<f>[^" + escapedNonFileNameChars + @"]+) \s+ # FILENAME
(?<r>[0-9]+) \s+ # REVISION
((?<y>[0-9]{4})-(?<mo>[0-9]{2})-(?<d>[0-9]{2})) \s+ # DATE
((?<h>[0-9]{2})\:(?<mi>[0-9]{2})\:(?<s>[0-9]{2})Z) \s+ # TIME (UTC)
(?<a>\w+) # AUTHOR",
RegexOptions.CultureInvariant
| RegexOptions.IgnoreCase
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Singleline
| RegexOptions.ExplicitCapture
| RegexOptions.Compiled);
}
/// <summary>
/// Initializes an <see cref="SccStamp"/> instance given a SCC stamp
/// ID. The ID is expected to be in the format popularized by CVS
/// and SVN.
/// </summary>
public SccStamp(string id)
{
if (id == null)
throw new ArgumentNullException("id");
if (id.Length == 0)
throw new ArgumentException(null, "id");
Match match = _regex.Match(id);
if (!match.Success)
throw new ArgumentException(null, "id");
_id = id;
GroupCollection groups = match.Groups;
_fileName = groups["f"].Value;
_revision = int.Parse(groups["r"].Value);
_author = groups["a"].Value;
int year = int.Parse(groups["y"].Value);
int month = int.Parse(groups["mo"].Value);
int day = int.Parse(groups["d"].Value);
int hour = int.Parse(groups["h"].Value);
int minute = int.Parse(groups["mi"].Value);
int second = int.Parse(groups["s"].Value);
_lastChanged = new DateTime(year, month, day, hour, minute, second).ToLocalTime();
}
/// <summary>
/// Gets the original SCC stamp ID.
/// </summary>
public string Id
{
get { return _id; }
}
/// <summary>
/// Gets the author component of the SCC stamp ID.
/// </summary>
public string Author
{
get { return _author; }
}
/// <summary>
/// Gets the file name component of the SCC stamp ID.
/// </summary>
public string FileName
{
get { return _fileName; }
}
/// <summary>
/// Gets the revision number component of the SCC stamp ID.
/// </summary>
public int Revision
{
get { return _revision; }
}
/// <summary>
/// Gets the last modification time component of the SCC stamp ID.
/// </summary>
public DateTime LastChanged
{
get { return _lastChanged; }
}
/// <summary>
/// Gets the last modification time, in coordinated universal time
/// (UTC), component of the SCC stamp ID in local time.
/// </summary>
public DateTime LastChangedUtc
{
get { return _lastChanged.ToUniversalTime(); }
}
public override string ToString()
{
return Id;
}
/// <summary>
/// Finds and builds an array of <see cref="SccStamp"/> instances
/// from all the <see cref="SccAttribute"/> attributes applied to
/// the given assembly.
/// </summary>
public static SccStamp[] FindAll(Assembly assembly)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
SccAttribute[] attributes = (SccAttribute[]) Attribute.GetCustomAttributes(assembly, typeof(SccAttribute), false);
if (attributes.Length == 0)
return new SccStamp[0];
List<SccStamp> list = new List<SccStamp>(attributes.Length);
foreach (SccAttribute attribute in attributes)
{
string id = attribute.Id.Trim();
if (id.Length > 0 && string.Compare("$Id" + /* IMPORTANT! */ "$", id, true, CultureInfo.InvariantCulture) != 0)
list.Add(new SccStamp(id));
}
return list.ToArray();
}
/// <summary>
/// Finds the latest SCC stamp for an assembly. The latest stamp is
/// the one with the highest revision number.
/// </summary>
public static SccStamp FindLatest(Assembly assembly)
{
return FindLatest(FindAll(assembly));
}
/// <summary>
/// Finds the latest stamp among an array of <see cref="SccStamp"/>
/// objects. The latest stamp is the one with the highest revision
/// number.
/// </summary>
public static SccStamp FindLatest(SccStamp[] stamps)
{
if (stamps == null)
throw new ArgumentNullException("stamps");
if (stamps.Length == 0)
return null;
stamps = (SccStamp[]) stamps.Clone();
SortByRevision(stamps, /* descending */ true);
return stamps[0];
}
/// <summary>
/// Sorts an array of <see cref="SccStamp"/> objects by their
/// revision numbers in ascending order.
/// </summary>
public static void SortByRevision(SccStamp[] stamps)
{
SortByRevision(stamps, false);
}
/// <summary>
/// Sorts an array of <see cref="SccStamp"/> objects by their
/// revision numbers in ascending or descending order.
/// </summary>
public static void SortByRevision(SccStamp[] stamps, bool descending)
{
Comparison<SccStamp> comparer = (lhs, rhs) => lhs.Revision.CompareTo(rhs.Revision);
Array.Sort(stamps, descending
? ((lhs, rhs) => -comparer(lhs, rhs))
: comparer);
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Edge.Settings.TemplateInfoReaders;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.TemplateEngine.Utils;
namespace Microsoft.TemplateEngine.Edge.Settings
{
public class TemplateInfo : ITemplateInfo, IShortNameList, ITemplateWithTimestamp
{
public TemplateInfo()
{
ShortNameList = new List<string>();
}
private static readonly Func<JObject, TemplateInfo> _defaultReader;
private static readonly IReadOnlyDictionary<string, Func<JObject, TemplateInfo>> _infoVersionReaders;
// Note: Be sure to keep the versioning consistent with SettingsStore
static TemplateInfo()
{
Dictionary<string, Func<JObject, TemplateInfo>> versionReaders = new Dictionary<string, Func<JObject, TemplateInfo>>();
versionReaders.Add("1.0.0.0", TemplateInfoReaderVersion1_0_0_0.FromJObject);
versionReaders.Add("1.0.0.1", TemplateInfoReaderVersion1_0_0_1.FromJObject);
versionReaders.Add("1.0.0.2", TemplateInfoReaderVersion1_0_0_2.FromJObject);
versionReaders.Add("1.0.0.3", TemplateInfoReaderVersion1_0_0_3.FromJObject);
_infoVersionReaders = versionReaders;
_defaultReader = TemplateInfoReaderInitialVersion.FromJObject;
}
public static TemplateInfo FromJObject(JObject entry, string cacheVersion)
{
Func<JObject, TemplateInfo> infoReader;
if (string.IsNullOrEmpty(cacheVersion) || !_infoVersionReaders.TryGetValue(cacheVersion, out infoReader))
{
infoReader = _defaultReader;
}
return infoReader(entry);
}
[JsonIgnore]
public IReadOnlyList<ITemplateParameter> Parameters
{
get
{
if (_parameters == null)
{
List<ITemplateParameter> parameters = new List<ITemplateParameter>();
foreach (KeyValuePair<string, ICacheTag> tagInfo in Tags)
{
ITemplateParameter param = new TemplateParameter
{
Name = tagInfo.Key,
Documentation = tagInfo.Value.Description,
DefaultValue = tagInfo.Value.DefaultValue,
Choices = tagInfo.Value.ChoicesAndDescriptions,
DataType = "choice"
};
if (param is IAllowDefaultIfOptionWithoutValue paramWithNoValueDefault
&& tagInfo.Value is IAllowDefaultIfOptionWithoutValue tagWithNoValueDefault)
{
paramWithNoValueDefault.DefaultIfOptionWithoutValue = tagWithNoValueDefault.DefaultIfOptionWithoutValue;
parameters.Add(paramWithNoValueDefault as TemplateParameter);
}
else
{
parameters.Add(param);
}
}
foreach (KeyValuePair<string, ICacheParameter> paramInfo in CacheParameters)
{
ITemplateParameter param = new TemplateParameter
{
Name = paramInfo.Key,
Documentation = paramInfo.Value.Description,
DataType = paramInfo.Value.DataType,
DefaultValue = paramInfo.Value.DefaultValue,
};
if (param is IAllowDefaultIfOptionWithoutValue paramWithNoValueDefault
&& paramInfo.Value is IAllowDefaultIfOptionWithoutValue infoWithNoValueDefault)
{
paramWithNoValueDefault.DefaultIfOptionWithoutValue = infoWithNoValueDefault.DefaultIfOptionWithoutValue;
parameters.Add(paramWithNoValueDefault as TemplateParameter);
}
else
{
parameters.Add(param);
}
}
_parameters = parameters;
}
return _parameters;
}
}
private IReadOnlyList<ITemplateParameter> _parameters;
[JsonProperty]
public Guid ConfigMountPointId { get; set; }
[JsonProperty]
public string Author { get; set; }
[JsonProperty]
public IReadOnlyList<string> Classifications { get; set; }
[JsonProperty]
public string DefaultName { get; set; }
[JsonProperty]
public string Description { get; set; }
[JsonProperty]
public string Identity { get; set; }
[JsonProperty]
public Guid GeneratorId { get; set; }
[JsonProperty]
public string GroupIdentity { get; set; }
[JsonProperty]
public int Precedence { get; set; }
[JsonProperty]
public string Name { get; set; }
[JsonProperty]
public string ShortName
{
get
{
if (ShortNameList.Count > 0)
{
return ShortNameList[0];
}
return String.Empty;
}
set
{
if (ShortNameList.Count > 0)
{
throw new Exception("Can't set the short name when the ShortNameList already has entries.");
}
ShortNameList = new List<string>() { value };
}
}
// ShortName should get deserialized when it exists, for backwards compat.
// But moving forward, ShortNameList should be the definitive source.
// It can still be ShortName in the template.json, but in the caches it'll be ShortNameList
public bool ShouldSerializeShortName()
{
return false;
}
public IReadOnlyList<string> ShortNameList { get; set; }
[JsonProperty]
public IReadOnlyDictionary<string, ICacheTag> Tags
{
get
{
return _tags;
}
set
{
_tags = value;
_parameters = null;
}
}
private IReadOnlyDictionary<string, ICacheTag> _tags;
[JsonProperty]
public IReadOnlyDictionary<string, ICacheParameter> CacheParameters
{
get
{
return _cacheParameters;
}
set
{
_cacheParameters = value;
_parameters = null;
}
}
private IReadOnlyDictionary<string, ICacheParameter> _cacheParameters;
[JsonProperty]
public string ConfigPlace { get; set; }
[JsonProperty]
public Guid LocaleConfigMountPointId { get; set; }
[JsonProperty]
public string LocaleConfigPlace { get; set; }
[JsonProperty]
public Guid HostConfigMountPointId { get; set; }
[JsonProperty]
public string HostConfigPlace { get; set; }
[JsonProperty]
public string ThirdPartyNotices { get; set; }
[JsonProperty]
public IReadOnlyDictionary<string, IBaselineInfo> BaselineInfo { get; set; }
[JsonProperty]
public bool HasScriptRunningPostActions { get; set; }
[JsonProperty]
public DateTime? ConfigTimestampUtc { get; set; }
}
}
| |
// <copyright file="RemoteSessionSettings.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using OpenQA.Selenium.Remote;
namespace OpenQA.Selenium
{
/// <summary>
/// Base class for managing options specific to a browser driver.
/// </summary>
public class RemoteSessionSettings : ICapabilities
{
private const string FirstMatchCapabilityName = "firstMatch";
private const string AlwaysMatchCapabilityName = "alwaysMatch";
private readonly List<string> reservedSettingNames = new List<string>() { FirstMatchCapabilityName, AlwaysMatchCapabilityName };
private DriverOptions mustMatchDriverOptions;
private List<DriverOptions> firstMatchOptions = new List<DriverOptions>();
private Dictionary<string, object> remoteMetadataSettings = new Dictionary<string, object>();
/// <summary>
/// Creates a new instance of the <see cref="RemoteSessionSettings"/> class.
/// </summary>
public RemoteSessionSettings()
{
}
/// <summary>
/// Gets a value indicating the options that must be matched by the remote end to create a session.
/// </summary>
internal DriverOptions MustMatchDriverOptions
{
get { return this.mustMatchDriverOptions; }
}
/// <summary>
/// Gets a value indicating the number of options that may be matched by the remote end to create a session.
/// </summary>
internal int FirstMatchOptionsCount
{
get { return this.firstMatchOptions.Count; }
}
/// <summary>
/// Gets the capability value with the specified name.
/// </summary>
/// <param name="capabilityName">The name of the capability to get.</param>
/// <returns>The value of the capability.</returns>
/// <exception cref="ArgumentException">
/// The specified capability name is not in the set of capabilities.
/// </exception>
public object this[string capabilityName]
{
get
{
if (capabilityName == AlwaysMatchCapabilityName)
{
return this.GetAlwaysMatchOptionsAsSerializableDictionary();
}
if (capabilityName == FirstMatchCapabilityName)
{
return this.GetFirstMatchOptionsAsSerializableList();
}
if (!this.remoteMetadataSettings.ContainsKey(capabilityName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The capability {0} is not present in this set of capabilities", capabilityName));
}
return null;
if (!this.remoteMetadataSettings.ContainsKey(capabilityName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The capability {0} is not present in this set of capabilities", capabilityName));
}
return this.remoteMetadataSettings[capabilityName];
}
}
/// <summary>
/// Creates a new instance of the <see cref="RemoteSessionSettings"/> class,
/// containing the specified <see cref="DriverOptions"/> to use in the remote
/// session.
/// </summary>
/// <param name="mustMatchDriverOptions">
/// A <see cref="DriverOptions"/> object that contains values that must be matched
/// by the remote end to create the remote session.
/// </param>
/// <param name="firstMatchDriverOptions">
/// A list of <see cref="DriverOptions"/> objects that contain values that may be matched
/// by the remote end to create the remote session.
/// </param>
public RemoteSessionSettings(DriverOptions mustMatchDriverOptions, params DriverOptions[] firstMatchDriverOptions)
{
this.mustMatchDriverOptions = mustMatchDriverOptions;
foreach (DriverOptions firstMatchOption in firstMatchDriverOptions)
{
this.AddFirstMatchDriverOption(firstMatchOption);
}
}
/// <summary>
/// Add a metadata setting to this set of remote session settings.
/// </summary>
/// <param name="settingName">The name of the setting to set.</param>
/// <param name="settingValue">The value of the setting.</param>
/// <remarks>
/// The value to be set must be serializable to JSON for transmission
/// across the wire to the remote end. To be JSON-serializable, the value
/// must be a string, a numeric value, a boolean value, an object that
/// implmeents <see cref="IEnumerable"/> that contains JSON-serializable
/// objects, or a <see cref="Dictionary{TKey, TValue}"/> where the keys
/// are strings and the values are JSON-serializable.
/// </remarks>
/// <exception cref="ArgumentException">
/// Thrown if the setting name is null, the empty string, or one of the
/// reserved names of metadata settings; or if the setting value is not
/// JSON serializable.
/// </exception>
public void AddMetadataSetting(string settingName, object settingValue)
{
if (string.IsNullOrEmpty(settingName))
{
throw new ArgumentException("Metadata setting name cannot be null or empty", "settingName");
}
if (this.reservedSettingNames.Contains(settingName))
{
throw new ArgumentException(string.Format("'{0}' is a reserved name for a metadata setting, and cannot be used as a name.", settingName), "settingName");
}
if (!this.IsJsonSerializable(settingValue))
{
throw new ArgumentException("Metadata setting value must be JSON serializable.", "settingValue");
}
this.remoteMetadataSettings[settingName] = settingValue;
}
/// <summary>
/// Adds a <see cref="DriverOptions"/> object to the list of options containing values to be
/// "first matched" by the remote end.
/// </summary>
/// <param name="options">The <see cref="DriverOptions"/> to add to the list of "first matched" options.</param>
public void AddFirstMatchDriverOption(DriverOptions options)
{
if (mustMatchDriverOptions != null)
{
DriverOptionsMergeResult mergeResult = mustMatchDriverOptions.GetMergeResult(options);
if (mergeResult.IsMergeConflict)
{
string msg = string.Format(CultureInfo.InvariantCulture, "You cannot request the same capability in both must-match and first-match capabilities. You are attempting to add a first-match driver options object that defines a capability, '{0}', that is already defined in the must-match driver options.", mergeResult.MergeConflictOptionName);
throw new ArgumentException(msg, "options");
}
}
firstMatchOptions.Add(options);
}
/// <summary>
/// Adds a <see cref="DriverOptions"/> object containing values that must be matched
/// by the remote end to successfully create a session.
/// </summary>
/// <param name="options">The <see cref="DriverOptions"/> that must be matched by
/// the remote end to successfully create a session.</param>
public void SetMustMatchDriverOptions(DriverOptions options)
{
if (this.firstMatchOptions.Count > 0)
{
int driverOptionIndex = 0;
foreach (DriverOptions firstMatchOption in this.firstMatchOptions)
{
DriverOptionsMergeResult mergeResult = firstMatchOption.GetMergeResult(options);
if (mergeResult.IsMergeConflict)
{
string msg = string.Format(CultureInfo.InvariantCulture, "You cannot request the same capability in both must-match and first-match capabilities. You are attempting to add a must-match driver options object that defines a capability, '{0}', that is already defined in the first-match driver options with index {1}.", mergeResult.MergeConflictOptionName, driverOptionIndex);
throw new ArgumentException(msg, "options");
}
driverOptionIndex++;
}
}
this.mustMatchDriverOptions = options;
}
/// <summary>
/// Gets a value indicating whether the browser has a given capability.
/// </summary>
/// <param name="capability">The capability to get.</param>
/// <returns>Returns <see langword="true"/> if this set of capabilities has the capability;
/// otherwise, <see langword="false"/>.</returns>
public bool HasCapability(string capability)
{
if (capability == AlwaysMatchCapabilityName || capability == FirstMatchCapabilityName)
{
return true;
}
return this.remoteMetadataSettings.ContainsKey(capability);
}
/// <summary>
/// Gets a capability of the browser.
/// </summary>
/// <param name="capability">The capability to get.</param>
/// <returns>An object associated with the capability, or <see langword="null"/>
/// if the capability is not set in this set of capabilities.</returns>
public object GetCapability(string capability)
{
if (capability == AlwaysMatchCapabilityName)
{
return this.GetAlwaysMatchOptionsAsSerializableDictionary();
}
if (capability == FirstMatchCapabilityName)
{
return this.GetFirstMatchOptionsAsSerializableList();
}
if (this.remoteMetadataSettings.ContainsKey(capability))
{
return this.remoteMetadataSettings[capability];
}
return null;
}
/// <summary>
/// Return a dictionary representation of this <see cref="RemoteSessionSettings"/>.
/// </summary>
/// <returns>A <see cref="Dictionary{TKey, TValue}"/> representation of this <see cref="RemoteSessionSettings"/>.</returns>
public Dictionary<string, object> ToDictionary()
{
Dictionary<string, object> capabilitiesDictionary = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> remoteMetadataSetting in this.remoteMetadataSettings)
{
capabilitiesDictionary[remoteMetadataSetting.Key] = remoteMetadataSetting.Value;
}
if (this.mustMatchDriverOptions != null)
{
capabilitiesDictionary["alwaysMatch"] = GetAlwaysMatchOptionsAsSerializableDictionary();
}
if (this.firstMatchOptions.Count > 0)
{
List<object> optionsMatches = GetFirstMatchOptionsAsSerializableList();
capabilitiesDictionary["firstMatch"] = optionsMatches;
}
return capabilitiesDictionary;
}
/// <summary>
/// Return a string representation of the remote session settings to be sent.
/// </summary>
/// <returns>String representation of the remote session settings to be sent.</returns>
public override string ToString()
{
return JsonConvert.SerializeObject(this.ToDictionary(), Formatting.Indented);
}
internal DriverOptions GetFirstMatchDriverOptions(int firstMatchIndex)
{
if (firstMatchIndex < 0 || firstMatchIndex >= this.firstMatchOptions.Count)
{
throw new ArgumentException("Requested index must be greater than zero and less than the count of firstMatch options added.");
}
return this.firstMatchOptions[firstMatchIndex];
}
private Dictionary<string, object> GetAlwaysMatchOptionsAsSerializableDictionary()
{
return this.mustMatchDriverOptions.ToDictionary();
}
private List<object> GetFirstMatchOptionsAsSerializableList()
{
List<object> optionsMatches = new List<object>();
foreach (DriverOptions options in this.firstMatchOptions)
{
optionsMatches.Add(options.ToDictionary());
}
return optionsMatches;
}
private bool IsJsonSerializable(object arg)
{
IEnumerable argAsEnumerable = arg as IEnumerable;
IDictionary argAsDictionary = arg as IDictionary;
if (arg is string || arg is float || arg is double || arg is int || arg is long || arg is bool || arg == null)
{
return true;
}
else if (argAsDictionary != null)
{
foreach (object key in argAsDictionary.Keys)
{
if (!(key is string))
{
return false;
}
}
foreach (object value in argAsDictionary.Values)
{
if (!IsJsonSerializable(value))
{
return false;
}
}
}
else if (argAsEnumerable != null)
{
foreach (object item in argAsEnumerable)
{
if (!IsJsonSerializable(item))
{
return false;
}
}
}
else
{
return false;
}
return true;
}
}
}
| |
#region Apache License, Version 2.0
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using NPanday.ProjectImporter.Parser.SlnParser.Model;
using System.IO;
/// Author: Leopoldo Lee Agdeppa III
namespace NPanday.ProjectImporter.Parser.SlnParser
{
public static class SolutionFactory
{
public static Solution GetSolution(FileInfo solutionFile)
{
LexicalAnalizer lexan = new LexicalAnalizer(solutionFile);
Solution solution = new Solution();
solution.File = solutionFile;
lexan.MoveNext();
while(lexan.Current.Token == Semantics.EOL)
{
// some sln files contains blank lines before the header values, so its best to recourse it first
lexan.Expect(Semantics.EOL);
lexan.MoveNext();
}
lexan.Expect(Semantics.STRING_VALUE);
solution.Header = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.COMMA);
lexan.MoveNext();
lexan.Expect(Semantics.STRING_VALUE);
solution.FormatVersion = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.EOL);
lexan.MoveNext();
lexan.Expect(Semantics.STRING_VALUE);
solution.VsVersion = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.EOL);
while (lexan.MoveNext())
{
switch (lexan.Current.Token)
{
case Semantics.PROJECT:
solution.Projects.Add(GetProject(lexan));
break;
case Semantics.GLOBAL:
solution.Globals.Add(GetGlobal(lexan));
break;
case Semantics.EOL:
break;
case Semantics.STRING_VALUE:
if (lexan.Current.Value.Trim().Equals("VisualStudioVersion"))
{
solution.VisualStudioVersion = GetProperty(lexan);
}
else if (lexan.Current.Value.Trim().Equals("MinimumVisualStudioVersion"))
{
solution.MinimumVisualStudioVersion = GetProperty(lexan);
}
break;
default:
throw new Exception("Unknown Solution token: " + lexan.Current.Token);
}
}
return solution;
}
private static string GetProperty(LexicalAnalizer lexan)
{
lexan.MoveNext();
lexan.Expect(Semantics.EQUALS);
lexan.MoveNext();
lexan.Expect(Semantics.STRING_VALUE);
string propertyValue = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.EOL);
return propertyValue;
}
public static Solution GetSolution(string solutionFile)
{
return GetSolution(new FileInfo(solutionFile));
}
private static Project GetProject(LexicalAnalizer lexan)
{
Project project = new Project();
lexan.Expect(Semantics.PROJECT);
lexan.MoveNext();
lexan.Expect(Semantics.OPEN_PARENTHESIS);
lexan.MoveNext();
// Project Type GUID
lexan.Expect(Semantics.QUOTED_STRING);
project.ProjectTypeGUID = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.CLOSE_PARENTHESIS);
lexan.MoveNext();
lexan.Expect(Semantics.EQUALS);
lexan.MoveNext();
// project name
lexan.Expect(Semantics.QUOTED_STRING);
project.ProjectName = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.COMMA);
lexan.MoveNext();
// project path
lexan.Expect(Semantics.QUOTED_STRING);
project.ProjectPath = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.COMMA);
lexan.MoveNext();
// project guid
lexan.Expect(Semantics.QUOTED_STRING);
project.ProjectGUID = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.EOL);
while (lexan.MoveNext())
{
switch (lexan.Current.Token)
{
case Semantics.END_PROJECT:
return project;
case Semantics.PROJECT_SECTION:
project.ProjectSections.Add(GetProjectSection(lexan));
break;
case Semantics.EOL:
break;
case Semantics.STRING_VALUE:
break;
default:
throw new Exception("Invalid Project Entry!");
}
}
throw new Exception("Expecting EndProject!");
}
private static ProjectSection GetProjectSection(LexicalAnalizer lexan)
{
ProjectSection ps = new ProjectSection();
lexan.Expect(Semantics.PROJECT_SECTION);
lexan.MoveNext();
lexan.Expect(Semantics.OPEN_PARENTHESIS);
lexan.MoveNext();
// Project Section Name
lexan.Expect(Semantics.STRING_VALUE);
ps.Name = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.CLOSE_PARENTHESIS);
lexan.MoveNext();
lexan.Expect(Semantics.EQUALS);
lexan.MoveNext();
// Project Section Name
lexan.Expect(Semantics.STRING_VALUE);
ps.Value = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.EOL);
while (lexan.MoveNext())
{
switch (lexan.Current.Token)
{
case Semantics.END_PROJECT_SECTION:
return ps;
case Semantics.STRING_VALUE:
{
lexan.Expect(Semantics.STRING_VALUE);
string key = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.EQUALS);
lexan.MoveNext();
lexan.ExpectQuotedOrString();
string value = lexan.Current.Value;
ps.Map.Add(key.Trim(' ', '\n', '\t'), value);
lexan.MoveNext();
lexan.Expect(Semantics.EOL);
}
break;
case Semantics.QUOTED_STRING:
{
lexan.Expect(Semantics.QUOTED_STRING);
string key = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.EQUALS);
lexan.MoveNext();
lexan.ExpectQuotedOrString();
string value = lexan.Current.Value;
ps.Map.Add(key.Trim(' ', '\n', '\t'), value);
lexan.MoveNext();
lexan.Expect(Semantics.EOL);
}
break;
case Semantics.EOL:
break;
default:
throw new Exception("Invalid ProjectSection Entry!");
}
}
throw new Exception("Expecting EndProjectSection!");
}
private static Global GetGlobal(LexicalAnalizer lexan)
{
Global global = new Global();
lexan.Expect(Semantics.GLOBAL);
lexan.MoveNext();
lexan.Expect(Semantics.EOL);
while (lexan.MoveNext())
{
switch (lexan.Current.Token)
{
case Semantics.END_GLOBAL:
return global;
case Semantics.GLOBAL_SECTION:
global.GlobalSections.Add(GetGlobalSection(lexan));
break;
case Semantics.EOL:
break;
case Semantics.STRING_VALUE:
break;
default:
throw new Exception("Invalid Global Entry!");
}
}
throw new Exception("Expecting EndGlobal!");
}
private static GlobalSection GetGlobalSection(LexicalAnalizer lexan)
{
GlobalSection gs = new GlobalSection();
lexan.Expect(Semantics.GLOBAL_SECTION);
lexan.MoveNext();
lexan.Expect(Semantics.OPEN_PARENTHESIS);
lexan.MoveNext();
lexan.Expect(Semantics.STRING_VALUE);
gs.Name = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.CLOSE_PARENTHESIS);
lexan.MoveNext();
lexan.Expect(Semantics.EQUALS);
lexan.MoveNext();
lexan.Expect(Semantics.STRING_VALUE);
gs.Value = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.EOL);
while (lexan.MoveNext())
{
switch (lexan.Current.Token)
{
case Semantics.END_GLOBAL_SECTION:
return gs;
case Semantics.STRING_VALUE:
{
lexan.Expect(Semantics.STRING_VALUE);
string key = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.EQUALS);
lexan.MoveNext();
lexan.ExpectQuotedOrString();
string value = lexan.Current.Value;
gs.Map.Add(key.Trim(' ', '\n', '\t'), value);
lexan.MoveNext();
lexan.Expect(Semantics.EOL);
}
break;
case Semantics.QUOTED_STRING:
{
lexan.Expect(Semantics.QUOTED_STRING);
string key = lexan.Current.Value;
lexan.MoveNext();
lexan.Expect(Semantics.EQUALS);
lexan.MoveNext();
lexan.ExpectQuotedOrString();
string value = lexan.Current.Value;
gs.Map.Add(key.Trim(' ', '\n', '\t'), value);
lexan.MoveNext();
lexan.Expect(Semantics.EOL);
}
break;
case Semantics.EOL:
break;
default:
throw new Exception("Invalid GlobalSection Entry!");
}
}
throw new Exception("Expecting EndGlobalSection!");
}
}
}
| |
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using CorDebugInterop;
using nanoFramework.Tools.Debugger;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace nanoFramework.Tools.VisualStudio.Extension
{
public class CorDebugEval : ICorDebugEval, ICorDebugEval2
{
const int SCRATCH_PAD_INDEX_NOT_INITIALIZED = -1;
bool m_fActive;
CorDebugThread m_threadReal;
CorDebugThread m_threadVirtual;
CorDebugAppDomain m_appDomain;
int m_iScratchPad;
CorDebugValue m_resultValue;
EvalResult m_resultType;
bool m_fException;
public enum EvalResult
{
NotFinished,
Complete,
Abort,
Exception,
}
public CorDebugEval (CorDebugThread thread)
{
m_appDomain = thread.Chain.ActiveFrame.AppDomain;
m_threadReal = thread;
m_resultType = EvalResult.NotFinished;
ResetScratchPadLocation ();
}
public CorDebugThread ThreadVirtual
{
get { return m_threadVirtual; }
}
public CorDebugThread ThreadReal
{
get { return m_threadReal; }
}
public Engine Engine
{
get { return Process.Engine; }
}
public CorDebugProcess Process
{
get { return m_threadReal.Process; }
}
public CorDebugAppDomain AppDomain
{
get { return m_appDomain; }
}
private CorDebugValue GetResultValue ()
{
if (m_resultValue == null)
{
m_resultValue = Process.ScratchPad.GetValue (m_iScratchPad, m_appDomain);
}
return m_resultValue;
}
private int GetScratchPadLocation ()
{
if (m_iScratchPad == SCRATCH_PAD_INDEX_NOT_INITIALIZED)
{
m_iScratchPad = Process.ScratchPad.ReserveScratchBlock ();
}
return m_iScratchPad;
}
private void ResetScratchPadLocation()
{
m_iScratchPad = SCRATCH_PAD_INDEX_NOT_INITIALIZED;
m_resultValue = null;
}
public void StoppedOnUnhandledException()
{
/*
* store the fact that this eval ended with an exception
* the exception will be stored in the scratch pad by nanoCLR
* but the event to cpde should wait to be queued until the eval
* thread completes. At that time, the information is lost as to
* the fact that the result was an exception (rather than the function returning
* an object of type exception. Hence, this flag.
*/
m_fException = true;
}
public void EndEval (EvalResult resultType, bool fSynchronousEval)
{
try
{
//This is used to avoid deadlock. Suspend commands synchronizes on this.Process
Process.SuspendCommands(true);
Debug.Assert(Utility.FImplies(fSynchronousEval, !m_fActive));
if (fSynchronousEval || m_fActive) //what to do if the eval isn't active anymore??
{
bool fKillThread = false;
if (m_threadVirtual != null)
{
if (m_threadReal.GetLastCorDebugThread() != m_threadVirtual)
throw new ArgumentException();
m_threadReal.RemoveVirtualThread(m_threadVirtual);
}
//Stack frames don't appear if they are not refreshed
if (fSynchronousEval)
{
for (CorDebugThread thread = this.m_threadReal; thread != null; thread = thread.NextThread)
{
thread.RefreshChain();
}
}
if(m_fException)
{
resultType = EvalResult.Exception;
}
//Check to see if we are able to EndEval -- is this the last virtual thread?
m_fActive = false;
m_resultType = resultType;
switch (resultType)
{
case EvalResult.Complete:
Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackEval(m_threadReal, this, ManagedCallbacks.ManagedCallbackEval.EventType.EvalComplete));
break;
case EvalResult.Exception:
Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackEval(m_threadReal, this, ManagedCallbacks.ManagedCallbackEval.EventType.EvalException));
break;
case EvalResult.Abort:
fKillThread = true;
/* WARNING!!!!
* If we do not give VS a EvalComplete message within 3 seconds of them calling ICorDebugEval::Abort then VS will attempt a RudeAbort
* and will display a scary error message about a serious internal debugger error and ignore all future debugging requests, among other bad things.
*/
Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackEval(m_threadReal, this, ManagedCallbacks.ManagedCallbackEval.EventType.EvalComplete));
break;
}
if (fKillThread && m_threadVirtual != null)
{
Engine.KillThread(m_threadVirtual.ID);
}
if (resultType == EvalResult.Abort)
{
Process.PauseExecution();
}
}
}
finally
{
Process.SuspendCommands(false);
}
}
private uint GetTypeDef_Index(CorElementType elementType, ICorDebugClass pElementClass)
{
uint tdIndex;
if (pElementClass != null)
{
tdIndex = ((CorDebugClass)pElementClass).TypeDef_Index;
}
else
{
CorDebugProcess.BuiltinType builtInType = this.Process.ResolveBuiltInType(elementType);
tdIndex = builtInType.GetClass(this.m_appDomain).TypeDef_Index;
}
return tdIndex;
}
#region ICorDebugEval Members
int ICorDebugEval.IsActive (out int pbActive)
{
pbActive = Boolean.BoolToInt (m_fActive);
return COM_HResults.S_OK;
}
int ICorDebugEval.GetThread( out ICorDebugThread ppThread )
{
ppThread = m_threadReal;
return COM_HResults.S_OK;
}
int ICorDebugEval.GetResult( out ICorDebugValue ppResult )
{
switch (m_resultType)
{
case EvalResult.Exception:
case EvalResult.Complete:
ppResult = GetResultValue ();
break;
default:
ppResult = null;
throw new ArgumentException ();
}
return COM_HResults.S_OK;
}
int ICorDebugEval.NewArray(CorElementType elementType, ICorDebugClass pElementClass, uint rank, ref uint dims, ref uint lowBounds)
{
if(rank != 1) return COM_HResults.E_FAIL;
this.Process.SetCurrentAppDomain( this.AppDomain );
uint tdIndex = GetTypeDef_Index(elementType, pElementClass);
Engine.AllocateArray(GetScratchPadLocation(), tdIndex, 1, (int)dims);
EndEval (EvalResult.Complete, true);
return COM_HResults.S_OK;
}
int ICorDebugEval.CallFunction( ICorDebugFunction pFunction, uint nArgs, ICorDebugValue[] ppArgs )
{
try
{
//CreateThread will cause a thread create event to occur. This is a virtual thread, so
//we need to suspend processing of nanoCLR commands until we have created the thread ourselves
//and the processing of a new virtual thread will be ignored.
Process.SuspendCommands (true);
//need to flush the breakpoints in case new breakpoints were waiting until process was resumed.
Process.UpdateBreakpoints ();
Debug.Assert (nArgs == ppArgs.Length);
Debug.Assert (Process.IsExecutionPaused);
CorDebugFunction function = (CorDebugFunction)pFunction;
uint md = function.MethodDef_Index;
if(function.IsVirtual && function.IsInstance)
{
Debug.Assert(nArgs > 0);
md = this.Engine.GetVirtualMethod(function.MethodDef_Index, ((CorDebugValue)ppArgs[0]).RuntimeValue);
}
this.Process.SetCurrentAppDomain( this.AppDomain );
//Send the selected thread ID to the device so calls that use Thread.CurrentThread work as the user expects.
uint pid = this.Engine.CreateThread(md, GetScratchPadLocation(), m_threadReal.ID);
if (pid == uint.MaxValue)
{
throw new ArgumentException("nanoCLR cannot call this function. Possible reasons include: ByRef arguments not supported");
}
//If anything below fails, we need to clean up by killing the thread
if (nArgs > 0)
{
List<RuntimeValue> stackFrameValues = this.Engine.GetStackFrameValueAll(pid, 0, function.NumArg, Engine.StackValueKind.Argument);
for (int iArg = 0; iArg < nArgs; iArg++)
{
CorDebugValue valSrc = (CorDebugValue)ppArgs[iArg];
CorDebugValue valDst = CorDebugValue.CreateValue (stackFrameValues[iArg], m_appDomain);
if (valDst.RuntimeValue.Assign(valSrc.RuntimeValue) == null)
{
throw new ArgumentException("nanoCLR cannot set argument " + iArg);
}
}
}
m_threadVirtual = new CorDebugThread (this.Process, pid, this);
m_threadReal.AttachVirtualThread (m_threadVirtual);
Debug.Assert (!m_fActive);
m_fActive = true;
//It is possible that a hard breakpoint is hit, the first line of the function
//to evaluate. If that is the case, than breakpoints need to be drained so the
//breakpoint event is fired, to avoid a race condition, where cpde resumes
//execution to start the function eval before it gets the breakpoint event
//This is primarily due to the difference in behaviour of the nanoCLR and the desktop.
//In the desktop, the hard breakpoint will not get hit until execution is resumed.
//The nanoCLR can hit the breakpoint during the Thread_Create call.
Process.DrainBreakpointsAsync().Wait();
}
finally
{
Process.SuspendCommands (false);
}
return COM_HResults.S_OK;
}
int ICorDebugEval.NewString( string @string )
{
this.Process.SetCurrentAppDomain( this.AppDomain );
//changing strings is dependant on this method working....
Engine.AllocateString(GetScratchPadLocation(), @string);
EndEval (EvalResult.Complete, true);
return COM_HResults.S_OK;
}
int ICorDebugEval.NewObjectNoConstructor( ICorDebugClass pClass )
{
this.Process.SetCurrentAppDomain( this.AppDomain );
Engine.AllocateObject(GetScratchPadLocation (), ((CorDebugClass)pClass).TypeDef_Index);
EndEval (EvalResult.Complete, true);
return COM_HResults.S_OK;
}
int ICorDebugEval.CreateValue(CorElementType elementType, ICorDebugClass pElementClass, out ICorDebugValue ppValue)
{
uint tdIndex = GetTypeDef_Index(elementType, pElementClass);
Debug.Assert(Utility.FImplies(pElementClass != null, elementType == CorElementType.ELEMENT_TYPE_VALUETYPE));
this.Process.SetCurrentAppDomain( this.AppDomain );
Engine.AllocateObject(GetScratchPadLocation (), tdIndex);
ppValue = GetResultValue ();
ResetScratchPadLocation ();
return COM_HResults.S_OK;
}
int ICorDebugEval.NewObject( ICorDebugFunction pConstructor, uint nArgs, ICorDebugValue[] ppArgs )
{
Debug.Assert (nArgs == ppArgs.Length);
CorDebugFunction f = (CorDebugFunction)pConstructor;
CorDebugClass c = f.Class;
this.Process.SetCurrentAppDomain( this.AppDomain );
Engine.AllocateObject(GetScratchPadLocation (), c.TypeDef_Index);
ICorDebugValue[] args = new ICorDebugValue[nArgs + 1];
args[0] = GetResultValue ();
ppArgs.CopyTo (args, 1);
((ICorDebugEval)this).CallFunction (pConstructor, (uint)args.Length, args);
return COM_HResults.S_OK;
}
int ICorDebugEval.Abort ()
{
EndEval (EvalResult.Abort, false);
return COM_HResults.S_OK;
}
#endregion
#region ICorDebugEval2 Members
int ICorDebugEval2.CallParameterizedFunction(ICorDebugFunction pFunction, uint nTypeArgs, ICorDebugType[] ppTypeArgs, uint nArgs, ICorDebugValue[] ppArgs)
{
return ((ICorDebugEval)this).CallFunction(pFunction, nArgs, ppArgs);
}
int ICorDebugEval2.CreateValueForType(ICorDebugType pType, out ICorDebugValue ppValue)
{
CorElementType type;
ICorDebugClass cls;
pType.GetType( out type );
pType.GetClass( out cls );
return ((ICorDebugEval)this).CreateValue(type, cls, out ppValue);
}
int ICorDebugEval2.NewParameterizedObject(ICorDebugFunction pConstructor, uint nTypeArgs, ICorDebugType[] ppTypeArgs, uint nArgs, ICorDebugValue[] ppArgs)
{
return ((ICorDebugEval)this).NewObject(pConstructor, nArgs, ppArgs);
}
int ICorDebugEval2.NewParameterizedObjectNoConstructor(ICorDebugClass pClass, uint nTypeArgs, ICorDebugType[] ppTypeArgs)
{
return ((ICorDebugEval)this).NewObjectNoConstructor(pClass);
}
int ICorDebugEval2.NewParameterizedArray(ICorDebugType pElementType, uint rank, ref uint dims, ref uint lowBounds)
{
CorElementType type;
ICorDebugClass cls;
pElementType.GetType(out type);
pElementType.GetClass(out cls);
return ((ICorDebugEval)this).NewArray(type, cls, rank, dims, lowBounds);
}
int ICorDebugEval2.NewStringWithLength(string @string, uint uiLength)
{
string strVal = @string.Substring(0, (int)uiLength);
return ((ICorDebugEval)this).NewString(strVal);
}
int ICorDebugEval2.RudeAbort()
{
return ((ICorDebugEval)this).Abort();
}
#endregion
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.QualityGuidelines.AssigningSymbolAndItsMemberInSameStatement,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.CodeQuality.Analyzers.UnitTests.QualityGuidelines
{
public class AssigningSymbolAndItsMemberInSameStatementTests
{
[Fact]
public async Task CSharpReassignLocalVariableAndReferToItsField()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public C Field;
}
public class Test
{
public void Method()
{
C a = new C(), b = new C();
a.Field = a = b;
}
}
",
GetCSharpResultAt(12, 9, "a", "Field"));
}
[Fact]
public async Task CSharpReassignLocalVariableAndReferToItsProperty()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public C Property { get; set; }
}
public class Test
{
public void Method()
{
C a = new C(), b = new C(), c;
a.Property = c = a = b;
}
}
",
GetCSharpResultAt(12, 9, "a", "Property"));
}
[Fact]
public async Task CSharpReassignLocalVariablesPropertyAndReferToItsProperty()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public C Property { get; set; }
}
public class Test
{
public void Method()
{
C a = new C(), b = new C();
a.Property.Property = a.Property = b;
}
}
",
GetCSharpResultAt(12, 9, "a.Property", "Property"));
}
[Fact]
public async Task CSharpReassignLocalVariableAndItsPropertyAndReferToItsProperty()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public C Property { get; set; }
}
public class Test
{
public void Method()
{
C a = new C(), b = new C();
a.Property.Property = a.Property = a = b;
}
}
",
GetCSharpResultAt(12, 9, "a.Property", "Property"),
GetCSharpResultAt(12, 31, "a", "Property"));
}
[Fact]
public async Task CSharpReferToFieldOfReferenceTypeLocalVariableAfterItsReassignment()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public C Field;
}
public class Test
{
static C x, y;
public void Method()
{
x.Field = x = y;
}
}
",
GetCSharpResultAt(13, 9, "x", "Field"));
}
[Fact]
public async Task CSharpReassignGlobalVariableAndReferToItsField()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public C Property { get; set; }
}
public class Test
{
static C x, y;
public void Method()
{
x.Property.Property = x.Property = y;
}
}
",
GetCSharpResultAt(13, 9, "x.Property", "Property"));
}
[Fact]
public async Task CSharpReassignGlobalVariableAndItsPropertyAndReferToItsProperty()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public C Property { get; set; }
}
public class Test
{
static C x, y;
public void Method()
{
x.Property.Property = x.Property = x = y;
}
}
",
GetCSharpResultAt(13, 9, "x.Property", "Property"),
GetCSharpResultAt(13, 31, "x", "Property"));
}
[Fact]
public async Task CSharpReassignGlobalPropertyAndItsPropertyAndReferToItsProperty()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public C Property { get; set; }
}
public class Test
{
static C x { get; set; }
static C y { get; set; }
public void Method()
{
x.Property.Property = x.Property = x = y;
}
}
",
GetCSharpResultAt(14, 9, "x.Property", "Property"),
GetCSharpResultAt(14, 31, "x", "Property"));
}
[Fact]
public async Task CSharpReassignSecondLocalVariableAndReferToItsPropertyOfFirstVariable()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public C Property { get; set; }
}
public class Test
{
public void Method()
{
C a = new C(), b;
a.Property = b = a;
}
}
");
}
[Fact]
public async Task CSharpReassignPropertyOfFirstLocalVariableWithSecondAndReferToPropertyOfSecondVariable()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public C Property { get; set; }
}
public class Test
{
public void Method()
{
C a = new C(), b = new C(), c;
b.Property.Property = a.Property = b;
}
}
");
}
[Fact]
public async Task CSharpReassignPropertyOfFirstLocalVariableWithThirdAndReferToPropertyOfSecondVariable()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public C Property { get; set; }
}
public class Test
{
public void Method()
{
C a = new C(), b = new C(), c = new C();
b.Property.Property = a.Property = c;
}
}
");
}
[Fact]
public async Task CSharpReassignMethodParameterAndReferToItsProperty()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public C Property { get; set; }
}
public class Test
{
public void Method(C b)
{
C a = new C();
b.Property = b = a;
}
}
",
GetCSharpResultAt(12, 9, "b", "Property"));
}
[Fact]
public async Task CSharpReassignLocalValueTypeVariableAndReferToItsField()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public struct S
{
public S {|CS0523:Field|};
}
public class Test
{
public void Method()
{
S a, b = new S();
a.Field = a = b;
}
}
");
}
[Fact]
public async Task CSharpReassignLocalValueTypeVariableAndReferToItsProperty()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public struct S
{
public S Property { get => default; set { } }
}
public class Test
{
public void Method()
{
S a, b = new S();
a.Property = a = b;
}
}
");
}
[Fact]
public async Task CSharpAssignmentInCodeWithOperationNone()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public struct Test
{
public System.IntPtr PtrField;
public unsafe void Method(Test a, Test *b)
{
b->PtrField = a.PtrField;
}
}
");
}
[Fact]
[WorkItem(2889, "https://github.com/dotnet/roslyn-analyzers/issues/2889")]
public async Task CSharpAssignmentLocalReferenceOperation()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public static class Class1
{
public static void SomeMethod()
{
var u = new System.UriBuilder();
u.Host = u.Path = string.Empty;
}
}
");
}
private static DiagnosticResult GetCSharpResultAt(int line, int column, params string[] arguments)
=> VerifyCS.Diagnostic()
.WithLocation(line, column)
.WithArguments(arguments);
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************
namespace NUnit.ConsoleRunner.Tests
{
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
[TestFixture]
public class CommandLineTests
{
[Test]
public void NoParametersCount()
{
ConsoleOptions options = new ConsoleOptions();
Assert.IsTrue(options.NoArgs);
}
[Test]
public void AllowForwardSlashDefaultsCorrectly()
{
ConsoleOptions options = new ConsoleOptions();
Assert.AreEqual( Path.DirectorySeparatorChar != '/', options.AllowForwardSlash );
}
private void TestBooleanOption( string fieldName )
{
TestBooleanOption( fieldName, fieldName );
}
private void TestBooleanOption( string fieldName, string option )
{
FieldInfo field = typeof(ConsoleOptions).GetField( fieldName );
Assert.IsNotNull( field, "Field '{0}' not found", fieldName );
Assert.AreEqual( typeof(bool), field.FieldType, "Field '{0}' is wrong type", fieldName );
ConsoleOptions options = new ConsoleOptions( "-" + option );
Assert.AreEqual( true, (bool)field.GetValue( options ), "Didn't recognize -" + option );
options = new ConsoleOptions( "--" + option );
Assert.AreEqual( true, (bool)field.GetValue( options ), "Didn't recognize --" + option );
options = new ConsoleOptions( false, "/" + option );
Assert.AreEqual( false, (bool)field.GetValue( options ), "Incorrectly recognized /" + option );
options = new ConsoleOptions( true, "/" + option );
Assert.AreEqual( true, (bool)field.GetValue( options ), "Didn't recognize /" + option );
}
private void TestStringOption( string fieldName )
{
TestStringOption( fieldName, fieldName );
}
private void TestStringOption( string fieldName, string option )
{
FieldInfo field = typeof(ConsoleOptions).GetField( fieldName );
Assert.IsNotNull( field, "Field {0} not found", fieldName );
Assert.AreEqual( typeof(string), field.FieldType );
ConsoleOptions options = new ConsoleOptions( "-" + option + ":text" );
Assert.AreEqual( "text", (string)field.GetValue( options ), "Didn't recognize -" + option );
options = new ConsoleOptions( "--" + option + ":text" );
Assert.AreEqual( "text", (string)field.GetValue( options ), "Didn't recognize --" + option );
options = new ConsoleOptions( false, "/" + option + ":text" );
Assert.AreEqual( null, (string)field.GetValue( options ), "Incorrectly recognized /" + option );
options = new ConsoleOptions( true, "/" + option + ":text" );
Assert.AreEqual( "text", (string)field.GetValue( options ), "Didn't recognize /" + option );
}
private void TestEnumOption( string fieldName )
{
FieldInfo field = typeof(ConsoleOptions).GetField( fieldName );
Assert.IsNotNull( field, "Field {0} not found", fieldName );
Assert.IsTrue( field.FieldType.IsEnum, "Field {0} is not an enum", fieldName );
}
[Test]
public void OptionsAreRecognized()
{
TestBooleanOption( "nologo" );
TestBooleanOption( "help" );
TestBooleanOption( "help", "?" );
TestBooleanOption( "wait" );
TestBooleanOption( "xmlConsole" );
TestBooleanOption( "labels" );
TestBooleanOption( "noshadow" );
TestBooleanOption( "nothread" );
TestStringOption( "fixture" );
TestStringOption( "config" );
TestStringOption( "xml" );
TestStringOption( "transform" );
TestStringOption( "output" );
TestStringOption( "output", "out" );
TestStringOption( "err" );
TestStringOption( "include" );
TestStringOption( "exclude" );
TestEnumOption( "domain" );
}
[Test]
public void AssemblyName()
{
ConsoleOptions options = new ConsoleOptions( "nunit.tests.dll" );
Assert.AreEqual( "nunit.tests.dll", options.Parameters[0] );
}
[Test]
public void IncludeCategories()
{
ConsoleOptions options = new ConsoleOptions( "tests.dll", "-include:Database;Slow" );
Assert.IsTrue( options.Validate() );
Assert.IsNotNull(options.include);
Assert.AreEqual(options.include, "Database;Slow");
Assert.IsTrue(options.HasInclude);
string[] categories = options.IncludedCategories;
Assert.IsNotNull(categories);
Assert.AreEqual(2, categories.Length);
Assert.AreEqual("Database", categories[0]);
Assert.AreEqual("Slow", categories[1]);
}
[Test]
public void ExcludeCategories()
{
ConsoleOptions options = new ConsoleOptions( "tests.dll", "-exclude:Database;Slow" );
Assert.IsTrue( options.Validate() );
Assert.IsNotNull(options.exclude);
Assert.AreEqual(options.exclude, "Database;Slow");
Assert.IsTrue(options.HasExclude);
string[] categories = options.ExcludedCategories;
Assert.IsNotNull(categories);
Assert.AreEqual(2, categories.Length);
Assert.AreEqual("Database", categories[0]);
Assert.AreEqual("Slow", categories[1]);
}
[Test]
public void IncludeAndExcludeAreInvalidTogether()
{
ConsoleOptions options = new ConsoleOptions( "tests.dll", "-include:Database;Slow", "-exclude:Fast" );
Assert.IsFalse( options.Validate() );
}
[Test]
public void FixtureNamePlusAssemblyIsValid()
{
ConsoleOptions options = new ConsoleOptions( "-fixture:NUnit.Tests.AllTests", "nunit.tests.dll" );
Assert.AreEqual("nunit.tests.dll", options.Parameters[0]);
Assert.AreEqual("NUnit.Tests.AllTests", options.fixture);
Assert.IsTrue(options.Validate());
}
[Test]
public void AssemblyAloneIsValid()
{
ConsoleOptions options = new ConsoleOptions( "nunit.tests.dll" );
Assert.IsTrue(options.Validate(), "command line should be valid");
}
[Test]
public void InvalidOption()
{
ConsoleOptions options = new ConsoleOptions( "-asembly:nunit.tests.dll" );
Assert.IsFalse(options.Validate());
}
[Test]
public void NoFixtureNameProvided()
{
ConsoleOptions options = new ConsoleOptions( "-fixture:", "nunit.tests.dll" );
Assert.IsFalse(options.Validate());
}
[Test]
public void InvalidCommandLineParms()
{
ConsoleOptions options = new ConsoleOptions( "-garbage:TestFixture", "-assembly:Tests.dll" );
Assert.IsFalse(options.Validate());
}
[Test]
public void XmlParameter()
{
ConsoleOptions options = new ConsoleOptions( "tests.dll", "-xml:results.xml" );
Assert.IsTrue(options.ParameterCount == 1, "assembly should be set");
Assert.AreEqual("tests.dll", options.Parameters[0]);
Assert.IsTrue(options.IsXml, "XML file name should be set");
Assert.AreEqual("results.xml", options.xml);
}
[Test]
public void XmlParameterWithFullPath()
{
ConsoleOptions options = new ConsoleOptions( "tests.dll", "-xml:C:/nunit/tests/bin/Debug/console-test.xml" );
Assert.IsTrue(options.ParameterCount == 1, "assembly should be set");
Assert.AreEqual("tests.dll", options.Parameters[0]);
Assert.IsTrue(options.IsXml, "XML file name should be set");
Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.xml);
}
[Test]
public void XmlParameterWithFullPathUsingEqualSign()
{
ConsoleOptions options = new ConsoleOptions( "tests.dll", "-xml=C:/nunit/tests/bin/Debug/console-test.xml" );
Assert.IsTrue(options.ParameterCount == 1, "assembly should be set");
Assert.AreEqual("tests.dll", options.Parameters[0]);
Assert.IsTrue(options.IsXml, "XML file name should be set");
Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.xml);
}
[Test]
public void TransformParameter()
{
ConsoleOptions options = new ConsoleOptions( "tests.dll", "-transform:Summary.xslt" );
Assert.IsTrue(options.ParameterCount == 1, "assembly should be set");
Assert.AreEqual("tests.dll", options.Parameters[0]);
Assert.IsTrue(options.IsTransform, "transform file name should be set");
Assert.AreEqual("Summary.xslt", options.transform);
}
[Test]
public void FileNameWithoutXmlParameterIsInvalid()
{
ConsoleOptions options = new ConsoleOptions( "tests.dll", ":result.xml" );
Assert.IsFalse(options.IsXml);
}
[Test]
public void XmlParameterWithoutFileNameIsInvalid()
{
ConsoleOptions options = new ConsoleOptions( "tests.dll", "-xml:" );
Assert.IsFalse(options.IsXml);
}
[Test]
public void HelpTextUsesCorrectDelimiterForPlatform()
{
string helpText = new ConsoleOptions().GetHelpText();
char delim = System.IO.Path.DirectorySeparatorChar == '/' ? '-' : '/';
string expected = string.Format( "{0}output=", delim );
StringAssert.Contains( expected, helpText );
expected = string.Format( "{0}out=", delim );
StringAssert.Contains( expected, helpText );
}
}
}
| |
// 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.Text.Tests
{
public static partial class NegativeEncodingTests
{
public static IEnumerable<object[]> Encodings_TestData()
{
yield return new object[] { new UnicodeEncoding(false, false) };
yield return new object[] { new UnicodeEncoding(true, false) };
yield return new object[] { new UnicodeEncoding(true, true) };
yield return new object[] { new UnicodeEncoding(true, true) };
yield return new object[] { Encoding.BigEndianUnicode };
yield return new object[] { Encoding.Unicode };
yield return new object[] { new UTF7Encoding(true) };
yield return new object[] { new UTF7Encoding(false) };
yield return new object[] { Encoding.UTF7 };
yield return new object[] { new UTF8Encoding(true, true) };
yield return new object[] { new UTF8Encoding(false, true) };
yield return new object[] { new UTF8Encoding(true, false) };
yield return new object[] { new UTF8Encoding(false, false) };
yield return new object[] { Encoding.UTF8 };
yield return new object[] { new ASCIIEncoding() };
yield return new object[] { Encoding.ASCII };
yield return new object[] { new UTF32Encoding(true, true, true) };
yield return new object[] { new UTF32Encoding(true, true, false) };
yield return new object[] { new UTF32Encoding(true, false, false) };
yield return new object[] { new UTF32Encoding(true, false, true) };
yield return new object[] { new UTF32Encoding(false, true, true) };
yield return new object[] { new UTF32Encoding(false, true, false) };
yield return new object[] { new UTF32Encoding(false, false, false) };
yield return new object[] { new UTF32Encoding(false, false, true) };
yield return new object[] { Encoding.UTF32 };
yield return new object[] { Encoding.GetEncoding("latin1") };
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static unsafe void GetByteCount_Invalid(Encoding encoding)
{
// Chars is null
AssertExtensions.Throws<ArgumentNullException>(encoding is ASCIIEncoding ? "chars" : "s", () => encoding.GetByteCount((string)null));
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetByteCount((char[])null));
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetByteCount((char[])null, 0, 0));
// Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetByteCount(new char[3], -1, 0));
// Count < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetByteCount(new char[3], 0, -1));
// Index + count > chars.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 0, 4));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 1, 3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 2, 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 3, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 4, 0));
char[] chars = new char[3];
fixed (char* pChars = chars)
{
char* pCharsLocal = pChars;
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetByteCount(null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetByteCount(pCharsLocal, -1));
}
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static unsafe void GetBytes_Invalid(Encoding encoding)
{
string expectedStringParamName = encoding is ASCIIEncoding ? "chars" : "s";
// Source is null
AssertExtensions.Throws<ArgumentNullException>("s", () => encoding.GetBytes((string)null));
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char[])null));
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char[])null, 0, 0));
AssertExtensions.Throws<ArgumentNullException>(expectedStringParamName, () => encoding.GetBytes((string)null, 0, 0, new byte[1], 0));
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char[])null, 0, 0, new byte[1], 0));
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetBytes("abc", 0, 3, null, 0));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetBytes(new char[3], 0, 3, null, 0));
// Char index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetBytes(new char[1], -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetBytes("a", -1, 0, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetBytes(new char[1], -1, 0, new byte[1], 0));
// Char count < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetBytes(new char[1], 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetBytes("a", 0, -1, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetBytes(new char[1], 0, -1, new byte[1], 0));
// Char index + count > source.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 2, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>(expectedStringParamName, () => encoding.GetBytes("a", 2, 0, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 2, 0, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(expectedStringParamName, () => encoding.GetBytes("a", 1, 1, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 1, 1, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 0, 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>(expectedStringParamName, () => encoding.GetBytes("a", 0, 2, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 0, 2, new byte[1], 0));
// Byte index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes("a", 0, 1, new byte[1], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes(new char[1], 0, 1, new byte[1], -1));
// Byte index > bytes.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes("a", 0, 1, new byte[1], 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes(new char[1], 0, 1, new byte[1], 2));
// Bytes does not have enough capacity to accomodate result
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("a", 0, 1, new byte[0], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("abc", 0, 3, new byte[1], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("\uD800\uDC00", 0, 2, new byte[1], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(new char[1], 0, 1, new byte[0], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(new char[3], 0, 3, new byte[1], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("\uD800\uDC00".ToCharArray(), 0, 2, new byte[1], 0));
char[] chars = new char[3];
byte[] bytes = new byte[3];
byte[] smallBytes = new byte[1];
fixed (char* pChars = chars)
fixed (byte* pBytes = bytes)
fixed (byte* pSmallBytes = smallBytes)
{
char* pCharsLocal = pChars;
byte* pBytesLocal = pBytes;
byte* pSmallBytesLocal = pSmallBytes;
// Bytes or chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char*)null, 0, pBytesLocal, bytes.Length));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetBytes(pCharsLocal, chars.Length, (byte*)null, bytes.Length));
// CharCount or byteCount is negative
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetBytes(pCharsLocal, -1, pBytesLocal, bytes.Length));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetBytes(pCharsLocal, chars.Length, pBytesLocal, -1));
// Bytes does not have enough capacity to accomodate result
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(pCharsLocal, chars.Length, pSmallBytesLocal, smallBytes.Length));
}
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static unsafe void GetCharCount_Invalid(Encoding encoding)
{
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetCharCount(null));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetCharCount(null, 0, 0));
// Index or count < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetCharCount(new byte[4], -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetCharCount(new byte[4], 0, -1));
// Index + count > bytes.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 5, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 4, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 3, 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 2, 3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 1, 4));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 0, 5));
byte[] bytes = new byte[4];
fixed (byte* pBytes = bytes)
{
byte* pBytesLocal = pBytes;
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetCharCount(null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetCharCount(pBytesLocal, -1));
}
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static unsafe void GetChars_Invalid(Encoding encoding)
{
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars(null));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars(null, 0, 0));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars(null, 0, 0, new char[0], 0));
// Chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetChars(new byte[4], 0, 4, null, 0));
// Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetChars(new byte[4], -1, 4));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetChars(new byte[4], -1, 4, new char[1], 0));
// Count < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetChars(new byte[4], 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetChars(new byte[4], 0, -1, new char[1], 0));
// Count > bytes.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 0, 5));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 0, 5, new char[1], 0));
// Index + count > bytes.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 5, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 5, 0, new char[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 4, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 4, 1, new char[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 3, 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 3, 2, new char[1], 0));
// CharIndex < 0 or >= chars.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetChars(new byte[4], 0, 4, new char[1], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetChars(new byte[4], 0, 4, new char[1], 2));
// Chars does not have enough capacity to accomodate result
AssertExtensions.Throws<ArgumentException>("chars", () => encoding.GetChars(new byte[4], 0, 4, new char[1], 1));
byte[] bytes = new byte[encoding.GetMaxByteCount(2)];
char[] chars = new char[4];
char[] smallChars = new char[1];
fixed (byte* pBytes = bytes)
fixed (char* pChars = chars)
fixed (char* pSmallChars = smallChars)
{
byte* pBytesLocal = pBytes;
char* pCharsLocal = pChars;
char* pSmallCharsLocal = pSmallChars;
// Bytes or chars is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars((byte*)null, 0, pCharsLocal, chars.Length));
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetChars(pBytesLocal, bytes.Length, (char*)null, chars.Length));
// ByteCount or charCount is negative
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetChars(pBytesLocal, -1, pCharsLocal, chars.Length));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetChars(pBytesLocal, bytes.Length, pCharsLocal, -1));
// Chars does not have enough capacity to accomodate result
AssertExtensions.Throws<ArgumentException>("chars", () => encoding.GetChars(pBytesLocal, bytes.Length, pSmallCharsLocal, smallChars.Length));
}
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static void GetMaxByteCount_Invalid(Encoding encoding)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetMaxByteCount(-1));
if (!encoding.IsSingleByte)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetMaxByteCount(int.MaxValue / 2));
}
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetMaxByteCount(int.MaxValue));
// Make sure that GetMaxByteCount respects the MaxCharCount property of EncoderFallback
// However, Utf7Encoding ignores this
if (!(encoding is UTF7Encoding))
{
Encoding customizedMaxCharCountEncoding = Encoding.GetEncoding(encoding.CodePage, new HighMaxCharCountEncoderFallback(), DecoderFallback.ReplacementFallback);
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => customizedMaxCharCountEncoding.GetMaxByteCount(2));
}
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static void GetMaxCharCount_Invalid(Encoding encoding)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetMaxCharCount(-1));
// TODO: find a more generic way to find what byteCount is invalid
if (encoding is UTF8Encoding)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetMaxCharCount(int.MaxValue));
}
// Make sure that GetMaxCharCount respects the MaxCharCount property of DecoderFallback
// However, Utf7Encoding ignores this
if (!(encoding is UTF7Encoding) && !(encoding is UTF32Encoding))
{
Encoding customizedMaxCharCountEncoding = Encoding.GetEncoding(encoding.CodePage, EncoderFallback.ReplacementFallback, new HighMaxCharCountDecoderFallback());
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => customizedMaxCharCountEncoding.GetMaxCharCount(2));
}
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static void GetString_Invalid(Encoding encoding)
{
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetString(null));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetString(null, 0, 0));
// Index or count < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(encoding is ASCIIEncoding ? "byteIndex" : "index", () => encoding.GetString(new byte[1], -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>(encoding is ASCIIEncoding ? "byteCount" : "count", () => encoding.GetString(new byte[1], 0, -1));
// Index + count > bytes.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetString(new byte[1], 2, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetString(new byte[1], 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetString(new byte[1], 0, 2));
}
public static unsafe void Encode_Invalid(Encoding encoding, string chars, int index, int count)
{
Assert.Equal(EncoderFallback.ExceptionFallback, encoding.EncoderFallback);
char[] charsArray = chars.ToCharArray();
byte[] bytes = new byte[encoding.GetMaxByteCount(count)];
if (index == 0 && count == chars.Length)
{
Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(chars));
Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(charsArray));
Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(chars));
Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(charsArray));
}
Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(charsArray, index, count));
Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(charsArray, index, count));
Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(chars, index, count, bytes, 0));
Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(charsArray, index, count, bytes, 0));
fixed (char* pChars = chars)
fixed (byte* pBytes = bytes)
{
char* pCharsLocal = pChars;
byte* pBytesLocal = pBytes;
Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(pCharsLocal + index, count));
Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(pCharsLocal + index, count, pBytesLocal, bytes.Length));
}
}
public static unsafe void Decode_Invalid(Encoding encoding, byte[] bytes, int index, int count)
{
Assert.Equal(DecoderFallback.ExceptionFallback, encoding.DecoderFallback);
char[] chars = new char[encoding.GetMaxCharCount(count)];
if (index == 0 && count == bytes.Length)
{
Assert.Throws<DecoderFallbackException>(() => encoding.GetCharCount(bytes));
Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(bytes));
Assert.Throws<DecoderFallbackException>(() => encoding.GetString(bytes));
}
Assert.Throws<DecoderFallbackException>(() => encoding.GetCharCount(bytes, index, count));
Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(bytes, index, count));
Assert.Throws<DecoderFallbackException>(() => encoding.GetString(bytes, index, count));
Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(bytes, index, count, chars, 0));
fixed (byte* pBytes = bytes)
fixed (char* pChars = chars)
{
byte* pBytesLocal = pBytes;
char* pCharsLocal = pChars;
Assert.Throws<DecoderFallbackException>(() => encoding.GetCharCount(pBytesLocal + index, count));
Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(pBytesLocal + index, count, pCharsLocal, chars.Length));
Assert.Throws<DecoderFallbackException>(() => encoding.GetString(pBytesLocal + index, count));
}
}
public static IEnumerable<object[]> Encoders_TestData()
{
foreach (object[] encodingTestData in Encodings_TestData())
{
Encoding encoding = (Encoding)encodingTestData[0];
yield return new object[] { encoding.GetEncoder(), true };
yield return new object[] { encoding.GetEncoder(), false };
}
}
[Theory]
[MemberData(nameof(Encoders_TestData))]
public static void Encoder_GetByteCount_Invalid(Encoder encoder, bool flush)
{
// Chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoder.GetByteCount(null, 0, 0, flush));
// Index is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoder.GetByteCount(new char[4], -1, 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetByteCount(new char[4], 5, 0, flush));
// Count is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoder.GetByteCount(new char[4], 0, -1, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetByteCount(new char[4], 0, 5, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetByteCount(new char[4], 1, 4, flush));
}
[Theory]
[MemberData(nameof(Encoders_TestData))]
public static void Encoder_GetBytes_Invalid(Encoder encoder, bool flush)
{
// Chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoder.GetBytes(null, 0, 0, new byte[4], 0, flush));
// CharIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoder.GetBytes(new char[4], -1, 0, new byte[4], 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetBytes(new char[4], 5, 0, new byte[4], 0, flush));
// CharCount is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoder.GetBytes(new char[4], 0, -1, new byte[4], 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetBytes(new char[4], 0, 5, new byte[4], 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetBytes(new char[4], 1, 4, new byte[4], 0, flush));
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoder.GetBytes(new char[1], 0, 1, null, 0, flush));
// ByteIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoder.GetBytes(new char[1], 0, 1, new byte[4], -1, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoder.GetBytes(new char[1], 0, 1, new byte[4], 5, flush));
// Bytes does not have enough space
int byteCount = encoder.GetByteCount(new char[] { 'a' }, 0, 1, flush);
AssertExtensions.Throws<ArgumentException>("bytes", () => encoder.GetBytes(new char[] { 'a' }, 0, 1, new byte[byteCount - 1], 0, flush));
}
[Theory]
[MemberData(nameof(Encoders_TestData))]
public static void Encoder_Convert_Invalid(Encoder encoder, bool flush)
{
int charsUsed = 0;
int bytesUsed = 0;
bool completed = false;
Action verifyOutParams = () =>
{
Assert.Equal(0, charsUsed);
Assert.Equal(0, bytesUsed);
Assert.False(completed);
};
// Chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoder.Convert(null, 0, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// CharIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoder.Convert(new char[4], -1, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 5, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// CharCount is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoder.Convert(new char[4], 0, -1, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 0, 5, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 1, 4, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoder.Convert(new char[1], 0, 1, null, 0, 0, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// ByteIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoder.Convert(new char[1], 0, 0, new byte[4], -1, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 5, 0, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// ByteCount is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoder.Convert(new char[1], 0, 0, new byte[4], 0, -1, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 0, 5, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 1, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// Bytes does not have enough space
int byteCount = encoder.GetByteCount(new char[] { 'a' }, 0, 1, flush);
AssertExtensions.Throws<ArgumentException>("bytes", () => encoder.Convert(new char[] { 'a' }, 0, 1, new byte[byteCount - 1], 0, byteCount - 1, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
}
public static IEnumerable<object[]> Decoders_TestData()
{
foreach (object[] encodingTestData in Encodings_TestData())
{
Encoding encoding = (Encoding)encodingTestData[0];
yield return new object[] { encoding, encoding.GetDecoder(), true };
yield return new object[] { encoding, encoding.GetDecoder(), false };
}
}
[Theory]
[MemberData(nameof(Decoders_TestData))]
public static void Decoder_GetCharCount_Invalid(Encoding _, Decoder decoder, bool flush)
{
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.GetCharCount(null, 0, 0, flush));
// Index is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => decoder.GetCharCount(new byte[4], -1, 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetCharCount(new byte[4], 5, 0, flush));
// Count is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => decoder.GetCharCount(new byte[4], 0, -1, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetCharCount(new byte[4], 0, 5, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetCharCount(new byte[4], 1, 4, flush));
}
[Theory]
[MemberData(nameof(Decoders_TestData))]
public static void Decoder_GetChars_Invalid(Encoding _, Decoder decoder, bool flush)
{
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.GetChars(null, 0, 0, new char[4], 0, flush));
// ByteIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => decoder.GetChars(new byte[4], -1, 0, new char[4], 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetChars(new byte[4], 5, 0, new char[4], 0, flush));
// ByteCount is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => decoder.GetChars(new byte[4], 0, -1, new char[4], 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetChars(new byte[4], 0, 5, new char[4], 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetChars(new byte
[4], 1, 4, new char[4], 0, flush));
// Chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => decoder.GetChars(new byte[1], 0, 1, null, 0, flush));
// CharIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => decoder.GetChars(new byte[1], 0, 1, new char[4], -1, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => decoder.GetChars(new byte[1], 0, 1, new char[4], 5, flush));
// Chars does not have enough space
int charCount = decoder.GetCharCount(new byte[4], 0, 4, flush);
AssertExtensions.Throws<ArgumentException>("chars", () => decoder.GetChars(new byte[4], 0, 4, new char[charCount - 1], 0, flush));
}
[Theory]
[MemberData(nameof(Decoders_TestData))]
public static void Decoder_Convert_Invalid(Encoding encoding, Decoder decoder, bool flush)
{
int bytesUsed = 0;
int charsUsed = 0;
bool completed = false;
Action verifyOutParams = () =>
{
Assert.Equal(0, bytesUsed);
Assert.Equal(0, charsUsed);
Assert.False(completed);
};
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.Convert(null, 0, 0, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// ByteIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => decoder.Convert(new byte[4], -1, 0, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.Convert(new byte[4], 5, 0, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// ByteCount is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => decoder.Convert(new byte[4], 0, -1, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.Convert(new byte[4], 0, 5, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.Convert(new byte[4], 1, 4, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// Chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => decoder.Convert(new byte[1], 0, 1, null, 0, 0, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// CharIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => decoder.Convert(new byte[1], 0, 0, new char[4], -1, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => decoder.Convert(new byte[1], 0, 0, new char[4], 5, 0, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// CharCount is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => decoder.Convert(new byte[1], 0, 0, new char[4], 0, -1, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => decoder.Convert(new byte[1], 0, 0, new char[4], 0, 5, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => decoder.Convert(new byte[1], 0, 0, new char[4], 1, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// Chars does not have enough space
AssertExtensions.Throws<ArgumentException>("chars", () => decoder.Convert(new byte[4], 0, 4, new char[0], 0, 0, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
}
}
public class HighMaxCharCountEncoderFallback : EncoderFallback
{
public override int MaxCharCount => int.MaxValue;
public override EncoderFallbackBuffer CreateFallbackBuffer() => ReplacementFallback.CreateFallbackBuffer();
}
public class HighMaxCharCountDecoderFallback : DecoderFallback
{
public override int MaxCharCount => int.MaxValue;
public override DecoderFallbackBuffer CreateFallbackBuffer() => ReplacementFallback.CreateFallbackBuffer();
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using TypeVisualiser.Properties;
namespace TypeVisualiser.Geometry
{
[DebuggerDisplay("Area ({TopLeft}) ({BottomRight})")]
public class Area
{
public Area(FrameworkElement control)
{
if (control == null)
{
throw new ArgumentNullResourceException("control", Resources.General_Given_Parameter_Cannot_Be_Null);
}
TopLeft = new Point(Canvas.GetLeft(control), Canvas.GetTop(control));
BottomRight = new Point(TopLeft.X + control.ActualWidth, TopLeft.Y + control.ActualHeight);
}
public Area(Point topLeft, double actualWidth, double actualHeight)
{
TopLeft = topLeft.Clone();
BottomRight = new Point(TopLeft.X + actualWidth, TopLeft.Y + actualHeight);
}
public Area(Point topLeft, Point bottomRight)
{
TopLeft = topLeft.Clone();
BottomRight = bottomRight.Clone();
}
public Point BottomRight { get; private set; }
public Point Centre
{
get
{
Point c = TopLeft.Clone();
c.Offset(Width / 2, Height / 2);
return c;
}
}
public double Height
{
get { return BottomRight.Y - TopLeft.Y; }
}
/// <summary>
/// Gets or sets the tag.
/// Used for debugging and logging.
/// </summary>
/// <value>
/// The tag.
/// </value>
public string Tag { get; set; }
public Point TopLeft { get; private set; }
public double Width
{
get { return BottomRight.X - TopLeft.X; }
}
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "Area: {0} ({1:F2}, {2:F2}) ({3:F2}, {4:F2})", Tag, TopLeft.X, TopLeft.Y, BottomRight.X, BottomRight.Y);
}
public Point CalculateCircumferenceIntersectionPoint(double northOrientedAngle)
{
Point intersectionPoint = Centre;
if (northOrientedAngle >= 360)
{
northOrientedAngle = northOrientedAngle % 360;
}
// Fringe cases
if (Math.Abs(northOrientedAngle - 0) < 0.01)
{
intersectionPoint.Offset(0, -Height / 2);
return intersectionPoint;
}
if (Math.Abs(northOrientedAngle - 180) < 0.01)
{
intersectionPoint.Offset(0, Height / 2);
return intersectionPoint;
}
int quadrant;
for (quadrant = 0; quadrant < 4; quadrant++)
{
if (northOrientedAngle < 90.0)
{
break;
}
northOrientedAngle -= 90.0;
}
// Try assuming line exits on vertical side
double adjacent, opporsite;
double angleInRadians = TrigHelper.DegreesToRadians(northOrientedAngle);
Func<double, double> calculateOpporsite = a => a * Math.Tan(angleInRadians);
Func<double, double> calculateAdjacent = o => o / Math.Tan(angleInRadians);
switch (quadrant)
{
case 0:
opporsite = Width / 2;
adjacent = calculateAdjacent(opporsite);
if (adjacent > Height / 2)
{
// havent found intersection yet
adjacent = Height / 2;
opporsite = calculateOpporsite(adjacent);
if (opporsite > Width / 2)
{
UnableToCalculateIntersectionPoint(northOrientedAngle, opporsite, adjacent, quadrant);
}
}
intersectionPoint.Offset(opporsite, -adjacent);
return intersectionPoint;
case 1:
adjacent = Width / 2;
opporsite = calculateOpporsite(adjacent);
if (opporsite > Height / 2)
{
// havent found intersection yet
opporsite = Height / 2;
adjacent = calculateAdjacent(opporsite);
if (adjacent > Width / 2)
{
UnableToCalculateIntersectionPoint(northOrientedAngle, opporsite, adjacent, quadrant);
}
}
intersectionPoint.Offset(adjacent, opporsite);
return intersectionPoint;
case 2:
opporsite = Width / 2;
adjacent = calculateAdjacent(opporsite);
if (adjacent > Height / 2)
{
// havent found intersection yet
adjacent = Height / 2;
opporsite = calculateOpporsite(adjacent);
if (opporsite > Width / 2)
{
UnableToCalculateIntersectionPoint(northOrientedAngle, opporsite, adjacent, quadrant);
}
}
intersectionPoint.Offset(-opporsite, adjacent);
return intersectionPoint;
case 3:
adjacent = Width / 2;
opporsite = calculateOpporsite(adjacent);
if (opporsite > Height / 2)
{
// havent found intersection yet
opporsite = Height / 2;
adjacent = calculateAdjacent(opporsite);
if (adjacent > Width / 2)
{
UnableToCalculateIntersectionPoint(northOrientedAngle, opporsite, adjacent, quadrant);
}
}
intersectionPoint.Offset(-adjacent, -opporsite);
return intersectionPoint;
default:
throw new NotSupportedException("Invalid quadrant detected in Calculate Intersection point: " + quadrant);
}
}
private static void UnableToCalculateIntersectionPoint(double northOrientedAngle, double opporsite, double adjacent, int quadrant)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
"Unable to calculate intersection point - bad data: angle={0:F2}, o={1:F2}, a={2:F2}, quadrant={3}",
northOrientedAngle,
opporsite,
adjacent,
quadrant));
}
public double DistanceToPoint(Point destination)
{
return destination.DistanceTo(TopLeft);
}
public Area Offset(double moveX, double moveY)
{
Point newTopLeft = TopLeft.Clone();
newTopLeft.Offset(moveX, moveY);
Point newBottom = BottomRight.Clone();
newBottom.Offset(moveX, moveY);
var newArea = new Area(newTopLeft, newBottom);
return newArea;
}
public Area OffsetToMakeTopLeftCentre()
{
Point topLeft = TopLeft.Clone();
topLeft.Offset(-(Width / 2), -(Height / 2));
Point bottomRight = BottomRight.Clone();
bottomRight.Offset(-(Width / 2), -(Height / 2));
return new Area(topLeft, bottomRight);
}
/// <summary>
/// Determines if the given proposed area overlaps with this instance.
/// Will return <see cref="Proximity.VeryClose"/> if within the <see cref="LayoutConstants.MinimumDistanceBetweenObjects"/>.
/// If it is very close, a direction will be given, otherwise <see cref="Direction.Unknown"/> will be returned.
/// </summary>
/// <param name="proposedArea">The proposed area.</param>
/// <returns></returns>
public ProximityTestResult OverlapsWith(Area proposedArea)
{
if (Double.IsNaN(TopLeft.X) || Double.IsNaN(TopLeft.Y) || Double.IsNaN(BottomRight.X) || Double.IsNaN(BottomRight.Y))
{
return new ProximityTestResult(Proximity.NotOverlapping);
}
if (proposedArea == null)
{
throw new ArgumentNullResourceException("proposedArea", Resources.General_Given_Parameter_Cannot_Be_Null);
}
if (Double.IsNaN(proposedArea.TopLeft.X) || Double.IsNaN(proposedArea.TopLeft.Y) || Double.IsNaN(proposedArea.BottomRight.X) || Double.IsNaN(proposedArea.BottomRight.Y))
{
throw new ArgumentException(Resources.Area_OverlapsWith_Error_in_usage_Attempt_to_find_overlapping_areas_where_the_proposed_area_is_NaN, "proposedArea");
}
// Cond1. If A's left edge is to the right of the B's right edge, then A is Totally to right Of B
ProximityTestResult overlapsWith;
if (IsProposedAreaToTheRightOfThis(proposedArea, out overlapsWith))
{
return overlapsWith;
}
// Cond2. If A's right edge is to the left of the B's left edge, then A is Totally to left Of B
if (IsProposedAreaToTheLeftOfThis(proposedArea, out overlapsWith))
{
return overlapsWith;
}
// Cond3. If A's top edge is below B's bottom edge, then A is Totally below B
if (IsProposedAreaBelowThis(proposedArea, out overlapsWith))
{
return overlapsWith;
}
// Cond4. If A's bottom edge is above B's top edge, then A is Totally above B
if (IsProposedAreaAboveThis(proposedArea, out overlapsWith))
{
return overlapsWith;
}
return new ProximityTestResult(Proximity.Overlapping);
}
public void Update(FrameworkElement control)
{
if (control == null)
{
throw new ArgumentNullResourceException("control", Resources.General_Given_Parameter_Cannot_Be_Null);
}
TopLeft = new Point(Canvas.GetLeft(control), Canvas.GetTop(control));
if (control.ActualHeight < 1 || control.ActualWidth < 1)
{
Logger.Instance.WriteEntry("WARNING: Actual width and/or height is zero for association control.");
}
BottomRight = new Point(TopLeft.X + control.ActualWidth, TopLeft.Y + control.ActualHeight);
}
private static bool ItMightBeClose(double coordinate1, double coordinate2)
{
return (Math.Abs(coordinate1 - coordinate2) < LayoutConstants.MinimumDistanceBetweenObjects);
}
private bool IsProposedAreaAboveThis(Area proposedArea, out ProximityTestResult comparisonResult)
{
if (proposedArea.BottomRight.Y <= TopLeft.Y)
{
// porposed area is completely above this area
if (ItMightBeClose(proposedArea.BottomRight.Y, TopLeft.Y))
{
if (proposedArea.TopLeft.X.IsBetween(TopLeft.X, BottomRight.X) || proposedArea.BottomRight.X.IsBetween(TopLeft.X, BottomRight.X))
{
{
comparisonResult = new ProximityTestResult(Proximity.VeryClose) { DirectionToOtherObject = Direction.Up, DistanceToClosestObject = TopLeft.Y - proposedArea.BottomRight.Y, };
return true;
}
}
}
{
comparisonResult = new ProximityTestResult(Proximity.NotOverlapping);
return true;
}
}
comparisonResult = new ProximityTestResult(Proximity.Unknown);
return false;
}
private bool IsProposedAreaBelowThis(Area proposedArea, out ProximityTestResult comparisonResult)
{
if (proposedArea.TopLeft.Y >= BottomRight.Y)
{
// proposed area is completely below this area
if (ItMightBeClose(proposedArea.TopLeft.Y, BottomRight.Y))
{
if (proposedArea.TopLeft.X.IsBetween(TopLeft.X, BottomRight.X) || proposedArea.BottomRight.X.IsBetween(TopLeft.X, BottomRight.X))
{
{
comparisonResult = new ProximityTestResult(Proximity.VeryClose) { DirectionToOtherObject = Direction.Down, DistanceToClosestObject = proposedArea.TopLeft.Y - BottomRight.Y, };
return true;
}
}
}
{
comparisonResult = new ProximityTestResult(Proximity.NotOverlapping);
return true;
}
}
comparisonResult = new ProximityTestResult(Proximity.Unknown);
return false;
}
private bool IsProposedAreaToTheLeftOfThis(Area proposedArea, out ProximityTestResult comparisonResult)
{
if (proposedArea.BottomRight.X <= TopLeft.X)
{
// proposed area is completely to the left of this area.
if (ItMightBeClose(proposedArea.BottomRight.X, TopLeft.X))
{
if (proposedArea.TopLeft.Y.IsBetween(TopLeft.Y, BottomRight.Y) || proposedArea.BottomRight.Y.IsBetween(TopLeft.Y, BottomRight.Y))
{
{
comparisonResult = new ProximityTestResult(Proximity.VeryClose) { DirectionToOtherObject = Direction.Left, DistanceToClosestObject = TopLeft.X - proposedArea.BottomRight.X, };
return true;
}
}
}
{
comparisonResult = new ProximityTestResult(Proximity.NotOverlapping);
return true;
}
}
comparisonResult = new ProximityTestResult(Proximity.Unknown);
return false;
}
private bool IsProposedAreaToTheRightOfThis(Area proposedArea, out ProximityTestResult comparisonResult)
{
if (proposedArea.TopLeft.X >= BottomRight.X)
{
// proposed area is completely to the right of this area.
if (ItMightBeClose(proposedArea.TopLeft.X, BottomRight.X))
{
if (proposedArea.TopLeft.Y.IsBetween(TopLeft.Y, BottomRight.Y) || proposedArea.BottomRight.Y.IsBetween(TopLeft.Y, BottomRight.Y))
{
{
comparisonResult = new ProximityTestResult(Proximity.VeryClose) { DirectionToOtherObject = Direction.Right, DistanceToClosestObject = proposedArea.TopLeft.X - BottomRight.X, };
return true;
}
}
}
{
comparisonResult = new ProximityTestResult(Proximity.NotOverlapping);
return true;
}
}
comparisonResult = new ProximityTestResult(Proximity.Unknown);
return false;
}
}
}
| |
#region License
// Pomona is open source software released under the terms of the LICENSE specified in the
// project's repository, or alternatively at http://pomona.io/
#endregion
using System;
namespace Pomona.Common.TypeSystem
{
public struct Maybe<T>
{
private readonly T value;
internal Maybe(T value)
{
HasValue = true;
this.value = value;
}
public static Maybe<T> Empty { get; } = new Maybe<T>();
public bool HasValue { get; }
public T Value
{
get
{
if (!HasValue)
throw new InvalidOperationException("Maybe has no value.");
return this.value;
}
}
public override bool Equals(object obj)
{
if (ReferenceEquals(obj, null))
return false;
if (obj is Maybe<T>)
{
var other = (Maybe<T>)obj;
if (HasValue && other.HasValue)
return this.value.Equals(other.value);
return HasValue == other.HasValue;
}
return false;
}
public override int GetHashCode()
{
return !HasValue ? 0 : this.value.GetHashCode();
}
public Maybe<TCast> OfType<TCast>()
{
if (HasValue && this.value is TCast)
return new Maybe<TCast>((TCast)((object)this.value));
return Maybe<TCast>.Empty;
}
public T OrDefault(T defaultValue)
{
if (HasValue)
return this.value;
return defaultValue;
}
public T OrDefault(Func<T> defaultFactory = null)
{
if (HasValue)
return this.value;
return defaultFactory == null ? default(T) : defaultFactory();
}
public Maybe<TRet> Select<TRet>(Func<T, TRet?> op)
where TRet : struct
{
if (!HasValue)
return Maybe<TRet>.Empty;
var result = op(this.value);
return Create(result);
}
public Maybe<TRet> Select<TRet>(Func<T, TRet> op)
{
if (!HasValue)
return Maybe<TRet>.Empty;
var result = op(this.value);
return Create(result);
}
public Maybe<TRet> Switch<TRet>(Func<ITypeSwitch, ITypeSwitch<TRet>> cases)
{
if (cases == null)
throw new ArgumentNullException(nameof(cases));
if (!HasValue)
return Maybe<TRet>.Empty;
return cases(Switch()).EndSwitch();
}
public ITypeSwitch Switch()
{
return new TypeSwitch(this);
}
public ITypeSwitch<TRet> Switch<TRet>()
{
if (HasValue)
return new TypeSwitch<TRet>(this.value);
return new FinishedTypeSwitch<TRet>(Maybe<TRet>.Empty);
}
public Maybe<T> Where(Func<T, bool> predicate)
{
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
if (HasValue && predicate(this.value))
return this;
return Empty;
}
private static Maybe<TRet> Create<TRet>(TRet? result) where TRet : struct
{
return result.HasValue ? new Maybe<TRet>(result.Value) : Maybe<TRet>.Empty;
}
private static Maybe<TRet> Create<TRet>(TRet result)
{
return (object)result == null ? Maybe<TRet>.Empty : new Maybe<TRet>(result);
}
#region Nested type: FinishedTypeSwitch
internal class FinishedTypeSwitch<TRet> : ITypeSwitch<TRet>
{
private readonly Maybe<TRet> result;
public FinishedTypeSwitch(Maybe<TRet> result)
{
this.result = result;
}
public ICaseThen<TCast, TRet> Case<TCast>()
{
return new PassthroughCaseThen<TCast, TRet>(this);
}
public ICaseThen<TCast, TRet> Case<TCast>(Func<TCast, bool> predicate)
{
return new PassthroughCaseThen<TCast, TRet>(this);
}
public ICaseThen<T, TRet> Case(Func<T, bool> predicate)
{
return new PassthroughCaseThen<T, TRet>(this);
}
public Maybe<TRet> EndSwitch()
{
return this.result;
}
}
#endregion
#region Nested type: NonMatchingCaseThen
internal class NonMatchingCaseThen<TIn> : ICaseThen<TIn>
{
private readonly Maybe<T> value;
public NonMatchingCaseThen(Maybe<T> value)
{
this.value = value;
}
public ITypeSwitch<TRet> Then<TRet>(Func<TIn, TRet> thenFunc)
{
if (this.value.HasValue)
return new TypeSwitch<TRet>(this.value.Value);
return new FinishedTypeSwitch<TRet>(Maybe<TRet>.Empty);
}
}
#endregion
#region Nested type: PassthroughCaseThen
internal class PassthroughCaseThen<TIn, TRet> : ICaseThen<TIn, TRet>
{
private readonly ITypeSwitch<TRet> passedSwitch;
public PassthroughCaseThen(ITypeSwitch<TRet> passedSwitch)
{
this.passedSwitch = passedSwitch;
}
public ITypeSwitch<TRet> Then(Func<TIn, TRet> thenFunc)
{
return this.passedSwitch;
}
}
#endregion
#region Operators
public static Maybe<T> operator +(Maybe<T> a, Maybe<T> b)
{
T result;
if (a.HasValue && b.HasValue && Calculator<T>.TryPlus(a.Value, b.Value, out result))
return new Maybe<T>(result);
return Empty;
}
public static Maybe<T> operator /(Maybe<T> a, Maybe<T> b)
{
T result;
if (a.HasValue && b.HasValue && Calculator<T>.TryDivide(a.Value, b.Value, out result))
return new Maybe<T>(result);
return Empty;
}
public static Maybe<bool> operator ==(Maybe<T> a, Maybe<T> b)
{
if (a.HasValue && b.HasValue)
{
bool result;
if (Calculator<T>.TryEquals(a.Value, b.Value, out result))
return new Maybe<bool>(result);
}
return Maybe<bool>.Empty;
}
public static explicit operator T(Maybe<T> maybe)
{
return maybe.Value;
}
public static Maybe<bool> operator !=(Maybe<T> a, Maybe<T> b)
{
return !(a == b);
}
public static Maybe<T> operator !(Maybe<T> a)
{
if (!a.HasValue)
return a;
T result;
if (Calculator<T>.TryNegate(a.Value, out result))
return new Maybe<T>(result);
return Empty;
}
public static Maybe<T> operator *(Maybe<T> a, Maybe<T> b)
{
T result;
if (a.HasValue && b.HasValue && Calculator<T>.TryMultiply(a.Value, b.Value, out result))
return new Maybe<T>(result);
return Empty;
}
public static Maybe<T> operator -(Maybe<T> a, Maybe<T> b)
{
T result;
if (a.HasValue && b.HasValue && Calculator<T>.TryMinus(a.Value, b.Value, out result))
return new Maybe<T>(result);
return Empty;
}
#endregion
#region Nested type: ICaseThen
public interface ICaseThen<TIn>
{
ITypeSwitch<TRet> Then<TRet>(Func<TIn, TRet> thenFunc);
}
public interface ICaseThen<TIn, TRet>
{
ITypeSwitch<TRet> Then(Func<TIn, TRet> thenFunc);
}
#endregion
#region Nested type: ITypeSwitch
public interface ITypeSwitch
{
ICaseThen<TCast> Case<TCast>();
ICaseThen<TCast> Case<TCast>(Func<TCast, bool> predicate);
ICaseThen<T> Case(Func<T, bool> predicate);
}
public interface ITypeSwitch<TRet>
{
ICaseThen<TCast, TRet> Case<TCast>();
ICaseThen<TCast, TRet> Case<TCast>(Func<TCast, bool> predicate);
ICaseThen<T, TRet> Case(Func<T, bool> predicate);
Maybe<TRet> EndSwitch();
}
#endregion
#region Nested type: MatchingCaseThen
internal class MatchingCaseThen<TIn> : ICaseThen<TIn>
{
private readonly Maybe<TIn> value;
public MatchingCaseThen(Maybe<TIn> value)
{
this.value = value;
}
public ITypeSwitch<TRet> Then<TRet>(Func<TIn, TRet> thenFunc)
{
if (thenFunc == null)
throw new ArgumentNullException(nameof(thenFunc));
return new FinishedTypeSwitch<TRet>(this.value.Select(thenFunc));
}
}
internal class MatchingCaseThen<TIn, TRet> : ICaseThen<TIn, TRet>
{
private readonly TIn value;
public MatchingCaseThen(TIn value)
{
this.value = value;
}
public ITypeSwitch<TRet> Then(Func<TIn, TRet> thenFunc)
{
if (thenFunc == null)
throw new ArgumentNullException(nameof(thenFunc));
return new FinishedTypeSwitch<TRet>(new Maybe<TRet>(thenFunc(this.value)));
}
}
#endregion
#region Nested type: TypeSwitch
internal class TypeSwitch : ITypeSwitch
{
private readonly Maybe<T> value;
public TypeSwitch(Maybe<T> value)
{
this.value = value;
}
public ICaseThen<TCast> Case<TCast>()
{
return Case<TCast>(x => true);
}
public ICaseThen<TCast> Case<TCast>(Func<TCast, bool> predicate)
{
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
if (!this.value.HasValue)
return new MatchingCaseThen<TCast>(Maybe<TCast>.Empty);
if (this.value.Value is TCast)
{
var castValue = (TCast)((object)this.value.Value);
if (predicate(castValue))
return new MatchingCaseThen<TCast>(new Maybe<TCast>(castValue));
}
return new NonMatchingCaseThen<TCast>(this.value);
}
public ICaseThen<T> Case(Func<T, bool> predicate)
{
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
if (!this.value.HasValue || predicate(this.value.Value))
return new MatchingCaseThen<T>(this.value);
return new NonMatchingCaseThen<T>(this.value);
}
}
internal class TypeSwitch<TRet> : ITypeSwitch<TRet>
{
private readonly T value;
public TypeSwitch(T value)
{
this.value = value;
}
public ICaseThen<TCast, TRet> Case<TCast>(Func<TCast, bool> predicate)
{
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
if (this.value is TCast)
{
var castValue = (TCast)((object)this.value);
if (predicate(castValue))
return new MatchingCaseThen<TCast, TRet>(castValue);
}
return new PassthroughCaseThen<TCast, TRet>(this);
}
public ICaseThen<TCast, TRet> Case<TCast>()
{
return Case<TCast>(x => true);
}
public ICaseThen<T, TRet> Case(Func<T, bool> predicate)
{
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
if (predicate(this.value))
return new MatchingCaseThen<T, TRet>(this.value);
return new PassthroughCaseThen<T, TRet>(this);
}
public Maybe<TRet> EndSwitch()
{
return Maybe<TRet>.Empty;
}
}
#endregion
}
}
| |
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
using System.IO;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
///<summary>
/// This is the object used by Runspace,pipeline,host to send data
/// to remote end. Transport layer owns breaking this into fragments
/// and sending to other end
///</summary>
internal class RemoteDataObject<T>
{
#region Private Members
private const int destinationOffset = 0;
private const int dataTypeOffset = 4;
private const int rsPoolIdOffset = 8;
private const int psIdOffset = 24;
private const int headerLength = 4 + 4 + 16 + 16;
private const int SessionMask = 0x00010000;
private const int RunspacePoolMask = 0x00021000;
private const int PowerShellMask = 0x00041000;
#endregion Private Members
#region Constructors
/// <summary>
/// Constructs a RemoteDataObject from its
/// individual components.
/// </summary>
/// <param name="destination">
/// Destination this object is going to.
/// </param>
/// <param name="dataType">
/// Payload type this object represents.
/// </param>
/// <param name="runspacePoolId">
/// Runspace id this object belongs to.
/// </param>
/// <param name="powerShellId">
/// PowerShell (pipeline) id this object belongs to.
/// This may be null if the payload belongs to runspace.
/// </param>
/// <param name="data">
/// Actual payload.
/// </param>
protected RemoteDataObject(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
T data)
{
Destination = destination;
DataType = dataType;
RunspacePoolId = runspacePoolId;
PowerShellId = powerShellId;
Data = data;
}
#endregion Constructors
#region Properties
internal RemotingDestination Destination { get; }
/// <summary>
/// Gets the target (Runspace / Pipeline / Powershell / Host)
/// the payload belongs to.
/// </summary>
internal RemotingTargetInterface TargetInterface
{
get
{
int dt = (int)DataType;
// get the most used ones in the top.
if ((dt & PowerShellMask) == PowerShellMask)
{
return RemotingTargetInterface.PowerShell;
}
if ((dt & RunspacePoolMask) == RunspacePoolMask)
{
return RemotingTargetInterface.RunspacePool;
}
if ((dt & SessionMask) == SessionMask)
{
return RemotingTargetInterface.Session;
}
return RemotingTargetInterface.InvalidTargetInterface;
}
}
internal RemotingDataType DataType { get; }
internal Guid RunspacePoolId { get; }
internal Guid PowerShellId { get; }
internal T Data { get; }
#endregion Properties
/// <summary>
///
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
/// <returns></returns>
internal static RemoteDataObject<T> CreateFrom(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
T data)
{
return new RemoteDataObject<T>(destination, dataType, runspacePoolId, powerShellId, data);
}
/// <summary>
/// Creates a RemoteDataObject by deserializing <paramref name="data"/>.
/// </summary>
/// <param name="serializedDataStream"></param>
/// <param name="defragmentor">
/// Defragmentor used to deserialize an object.
/// </param>
/// <returns></returns>
internal static RemoteDataObject<T> CreateFrom(Stream serializedDataStream, Fragmentor defragmentor)
{
Dbg.Assert(null != serializedDataStream, "cannot construct a RemoteDataObject from null data");
Dbg.Assert(null != defragmentor, "defragmentor cannot be null.");
if ((serializedDataStream.Length - serializedDataStream.Position) < headerLength)
{
PSRemotingTransportException e =
new PSRemotingTransportException(PSRemotingErrorId.NotEnoughHeaderForRemoteDataObject,
RemotingErrorIdStrings.NotEnoughHeaderForRemoteDataObject,
headerLength + FragmentedRemoteObject.HeaderLength);
throw e;
}
RemotingDestination destination = (RemotingDestination)DeserializeUInt(serializedDataStream);
RemotingDataType dataType = (RemotingDataType)DeserializeUInt(serializedDataStream);
Guid runspacePoolId = DeserializeGuid(serializedDataStream);
Guid powerShellId = DeserializeGuid(serializedDataStream);
object actualData = null;
if ((serializedDataStream.Length - headerLength) > 0)
{
actualData = defragmentor.DeserializeToPSObject(serializedDataStream);
}
T deserializedObject = (T)LanguagePrimitives.ConvertTo(actualData, typeof(T),
System.Globalization.CultureInfo.CurrentCulture);
return new RemoteDataObject<T>(destination, dataType, runspacePoolId, powerShellId, deserializedObject);
}
#region Serialize / Deserialize
/// <summary>
/// Serializes the object into the stream specified. The serialization mechanism uses
/// UTF8 encoding to encode data.
/// </summary>
/// <param name="streamToWriteTo"></param>
/// <param name="fragmentor">
/// fragmentor used to serialize and fragment the object.
/// </param>
internal virtual void Serialize(Stream streamToWriteTo, Fragmentor fragmentor)
{
Dbg.Assert(null != streamToWriteTo, "Stream to write to cannot be null.");
Dbg.Assert(null != fragmentor, "Fragmentor cannot be null.");
SerializeHeader(streamToWriteTo);
if (null != Data)
{
fragmentor.SerializeToBytes(Data, streamToWriteTo);
}
return;
}
/// <summary>
/// Serializes only the header portion of the object. ie., runspaceId,
/// powerShellId, destination and dataType.
/// </summary>
/// <param name="streamToWriteTo">
/// place where the serialized data is stored into.
/// </param>
/// <returns></returns>
private void SerializeHeader(Stream streamToWriteTo)
{
Dbg.Assert(null != streamToWriteTo, "stream to write to cannot be null");
// Serialize destination
SerializeUInt((uint)Destination, streamToWriteTo);
// Serialize data type
SerializeUInt((uint)DataType, streamToWriteTo);
// Serialize runspace guid
SerializeGuid(RunspacePoolId, streamToWriteTo);
// Serialize powershell guid
SerializeGuid(PowerShellId, streamToWriteTo);
return;
}
private void SerializeUInt(uint data, Stream streamToWriteTo)
{
Dbg.Assert(null != streamToWriteTo, "stream to write to cannot be null");
byte[] result = new byte[4]; // size of int
int idx = 0;
result[idx++] = (byte)(data & 0xFF);
result[idx++] = (byte)((data >> 8) & 0xFF);
result[idx++] = (byte)((data >> (2 * 8)) & 0xFF);
result[idx++] = (byte)((data >> (3 * 8)) & 0xFF);
streamToWriteTo.Write(result, 0, 4);
}
private static uint DeserializeUInt(Stream serializedDataStream)
{
Dbg.Assert(serializedDataStream.Length >= 4, "Not enough data to get Int.");
uint result = 0;
result |= (((uint)(serializedDataStream.ReadByte())) & 0xFF);
result |= (((uint)(serializedDataStream.ReadByte() << 8)) & 0xFF00);
result |= (((uint)(serializedDataStream.ReadByte() << (2 * 8))) & 0xFF0000);
result |= (((uint)(serializedDataStream.ReadByte() << (3 * 8))) & 0xFF000000);
return result;
}
private void SerializeGuid(Guid guid, Stream streamToWriteTo)
{
Dbg.Assert(null != streamToWriteTo, "stream to write to cannot be null");
byte[] guidArray = guid.ToByteArray();
streamToWriteTo.Write(guidArray, 0, guidArray.Length);
}
private static Guid DeserializeGuid(Stream serializedDataStream)
{
Dbg.Assert(serializedDataStream.Length >= 16, "Not enough data to get Guid.");
byte[] guidarray = new byte[16]; // Size of GUID.
for (int idx = 0; idx < 16; idx++)
{
guidarray[idx] = (byte)serializedDataStream.ReadByte();
}
return new Guid(guidarray);
}
#endregion
}
internal class RemoteDataObject : RemoteDataObject<object>
{
#region Constructors / Factory
/// <summary>
///
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
private RemoteDataObject(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
object data) : base(destination, dataType, runspacePoolId, powerShellId, data)
{
}
/// <summary>
///
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
/// <returns></returns>
internal new static RemoteDataObject CreateFrom(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
object data)
{
return new RemoteDataObject(destination, dataType, runspacePoolId,
powerShellId, data);
}
#endregion Constructors
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace LWBoilerPlate.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.